mockforme 14.5.0 → 14.5.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md
CHANGED
|
@@ -33,9 +33,9 @@ yarn add mockforme -D
|
|
|
33
33
|
```
|
|
34
34
|
|
|
35
35
|
> **Note:** MockForMe **client** initialisation doesn't required access token, you can enter the token using MockForMe widget
|
|
36
|
-

|
|
37
37
|
|
|
38
|
-
[](https://www.youtube.com/watch?v=CmG5g94_T_8)
|
|
39
39
|
|
|
40
40
|
|
|
41
41
|
* You can also access mockforme object in your browser from window object:
|
|
@@ -17,4 +17,4 @@
|
|
|
17
17
|
0% { transform: translateX(-100%) scaleX(0.4); }
|
|
18
18
|
50% { transform: translateX(20%) scaleX(0.6); }
|
|
19
19
|
100% { transform: translateX(100%) scaleX(0.4); }
|
|
20
|
-
`;function AA({message:e,theme:t}){return Ct("div",{role:"alert",css:gt("background:#fef2f2;border:1px solid #fecaca;border-left:3px solid ",t.color.error,";color:",t.color.error,";padding:",t.spacing.md," ",t.spacing.lg,";border-radius:",t.radius.md,";font-size:",t.typography.fontSizeBase,";line-height:1.5;display:flex;align-items:flex-start;gap:",t.spacing.sm,";",""),children:[xt("strong",{css:gt("font-weight:",t.typography.fontWeightBold,";",""),children:"✗"}),xt("span",{children:e})]})}function lA(e){const t=document.getElementById("mfm-root");return!!t&&(t===e||t.contains(e))}function cA(e){if(!e)return"";if(e.length<=1e3)return e;return e.slice(0,988)+"…[truncated]"}function dA(){const e=Ut(),{confirmState:t,dismissConfirm:n}=un();if(u.useEffect(()=>{if(!t)return;const e=e=>{"Escape"===e.key&&n()};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[t,n]),!t)return null;const{title:r,message:o,confirmLabel:i,cancelLabel:s,danger:a,onConfirm:A}=t;return xt("div",{role:"dialog","aria-label":r??"Confirm","aria-modal":"true",onClick:e=>{e.target===e.currentTarget&&n()},css:gt("position:absolute;inset:0;background:rgba(15, 23, 42, 0.5);z-index:",e.z.confirm,";display:flex;align-items:center;justify-content:center;padding:",e.spacing.xl,";",""),children:Ct("div",{css:gt("background:",e.color.bg,";border-radius:",e.radius.lg,";box-shadow:",e.shadow.lg,";padding:",e.spacing.xl,";max-width:360px;width:100%;display:flex;flex-direction:column;gap:",e.spacing.md,";",""),children:[r?xt("h3",{css:gt("margin:0;font-size:",e.typography.fontSizeLg,";font-weight:",e.typography.fontWeightBold,";color:",e.color.text,";",""),children:r}):null,xt("p",{css:gt("margin:0;color:",e.color.text,";font-size:",e.typography.fontSizeBase,";line-height:1.5;",""),children:o}),Ct("div",{css:gt("display:flex;justify-content:flex-end;gap:",e.spacing.md,";margin-top:",e.spacing.sm,";",""),children:[xt("button",{type:"button",onClick:n,css:gt("appearance:none;background:transparent;border:1px solid ",e.color.border,";color:",e.color.text,";font-family:inherit;font-size:",e.typography.fontSizeBase,";padding:",e.spacing.sm," ",e.spacing.lg,";border-radius:",e.radius.md,";cursor:pointer;&:hover{background:",e.color.surfaceBright,";}",""),children:s??"Cancel"}),xt("button",{type:"button",autoFocus:!0,onClick:()=>{n(),A()},css:gt("appearance:none;border:none;background:",a?e.color.error:e.color.primary,";color:#fff;font-family:inherit;font-weight:",e.typography.fontWeightSemibold,";font-size:",e.typography.fontSizeBase,";padding:",e.spacing.sm," ",e.spacing.lg,";border-radius:",e.radius.md,";cursor:pointer;&:hover{filter:brightness(0.95);}",""),children:i??"Confirm"})]})]})})}function uA(){const{analyticsEnabled:e}=tr(),{token:t,organisationId:n}=gn();return u.useEffect(()=>{rn.setEnabled(e)},[e]),u.useEffect(()=>{rn.setToken(t)},[t]),u.useEffect(()=>{rn.setOrganisationId(n)},[n]),null}function fA({clientType:e,version:t}={}){return Ct(Qt,{initialMode:"light",children:[xt(hA,{}),xt(Mt,{children:xt(dn,{clientType:e,version:t,children:xt(pn,{children:xt(yn,{children:xt(Un,{children:xt(Nn,{children:xt(er,{children:xt(Jn,{children:Ct(ir,{children:[xt(uA,{}),xt(So,{}),xt(pA,{})]})})})})})})})})})]})}function hA(){const e=Ut();return xt(pt,{styles:gt(":host,[data-mfm-mount]{all:initial;color:",e.color.text,";font-family:",e.typography.fontFamily,";font-size:",e.typography.fontSizeBase,";line-height:1.4;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;text-rendering:optimizeLegibility;}*,*::before,*::after{box-sizing:border-box;}::-webkit-scrollbar{width:8px;height:8px;}::-webkit-scrollbar-thumb{background:",e.color.border,";border-radius:",e.radius.pill,";}::-webkit-scrollbar-thumb:hover{background:",e.color.textDim,";}","")})}function pA(){const{setOpen:e,isInterceptEnabled:t,toggleIntercept:n,isSettingsOpen:r,openSettings:o,startSnipping:i,requestConfirm:s}=un(),{token:a,isTokenValidated:A,isValidating:l,isLoading:c,reloadMappings:d,deleteToken:u}=gn(),{debugRules:f,editRules:h}=Wn(),{globalDelay:p}=tr();if(!A&&(l||a))return Ct(Bt,{children:[xt(_o,{children:xt(bA,{children:xt(mA,{})})}),xt(qa,{})]});if(!a)return Ct(Bt,{children:[xt(_o,{children:Ct(bA,{children:[xt(pa,{}),xt(dA,{})]})}),xt(qa,{})]});const g=r||f.length>0||h.length>0||p.enabled;return Ct(Bt,{children:[Ct(_o,{children:[xt(Oo,{onSnip:i,onReload:d,onOpenSettings:o,onDeleteToken:()=>{s({title:"Delete token?",message:"Are you sure you want to delete token? API interception will stop once the token is removed.",confirmLabel:"Delete",danger:!0,onConfirm:u})},isInterceptEnabled:t,onToggleIntercept:()=>{t?s({title:"Disable interception?",message:"Once disabled, the widget will stop intercepting requests and disappear from the page. Please refresh the page after disabling it. You can re-enable it anytime from the MockForMe settings page via the extension icon in tray or the right-click menu. You can also re-enable it from inside Widget Settings → Whitelisted Hosts.",confirmLabel:"Disable",danger:!0,onConfirm:n}):n()},onClose:()=>e(!1),isSettingsActive:g,isReloading:c,isAuthenticated:!0}),xt(Po,{}),Ct(bA,{children:[xt(da,{}),xt(ga,{}),xt(ka,{}),xt(Ba,{}),xt(Ua,{}),xt(Na,{}),xt(dA,{}),xt(yA,{})]})]}),xt(qa,{})]})}var gA={name:"3kwpv8",styles:"flex:1;min-height:0;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:14px;padding:24px;text-align:center"};function mA(){const e=Ut();return Ct("div",{css:gA,children:[xt(yi,{size:26,color:e.color.primary,label:"Validating token"}),xt("div",{css:gt("font-size:",e.typography.fontSizeBase,";font-weight:600;color:",e.color.text,";",""),children:"Validating your token…"}),xt("div",{css:gt("font-size:12px;color:",e.color.textDim,";max-width:260px;line-height:1.5;",""),children:"Hang tight — we're verifying your session before loading the widget."})]})}function yA(){const{invalidatedMessage:e,acknowledgeInvalidation:t}=gn(),n=Ut();return null==e?null:xt(ri,{open:!0,hideClose:!0,title:"Token no longer valid",leadingDot:"live",onClose:()=>{},footer:xt("button",{type:"button",onClick:t,css:gt("appearance:none;border:none;border-radius:",n.radius.sm,";background:",n.color.primary,";color:#fff;font-size:",n.typography.fontSizeBase,";font-weight:",n.typography.fontWeightBold,";padding:8px 20px;cursor:pointer;&:hover{background:",n.color.primaryHover,";}",""),children:"OK"}),children:xt("p",{css:gt("margin:0;font-size:",n.typography.fontSizeBase,";line-height:1.5;color:",n.color.text,";",""),children:e})})}var wA={name:"4oq8x6",styles:"position:absolute;inset:0;pointer-events:none;z-index:1500;&:empty{display:none;}&>*{pointer-events:auto;}"},kA={name:"p72qif",styles:"flex:1;min-height:0;position:relative;display:flex;flex-direction:column;overflow:hidden"};function bA({children:e}){const{fullscreenSlotRef:t}=un();return Ct("div",{css:kA,children:[e,xt("div",{ref:t,"data-mfm-fullscreen-slot":!0,css:wA})]})}class vA extends u.Component{constructor(){super(...arguments),o(this,"state",{hasError:!1})}static getDerivedStateFromError(){return Or(),{hasError:!0}}componentDidCatch(e,t){try{this.props.onError(e,t)}catch{}}render(){return this.state.hasError?null:this.props.children}}const BA=(()=>{try{const e="file:///Users/sushilkumar/mockforme/shared/mockforme_widget/dist/chunks/widget-B8TRg0gv.js",t=e.lastIndexOf("/");return t>0?e.slice(0,t+1):e}catch{return""}})();function xA(e,t){return!(!BA||!function(){try{const e=typeof document<"u"&&(document.baseURI||document.location&&document.location.href)||"";return!!e&&!e.startsWith(BA)}catch{return!1}}()||!(e&&e.startsWith(BA)||t&&-1!==t.indexOf(BA)))}let CA=null;const EA="data-mfm-mount";function FA(e){return e||document.getElementById("mfm-root")||(document.body?document.body:null)}function SA(e,t){let n;"mfm-root"===e.id?n=e:(n=document.createElement("div"),n.id="mfm-root",e.appendChild(n)),n.style.cssText="all: initial; display: block;",function(e){try{rn.init(),rn.setClientType(e);const t=tn().read("MFM_TOKEN");t&&rn.setToken(t)}catch{}}(t.clientType);const r=["click","dblclick","mousedown","mouseup","mousemove","pointerdown","pointerup","pointermove","contextmenu","wheel","touchstart","touchend","touchmove"],o=e=>e.stopPropagation();for(const e of r){const t="wheel"===e||"touchstart"===e||"touchend"===e||"touchmove"===e;n.addEventListener(e,o,{passive:t})}const i=n.shadowRoot??n.attachShadow({mode:"open"});let s=i.querySelector(`[${EA}]`);s||(s=document.createElement("div"),s.setAttribute(EA,""),i.appendChild(s));const a=Ue({key:"mfm",container:i,prepend:!0}),A={run:()=>{}},l=F.createRoot(s);l.render(u.createElement(u.StrictMode,null,u.createElement(rt,{value:a},u.createElement(vA,{onError:e=>{setTimeout(()=>A.run(e),0)}},u.createElement(fA,{clientType:t.clientType,version:t.version})))));const c=e=>{const t=e.error;xA(e.filename,t?.stack)&&(Or(),e.preventDefault(),A.run(e.error))},d=e=>{const t=e.reason;xA(void 0,t?.stack??(t?String(t):void 0))&&(Or(),e.preventDefault(),A.run(e.reason))};window.addEventListener("error",c),window.addEventListener("unhandledrejection",d);const f=console.error;console.error=function(...e){if(!(jr>0)){if(BA)for(let t=0;t<e.length;t++){const n=e[t];if(-1!==((n&&"object"==typeof n&&"stack"in n?String(n.stack??""):"")||String(n)).indexOf(BA))return}f.apply(console,e)}};let h=!1,p=null;const g=e=>{if(!h){if(h=!0,window.removeEventListener("error",c),window.removeEventListener("unhandledrejection",d),console.error!==f)try{console.error=f}catch{}try{l.unmount()}catch{}try{n.remove()}catch{}CA=null;try{if(void 0!==e){const t=e,n=t&&"string"==typeof t.message?t.message:"string"==typeof e?e:String(e),r=t&&"string"==typeof t.stack?t.stack:"";Vr("widget_load_failed",{errorName:t&&"string"==typeof t.name?t.name:"Error",errorMessage:n,errorStack:r.slice(0,4e3),userAgent:typeof navigator<"u"?navigator.userAgent:"",url:typeof location<"u"?location.href:""})}else rn.track("widget_destroyed");Gr()}catch{}if(void 0!==e)try{p=function(){if(typeof document>"u"||!document.body)return{dismiss(){}};const e=document.createElement("div");e.id="mfm-error-snackbar",e.style.cssText=["all: initial","position: fixed","right: 16px","bottom: 16px","z-index: 2147483646"].join(";"),document.body.appendChild(e);const t=e.attachShadow({mode:"closed"}),n=document.createElement("div");n.style.cssText=["box-sizing: border-box","display: flex","align-items: center","gap: 10px","min-width: 280px","max-width: 380px","padding: 10px 12px","background: #1f2937","color: #f9fafb","border: 1px solid #374151","border-radius: 8px","box-shadow: 0 8px 24px rgba(0,0,0,0.25)",'font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',"font-size: 13px","line-height: 1.4"].join(";");const r=document.createElement("div");r.style.cssText=["flex: 1 1 auto","min-width: 0"].join(";");const o=document.createElement("div");o.textContent="MockForMe is unable to load.",o.style.cssText="font-weight: 500";const i=document.createElement("div");i.textContent="The issue has been reported.",i.style.cssText=["margin-top: 2px","color: #9ca3af","font-size: 12px"].join(";"),r.appendChild(o),r.appendChild(i);const s=document.createElement("button");s.type="button",s.setAttribute("aria-label","Dismiss"),s.textContent="×",s.style.cssText=["flex: 0 0 auto","width: 24px","height: 24px","padding: 0","background: transparent","color: #9ca3af","border: 0","border-radius: 4px","cursor: pointer","font-size: 18px","line-height: 1"].join(";");let a=!1;const A=()=>{if(!a){a=!0;try{e.remove()}catch{}}};return s.addEventListener("click",A),n.appendChild(r),n.appendChild(s),t.appendChild(n),{dismiss:A}}()}catch{}}};return A.run=g,{destroy(){if(g(),p){try{p.dismiss()}catch{}p=null}}}}const QA={run(e,t={}){if(CA)return CA;if(typeof document<"u"&&"loading"===document.readyState){let n=!1;const r=()=>{if(n)return;const r=FA(e);r&&(CA=SA(r,t))};return document.addEventListener("DOMContentLoaded",r,{once:!0}),{destroy(){n=!0,document.removeEventListener("DOMContentLoaded",r),CA&&CA.destroy()}}}const n=FA(e);return n?(CA=SA(n,t),CA):(console.warn("[MockForMeWidget] no mount target available"),{destroy(){}})}};typeof window<"u"&&(window.MockForMeWidget=QA),n.d(t,["M",0,QA])}};const t={};function n(r){const o=t[r];if(void 0!==o)return o.exports;const i=t[r]={exports:{}};return e[r](i,i.exports,n),i.exports}n.d=(e,t)=>{if(Array.isArray(t))for(var r=0;r<t.length;){var o=t[r++],i=t[r++];n.o(e,o)?0===i&&r++:0===i?Object.defineProperty(e,o,{enumerable:!0,value:t[r++]}):Object.defineProperty(e,o,{enumerable:!0,get:i})}else 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=>{Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};let r={};n.r(r),n.d(r,{mockforme:()=>he});const o=()=>"undefined"!=typeof process&&null!=process.versions?.node,i=e=>{try{return e?e.toLowerCase():e}catch(e){return console.log(e),null}},s=(e,t)=>{const n=e.split("/"),r=t.split("/");if(n.length!==r.length)return!1;for(let e=0;e<n.length;e++){const t=n[e];if(t!==r[e]&&":any"!==t&&":"!==t.charAt(0))return!1}return!0},a=new Map;let A=[];function l(e){A=e}function c(){return A}function d(e,t="get"){const n=e=>e.startsWith("/")?e:`/${e}`,r=n(e),o=function(e,t){if(0===a.size)return null;for(const n of a.values())for(const r of n){if(i(r.apiMethod)!==i(t))continue;const n=r.apiEndpoint.startsWith("/")?r.apiEndpoint:`/${r.apiEndpoint}`;if(n===e||s(n,e)){const t={url:e,method:r.apiMethod,_ack:r._ack||null};return r._ri_&&(t._ri_=r._ri_),t}}return null}(r,t);if(o)return console.log(`[MockForMe] Flow Mock Match: ${t} ${e} -> ${o.url}`),o;for(const o of A)if(i(o.apiMethod)===i(t)){const i=n(o.apiEndpoint);if(i===r||s(i,r)){console.log(`[MockForMe] Match Found: ${t} ${e} -> ${o.apiEndpoint}`);const n={url:e,method:o.apiMethod,apiEndpoint:o.apiEndpoint,_ack:o._ack||null};return o._ri_&&(n._ri_=o._ri_),n}}return null}const u="JAVASCRIPT",f="mockforme",h="https://api.mockforme.com",p=`${h}/mockforme`,g=`${h}/gateway/3f4eae522b`;let m=null,y=null,w=null,k=[];function b({_o:e,mk:t,_mck:n,_rules:r}){m=e,y=t,w=n,k=r}function v(){return k}function B(){return`${p}/${m}/${y}`}function x(){return w}function C(e,t,n,r){fetch(g,{method:"GET",headers:{[f]:e,mfmver:"14.5.0","x-mfm-adaptor":t}}).then(e=>{if(!e.ok)throw e;return e.json()}).then(e=>{if(e){const{di:t,iv:r,_o:o,_mck:i,mk:s,r:a}=e,A=function({di:e,iv:t},n){var r;const o=function(e,t){const n=t.length;return e.split("").map((e,r)=>String.fromCharCode(e.charCodeAt(0)^t.charCodeAt(r%n))).join("")}((r=e,"undefined"!=typeof Buffer?Buffer.from(r,"base64").toString("utf8"):decodeURIComponent(escape(atob(r)))),n+t);return JSON.parse(o)}({di:t,iv:r},o);b({_o:o,mk:s,_mck:i,_rules:a}),A&&(l(A),n(A,{_o:o,mk:s,_mck:i,_rules:a}))}}).catch(e=>{console.error("Error in loading mocked APIs:",e),r(e)})}const E=`${h}/mockforme/mfm_op_3f4eae522b/manage`,F=e=>({[f]:e,mfmver:"14.5.0","Content-Type":"application/json"}),S=async e=>{let t=null;try{t=await e.json()}catch(e){}return{ok:!(!e.ok||!t||!0!==t.status&&"success"!==t.status&&1!==t.status),message:t&&t.message||(e.ok?"":`Request failed (${e.status})`),result:t?t.result:null}},Q="MFM_INTERCEPTOR_RULES";let U=[];const T=new Map;function I(){try{if("undefined"==typeof localStorage)return[];const e=localStorage.getItem(Q);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>e&&e.enabled):[]}catch(e){return[]}}function _(e){U=Array.isArray(e)?e.filter(e=>e&&e.enabled):[]}function M(e,t){if(!e||!t)return null;if(!U.length&&(U=I(),!U.length))return null;const n=String(e).toUpperCase();return U.find(e=>{if(!e.enabled||String(e.method).toUpperCase()!==n)return!1;if("PATH"===e.matchType)try{return new URL(e.url,"http://localhost").pathname===new URL(t,"http://localhost").pathname}catch(n){return e.url===t}return e.url===t})||null}function H({requestId:e,ruleId:t,request:n,response:r,timeoutMs:o=3e5}){return new Promise(i=>{const s=setTimeout(()=>{T.has(e)&&(T.delete(e),i({requestId:e,simulateTimeout:!1,delayMs:0,statusCode:r?.statusCode??200,headers:r?.headers||{},body:r?.body}))},o);T.set(e,{resolve:i,timer:s});try{"undefined"!=typeof window&&window.postMessage({type:"MFM_DEBUG_INTERCEPT_REQ",payload:{requestId:e,ruleId:t,request:n,response:r,timestamp:Date.now()}},"*")}catch(t){clearTimeout(s),T.delete(e),i({requestId:e,simulateTimeout:!1,delayMs:0,statusCode:r?.statusCode??200,headers:r?.headers||{},body:r?.body})}})}U=I(),"undefined"!=typeof document&&"function"==typeof document.addEventListener&&document.addEventListener("mfm:rule-sync",e=>{const t=e&&e.detail;t&&"debugger"===t.kind&&_(t.payload?.rules||[])}),"undefined"!=typeof window&&"function"==typeof window.addEventListener&&window.addEventListener("storage",e=>{e.key===Q&&(U=I())});const L="MFM_REQUEST_EDITOR_RULES";let D=[];const N=new Map;function j(){try{if("undefined"==typeof localStorage)return[];const e=localStorage.getItem(L);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>e&&e.enabled):[]}catch(e){return[]}}function O(e){D=Array.isArray(e)?e.filter(e=>e&&e.enabled):[]}function R(e,t){if(!e||!t)return null;if(!D.length&&(D=j(),!D.length))return null;const n=String(e).toUpperCase();return D.find(e=>{if(!e.enabled||String(e.method).toUpperCase()!==n)return!1;if("PATH"===e.matchType)try{return new URL(e.url,"http://localhost").pathname===new URL(t,"http://localhost").pathname}catch(n){return e.url===t}return e.url===t})||null}function P(e,t,n){const r={};return Object.entries(t?.headers||{}).forEach(([e,t])=>{r[e]=String(t??"")}),{requestId:e,cancel:!1,headers:r,queryParams:n||{},body:"string"==typeof t?.body?t.body:null}}function z({requestId:e,ruleId:t,request:n,queryParams:r,timeoutMs:o=3e5}){return new Promise(i=>{const s=setTimeout(()=>{N.has(e)&&(N.delete(e),i(P(e,n,r)))},o);N.set(e,{resolve:i,timer:s});try{"undefined"!=typeof window&&window.postMessage({type:"MFM_REQUEST_EDIT_REQ",payload:{requestId:e,ruleId:t,request:n,queryParams:r,timestamp:Date.now()}},"*")}catch(t){clearTimeout(s),N.delete(e),i(P(e,n,r))}})}D=j(),"undefined"!=typeof document&&"function"==typeof document.addEventListener&&document.addEventListener("mfm:rule-sync",e=>{const t=e&&e.detail;t&&"editor"===t.kind&&O(t.payload?.rules||[])}),"undefined"!=typeof window&&"function"==typeof window.addEventListener&&window.addEventListener("storage",e=>{e.key===L&&(D=j())});const K="MFM_GLOBAL_DELAY";let V={enabled:!1,seconds:0},G=0;function q(){try{if("undefined"==typeof localStorage)return{enabled:!1,seconds:0};const e=localStorage.getItem(K);if(!e)return{enabled:!1,seconds:0};const t=JSON.parse(e);return t&&"object"==typeof t?{enabled:!!t.enabled&&Number.isFinite(t.seconds)&&t.seconds>0,seconds:Number.isFinite(t.seconds)?Number(t.seconds):0}:{enabled:!1,seconds:0}}catch(e){return{enabled:!1,seconds:0}}}function J(){const e=Date.now();return e-G>500&&(V=q(),G=e),V.enabled&&V.seconds>0?Math.round(1e3*V.seconds):0}V=q(),G=Date.now(),"undefined"!=typeof window&&"function"==typeof window.addEventListener&&window.addEventListener("storage",e=>{e.key===K&&(V=q(),G=Date.now())});var W,$,X=n(411);!function(e){e[e.NONE=0]="NONE",e[e.INFO=1]="INFO",e[e.WARN=2]="WARN",e[e.ERROR=3]="ERROR"}(W||(W={})),function(e){e.MFM_REQ_MAPPINGS="MFM_REQ_MAPPINGS",e.MFM_REQ_SAVED_MAPPINGS="MFM_REQ_SAVED_MAPPINGS",e.MFM_DEL_CLIENT_TOKEN="MFM_DEL_CLIENT_TOKEN",e.MFM_SUBMIT_TOKEN="MFM_SUBMIT_TOKEN",e.MFM_TOGGLE_INTERCEPTION="MFM_TOGGLE_INTERCEPTION",e.MFM_REQ_ALL_APIS="MFM_REQ_ALL_APIS",e.MFM_TOGGLE_API="MFM_TOGGLE_API",e.MFM_DEBUG_RULES_UPDATE="MFM_DEBUG_RULES_UPDATE",e.MFM_DEBUG_INTERCEPT_RES="MFM_DEBUG_INTERCEPT_RES",e.MFM_REQUEST_EDIT_RULES_UPDATE="MFM_REQUEST_EDIT_RULES_UPDATE",e.MFM_REQUEST_EDIT_ACK="MFM_REQUEST_EDIT_ACK",e.MFM_REQUEST_EDIT_RES="MFM_REQUEST_EDIT_RES",e.MFM_GLOBAL_DELAY_UPDATE="MFM_GLOBAL_DELAY_UPDATE",e.MFM_FLOW_MOCK_SET="MFM_FLOW_MOCK_SET",e.MFM_FLOW_MOCK_CLEAR="MFM_FLOW_MOCK_CLEAR",e.MFM_PING_SCREENSHOT="MFM_PING_SCREENSHOT",e.MFM_REQUEST_SCREENSHOT="MFM_REQUEST_SCREENSHOT",e.MFM_RES_MAPPINGS="MFM_RES_MAPPINGS",e.MFM_RES_ALL_APIS="MFM_RES_ALL_APIS",e.MFM_TOGGLE_API_RESULT="MFM_TOGGLE_API_RESULT",e.MFM_REQ="MFM_REQ",e.MFM_RES="MFM_RES",e.MFM_TOKEN_ERROR="MFM_TOKEN_ERROR",e.MFM_TOKEN_API_FAILED="MFM_TOKEN_API_FAILED",e.MFM_TOKEN_INVALIDATED="MFM_TOKEN_INVALIDATED",e.MFM_MOCK_DISABLED="MFM_MOCK_DISABLED",e.MFM_TOKEN_CLEARED="MFM_TOKEN_CLEARED",e.MFM_DEBUG_INTERCEPT_REQ="MFM_DEBUG_INTERCEPT_REQ",e.MFM_REQUEST_EDIT_REQ="MFM_REQUEST_EDIT_REQ",e.MFM_PONG_SCREENSHOT="MFM_PONG_SCREENSHOT",e.MFM_SCREENSHOT_RESULT="MFM_SCREENSHOT_RESULT",e.MFM_SCREENSHOT_ERROR="MFM_SCREENSHOT_ERROR",e.MFM_LOG_INFO="MFM_LOG_INFO",e.MFM_LOG_WARN="MFM_LOG_WARN",e.MFM_LOG_ERROR="MFM_LOG_ERROR"}($||($={}));const Y="MFM_TOKEN",Z="MFM_CACHED_MAPPINGS",ee="MFM_INTERCEPTION_ENABLED",te=new class{constructor(e={}){o()||(this.token=e.token||("undefined"!=typeof localStorage?localStorage.getItem(Y):null),this.isAuthenticated=!!this.token,this.onAuthSuccess=e.onAuthSuccess||(()=>{}),this.mappings=e.mappings||[],this.rules=e.rules||[],this.widgetKey=e.widgetKey||null,this.tokenInvalidated=!1,this.setupMessageListeners())}get interceptionEnabled(){if(this.tokenInvalidated)return!1;if("undefined"==typeof localStorage)return!1!==this._interceptionEnabled;const e=localStorage.getItem(ee);return"false"!==e&&("true"===e||!1!==this._interceptionEnabled)}set interceptionEnabled(e){const t=!!e;this._interceptionEnabled=t,"undefined"!=typeof localStorage&&localStorage.setItem(ee,t?"true":"false")}setupMessageListeners(){"undefined"!=typeof window&&window.addEventListener("message",e=>{const{type:t,payload:n}=e.data||{};var r,o;if(t&&"string"==typeof t&&t.startsWith("MFM_"))switch(t){case $.MFM_REQ_MAPPINGS:this.refreshMappings();break;case $.MFM_REQ_SAVED_MAPPINGS:this.handleReqSavedMappings();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;break;case $.MFM_REQ_ALL_APIS:this.handleReqAllApis();break;case $.MFM_TOGGLE_API:this.handleToggleApi(n?.apiId,n?.enabled);break;case $.MFM_DEBUG_RULES_UPDATE:_(n?.rules||[]);break;case $.MFM_DEBUG_INTERCEPT_RES:!function(e){if(!e||!e.requestId)return;const t=T.get(e.requestId);t&&(clearTimeout(t.timer),T.delete(e.requestId),t.resolve(e))}(n);break;case $.MFM_REQUEST_EDIT_RULES_UPDATE:O(n?.rules||[]);break;case $.MFM_REQUEST_EDIT_RES:!function(e){if(!e||!e.requestId)return;const t=N.get(e.requestId);t&&(clearTimeout(t.timer),N.delete(e.requestId),t.resolve(e))}(n);break;case $.MFM_GLOBAL_DELAY_UPDATE:!function(e){if(!e||"object"!=typeof e)return V={enabled:!1,seconds:0},void(G=Date.now());V={enabled:!!e.enabled&&Number.isFinite(e.seconds)&&e.seconds>0,seconds:Number.isFinite(e.seconds)?Number(e.seconds):0},G=Date.now()}(n);break;case $.MFM_FLOW_MOCK_SET:r=n?.runId,o=n?.apis||[],r&&a.set(String(r),Array.isArray(o)?o:[]);break;case $.MFM_FLOW_MOCK_CLEAR:!function(e){e&&a.delete(String(e))}(n?.runId)}})}init(){if("undefined"!=typeof document&&this.checkVisibility()){if("undefined"!=typeof window){const e=window.MockForMeWidget||X.M;e&&"function"==typeof e.run&&(e.run(null,{clientType:"NPM",version:"14.5.0"}),this.syncInterceptionToggleToWidget())}if(console.log("[MockForMe] Widget initialized"),this.token){const e=this.getSavedMappings(this.token,"JAVASCRIPT");e&&(this.mappings=e.mappings||[],this.rules=e.meta?._rules||[],this.onAuthSuccess(this.token,this.mappings,e.meta),this.updateMappings(this.mappings,e.meta))}}}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(Y,e),this.refreshMappings())}handleTokenDeletion(){this.token=null,this.isAuthenticated=!1,"undefined"!=typeof localStorage&&(localStorage.removeItem(Y),localStorage.removeItem(Z)),this.mappings=[],this.rules=[],this.onAuthSuccess(null,[],{_rules:[]}),this.updateMappings([],{_rules:[]})}handleReqAllApis(){this.token?(async e=>{if(!e)return{ok:!1,message:"Missing token",result:[]};const t=await fetch(`${E}/apis`,{method:"GET",headers:F(e)});return S(t)})(this.token).then(e=>{const t=e.ok&&Array.isArray(e.result)?e.result:[];this.sendMessage($.MFM_RES_ALL_APIS,{apis:t})}).catch(()=>this.sendMessage($.MFM_RES_ALL_APIS,{apis:[]})):this.sendMessage($.MFM_RES_ALL_APIS,{apis:[]})}handleToggleApi(e,t){this.token&&e?(async(e,t,n)=>{if(!e)return{ok:!1,message:"Missing token",result:null};const r=await fetch(`${E}/api/${t}/toggle-state`,{method:"PUT",headers:F(e),body:JSON.stringify({enabled:!!n})});return S(r)})(this.token,e,t).then(n=>{this.sendMessage($.MFM_TOGGLE_API_RESULT,{apiId:e,enabled:!!t,ok:!!n.ok,message:n.message||""}),n.ok&&this.refreshMappings()}).catch(()=>this.sendMessage($.MFM_TOGGLE_API_RESULT,{apiId:e,enabled:!!t,ok:!1,message:"Failed to update the mock"})):this.sendMessage($.MFM_TOGGLE_API_RESULT,{apiId:e,enabled:!!t,ok:!1,message:"Missing token"})}refreshMappings(){this.token&&C(this.token,"JAVASCRIPT",(e,t)=>{this.mappings=e||[],this.rules=t?._rules||[],this.tokenInvalidated=!1,this.saveMappings(e,t,this.token,"JAVASCRIPT"),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.token=null,this.isAuthenticated=!1,"undefined"!=typeof localStorage&&(localStorage.removeItem(Y),localStorage.removeItem(Z)),this.mappings=[],this.rules=[],this.onAuthSuccess(null,[],{_rules:[]}),this.sendMessage($.MFM_TOKEN_ERROR,{message:"Unauthorized: Invalid token"})):this.sendMessage($.MFM_TOKEN_API_FAILED,{message:"Unable to reach the mappings service. Please try again."})})}saveMappings(e,t,n=this.token,r="JAVASCRIPT"){if("undefined"!=typeof localStorage)try{localStorage.setItem(Z,JSON.stringify({token:n,adaptor:r,mappings:e,meta:t,timestamp:Date.now()}))}catch(e){console.error("[MockForMe] Failed to save mappings to storage",e)}}handleReqSavedMappings(){const e=this.getSavedMappings(this.token,"JAVASCRIPT");e?(this.mappings=e.mappings||[],this.rules=e.meta?._rules||[],this.onAuthSuccess(this.token,this.mappings,e.meta),this.updateMappings(this.mappings,e.meta)):this.updateMappings([],{_rules:[]})}getSavedMappings(e=this.token,t="JAVASCRIPT"){if("undefined"==typeof localStorage)return null;try{const n=localStorage.getItem(Z);if(!n)return null;const r=JSON.parse(n);return r?.token&&e&&r.token!==e||r?.adaptor&&t&&r.adaptor!==t?null:r}catch(e){return null}}syncInterceptionToggleToWidget(){this.sendMessage($.MFM_TOGGLE_INTERCEPTION,{enabled:this.interceptionEnabled})}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="object"==typeof e.rule&&null!==e.rule?e.rule:{},n={...e,...t},r=n.timingAction||{},o=r.activeAction||"MODIFY";let i="MODIFY";"delay"===o?i="DELAY":"delay_and_timeout"===o?i="TIMEOUT":"delay_and_redirect"===o&&(i="REDIRECT");const s={ruleName:n.ruleName||n._id||"Unnamed Rule",type:i,conditions:n.conditions||[],modificationActions:n.modificationActions||{}};return("MODIFY"!==i||r.activeAction)&&(s.timingAction=r),s}),token:this.token})}handleMockDisabled({apiMethod:e,apiEndpoint:t}={}){if(!t)return;const n=function(e,t){if(!t)return!1;const n=A.length,r=i(e||"");return A=A.filter(e=>!(i(e.apiMethod)===r&&e.apiEndpoint===t)),A.length!==n}(e,t),r=this.mappings.length;if(this.mappings=(this.mappings||[]).filter(n=>!((n.apiMethod||"").toLowerCase()===(e||"").toLowerCase()&&n.apiEndpoint===t)),!n&&this.mappings.length===r)return;this.updateMappings(this.mappings,{_rules:this.rules});const o=`${(e||"").toUpperCase()} ${t}`.trim();this.sendMessage($.MFM_MOCK_DISABLED,{method:e,url:t,message:`${o} mock was disabled and has been removed.`})}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(": "),r=n.shift();r&&(t[r]=n.join(": "))}):t="function"==typeof e.entries?Object.fromEntries(e.entries()):e,Object.keys(t).reduce((e,n)=>(e[n.toLowerCase()]=t[n],e),{})};let r,o,i;if(void 0===t.status||null===t.status)r=void 0;else if("number"==typeof t.status)r=t.status;else{const e=Number(t.status);Number.isFinite(e)?r=e:(r=0,o=String(t.status))}t.aborted||"Aborted"===t.status?i="aborted":t.timeout||"Timeout"===t.status?i="timeout":"Cancelled"===t.status?i="cancelled":(t.error||"Error"===o)&&(i="error");const s=t.pending&&void 0===t.status?null:{statusCode:r,headers:n(t.responseHeaders),body:t.responseBody,endTime:(new Date).toISOString(),...o?{statusText:o}:{},...i?{errorReason:i,failed:!0}:{}},a={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:s,rule:t.rule,timestamp:t.pending&&t.startTime||Date.now(),...Number.isFinite(t.duration)?{duration:t.duration}:{}};if(t.pending)this.sendMessage($.MFM_REQ,a);else if(this.sendMessage($.MFM_RES,a),!this.tokenInvalidated&&a.response&&a.response.headers){const e=a.response.headers["mfm-invalid-token"];if("true"===e||!0===e){console.warn("[MockForMe] Invalid token detected from response headers"),this.tokenInvalidated=!0;let e="Your token is no longer valid. Please enter a valid token.";try{const n=t.responseBody,r="string"==typeof n?JSON.parse(n):n;r&&"string"==typeof r.message&&r.message.trim()&&(e=r.message.trim())}catch(e){}this.sendMessage($.MFM_TOKEN_INVALIDATED,{message:e})}}}sendMessage(e,t){"undefined"!=typeof window&&window.postMessage({type:e,payload:t},"*")}};function ne(e){const t=function(e,t){if(e)return"function"==typeof e.get?e.get(t):"string"==typeof e?((e,t)=>{const n=t.toLowerCase();return e.split(/\r?\n/).map(e=>{const t=e.indexOf(":");return t<0?null:[e.slice(0,t).trim().toLowerCase(),e.slice(t+1).trim()]}).filter(Boolean).find(([e])=>e===n)?.[1]})(e,t):((e,t)=>{const n=t.toLowerCase();for(const t of Object.keys(e||{}))if(t.toLowerCase()===n)return e[t]})(e,t)}(e,"mfm-mock-disabled");return"true"===t||!0===t}class re{static match(e,t){if(!Array.isArray(t)||0===t.length)return!1;const{url:n,headers:r,queryParams:o,body:i}=e,s="undefined"!=typeof window?window.location.origin:globalThis.location?.origin||"http://localhost";for(const e of t){let t="";const{type:a,key:A,operator:l,value:c}=e;switch(a){case"URL":try{t=new URL(n,s).pathname}catch{t=n}break;case"QUERY_PARAM":if(o&&void 0!==o[A])t=String(o[A]);else try{t=new URL(n,s).searchParams.get(A)||""}catch{t=""}break;case"REQUEST_BODY":if(A){if("object"==typeof i&&null!==i)t=void 0!==i[A]?String(i[A]):"";else if("string"==typeof i)try{const e=JSON.parse(i);t=void 0!==e[A]?String(e[A]):""}catch{t=""}}else t="object"==typeof i?JSON.stringify(i):String(i||"");break;case"REQUEST_HEADER":if(A){const e=A?.toLowerCase();if(t="",r){const n=Object.keys(r).find(t=>t.toLowerCase()===e);t=n?String(r[n]):""}}else t=JSON.stringify(r||{});break;default:return!1}if(!this.evaluate(t,l,c))return!1}return!0}static evaluate(e,t,n){const r=t?.toLowerCase(),o=String(e),i=String(n);switch(r){case"contains":return o.includes(i);case"equal":case"equals":return o===i;case"regexp":try{let e=i;if(e.startsWith("/")&&e.lastIndexOf("/")>0){const t=e.lastIndexOf("/"),n=e.slice(1,t),r=e.slice(t+1);return new RegExp(n,r).test(o)}return new RegExp(e).test(o)}catch{return!1}default:return!1}}}class oe{static async apply(e){if(!e||!e.activeAction)return{type:"passThrough",delay:0};const{activeAction:t,actions:n}=e,r=n?.[t];if(!r)return{type:"passThrough",delay:0};const o={type:"passThrough",delay:0},i=Number(r.value||0);switch(t){case"delay":o.delay=i,o.delay>0&&await new Promise(e=>setTimeout(e,1e3*o.delay));break;case"redirect":case"delay_and_redirect":o.type="redirect",o.delay=i,o.redirectUrl=r.redirectUrl,o.delay>0&&await new Promise(e=>setTimeout(e,1e3*o.delay));break;case"delay_and_timeout":o.type="timeout",o.delay=i,o.delay>0&&await new Promise(e=>setTimeout(e,1e3*o.delay))}return o}}class ie{static applyRequestModifications(e,t){if(!t)return e;let{url:n,method:r,headers:o,queryParams:i,body:s}={...e};o&&(o={...o}),i&&(i={...i});const{modifyQueryParams:a,modifyRequestBody:A,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),i&&delete i[t]}),Array.isArray(a.add)&&a.add.forEach(({key:t,value:n})=>{e.searchParams.set(t,n),i&&(i[t]=n)}),n=e.toString()}catch(e){console.error("[MockForMe] Failed to modify query params",e)}l?.enabled&&(o={...o},Array.isArray(l.remove)&&l.remove.forEach(e=>{const t=e.toLowerCase(),n=Object.keys(o).find(e=>e.toLowerCase()===t);n&&delete o[n]}),Array.isArray(l.add)&&l.add.forEach(({key:e,value:t})=>{o[e]=t}));const c=String(r||"GET").toUpperCase(),d="GET"===c||"HEAD"===c;if(A?.enabled&&!d)try{let e=null;if("string"==typeof s)try{e=JSON.parse(s)}catch{e={}}else if("object"==typeof s&&null!==s)try{e=JSON.parse(JSON.stringify(s))}catch{e={...s}}else(Array.isArray(A.add)&&A.add.length>0||Array.isArray(A.update)&&A.update.length>0)&&(e={});e&&(Array.isArray(A.remove)&&A.remove.forEach(t=>delete e[t]),Array.isArray(A.add)&&A.add.forEach(({key:t,value:n})=>e[t]=n),Array.isArray(A.update)&&A.update.forEach(({key:t,value:n})=>e[t]=n),s=JSON.stringify(e))}catch(e){console.error("[MockForMe] Failed to modify request body",e)}return{...e,url:n,headers:o,queryParams:i,body:s}}static applyResponseModifications(e,t){if(!t?.modifyResponseHeaders?.enabled)return e;const{modifyResponseHeaders:n}=t,r={...e};return Array.isArray(n.remove)&&n.remove.forEach(e=>{const t=e.toLowerCase(),n=Object.keys(r).find(e=>e.toLowerCase()===t);n&&delete r[n]}),Array.isArray(n.add)&&n.add.forEach(({key:e,value:t})=>{r[e]=t}),r}}class se{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)&&re.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,r=ie.applyRequestModifications(t,n.modificationActions);return{...await oe.apply(n.timingAction),modifiedRequest:r,rule:n}}static applyResponseModifications(e,t){return ie.applyResponseModifications(e,t)}}class ae{static apply({target:e=("undefined"!=typeof window?window:globalThis),originalFetch:t=e.fetch,ruleProvider:n=()=>[],mappingProvider:r=e=>null,onBeforeRequest:o=e=>{},onRuleMatch:i=async(e,t,n,r,o)=>null,onMockMatch:s=async(e,t,n,r,o)=>null,onOtherRequest:a=async(e,t,n,r)=>null,isEnabled:A=()=>!0,shouldBypassRequest:l=()=>!1}){t&&(e.fetch=async function(e,c={}){if(!A())return t(e,c);let d;try{const n="string"==typeof e?e:e.url,r=String(c.method||(e instanceof Request?e.method:"GET")).toUpperCase().trim(),i=Math.random().toString(36).substring(7);if(d={url:n,method:r,headers:c.headers||(e instanceof Request?e.headers:{}),body:c.body||(e instanceof Request?"{binary/stream}":null),requestId:i,queryParams:ae.getQueryParams(n)},l(d))return t(e,c);o(d)}catch(n){return console.warn("[MockForMe] Fetch Interceptor Setup Error:",n),t(e,c)}try{const o=n(),A=se.match(d,o);if(A){const n=await i(A,d,e,c,t);if(n)return n}const l=r(d);if(l){const n=await s(l,d,e,c,t);if(n)return n}const u=await a(d,e,c,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,c)})}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 Ae{static apply({target:e=("undefined"!=typeof window?window:{}),OriginalXHR:t=e.XMLHttpRequest,ruleProvider:n=()=>[],mappingProvider:r=e=>null,onBeforeRequest:o=e=>{},onRuleMatch:i=(e,t,n,r)=>{r.call(n.proxy,t.body)},onMockMatch:s=(e,t,n,r)=>{r.call(n.proxy,t.body)},onOtherRequest:a=(e,t,n)=>{n.call(t.proxy,e.body)},isEnabled:A=()=>!0,shouldBypassRequest:l=()=>!1}){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,r={}){if(this._captured)return;this._captured=!0;const o=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}),o("readystatechange"),"Aborted"===e||r.aborted?o("abort"):0===e||"Error"===e||r.error?o("error"):"Timeout"===e||r.timeout?o("timeout"):o("load")}abort(){if(!this._isMocked||"function"!=typeof this._onAbort)return this._xhr.abort();this._onAbort()}open(e,t,n=!0,r=null,o=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,r,o)}setRequestHeader(e,t){return this._headers[e]=t,this._xhr.setRequestHeader(e,t)}send(e){if(!A())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:Ae.getQueryParams(this._url)};if(l(t))return this._xhr.send(e);o(t);const c=n(),d=se.match(t,c),u=e=>this._xhr.send(e);if(d)return this._isMocked=!0,i(d,t,this,u);const f=r(t);return f?(this._isMocked=!0,s(f,t,this,u)):(this._isMocked=!1,a(t,this,u))}})}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 le=[g,"https://api.mockforme.com/mockforme/httpRequestBulkMock/bulk_mock"];function ce(e){try{const t="undefined"!=typeof window?window.location.origin:"http://localhost",n=new URL(e.url,t);return le.some(e=>{const r=new URL(e,t);return n.origin===r.origin&&n.pathname===r.pathname})}catch{return!1}}const de=(e,t=null,n=u)=>{if(o())return;let r="string"==typeof e?e:e?.token,i="object"==typeof e?e?.widgetKey:null;if(n===u)try{r&&("undefined"!=typeof localStorage&&(localStorage.removeItem("mockforme-token"),localStorage.setItem("MFM_TOKEN",r)),te.token=r,te.isAuthenticated=!0),!r&&te.token&&(r=te.token),te.onAuthSuccess=(e,t,n)=>{l(t),b(n),te.updateMappings(t,n)},i?te.setWidgetKey(i):te.init()}catch(e){console.log("Error in showing mockforme widget",e)}t||={mappings:[],_o:null,mk:null,_mck:null,_rules:[]};const{mappings:s=[],_o:a,mk:A,_mck:h,_rules:p=[]}=t;return l(s),b({_o:a,mk:A,_mck:h,_rules:p}),{run:(e,t=()=>{})=>{if(function(e,t){if("undefined"!=typeof window){if(window._mfm_intercepted)return;window._mfm_intercepted=!0}const n=()=>te.token||e;ae.apply({isEnabled:()=>te.interceptionEnabled,shouldBypassRequest:ce,ruleProvider:()=>v(),mappingProvider:e=>{try{return d(new URL(e.url,window.location.origin).pathname,e.method)}catch{return null}},onRuleMatch:async(e,t,n,r,o)=>{const i=t.requestId||Math.random().toString(36).substring(7),s=Date.now();te.addRequest("mocked",{...t,requestId:i,pending:!0,startTime:s,rule:e});const a=await se.apply(e,t),{modifiedRequest:A,type:l,delay:c,redirectUrl:d}=a;if("timeout"!==l&&te.addRequest("mocked",{...A,requestId:i,pending:!0,startTime:s,rule:e}),"timeout"===l){const t=Date.now()-s;throw te.addRequest("mocked",{...A,requestId:i,status:"Aborted",pending:!1,duration:t,aborted:!0,rule:e}),new Error("Fetch timed out by rules")}if("redirect"===l&&!d)throw new Error("rules: Redirect missing URL");let u="redirect"===l?d:A.url,f={...r};A.headers&&(f.headers=A.headers),A.body&&(f.body=A.body);let h=null;if("redirect"===l){h=Math.random().toString(36).substring(7);const e={url:d,method:A.method,headers:f.headers||{},body:f.body,requestId:h,queryParams:ae.getQueryParams(d),requestHeaders:f.headers||{},requestBody:f.body,pending:!0,startTime:Date.now()};te.addRequest("mocked",e)}return o(u,f).then(async e=>{const t=Date.now()-s;let n=Object.fromEntries(e.headers.entries());if(a.rule.modificationActions?.modifyResponseHeaders?.enabled&&(n=se.applyResponseModifications(n,a.rule.modificationActions)),"redirect"===l&&h){const t=e.clone(),r=t.headers.get("content-type")||"",o=Date.now()-s;try{let i;i=r.includes("application/json")?await t.json():await t.text(),te.addRequest("mocked",{url:d,method:A.method,requestId:h,status:e.status,pending:!1,duration:o,responseHeaders:n,responseBody:i,requestHeaders:f.headers||{},requestBody:f.body})}catch(t){te.addRequest("mocked",{url:d,method:A.method,requestId:h,status:e.status,pending:!1,duration:o,responseHeaders:n,requestHeaders:f.headers||{},requestBody:f.body})}}return te.addRequest("mocked",{...A,requestId:i,status:e.status,pending:!1,duration:t,responseHeaders:n,rule:a.rule}),e}).catch(e=>{const t=Date.now()-s,n="AbortError"===e.name||e.message.includes("aborted");if(te.addRequest("mocked",{...A,requestId:i,status:n?"Aborted":0,pending:!1,duration:t,rule:a.rule}),"redirect"===l&&h&&te.addRequest("mocked",{url:d,method:A.method,requestId:h,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,r,o,i,s)=>{const a=r.requestId||Math.random().toString(36).substring(7),A=Date.now();te.addRequest("mocked",{...r,requestId:a,pending:!0,startTime:A});const l=n(),c=new URL(r.url,window.location.origin).search;let d=`${B()}${e.url}${c}`,u={[f]:l,mfmver:"14.5.0","x-mfm-adaptor":t};const h=x();h&&e._ack&&(u["x-mfm-key"]=`${h}-${e._ack}`),e?._ri_&&(u._ri_=e._ri_);const p=o instanceof Request?o.headers:i.headers,g=new Headers(p||{});Object.entries(u).forEach(([e,t])=>g.set(e,t)),g.set("x-mfm-internal","true");let m=i.body;if(!m&&o instanceof Request){const e=o.clone();"GET"!==e.method&&"HEAD"!==e.method&&(m=await e.text())}const y={method:r.method,headers:g,credentials:o instanceof Request&&o.credentials||i.credentials||"include",mode:o instanceof Request&&o.mode||i.mode||"cors",signal:o instanceof Request&&o.signal||i.signal};return m&&(y.body=m),s(d,y).then(async t=>{const n=t.clone(),o=n.headers.get("content-type")||"",i=Date.now()-A;ne(t.headers)&&te.handleMockDisabled({apiMethod:e.method,apiEndpoint:e.apiEndpoint});const s=e=>(te.addRequest("mocked",{...r,requestId:a,status:t.status,responseHeaders:Object.fromEntries(n.headers.entries()),responseBody:e,pending:!1,duration:i}),new Response("string"==typeof e?e:JSON.stringify(e),{status:t.status,headers:n.headers}));return o.includes("application/json")?n.json().then(s):n.text().then(s)}).catch(e=>{const t=Date.now()-A,n=e&&("AbortError"===e.name||String(e.message||"").toLowerCase().includes("abort"));if(te.addRequest("mocked",{...r,requestId:a,status:n?"Aborted":0,pending:!1,duration:t,aborted:n}),n)throw e;return s(o,i)})},onOtherRequest:async(e,t,n,r)=>{const o=n?.headers||(t instanceof Request?t.headers:{});let i=!1;o instanceof Headers?i="true"===o.get("x-mfm-internal"):"object"==typeof o&&(i="true"===o["x-mfm-internal"]);const s=B();if(e.url.startsWith(s)&&(i=!0),"OPTIONS"===e.method||i)return r(t,n);const a=e.requestId,A=Date.now();te.addRequest("other",{...e,requestId:a,pending:!0,startTime:A});const l=R(e.method,e.url),c=M(e.method,e.url);let d=t,u=n,f=e;if(l){const t={};try{new URL(e.url,"undefined"!=typeof window?window.location.origin:"http://localhost").searchParams.forEach((e,n)=>{t[n]=e})}catch(e){}const r=await z({requestId:a,ruleId:l.id,request:{method:e.method,url:e.url,headers:e.headers,body:e.body},queryParams:t});if(r.cancel){te.addRequest("other",{...e,requestId:a,status:"Cancelled",pending:!1,duration:Date.now()-A,error:!0});const t=new Error("Request cancelled by MockForMe request editor");throw t.name="AbortError",t}let o=e.url;try{const t=new URL(e.url,"undefined"!=typeof window?window.location.origin:"http://localhost");[...t.searchParams.keys()].forEach(e=>t.searchParams.delete(e)),Object.entries(r.queryParams||{}).forEach(([e,n])=>{t.searchParams.set(e,String(n??""))}),o="string"==typeof e.url&&e.url.startsWith("/")?`${t.pathname}${t.search}`:t.href}catch(e){}const i=String(e.method||"GET").toUpperCase(),s="GET"!==i&&"HEAD"!==i;u={...n,method:e.method,headers:r.headers||{},body:s?null==r.body?void 0:r.body:void 0},d=o,f={...e,url:o,headers:r.headers||{},body:s?r.body:null}}const h=J();h>0&&await new Promise(e=>setTimeout(e,h));let p=null,g=null;try{p=await r(d,u)}catch(e){g=e}if(c){let t="",n=0,r={};if(p){try{t=await p.clone().text()}catch(e){}n=p.status,r=Object.fromEntries(p.headers.entries())}else g&&(t=g.message||"Network error",n=0);const o=await H({requestId:a,ruleId:c.id,request:{method:f.method,url:f.url,headers:f.headers,body:f.body},response:{statusCode:n,headers:r,body:t}});if(o.simulateTimeout){te.addRequest("other",{...e,requestId:a,status:"Timeout",responseHeaders:{},pending:!1,duration:Date.now()-A,timeout:!0});const t=new Error("Network request failed (simulated by MockForMe debugger)");throw t.name="AbortError",t}o.delayMs>0&&await new Promise(e=>setTimeout(e,o.delayMs));const i=Number(o.statusCode),s=Number.isFinite(i)&&i>=200&&i<=599?i:n>=200?n:200,l=o.headers&&"object"==typeof o.headers?o.headers:r,d="string"==typeof o.body?o.body:null==o.body?"":JSON.stringify(o.body);te.addRequest("other",{...e,requestId:a,status:s,responseHeaders:l,responseBody:d,pending:!1,duration:Date.now()-A});const u={};return Object.entries(l).forEach(([e,t])=>{const n=e.toLowerCase();"content-length"!==n&&"content-encoding"!==n&&"transfer-encoding"!==n&&(u[e]=t)}),new Response(d,{status:s,statusText:p?p.statusText:"",headers:new Headers(u)})}const m=Date.now()-A;if(g){const t="AbortError"===g.name||(g.message||"").includes("aborted"),n="TimeoutError"===g.name||(g.message||"").includes("timed out");throw te.addRequest("other",{...e,requestId:a,status:t?"Aborted":n?"Timeout":"Error",pending:!1,duration:m,aborted:t,timeout:n,error:!t&&!n}),g}const y=Object.fromEntries(p.headers.entries());let w;try{const e=p.clone(),t=5e3,n=Symbol("body-timed-out"),r=await Promise.race([e.text(),new Promise(e=>setTimeout(()=>e(n),t))]);w=r===n?void 0:r}catch(e){w=void 0}return te.addRequest("other",{...e,requestId:a,status:p.status,responseHeaders:y,responseBody:w,pending:!1,duration:m}),p}}),Ae.apply({isEnabled:()=>te.interceptionEnabled,shouldBypassRequest:ce,ruleProvider:()=>v(),mappingProvider:e=>{try{return d(new URL(e.url,window.location.origin).pathname,e.method)}catch{return null}},onRuleMatch:async(e,t,n,r)=>{const o=t.requestId,i=Date.now();te.addRequest("mocked",{...t,requestId:o,pending:!0,startTime:i,rule:e});const s=await se.apply(e,t),{modifiedRequest:a,type:A,redirectUrl:l}=s;"timeout"!==A&&te.addRequest("mocked",{...a,requestId:o,pending:!0,startTime:i,rule:e});let c=null;if("redirect"===A){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()};te.addRequest("mocked",e)}const d=(e,t,r,d={})=>{const u=Date.now()-i;if(s.rule.modificationActions?.modifyResponseHeaders?.enabled){let e="string"==typeof r?Object.fromEntries(r.split("\r\n").filter(e=>e).map(e=>e.split(": "))):r;e=se.applyResponseModifications(e,s.rule.modificationActions),r=e}te.addRequest("mocked",{...a,requestId:o,status:e,responseBody:t,responseHeaders:r,pending:!1,duration:u,rule:s.rule,...d}),"redirect"===A&&c&&te.addRequest("mocked",{url:l,method:a.method,requestId:c,status:e,responseBody:t,responseHeaders:r,pending:!1,duration:u,requestHeaders:a.headers||{},requestBody:a.body,...d}),n._capture(e,t,r,d)};if("timeout"===A)return d("Aborted","Timed out by rule",{},{aborted:!0}),void n._xhr.abort();if("redirect"===A){if(!l)return void d(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",()=>d("Aborted","Aborted",{},{aborted:!0}),{once:!0}),n._xhr.addEventListener("error",()=>d(0,"Error",{},{error:!0}),{once:!0}),n._xhr.addEventListener("timeout",()=>d("Timeout","Timeout",{},{timeout:!0}),{once:!0}),n._xhr.addEventListener("load",()=>d(n._xhr.status,n._xhr.responseText,n._xhr.getAllResponseHeaders()),{once:!0}),r(a.body)},onMockMatch:(e,r,o,i)=>{const s=r.requestId,a=Date.now(),A=n(),l=new URL(r.url,window.location.origin);let c=`${B()}${e.url}${l.search}`,d={[f]:A,mfmver:"14.5.0","x-mfm-adaptor":t};const u=x();u&&e._ack&&(d["x-mfm-key"]=`${u}-${e._ack}`),e?._ri_&&(d._ri_=e._ri_),d["x-mfm-internal"]="true";const h={...r.headers,...d};te.addRequest("mocked",{...r,requestId:s,pending:!0,startTime:a});const p=(t,n,i,A={})=>{if(o._captured)return;const l=Date.now()-a;ne(i)&&te.handleMockDisabled({apiMethod:e.method,apiEndpoint:e.apiEndpoint}),te.addRequest("mocked",{...r,requestId:s,status:t,responseBody:n,responseHeaders:i,pending:!1,duration:l,...A}),o._capture(t,n,i,A)};o._xhr.addEventListener("abort",()=>p("Aborted","Aborted",{},{aborted:!0}),{once:!0}),o._xhr.addEventListener("error",()=>p(0,"Error",{},{error:!0}),{once:!0}),o._xhr.addEventListener("timeout",()=>p("Timeout","Timeout",{},{timeout:!0}),{once:!0});const g=new window.XMLHttpRequest;g.open(r.method,c,!0);for(const e in h)g.setRequestHeader(e,h[e]);g.withCredentials=o.proxy.withCredentials,o._onAbort=()=>{try{g.abort()}catch(e){}p("Aborted","Aborted",{},{aborted:!0})},g.onload=()=>p(g.status,g.responseText,g.getAllResponseHeaders()),g.onerror=()=>p(0,"Network Error",{},{error:!0}),g.ontimeout=()=>p("Timeout","Request timed out",{},{timeout:!0}),g.send(r.body)},onOtherRequest:(e,t,n)=>{const r="true"===e.headers?.["x-mfm-internal"],o=B(),i=e.url.startsWith(o);if("OPTIONS"===e.method||r||i)return n(e.body);const s=Date.now();te.addRequest("other",{...e,pending:!0,startTime:s});const a=R(e.method,e.url),A=M(e.method,e.url);let l=e;const c=(n,r,o,i={})=>{const a=Date.now()-s;te.addRequest("other",{...e,status:n,responseBody:r,responseHeaders:o,pending:!1,duration:a,...i}),t._capture(n,r,o,i)};if(t._xhr.addEventListener("abort",()=>c("Aborted","Aborted",{},{aborted:!0}),{once:!0}),t._xhr.addEventListener("error",()=>c(0,"Error",{},{error:!0}),{once:!0}),t._xhr.addEventListener("timeout",()=>c("Timeout","Timeout",{},{timeout:!0}),{once:!0}),t._xhr.addEventListener("load",async()=>{const n=t._xhr.status,r=t._xhr.responseText,o=t._xhr.getAllResponseHeaders();if(A){const t={};"string"==typeof o&&o.split("\r\n").forEach(e=>{const n=e.indexOf(": ");n>0&&(t[e.slice(0,n)]=e.slice(n+2))});const i=await H({requestId:e.requestId,ruleId:A.id,request:{method:l.method,url:l.url,headers:l.headers,body:l.body},response:{statusCode:n,headers:t,body:r}});if(i.simulateTimeout)return void c("Timeout","Timeout (Debugger)",{},{timeout:!0});i.delayMs>0&&await new Promise(e=>setTimeout(e,i.delayMs));const s=Number(i.statusCode)||n,a=i.headers&&"object"==typeof i.headers?i.headers:t,d="string"==typeof i.body?i.body:null==i.body?"":JSON.stringify(i.body);return void c(s,d,a)}c(n,r,o)},{once:!0}),t._xhr.addEventListener("readystatechange",()=>{if(t._xhr.readyState>=2&&!t._captured){const n=t._xhr.status;if(n>0){const r=Date.now()-s;te.addRequest("other",{...e,status:n,responseHeaders:t._xhr.getAllResponseHeaders(),pending:t._xhr.readyState<4,duration:r})}}}),a)return void(async()=>{const r={};try{new URL(e.url,"undefined"!=typeof window?window.location.origin:"http://localhost").searchParams.forEach((e,t)=>{r[t]=e})}catch(e){}const o=await z({requestId:e.requestId,ruleId:a.id,request:{method:e.method,url:e.url,headers:e.headers,body:e.body},queryParams:r});if(o.cancel){c("Cancelled","Cancelled by editor",{},{aborted:!0});try{t._xhr.abort()}catch(e){}return}let i=e.url;try{const t=new URL(e.url,"undefined"!=typeof window?window.location.origin:"http://localhost");[...t.searchParams.keys()].forEach(e=>t.searchParams.delete(e)),Object.entries(o.queryParams||{}).forEach(([e,n])=>{t.searchParams.set(e,String(n??""))}),i="string"==typeof e.url&&e.url.startsWith("/")?`${t.pathname}${t.search}`:t.href}catch(e){}if(i!==e.url)try{t._xhr.open(e.method,i,!0)}catch(e){}Object.entries(o.headers||{}).forEach(([e,n])=>{try{t._xhr.setRequestHeader(e,String(n??""))}catch(e){}}),l={...e,url:i,headers:o.headers||{},body:o.body};const s=String(e.method||"GET").toUpperCase(),A="GET"!==s&&"HEAD"!==s?null==o.body?null:o.body:null,d=J();d>0?setTimeout(()=>{try{n(A)}catch(e){}},d):n(A)})();const d=J();d>0?setTimeout(()=>{try{n(e.body)}catch(e){}},d):n(e.body)}})}(r,n),a&&A)te.mappings=s,te.rules=p,e?.(s,{_o:a,mk:A,_mck:h,_rules:p});else if(r){const t=te.getSavedMappings(r,n);if(t&&Array.isArray(t.mappings))return te.mappings=t.mappings,te.rules=t.meta?._rules||[],l(t.mappings),b(t.meta),te.updateMappings(t.mappings,t.meta),void e?.(t.mappings,t.meta);te.updateMappings([],{_rules:[]}),e?.([],{_rules:[]})}},checkIfApiToBeMocked:d,getMappings:c,doFetchMappings:(e,t)=>{C(r||te.token,n,(t,o)=>{te.saveMappings(t,o,r||te.token,n),te.updateMappings(t,o),e?.(t,o)},t)},recheckWidgetVisibility:()=>{te.init()}}},ue=o();ue||(globalThis.mockforme=de);let fe=de;ue&&(fe=e=>({run:()=>{}}));const he=fe;module.exports=r})();
|
|
20
|
+
`;function AA({message:e,theme:t}){return Ct("div",{role:"alert",css:gt("background:#fef2f2;border:1px solid #fecaca;border-left:3px solid ",t.color.error,";color:",t.color.error,";padding:",t.spacing.md," ",t.spacing.lg,";border-radius:",t.radius.md,";font-size:",t.typography.fontSizeBase,";line-height:1.5;display:flex;align-items:flex-start;gap:",t.spacing.sm,";",""),children:[xt("strong",{css:gt("font-weight:",t.typography.fontWeightBold,";",""),children:"✗"}),xt("span",{children:e})]})}function lA(e){const t=document.getElementById("mfm-root");return!!t&&(t===e||t.contains(e))}function cA(e){if(!e)return"";if(e.length<=1e3)return e;return e.slice(0,988)+"…[truncated]"}function dA(){const e=Ut(),{confirmState:t,dismissConfirm:n}=un();if(u.useEffect(()=>{if(!t)return;const e=e=>{"Escape"===e.key&&n()};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[t,n]),!t)return null;const{title:r,message:o,confirmLabel:i,cancelLabel:s,danger:a,onConfirm:A}=t;return xt("div",{role:"dialog","aria-label":r??"Confirm","aria-modal":"true",onClick:e=>{e.target===e.currentTarget&&n()},css:gt("position:absolute;inset:0;background:rgba(15, 23, 42, 0.5);z-index:",e.z.confirm,";display:flex;align-items:center;justify-content:center;padding:",e.spacing.xl,";",""),children:Ct("div",{css:gt("background:",e.color.bg,";border-radius:",e.radius.lg,";box-shadow:",e.shadow.lg,";padding:",e.spacing.xl,";max-width:360px;width:100%;display:flex;flex-direction:column;gap:",e.spacing.md,";",""),children:[r?xt("h3",{css:gt("margin:0;font-size:",e.typography.fontSizeLg,";font-weight:",e.typography.fontWeightBold,";color:",e.color.text,";",""),children:r}):null,xt("p",{css:gt("margin:0;color:",e.color.text,";font-size:",e.typography.fontSizeBase,";line-height:1.5;",""),children:o}),Ct("div",{css:gt("display:flex;justify-content:flex-end;gap:",e.spacing.md,";margin-top:",e.spacing.sm,";",""),children:[xt("button",{type:"button",onClick:n,css:gt("appearance:none;background:transparent;border:1px solid ",e.color.border,";color:",e.color.text,";font-family:inherit;font-size:",e.typography.fontSizeBase,";padding:",e.spacing.sm," ",e.spacing.lg,";border-radius:",e.radius.md,";cursor:pointer;&:hover{background:",e.color.surfaceBright,";}",""),children:s??"Cancel"}),xt("button",{type:"button",autoFocus:!0,onClick:()=>{n(),A()},css:gt("appearance:none;border:none;background:",a?e.color.error:e.color.primary,";color:#fff;font-family:inherit;font-weight:",e.typography.fontWeightSemibold,";font-size:",e.typography.fontSizeBase,";padding:",e.spacing.sm," ",e.spacing.lg,";border-radius:",e.radius.md,";cursor:pointer;&:hover{filter:brightness(0.95);}",""),children:i??"Confirm"})]})]})})}function uA(){const{analyticsEnabled:e}=tr(),{token:t,organisationId:n}=gn();return u.useEffect(()=>{rn.setEnabled(e)},[e]),u.useEffect(()=>{rn.setToken(t)},[t]),u.useEffect(()=>{rn.setOrganisationId(n)},[n]),null}function fA({clientType:e,version:t}={}){return Ct(Qt,{initialMode:"light",children:[xt(hA,{}),xt(Mt,{children:xt(dn,{clientType:e,version:t,children:xt(pn,{children:xt(yn,{children:xt(Un,{children:xt(Nn,{children:xt(er,{children:xt(Jn,{children:Ct(ir,{children:[xt(uA,{}),xt(So,{}),xt(pA,{})]})})})})})})})})})]})}function hA(){const e=Ut();return xt(pt,{styles:gt(":host,[data-mfm-mount]{all:initial;color:",e.color.text,";font-family:",e.typography.fontFamily,";font-size:",e.typography.fontSizeBase,";line-height:1.4;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;text-rendering:optimizeLegibility;}*,*::before,*::after{box-sizing:border-box;}::-webkit-scrollbar{width:8px;height:8px;}::-webkit-scrollbar-thumb{background:",e.color.border,";border-radius:",e.radius.pill,";}::-webkit-scrollbar-thumb:hover{background:",e.color.textDim,";}","")})}function pA(){const{setOpen:e,isInterceptEnabled:t,toggleIntercept:n,isSettingsOpen:r,openSettings:o,startSnipping:i,requestConfirm:s}=un(),{token:a,isTokenValidated:A,isValidating:l,isLoading:c,reloadMappings:d,deleteToken:u}=gn(),{debugRules:f,editRules:h}=Wn(),{globalDelay:p}=tr();if(!A&&(l||a))return Ct(Bt,{children:[xt(_o,{children:xt(bA,{children:xt(mA,{})})}),xt(qa,{})]});if(!a)return Ct(Bt,{children:[xt(_o,{children:Ct(bA,{children:[xt(pa,{}),xt(dA,{})]})}),xt(qa,{})]});const g=r||f.length>0||h.length>0||p.enabled;return Ct(Bt,{children:[Ct(_o,{children:[xt(Oo,{onSnip:i,onReload:d,onOpenSettings:o,onDeleteToken:()=>{s({title:"Delete token?",message:"Are you sure you want to delete token? API interception will stop once the token is removed.",confirmLabel:"Delete",danger:!0,onConfirm:u})},isInterceptEnabled:t,onToggleIntercept:()=>{t?s({title:"Disable interception?",message:"Once disabled, the widget will stop intercepting requests and disappear from the page. Please refresh the page after disabling it. You can re-enable it anytime from the MockForMe settings page via the extension icon in tray or the right-click menu. You can also re-enable it from inside Widget Settings → Whitelisted Hosts.",confirmLabel:"Disable",danger:!0,onConfirm:n}):n()},onClose:()=>e(!1),isSettingsActive:g,isReloading:c,isAuthenticated:!0}),xt(Po,{}),Ct(bA,{children:[xt(da,{}),xt(ga,{}),xt(ka,{}),xt(Ba,{}),xt(Ua,{}),xt(Na,{}),xt(dA,{}),xt(yA,{})]})]}),xt(qa,{})]})}var gA={name:"3kwpv8",styles:"flex:1;min-height:0;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:14px;padding:24px;text-align:center"};function mA(){const e=Ut();return Ct("div",{css:gA,children:[xt(yi,{size:26,color:e.color.primary,label:"Validating token"}),xt("div",{css:gt("font-size:",e.typography.fontSizeBase,";font-weight:600;color:",e.color.text,";",""),children:"Validating your token…"}),xt("div",{css:gt("font-size:12px;color:",e.color.textDim,";max-width:260px;line-height:1.5;",""),children:"Hang tight — we're verifying your session before loading the widget."})]})}function yA(){const{invalidatedMessage:e,acknowledgeInvalidation:t}=gn(),n=Ut();return null==e?null:xt(ri,{open:!0,hideClose:!0,title:"Token no longer valid",leadingDot:"live",onClose:()=>{},footer:xt("button",{type:"button",onClick:t,css:gt("appearance:none;border:none;border-radius:",n.radius.sm,";background:",n.color.primary,";color:#fff;font-size:",n.typography.fontSizeBase,";font-weight:",n.typography.fontWeightBold,";padding:8px 20px;cursor:pointer;&:hover{background:",n.color.primaryHover,";}",""),children:"OK"}),children:xt("p",{css:gt("margin:0;font-size:",n.typography.fontSizeBase,";line-height:1.5;color:",n.color.text,";",""),children:e})})}var wA={name:"4oq8x6",styles:"position:absolute;inset:0;pointer-events:none;z-index:1500;&:empty{display:none;}&>*{pointer-events:auto;}"},kA={name:"p72qif",styles:"flex:1;min-height:0;position:relative;display:flex;flex-direction:column;overflow:hidden"};function bA({children:e}){const{fullscreenSlotRef:t}=un();return Ct("div",{css:kA,children:[e,xt("div",{ref:t,"data-mfm-fullscreen-slot":!0,css:wA})]})}class vA extends u.Component{constructor(){super(...arguments),o(this,"state",{hasError:!1})}static getDerivedStateFromError(){return Or(),{hasError:!0}}componentDidCatch(e,t){try{this.props.onError(e,t)}catch{}}render(){return this.state.hasError?null:this.props.children}}const BA=(()=>{try{const e="file:///Users/sushilkumar/mockforme/shared/mockforme_widget/dist/chunks/widget-B8TRg0gv.js",t=e.lastIndexOf("/");return t>0?e.slice(0,t+1):e}catch{return""}})();function xA(e,t){return!(!BA||!function(){try{const e=typeof document<"u"&&(document.baseURI||document.location&&document.location.href)||"";return!!e&&!e.startsWith(BA)}catch{return!1}}()||!(e&&e.startsWith(BA)||t&&-1!==t.indexOf(BA)))}let CA=null;const EA="data-mfm-mount";function FA(e){return e||document.getElementById("mfm-root")||(document.body?document.body:null)}function SA(e,t){let n;"mfm-root"===e.id?n=e:(n=document.createElement("div"),n.id="mfm-root",e.appendChild(n)),n.style.cssText="all: initial; display: block;",function(e){try{rn.init(),rn.setClientType(e);const t=tn().read("MFM_TOKEN");t&&rn.setToken(t)}catch{}}(t.clientType);const r=["click","dblclick","mousedown","mouseup","mousemove","pointerdown","pointerup","pointermove","contextmenu","wheel","touchstart","touchend","touchmove"],o=e=>e.stopPropagation();for(const e of r){const t="wheel"===e||"touchstart"===e||"touchend"===e||"touchmove"===e;n.addEventListener(e,o,{passive:t})}const i=n.shadowRoot??n.attachShadow({mode:"open"});let s=i.querySelector(`[${EA}]`);s||(s=document.createElement("div"),s.setAttribute(EA,""),i.appendChild(s));const a=Ue({key:"mfm",container:i,prepend:!0}),A={run:()=>{}},l=F.createRoot(s);l.render(u.createElement(u.StrictMode,null,u.createElement(rt,{value:a},u.createElement(vA,{onError:e=>{setTimeout(()=>A.run(e),0)}},u.createElement(fA,{clientType:t.clientType,version:t.version})))));const c=e=>{const t=e.error;xA(e.filename,t?.stack)&&(Or(),e.preventDefault(),A.run(e.error))},d=e=>{const t=e.reason;xA(void 0,t?.stack??(t?String(t):void 0))&&(Or(),e.preventDefault(),A.run(e.reason))};window.addEventListener("error",c),window.addEventListener("unhandledrejection",d);const f=console.error;console.error=function(...e){if(!(jr>0)){if(BA)for(let t=0;t<e.length;t++){const n=e[t];if(-1!==((n&&"object"==typeof n&&"stack"in n?String(n.stack??""):"")||String(n)).indexOf(BA))return}f.apply(console,e)}};let h=!1,p=null;const g=e=>{if(!h){if(h=!0,window.removeEventListener("error",c),window.removeEventListener("unhandledrejection",d),console.error!==f)try{console.error=f}catch{}try{l.unmount()}catch{}try{n.remove()}catch{}CA=null;try{if(void 0!==e){const t=e,n=t&&"string"==typeof t.message?t.message:"string"==typeof e?e:String(e),r=t&&"string"==typeof t.stack?t.stack:"";Vr("widget_load_failed",{errorName:t&&"string"==typeof t.name?t.name:"Error",errorMessage:n,errorStack:r.slice(0,4e3),userAgent:typeof navigator<"u"?navigator.userAgent:"",url:typeof location<"u"?location.href:""})}else rn.track("widget_destroyed");Gr()}catch{}if(void 0!==e)try{p=function(){if(typeof document>"u"||!document.body)return{dismiss(){}};const e=document.createElement("div");e.id="mfm-error-snackbar",e.style.cssText=["all: initial","position: fixed","right: 16px","bottom: 16px","z-index: 2147483646"].join(";"),document.body.appendChild(e);const t=e.attachShadow({mode:"closed"}),n=document.createElement("div");n.style.cssText=["box-sizing: border-box","display: flex","align-items: center","gap: 10px","min-width: 280px","max-width: 380px","padding: 10px 12px","background: #1f2937","color: #f9fafb","border: 1px solid #374151","border-radius: 8px","box-shadow: 0 8px 24px rgba(0,0,0,0.25)",'font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',"font-size: 13px","line-height: 1.4"].join(";");const r=document.createElement("div");r.style.cssText=["flex: 1 1 auto","min-width: 0"].join(";");const o=document.createElement("div");o.textContent="MockForMe is unable to load.",o.style.cssText="font-weight: 500";const i=document.createElement("div");i.textContent="The issue has been reported.",i.style.cssText=["margin-top: 2px","color: #9ca3af","font-size: 12px"].join(";"),r.appendChild(o),r.appendChild(i);const s=document.createElement("button");s.type="button",s.setAttribute("aria-label","Dismiss"),s.textContent="×",s.style.cssText=["flex: 0 0 auto","width: 24px","height: 24px","padding: 0","background: transparent","color: #9ca3af","border: 0","border-radius: 4px","cursor: pointer","font-size: 18px","line-height: 1"].join(";");let a=!1;const A=()=>{if(!a){a=!0;try{e.remove()}catch{}}};return s.addEventListener("click",A),n.appendChild(r),n.appendChild(s),t.appendChild(n),{dismiss:A}}()}catch{}}};return A.run=g,{destroy(){if(g(),p){try{p.dismiss()}catch{}p=null}}}}const QA={run(e,t={}){if(CA)return CA;if(typeof document<"u"&&"loading"===document.readyState){let n=!1;const r=()=>{if(n)return;const r=FA(e);r&&(CA=SA(r,t))};return document.addEventListener("DOMContentLoaded",r,{once:!0}),{destroy(){n=!0,document.removeEventListener("DOMContentLoaded",r),CA&&CA.destroy()}}}const n=FA(e);return n?(CA=SA(n,t),CA):(console.warn("[MockForMeWidget] no mount target available"),{destroy(){}})}};typeof window<"u"&&(window.MockForMeWidget=QA),n.d(t,["M",0,QA])},435(e,t,n){n.d(t,{MockForMeWidget:()=>r.M});var r=n(411)}};const t={};function n(r){const o=t[r];if(void 0!==o)return o.exports;const i=t[r]={exports:{}};return e[r](i,i.exports,n),i.exports}n.d=(e,t)=>{if(Array.isArray(t))for(var r=0;r<t.length;){var o=t[r++],i=t[r++];n.o(e,o)?0===i&&r++:0===i?Object.defineProperty(e,o,{enumerable:!0,value:t[r++]}):Object.defineProperty(e,o,{enumerable:!0,get:i})}else 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=>{Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};let r={};n.r(r),n.d(r,{mockforme:()=>fe});const o=()=>"undefined"!=typeof process&&null!=process.versions?.node,i=e=>{try{return e?e.toLowerCase():e}catch(e){return console.log(e),null}},s=(e,t)=>{const n=e.split("/"),r=t.split("/");if(n.length!==r.length)return!1;for(let e=0;e<n.length;e++){const t=n[e];if(t!==r[e]&&":any"!==t&&":"!==t.charAt(0))return!1}return!0},a=new Map;let A=[];function l(e){A=e}function c(){return A}function d(e,t="get"){const n=e=>e.startsWith("/")?e:`/${e}`,r=n(e),o=function(e,t){if(0===a.size)return null;for(const n of a.values())for(const r of n){if(i(r.apiMethod)!==i(t))continue;const n=r.apiEndpoint.startsWith("/")?r.apiEndpoint:`/${r.apiEndpoint}`;if(n===e||s(n,e)){const t={url:e,method:r.apiMethod,_ack:r._ack||null};return r._ri_&&(t._ri_=r._ri_),t}}return null}(r,t);if(o)return console.log(`[MockForMe] Flow Mock Match: ${t} ${e} -> ${o.url}`),o;for(const o of A)if(i(o.apiMethod)===i(t)){const i=n(o.apiEndpoint);if(i===r||s(i,r)){console.log(`[MockForMe] Match Found: ${t} ${e} -> ${o.apiEndpoint}`);const n={url:e,method:o.apiMethod,apiEndpoint:o.apiEndpoint,_ack:o._ack||null};return o._ri_&&(n._ri_=o._ri_),n}}return null}const u="JAVASCRIPT",f="mockforme",h="https://api.mockforme.com",p=`${h}/mockforme`,g=`${h}/gateway/3f4eae522b`;let m=null,y=null,w=null,k=[];function b({_o:e,mk:t,_mck:n,_rules:r}){m=e,y=t,w=n,k=r}function v(){return k}function B(){return`${p}/${m}/${y}`}function x(){return w}function C(e,t,n,r){fetch(g,{method:"GET",headers:{[f]:e,mfmver:"14.5.1","x-mfm-adaptor":t}}).then(e=>{if(!e.ok)throw e;return e.json()}).then(e=>{if(e){const{di:t,iv:r,_o:o,_mck:i,mk:s,r:a}=e,A=function({di:e,iv:t},n){var r;const o=function(e,t){const n=t.length;return e.split("").map((e,r)=>String.fromCharCode(e.charCodeAt(0)^t.charCodeAt(r%n))).join("")}((r=e,"undefined"!=typeof Buffer?Buffer.from(r,"base64").toString("utf8"):decodeURIComponent(escape(atob(r)))),n+t);return JSON.parse(o)}({di:t,iv:r},o);b({_o:o,mk:s,_mck:i,_rules:a}),A&&(l(A),n(A,{_o:o,mk:s,_mck:i,_rules:a}))}}).catch(e=>{console.error("Error in loading mocked APIs:",e),r(e)})}const E=`${h}/mockforme/mfm_op_3f4eae522b/manage`,F=e=>({[f]:e,mfmver:"14.5.1","Content-Type":"application/json"}),S=async e=>{let t=null;try{t=await e.json()}catch(e){}return{ok:!(!e.ok||!t||!0!==t.status&&"success"!==t.status&&1!==t.status),message:t&&t.message||(e.ok?"":`Request failed (${e.status})`),result:t?t.result:null}},Q="MFM_INTERCEPTOR_RULES";let U=[];const T=new Map;function I(){try{if("undefined"==typeof localStorage)return[];const e=localStorage.getItem(Q);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>e&&e.enabled):[]}catch(e){return[]}}function _(e){U=Array.isArray(e)?e.filter(e=>e&&e.enabled):[]}function M(e,t){if(!e||!t)return null;if(!U.length&&(U=I(),!U.length))return null;const n=String(e).toUpperCase();return U.find(e=>{if(!e.enabled||String(e.method).toUpperCase()!==n)return!1;if("PATH"===e.matchType)try{return new URL(e.url,"http://localhost").pathname===new URL(t,"http://localhost").pathname}catch(n){return e.url===t}return e.url===t})||null}function H({requestId:e,ruleId:t,request:n,response:r,timeoutMs:o=3e5}){return new Promise(i=>{const s=setTimeout(()=>{T.has(e)&&(T.delete(e),i({requestId:e,simulateTimeout:!1,delayMs:0,statusCode:r?.statusCode??200,headers:r?.headers||{},body:r?.body}))},o);T.set(e,{resolve:i,timer:s});try{"undefined"!=typeof window&&window.postMessage({type:"MFM_DEBUG_INTERCEPT_REQ",payload:{requestId:e,ruleId:t,request:n,response:r,timestamp:Date.now()}},"*")}catch(t){clearTimeout(s),T.delete(e),i({requestId:e,simulateTimeout:!1,delayMs:0,statusCode:r?.statusCode??200,headers:r?.headers||{},body:r?.body})}})}U=I(),"undefined"!=typeof document&&"function"==typeof document.addEventListener&&document.addEventListener("mfm:rule-sync",e=>{const t=e&&e.detail;t&&"debugger"===t.kind&&_(t.payload?.rules||[])}),"undefined"!=typeof window&&"function"==typeof window.addEventListener&&window.addEventListener("storage",e=>{e.key===Q&&(U=I())});const L="MFM_REQUEST_EDITOR_RULES";let D=[];const N=new Map;function j(){try{if("undefined"==typeof localStorage)return[];const e=localStorage.getItem(L);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>e&&e.enabled):[]}catch(e){return[]}}function O(e){D=Array.isArray(e)?e.filter(e=>e&&e.enabled):[]}function R(e,t){if(!e||!t)return null;if(!D.length&&(D=j(),!D.length))return null;const n=String(e).toUpperCase();return D.find(e=>{if(!e.enabled||String(e.method).toUpperCase()!==n)return!1;if("PATH"===e.matchType)try{return new URL(e.url,"http://localhost").pathname===new URL(t,"http://localhost").pathname}catch(n){return e.url===t}return e.url===t})||null}function P(e,t,n){const r={};return Object.entries(t?.headers||{}).forEach(([e,t])=>{r[e]=String(t??"")}),{requestId:e,cancel:!1,headers:r,queryParams:n||{},body:"string"==typeof t?.body?t.body:null}}function z({requestId:e,ruleId:t,request:n,queryParams:r,timeoutMs:o=3e5}){return new Promise(i=>{const s=setTimeout(()=>{N.has(e)&&(N.delete(e),i(P(e,n,r)))},o);N.set(e,{resolve:i,timer:s});try{"undefined"!=typeof window&&window.postMessage({type:"MFM_REQUEST_EDIT_REQ",payload:{requestId:e,ruleId:t,request:n,queryParams:r,timestamp:Date.now()}},"*")}catch(t){clearTimeout(s),N.delete(e),i(P(e,n,r))}})}D=j(),"undefined"!=typeof document&&"function"==typeof document.addEventListener&&document.addEventListener("mfm:rule-sync",e=>{const t=e&&e.detail;t&&"editor"===t.kind&&O(t.payload?.rules||[])}),"undefined"!=typeof window&&"function"==typeof window.addEventListener&&window.addEventListener("storage",e=>{e.key===L&&(D=j())});const K="MFM_GLOBAL_DELAY";let V={enabled:!1,seconds:0},G=0;function q(){try{if("undefined"==typeof localStorage)return{enabled:!1,seconds:0};const e=localStorage.getItem(K);if(!e)return{enabled:!1,seconds:0};const t=JSON.parse(e);return t&&"object"==typeof t?{enabled:!!t.enabled&&Number.isFinite(t.seconds)&&t.seconds>0,seconds:Number.isFinite(t.seconds)?Number(t.seconds):0}:{enabled:!1,seconds:0}}catch(e){return{enabled:!1,seconds:0}}}function J(){const e=Date.now();return e-G>500&&(V=q(),G=e),V.enabled&&V.seconds>0?Math.round(1e3*V.seconds):0}var W,$;V=q(),G=Date.now(),"undefined"!=typeof window&&"function"==typeof window.addEventListener&&window.addEventListener("storage",e=>{e.key===K&&(V=q(),G=Date.now())}),function(e){e[e.NONE=0]="NONE",e[e.INFO=1]="INFO",e[e.WARN=2]="WARN",e[e.ERROR=3]="ERROR"}(W||(W={})),function(e){e.MFM_REQ_MAPPINGS="MFM_REQ_MAPPINGS",e.MFM_REQ_SAVED_MAPPINGS="MFM_REQ_SAVED_MAPPINGS",e.MFM_DEL_CLIENT_TOKEN="MFM_DEL_CLIENT_TOKEN",e.MFM_SUBMIT_TOKEN="MFM_SUBMIT_TOKEN",e.MFM_TOGGLE_INTERCEPTION="MFM_TOGGLE_INTERCEPTION",e.MFM_REQ_ALL_APIS="MFM_REQ_ALL_APIS",e.MFM_TOGGLE_API="MFM_TOGGLE_API",e.MFM_DEBUG_RULES_UPDATE="MFM_DEBUG_RULES_UPDATE",e.MFM_DEBUG_INTERCEPT_RES="MFM_DEBUG_INTERCEPT_RES",e.MFM_REQUEST_EDIT_RULES_UPDATE="MFM_REQUEST_EDIT_RULES_UPDATE",e.MFM_REQUEST_EDIT_ACK="MFM_REQUEST_EDIT_ACK",e.MFM_REQUEST_EDIT_RES="MFM_REQUEST_EDIT_RES",e.MFM_GLOBAL_DELAY_UPDATE="MFM_GLOBAL_DELAY_UPDATE",e.MFM_FLOW_MOCK_SET="MFM_FLOW_MOCK_SET",e.MFM_FLOW_MOCK_CLEAR="MFM_FLOW_MOCK_CLEAR",e.MFM_PING_SCREENSHOT="MFM_PING_SCREENSHOT",e.MFM_REQUEST_SCREENSHOT="MFM_REQUEST_SCREENSHOT",e.MFM_RES_MAPPINGS="MFM_RES_MAPPINGS",e.MFM_RES_ALL_APIS="MFM_RES_ALL_APIS",e.MFM_TOGGLE_API_RESULT="MFM_TOGGLE_API_RESULT",e.MFM_REQ="MFM_REQ",e.MFM_RES="MFM_RES",e.MFM_TOKEN_ERROR="MFM_TOKEN_ERROR",e.MFM_TOKEN_API_FAILED="MFM_TOKEN_API_FAILED",e.MFM_TOKEN_INVALIDATED="MFM_TOKEN_INVALIDATED",e.MFM_MOCK_DISABLED="MFM_MOCK_DISABLED",e.MFM_TOKEN_CLEARED="MFM_TOKEN_CLEARED",e.MFM_DEBUG_INTERCEPT_REQ="MFM_DEBUG_INTERCEPT_REQ",e.MFM_REQUEST_EDIT_REQ="MFM_REQUEST_EDIT_REQ",e.MFM_PONG_SCREENSHOT="MFM_PONG_SCREENSHOT",e.MFM_SCREENSHOT_RESULT="MFM_SCREENSHOT_RESULT",e.MFM_SCREENSHOT_ERROR="MFM_SCREENSHOT_ERROR",e.MFM_LOG_INFO="MFM_LOG_INFO",e.MFM_LOG_WARN="MFM_LOG_WARN",e.MFM_LOG_ERROR="MFM_LOG_ERROR"}($||($={}));const X="MFM_TOKEN",Y="MFM_CACHED_MAPPINGS",Z="MFM_INTERCEPTION_ENABLED",ee=new class{constructor(e={}){o()||(this.token=e.token||("undefined"!=typeof localStorage?localStorage.getItem(X):null),this.isAuthenticated=!!this.token,this.onAuthSuccess=e.onAuthSuccess||(()=>{}),this.mappings=e.mappings||[],this.rules=e.rules||[],this.widgetKey=e.widgetKey||null,this.tokenInvalidated=!1,this.setupMessageListeners())}get interceptionEnabled(){if(this.tokenInvalidated)return!1;if("undefined"==typeof localStorage)return!1!==this._interceptionEnabled;const e=localStorage.getItem(Z);return"false"!==e&&("true"===e||!1!==this._interceptionEnabled)}set interceptionEnabled(e){const t=!!e;this._interceptionEnabled=t,"undefined"!=typeof localStorage&&localStorage.setItem(Z,t?"true":"false")}setupMessageListeners(){"undefined"!=typeof window&&window.addEventListener("message",e=>{const{type:t,payload:n}=e.data||{};var r,o;if(t&&"string"==typeof t&&t.startsWith("MFM_"))switch(t){case $.MFM_REQ_MAPPINGS:this.refreshMappings();break;case $.MFM_REQ_SAVED_MAPPINGS:this.handleReqSavedMappings();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;break;case $.MFM_REQ_ALL_APIS:this.handleReqAllApis();break;case $.MFM_TOGGLE_API:this.handleToggleApi(n?.apiId,n?.enabled);break;case $.MFM_DEBUG_RULES_UPDATE:_(n?.rules||[]);break;case $.MFM_DEBUG_INTERCEPT_RES:!function(e){if(!e||!e.requestId)return;const t=T.get(e.requestId);t&&(clearTimeout(t.timer),T.delete(e.requestId),t.resolve(e))}(n);break;case $.MFM_REQUEST_EDIT_RULES_UPDATE:O(n?.rules||[]);break;case $.MFM_REQUEST_EDIT_RES:!function(e){if(!e||!e.requestId)return;const t=N.get(e.requestId);t&&(clearTimeout(t.timer),N.delete(e.requestId),t.resolve(e))}(n);break;case $.MFM_GLOBAL_DELAY_UPDATE:!function(e){if(!e||"object"!=typeof e)return V={enabled:!1,seconds:0},void(G=Date.now());V={enabled:!!e.enabled&&Number.isFinite(e.seconds)&&e.seconds>0,seconds:Number.isFinite(e.seconds)?Number(e.seconds):0},G=Date.now()}(n);break;case $.MFM_FLOW_MOCK_SET:r=n?.runId,o=n?.apis||[],r&&a.set(String(r),Array.isArray(o)?o:[]);break;case $.MFM_FLOW_MOCK_CLEAR:!function(e){e&&a.delete(String(e))}(n?.runId)}})}init(){if("undefined"!=typeof document&&this.checkVisibility()&&("undefined"!=typeof window&&Promise.resolve().then(n.bind(n,435)).then(e=>{const t=window.MockForMeWidget||e.MockForMeWidget;t&&"function"==typeof t.run&&(t.run(null,{clientType:"NPM",version:"14.5.1"}),this.syncInterceptionToggleToWidget())}).catch(e=>{console.error("[MockForMe] Failed to load mfm-widget",e)}),console.log("[MockForMe] Widget initialized"),this.token)){const e=this.getSavedMappings(this.token,"JAVASCRIPT");e&&(this.mappings=e.mappings||[],this.rules=e.meta?._rules||[],this.onAuthSuccess(this.token,this.mappings,e.meta),this.updateMappings(this.mappings,e.meta))}}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(X,e),this.refreshMappings())}handleTokenDeletion(){this.token=null,this.isAuthenticated=!1,"undefined"!=typeof localStorage&&(localStorage.removeItem(X),localStorage.removeItem(Y)),this.mappings=[],this.rules=[],this.onAuthSuccess(null,[],{_rules:[]}),this.updateMappings([],{_rules:[]})}handleReqAllApis(){this.token?(async e=>{if(!e)return{ok:!1,message:"Missing token",result:[]};const t=await fetch(`${E}/apis`,{method:"GET",headers:F(e)});return S(t)})(this.token).then(e=>{const t=e.ok&&Array.isArray(e.result)?e.result:[];this.sendMessage($.MFM_RES_ALL_APIS,{apis:t})}).catch(()=>this.sendMessage($.MFM_RES_ALL_APIS,{apis:[]})):this.sendMessage($.MFM_RES_ALL_APIS,{apis:[]})}handleToggleApi(e,t){this.token&&e?(async(e,t,n)=>{if(!e)return{ok:!1,message:"Missing token",result:null};const r=await fetch(`${E}/api/${t}/toggle-state`,{method:"PUT",headers:F(e),body:JSON.stringify({enabled:!!n})});return S(r)})(this.token,e,t).then(n=>{this.sendMessage($.MFM_TOGGLE_API_RESULT,{apiId:e,enabled:!!t,ok:!!n.ok,message:n.message||""}),n.ok&&this.refreshMappings()}).catch(()=>this.sendMessage($.MFM_TOGGLE_API_RESULT,{apiId:e,enabled:!!t,ok:!1,message:"Failed to update the mock"})):this.sendMessage($.MFM_TOGGLE_API_RESULT,{apiId:e,enabled:!!t,ok:!1,message:"Missing token"})}refreshMappings(){this.token&&C(this.token,"JAVASCRIPT",(e,t)=>{this.mappings=e||[],this.rules=t?._rules||[],this.tokenInvalidated=!1,this.saveMappings(e,t,this.token,"JAVASCRIPT"),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.token=null,this.isAuthenticated=!1,"undefined"!=typeof localStorage&&(localStorage.removeItem(X),localStorage.removeItem(Y)),this.mappings=[],this.rules=[],this.onAuthSuccess(null,[],{_rules:[]}),this.sendMessage($.MFM_TOKEN_ERROR,{message:"Unauthorized: Invalid token"})):this.sendMessage($.MFM_TOKEN_API_FAILED,{message:"Unable to reach the mappings service. Please try again."})})}saveMappings(e,t,n=this.token,r="JAVASCRIPT"){if("undefined"!=typeof localStorage)try{localStorage.setItem(Y,JSON.stringify({token:n,adaptor:r,mappings:e,meta:t,timestamp:Date.now()}))}catch(e){console.error("[MockForMe] Failed to save mappings to storage",e)}}handleReqSavedMappings(){const e=this.getSavedMappings(this.token,"JAVASCRIPT");e?(this.mappings=e.mappings||[],this.rules=e.meta?._rules||[],this.onAuthSuccess(this.token,this.mappings,e.meta),this.updateMappings(this.mappings,e.meta)):this.updateMappings([],{_rules:[]})}getSavedMappings(e=this.token,t="JAVASCRIPT"){if("undefined"==typeof localStorage)return null;try{const n=localStorage.getItem(Y);if(!n)return null;const r=JSON.parse(n);return r?.token&&e&&r.token!==e||r?.adaptor&&t&&r.adaptor!==t?null:r}catch(e){return null}}syncInterceptionToggleToWidget(){this.sendMessage($.MFM_TOGGLE_INTERCEPTION,{enabled:this.interceptionEnabled})}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="object"==typeof e.rule&&null!==e.rule?e.rule:{},n={...e,...t},r=n.timingAction||{},o=r.activeAction||"MODIFY";let i="MODIFY";"delay"===o?i="DELAY":"delay_and_timeout"===o?i="TIMEOUT":"delay_and_redirect"===o&&(i="REDIRECT");const s={ruleName:n.ruleName||n._id||"Unnamed Rule",type:i,conditions:n.conditions||[],modificationActions:n.modificationActions||{}};return("MODIFY"!==i||r.activeAction)&&(s.timingAction=r),s}),token:this.token})}handleMockDisabled({apiMethod:e,apiEndpoint:t}={}){if(!t)return;const n=function(e,t){if(!t)return!1;const n=A.length,r=i(e||"");return A=A.filter(e=>!(i(e.apiMethod)===r&&e.apiEndpoint===t)),A.length!==n}(e,t),r=this.mappings.length;if(this.mappings=(this.mappings||[]).filter(n=>!((n.apiMethod||"").toLowerCase()===(e||"").toLowerCase()&&n.apiEndpoint===t)),!n&&this.mappings.length===r)return;this.updateMappings(this.mappings,{_rules:this.rules});const o=`${(e||"").toUpperCase()} ${t}`.trim();this.sendMessage($.MFM_MOCK_DISABLED,{method:e,url:t,message:`${o} mock was disabled and has been removed.`})}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(": "),r=n.shift();r&&(t[r]=n.join(": "))}):t="function"==typeof e.entries?Object.fromEntries(e.entries()):e,Object.keys(t).reduce((e,n)=>(e[n.toLowerCase()]=t[n],e),{})};let r,o,i;if(void 0===t.status||null===t.status)r=void 0;else if("number"==typeof t.status)r=t.status;else{const e=Number(t.status);Number.isFinite(e)?r=e:(r=0,o=String(t.status))}t.aborted||"Aborted"===t.status?i="aborted":t.timeout||"Timeout"===t.status?i="timeout":"Cancelled"===t.status?i="cancelled":(t.error||"Error"===o)&&(i="error");const s=t.pending&&void 0===t.status?null:{statusCode:r,headers:n(t.responseHeaders),body:t.responseBody,endTime:(new Date).toISOString(),...o?{statusText:o}:{},...i?{errorReason:i,failed:!0}:{}},a={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:s,rule:t.rule,timestamp:t.pending&&t.startTime||Date.now(),...Number.isFinite(t.duration)?{duration:t.duration}:{}};if(t.pending)this.sendMessage($.MFM_REQ,a);else if(this.sendMessage($.MFM_RES,a),!this.tokenInvalidated&&a.response&&a.response.headers){const e=a.response.headers["mfm-invalid-token"];if("true"===e||!0===e){console.warn("[MockForMe] Invalid token detected from response headers"),this.tokenInvalidated=!0;let e="Your token is no longer valid. Please enter a valid token.";try{const n=t.responseBody,r="string"==typeof n?JSON.parse(n):n;r&&"string"==typeof r.message&&r.message.trim()&&(e=r.message.trim())}catch(e){}this.sendMessage($.MFM_TOKEN_INVALIDATED,{message:e})}}}sendMessage(e,t){"undefined"!=typeof window&&window.postMessage({type:e,payload:t},"*")}};function te(e){const t=function(e,t){if(e)return"function"==typeof e.get?e.get(t):"string"==typeof e?((e,t)=>{const n=t.toLowerCase();return e.split(/\r?\n/).map(e=>{const t=e.indexOf(":");return t<0?null:[e.slice(0,t).trim().toLowerCase(),e.slice(t+1).trim()]}).filter(Boolean).find(([e])=>e===n)?.[1]})(e,t):((e,t)=>{const n=t.toLowerCase();for(const t of Object.keys(e||{}))if(t.toLowerCase()===n)return e[t]})(e,t)}(e,"mfm-mock-disabled");return"true"===t||!0===t}class ne{static match(e,t){if(!Array.isArray(t)||0===t.length)return!1;const{url:n,headers:r,queryParams:o,body:i}=e,s="undefined"!=typeof window?window.location.origin:globalThis.location?.origin||"http://localhost";for(const e of t){let t="";const{type:a,key:A,operator:l,value:c}=e;switch(a){case"URL":try{t=new URL(n,s).pathname}catch{t=n}break;case"QUERY_PARAM":if(o&&void 0!==o[A])t=String(o[A]);else try{t=new URL(n,s).searchParams.get(A)||""}catch{t=""}break;case"REQUEST_BODY":if(A){if("object"==typeof i&&null!==i)t=void 0!==i[A]?String(i[A]):"";else if("string"==typeof i)try{const e=JSON.parse(i);t=void 0!==e[A]?String(e[A]):""}catch{t=""}}else t="object"==typeof i?JSON.stringify(i):String(i||"");break;case"REQUEST_HEADER":if(A){const e=A?.toLowerCase();if(t="",r){const n=Object.keys(r).find(t=>t.toLowerCase()===e);t=n?String(r[n]):""}}else t=JSON.stringify(r||{});break;default:return!1}if(!this.evaluate(t,l,c))return!1}return!0}static evaluate(e,t,n){const r=t?.toLowerCase(),o=String(e),i=String(n);switch(r){case"contains":return o.includes(i);case"equal":case"equals":return o===i;case"regexp":try{let e=i;if(e.startsWith("/")&&e.lastIndexOf("/")>0){const t=e.lastIndexOf("/"),n=e.slice(1,t),r=e.slice(t+1);return new RegExp(n,r).test(o)}return new RegExp(e).test(o)}catch{return!1}default:return!1}}}class re{static async apply(e){if(!e||!e.activeAction)return{type:"passThrough",delay:0};const{activeAction:t,actions:n}=e,r=n?.[t];if(!r)return{type:"passThrough",delay:0};const o={type:"passThrough",delay:0},i=Number(r.value||0);switch(t){case"delay":o.delay=i,o.delay>0&&await new Promise(e=>setTimeout(e,1e3*o.delay));break;case"redirect":case"delay_and_redirect":o.type="redirect",o.delay=i,o.redirectUrl=r.redirectUrl,o.delay>0&&await new Promise(e=>setTimeout(e,1e3*o.delay));break;case"delay_and_timeout":o.type="timeout",o.delay=i,o.delay>0&&await new Promise(e=>setTimeout(e,1e3*o.delay))}return o}}class oe{static applyRequestModifications(e,t){if(!t)return e;let{url:n,method:r,headers:o,queryParams:i,body:s}={...e};o&&(o={...o}),i&&(i={...i});const{modifyQueryParams:a,modifyRequestBody:A,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),i&&delete i[t]}),Array.isArray(a.add)&&a.add.forEach(({key:t,value:n})=>{e.searchParams.set(t,n),i&&(i[t]=n)}),n=e.toString()}catch(e){console.error("[MockForMe] Failed to modify query params",e)}l?.enabled&&(o={...o},Array.isArray(l.remove)&&l.remove.forEach(e=>{const t=e.toLowerCase(),n=Object.keys(o).find(e=>e.toLowerCase()===t);n&&delete o[n]}),Array.isArray(l.add)&&l.add.forEach(({key:e,value:t})=>{o[e]=t}));const c=String(r||"GET").toUpperCase(),d="GET"===c||"HEAD"===c;if(A?.enabled&&!d)try{let e=null;if("string"==typeof s)try{e=JSON.parse(s)}catch{e={}}else if("object"==typeof s&&null!==s)try{e=JSON.parse(JSON.stringify(s))}catch{e={...s}}else(Array.isArray(A.add)&&A.add.length>0||Array.isArray(A.update)&&A.update.length>0)&&(e={});e&&(Array.isArray(A.remove)&&A.remove.forEach(t=>delete e[t]),Array.isArray(A.add)&&A.add.forEach(({key:t,value:n})=>e[t]=n),Array.isArray(A.update)&&A.update.forEach(({key:t,value:n})=>e[t]=n),s=JSON.stringify(e))}catch(e){console.error("[MockForMe] Failed to modify request body",e)}return{...e,url:n,headers:o,queryParams:i,body:s}}static applyResponseModifications(e,t){if(!t?.modifyResponseHeaders?.enabled)return e;const{modifyResponseHeaders:n}=t,r={...e};return Array.isArray(n.remove)&&n.remove.forEach(e=>{const t=e.toLowerCase(),n=Object.keys(r).find(e=>e.toLowerCase()===t);n&&delete r[n]}),Array.isArray(n.add)&&n.add.forEach(({key:e,value:t})=>{r[e]=t}),r}}class ie{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)&&ne.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,r=oe.applyRequestModifications(t,n.modificationActions);return{...await re.apply(n.timingAction),modifiedRequest:r,rule:n}}static applyResponseModifications(e,t){return oe.applyResponseModifications(e,t)}}class se{static apply({target:e=("undefined"!=typeof window?window:globalThis),originalFetch:t=e.fetch,ruleProvider:n=()=>[],mappingProvider:r=e=>null,onBeforeRequest:o=e=>{},onRuleMatch:i=async(e,t,n,r,o)=>null,onMockMatch:s=async(e,t,n,r,o)=>null,onOtherRequest:a=async(e,t,n,r)=>null,isEnabled:A=()=>!0,shouldBypassRequest:l=()=>!1}){t&&(e.fetch=async function(e,c={}){if(!A())return t(e,c);let d;try{const n="string"==typeof e?e:e.url,r=String(c.method||(e instanceof Request?e.method:"GET")).toUpperCase().trim(),i=Math.random().toString(36).substring(7);if(d={url:n,method:r,headers:c.headers||(e instanceof Request?e.headers:{}),body:c.body||(e instanceof Request?"{binary/stream}":null),requestId:i,queryParams:se.getQueryParams(n)},l(d))return t(e,c);o(d)}catch(n){return console.warn("[MockForMe] Fetch Interceptor Setup Error:",n),t(e,c)}try{const o=n(),A=ie.match(d,o);if(A){const n=await i(A,d,e,c,t);if(n)return n}const l=r(d);if(l){const n=await s(l,d,e,c,t);if(n)return n}const u=await a(d,e,c,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,c)})}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 ae{static apply({target:e=("undefined"!=typeof window?window:{}),OriginalXHR:t=e.XMLHttpRequest,ruleProvider:n=()=>[],mappingProvider:r=e=>null,onBeforeRequest:o=e=>{},onRuleMatch:i=(e,t,n,r)=>{r.call(n.proxy,t.body)},onMockMatch:s=(e,t,n,r)=>{r.call(n.proxy,t.body)},onOtherRequest:a=(e,t,n)=>{n.call(t.proxy,e.body)},isEnabled:A=()=>!0,shouldBypassRequest:l=()=>!1}){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,r={}){if(this._captured)return;this._captured=!0;const o=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}),o("readystatechange"),"Aborted"===e||r.aborted?o("abort"):0===e||"Error"===e||r.error?o("error"):"Timeout"===e||r.timeout?o("timeout"):o("load")}abort(){if(!this._isMocked||"function"!=typeof this._onAbort)return this._xhr.abort();this._onAbort()}open(e,t,n=!0,r=null,o=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,r,o)}setRequestHeader(e,t){return this._headers[e]=t,this._xhr.setRequestHeader(e,t)}send(e){if(!A())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:ae.getQueryParams(this._url)};if(l(t))return this._xhr.send(e);o(t);const c=n(),d=ie.match(t,c),u=e=>this._xhr.send(e);if(d)return this._isMocked=!0,i(d,t,this,u);const f=r(t);return f?(this._isMocked=!0,s(f,t,this,u)):(this._isMocked=!1,a(t,this,u))}})}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 Ae=[g,"https://api.mockforme.com/mockforme/httpRequestBulkMock/bulk_mock"];function le(e){try{const t="undefined"!=typeof window?window.location.origin:"http://localhost",n=new URL(e.url,t);return Ae.some(e=>{const r=new URL(e,t);return n.origin===r.origin&&n.pathname===r.pathname})}catch{return!1}}const ce=(e,t=null,n=u)=>{if(o())return;let r="string"==typeof e?e:e?.token,i="object"==typeof e?e?.widgetKey:null;if(n===u)try{r&&("undefined"!=typeof localStorage&&(localStorage.removeItem("mockforme-token"),localStorage.setItem("MFM_TOKEN",r)),ee.token=r,ee.isAuthenticated=!0),!r&&ee.token&&(r=ee.token),ee.onAuthSuccess=(e,t,n)=>{l(t),b(n),ee.updateMappings(t,n)},i?ee.setWidgetKey(i):ee.init()}catch(e){console.log("Error in showing mockforme widget",e)}t||={mappings:[],_o:null,mk:null,_mck:null,_rules:[]};const{mappings:s=[],_o:a,mk:A,_mck:h,_rules:p=[]}=t;return l(s),b({_o:a,mk:A,_mck:h,_rules:p}),{run:(e,t=()=>{})=>{if(function(e,t){if("undefined"!=typeof window){if(window._mfm_intercepted)return;window._mfm_intercepted=!0}const n=()=>ee.token||e;se.apply({isEnabled:()=>ee.interceptionEnabled,shouldBypassRequest:le,ruleProvider:()=>v(),mappingProvider:e=>{try{return d(new URL(e.url,window.location.origin).pathname,e.method)}catch{return null}},onRuleMatch:async(e,t,n,r,o)=>{const i=t.requestId||Math.random().toString(36).substring(7),s=Date.now();ee.addRequest("mocked",{...t,requestId:i,pending:!0,startTime:s,rule:e});const a=await ie.apply(e,t),{modifiedRequest:A,type:l,delay:c,redirectUrl:d}=a;if("timeout"!==l&&ee.addRequest("mocked",{...A,requestId:i,pending:!0,startTime:s,rule:e}),"timeout"===l){const t=Date.now()-s;throw ee.addRequest("mocked",{...A,requestId:i,status:"Aborted",pending:!1,duration:t,aborted:!0,rule:e}),new Error("Fetch timed out by rules")}if("redirect"===l&&!d)throw new Error("rules: Redirect missing URL");let u="redirect"===l?d:A.url,f={...r};A.headers&&(f.headers=A.headers),A.body&&(f.body=A.body);let h=null;if("redirect"===l){h=Math.random().toString(36).substring(7);const e={url:d,method:A.method,headers:f.headers||{},body:f.body,requestId:h,queryParams:se.getQueryParams(d),requestHeaders:f.headers||{},requestBody:f.body,pending:!0,startTime:Date.now()};ee.addRequest("mocked",e)}return o(u,f).then(async e=>{const t=Date.now()-s;let n=Object.fromEntries(e.headers.entries());if(a.rule.modificationActions?.modifyResponseHeaders?.enabled&&(n=ie.applyResponseModifications(n,a.rule.modificationActions)),"redirect"===l&&h){const t=e.clone(),r=t.headers.get("content-type")||"",o=Date.now()-s;try{let i;i=r.includes("application/json")?await t.json():await t.text(),ee.addRequest("mocked",{url:d,method:A.method,requestId:h,status:e.status,pending:!1,duration:o,responseHeaders:n,responseBody:i,requestHeaders:f.headers||{},requestBody:f.body})}catch(t){ee.addRequest("mocked",{url:d,method:A.method,requestId:h,status:e.status,pending:!1,duration:o,responseHeaders:n,requestHeaders:f.headers||{},requestBody:f.body})}}return ee.addRequest("mocked",{...A,requestId:i,status:e.status,pending:!1,duration:t,responseHeaders:n,rule:a.rule}),e}).catch(e=>{const t=Date.now()-s,n="AbortError"===e.name||e.message.includes("aborted");if(ee.addRequest("mocked",{...A,requestId:i,status:n?"Aborted":0,pending:!1,duration:t,rule:a.rule}),"redirect"===l&&h&&ee.addRequest("mocked",{url:d,method:A.method,requestId:h,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,r,o,i,s)=>{const a=r.requestId||Math.random().toString(36).substring(7),A=Date.now();ee.addRequest("mocked",{...r,requestId:a,pending:!0,startTime:A});const l=n(),c=new URL(r.url,window.location.origin).search;let d=`${B()}${e.url}${c}`,u={[f]:l,mfmver:"14.5.1","x-mfm-adaptor":t};const h=x();h&&e._ack&&(u["x-mfm-key"]=`${h}-${e._ack}`),e?._ri_&&(u._ri_=e._ri_);const p=o instanceof Request?o.headers:i.headers,g=new Headers(p||{});Object.entries(u).forEach(([e,t])=>g.set(e,t)),g.set("x-mfm-internal","true");let m=i.body;if(!m&&o instanceof Request){const e=o.clone();"GET"!==e.method&&"HEAD"!==e.method&&(m=await e.text())}const y={method:r.method,headers:g,credentials:o instanceof Request&&o.credentials||i.credentials||"include",mode:o instanceof Request&&o.mode||i.mode||"cors",signal:o instanceof Request&&o.signal||i.signal};return m&&(y.body=m),s(d,y).then(async t=>{const n=t.clone(),o=n.headers.get("content-type")||"",i=Date.now()-A;te(t.headers)&&ee.handleMockDisabled({apiMethod:e.method,apiEndpoint:e.apiEndpoint});const s=e=>(ee.addRequest("mocked",{...r,requestId:a,status:t.status,responseHeaders:Object.fromEntries(n.headers.entries()),responseBody:e,pending:!1,duration:i}),new Response("string"==typeof e?e:JSON.stringify(e),{status:t.status,headers:n.headers}));return o.includes("application/json")?n.json().then(s):n.text().then(s)}).catch(e=>{const t=Date.now()-A,n=e&&("AbortError"===e.name||String(e.message||"").toLowerCase().includes("abort"));if(ee.addRequest("mocked",{...r,requestId:a,status:n?"Aborted":0,pending:!1,duration:t,aborted:n}),n)throw e;return s(o,i)})},onOtherRequest:async(e,t,n,r)=>{const o=n?.headers||(t instanceof Request?t.headers:{});let i=!1;o instanceof Headers?i="true"===o.get("x-mfm-internal"):"object"==typeof o&&(i="true"===o["x-mfm-internal"]);const s=B();if(e.url.startsWith(s)&&(i=!0),"OPTIONS"===e.method||i)return r(t,n);const a=e.requestId,A=Date.now();ee.addRequest("other",{...e,requestId:a,pending:!0,startTime:A});const l=R(e.method,e.url),c=M(e.method,e.url);let d=t,u=n,f=e;if(l){const t={};try{new URL(e.url,"undefined"!=typeof window?window.location.origin:"http://localhost").searchParams.forEach((e,n)=>{t[n]=e})}catch(e){}const r=await z({requestId:a,ruleId:l.id,request:{method:e.method,url:e.url,headers:e.headers,body:e.body},queryParams:t});if(r.cancel){ee.addRequest("other",{...e,requestId:a,status:"Cancelled",pending:!1,duration:Date.now()-A,error:!0});const t=new Error("Request cancelled by MockForMe request editor");throw t.name="AbortError",t}let o=e.url;try{const t=new URL(e.url,"undefined"!=typeof window?window.location.origin:"http://localhost");[...t.searchParams.keys()].forEach(e=>t.searchParams.delete(e)),Object.entries(r.queryParams||{}).forEach(([e,n])=>{t.searchParams.set(e,String(n??""))}),o="string"==typeof e.url&&e.url.startsWith("/")?`${t.pathname}${t.search}`:t.href}catch(e){}const i=String(e.method||"GET").toUpperCase(),s="GET"!==i&&"HEAD"!==i;u={...n,method:e.method,headers:r.headers||{},body:s?null==r.body?void 0:r.body:void 0},d=o,f={...e,url:o,headers:r.headers||{},body:s?r.body:null}}const h=J();h>0&&await new Promise(e=>setTimeout(e,h));let p=null,g=null;try{p=await r(d,u)}catch(e){g=e}if(c){let t="",n=0,r={};if(p){try{t=await p.clone().text()}catch(e){}n=p.status,r=Object.fromEntries(p.headers.entries())}else g&&(t=g.message||"Network error",n=0);const o=await H({requestId:a,ruleId:c.id,request:{method:f.method,url:f.url,headers:f.headers,body:f.body},response:{statusCode:n,headers:r,body:t}});if(o.simulateTimeout){ee.addRequest("other",{...e,requestId:a,status:"Timeout",responseHeaders:{},pending:!1,duration:Date.now()-A,timeout:!0});const t=new Error("Network request failed (simulated by MockForMe debugger)");throw t.name="AbortError",t}o.delayMs>0&&await new Promise(e=>setTimeout(e,o.delayMs));const i=Number(o.statusCode),s=Number.isFinite(i)&&i>=200&&i<=599?i:n>=200?n:200,l=o.headers&&"object"==typeof o.headers?o.headers:r,d="string"==typeof o.body?o.body:null==o.body?"":JSON.stringify(o.body);ee.addRequest("other",{...e,requestId:a,status:s,responseHeaders:l,responseBody:d,pending:!1,duration:Date.now()-A});const u={};return Object.entries(l).forEach(([e,t])=>{const n=e.toLowerCase();"content-length"!==n&&"content-encoding"!==n&&"transfer-encoding"!==n&&(u[e]=t)}),new Response(d,{status:s,statusText:p?p.statusText:"",headers:new Headers(u)})}const m=Date.now()-A;if(g){const t="AbortError"===g.name||(g.message||"").includes("aborted"),n="TimeoutError"===g.name||(g.message||"").includes("timed out");throw ee.addRequest("other",{...e,requestId:a,status:t?"Aborted":n?"Timeout":"Error",pending:!1,duration:m,aborted:t,timeout:n,error:!t&&!n}),g}const y=Object.fromEntries(p.headers.entries());let w;try{const e=p.clone(),t=5e3,n=Symbol("body-timed-out"),r=await Promise.race([e.text(),new Promise(e=>setTimeout(()=>e(n),t))]);w=r===n?void 0:r}catch(e){w=void 0}return ee.addRequest("other",{...e,requestId:a,status:p.status,responseHeaders:y,responseBody:w,pending:!1,duration:m}),p}}),ae.apply({isEnabled:()=>ee.interceptionEnabled,shouldBypassRequest:le,ruleProvider:()=>v(),mappingProvider:e=>{try{return d(new URL(e.url,window.location.origin).pathname,e.method)}catch{return null}},onRuleMatch:async(e,t,n,r)=>{const o=t.requestId,i=Date.now();ee.addRequest("mocked",{...t,requestId:o,pending:!0,startTime:i,rule:e});const s=await ie.apply(e,t),{modifiedRequest:a,type:A,redirectUrl:l}=s;"timeout"!==A&&ee.addRequest("mocked",{...a,requestId:o,pending:!0,startTime:i,rule:e});let c=null;if("redirect"===A){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()};ee.addRequest("mocked",e)}const d=(e,t,r,d={})=>{const u=Date.now()-i;if(s.rule.modificationActions?.modifyResponseHeaders?.enabled){let e="string"==typeof r?Object.fromEntries(r.split("\r\n").filter(e=>e).map(e=>e.split(": "))):r;e=ie.applyResponseModifications(e,s.rule.modificationActions),r=e}ee.addRequest("mocked",{...a,requestId:o,status:e,responseBody:t,responseHeaders:r,pending:!1,duration:u,rule:s.rule,...d}),"redirect"===A&&c&&ee.addRequest("mocked",{url:l,method:a.method,requestId:c,status:e,responseBody:t,responseHeaders:r,pending:!1,duration:u,requestHeaders:a.headers||{},requestBody:a.body,...d}),n._capture(e,t,r,d)};if("timeout"===A)return d("Aborted","Timed out by rule",{},{aborted:!0}),void n._xhr.abort();if("redirect"===A){if(!l)return void d(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",()=>d("Aborted","Aborted",{},{aborted:!0}),{once:!0}),n._xhr.addEventListener("error",()=>d(0,"Error",{},{error:!0}),{once:!0}),n._xhr.addEventListener("timeout",()=>d("Timeout","Timeout",{},{timeout:!0}),{once:!0}),n._xhr.addEventListener("load",()=>d(n._xhr.status,n._xhr.responseText,n._xhr.getAllResponseHeaders()),{once:!0}),r(a.body)},onMockMatch:(e,r,o,i)=>{const s=r.requestId,a=Date.now(),A=n(),l=new URL(r.url,window.location.origin);let c=`${B()}${e.url}${l.search}`,d={[f]:A,mfmver:"14.5.1","x-mfm-adaptor":t};const u=x();u&&e._ack&&(d["x-mfm-key"]=`${u}-${e._ack}`),e?._ri_&&(d._ri_=e._ri_),d["x-mfm-internal"]="true";const h={...r.headers,...d};ee.addRequest("mocked",{...r,requestId:s,pending:!0,startTime:a});const p=(t,n,i,A={})=>{if(o._captured)return;const l=Date.now()-a;te(i)&&ee.handleMockDisabled({apiMethod:e.method,apiEndpoint:e.apiEndpoint}),ee.addRequest("mocked",{...r,requestId:s,status:t,responseBody:n,responseHeaders:i,pending:!1,duration:l,...A}),o._capture(t,n,i,A)};o._xhr.addEventListener("abort",()=>p("Aborted","Aborted",{},{aborted:!0}),{once:!0}),o._xhr.addEventListener("error",()=>p(0,"Error",{},{error:!0}),{once:!0}),o._xhr.addEventListener("timeout",()=>p("Timeout","Timeout",{},{timeout:!0}),{once:!0});const g=new window.XMLHttpRequest;g.open(r.method,c,!0);for(const e in h)g.setRequestHeader(e,h[e]);g.withCredentials=o.proxy.withCredentials,o._onAbort=()=>{try{g.abort()}catch(e){}p("Aborted","Aborted",{},{aborted:!0})},g.onload=()=>p(g.status,g.responseText,g.getAllResponseHeaders()),g.onerror=()=>p(0,"Network Error",{},{error:!0}),g.ontimeout=()=>p("Timeout","Request timed out",{},{timeout:!0}),g.send(r.body)},onOtherRequest:(e,t,n)=>{const r="true"===e.headers?.["x-mfm-internal"],o=B(),i=e.url.startsWith(o);if("OPTIONS"===e.method||r||i)return n(e.body);const s=Date.now();ee.addRequest("other",{...e,pending:!0,startTime:s});const a=R(e.method,e.url),A=M(e.method,e.url);let l=e;const c=(n,r,o,i={})=>{const a=Date.now()-s;ee.addRequest("other",{...e,status:n,responseBody:r,responseHeaders:o,pending:!1,duration:a,...i}),t._capture(n,r,o,i)};if(t._xhr.addEventListener("abort",()=>c("Aborted","Aborted",{},{aborted:!0}),{once:!0}),t._xhr.addEventListener("error",()=>c(0,"Error",{},{error:!0}),{once:!0}),t._xhr.addEventListener("timeout",()=>c("Timeout","Timeout",{},{timeout:!0}),{once:!0}),t._xhr.addEventListener("load",async()=>{const n=t._xhr.status,r=t._xhr.responseText,o=t._xhr.getAllResponseHeaders();if(A){const t={};"string"==typeof o&&o.split("\r\n").forEach(e=>{const n=e.indexOf(": ");n>0&&(t[e.slice(0,n)]=e.slice(n+2))});const i=await H({requestId:e.requestId,ruleId:A.id,request:{method:l.method,url:l.url,headers:l.headers,body:l.body},response:{statusCode:n,headers:t,body:r}});if(i.simulateTimeout)return void c("Timeout","Timeout (Debugger)",{},{timeout:!0});i.delayMs>0&&await new Promise(e=>setTimeout(e,i.delayMs));const s=Number(i.statusCode)||n,a=i.headers&&"object"==typeof i.headers?i.headers:t,d="string"==typeof i.body?i.body:null==i.body?"":JSON.stringify(i.body);return void c(s,d,a)}c(n,r,o)},{once:!0}),t._xhr.addEventListener("readystatechange",()=>{if(t._xhr.readyState>=2&&!t._captured){const n=t._xhr.status;if(n>0){const r=Date.now()-s;ee.addRequest("other",{...e,status:n,responseHeaders:t._xhr.getAllResponseHeaders(),pending:t._xhr.readyState<4,duration:r})}}}),a)return void(async()=>{const r={};try{new URL(e.url,"undefined"!=typeof window?window.location.origin:"http://localhost").searchParams.forEach((e,t)=>{r[t]=e})}catch(e){}const o=await z({requestId:e.requestId,ruleId:a.id,request:{method:e.method,url:e.url,headers:e.headers,body:e.body},queryParams:r});if(o.cancel){c("Cancelled","Cancelled by editor",{},{aborted:!0});try{t._xhr.abort()}catch(e){}return}let i=e.url;try{const t=new URL(e.url,"undefined"!=typeof window?window.location.origin:"http://localhost");[...t.searchParams.keys()].forEach(e=>t.searchParams.delete(e)),Object.entries(o.queryParams||{}).forEach(([e,n])=>{t.searchParams.set(e,String(n??""))}),i="string"==typeof e.url&&e.url.startsWith("/")?`${t.pathname}${t.search}`:t.href}catch(e){}if(i!==e.url)try{t._xhr.open(e.method,i,!0)}catch(e){}Object.entries(o.headers||{}).forEach(([e,n])=>{try{t._xhr.setRequestHeader(e,String(n??""))}catch(e){}}),l={...e,url:i,headers:o.headers||{},body:o.body};const s=String(e.method||"GET").toUpperCase(),A="GET"!==s&&"HEAD"!==s?null==o.body?null:o.body:null,d=J();d>0?setTimeout(()=>{try{n(A)}catch(e){}},d):n(A)})();const d=J();d>0?setTimeout(()=>{try{n(e.body)}catch(e){}},d):n(e.body)}})}(r,n),a&&A)ee.mappings=s,ee.rules=p,e?.(s,{_o:a,mk:A,_mck:h,_rules:p});else if(r){const t=ee.getSavedMappings(r,n);if(t&&Array.isArray(t.mappings))return ee.mappings=t.mappings,ee.rules=t.meta?._rules||[],l(t.mappings),b(t.meta),ee.updateMappings(t.mappings,t.meta),void e?.(t.mappings,t.meta);ee.updateMappings([],{_rules:[]}),e?.([],{_rules:[]})}},checkIfApiToBeMocked:d,getMappings:c,doFetchMappings:(e,t)=>{C(r||ee.token,n,(t,o)=>{ee.saveMappings(t,o,r||ee.token,n),ee.updateMappings(t,o),e?.(t,o)},t)},recheckWidgetVisibility:()=>{ee.init()}}},de=o();de||(globalThis.mockforme=ce);let ue=ce;de&&(ue=e=>({run:()=>{}}));const fe=ue;module.exports=r})();
|
|
@@ -17,4 +17,4 @@ var e={352(e,t,n){n.r(t),n.d(t,{default:()=>k});var r,o=n(411),i={exports:{}},s=
|
|
|
17
17
|
0% { transform: translateX(-100%) scaleX(0.4); }
|
|
18
18
|
50% { transform: translateX(20%) scaleX(0.6); }
|
|
19
19
|
100% { transform: translateX(100%) scaleX(0.4); }
|
|
20
|
-
`;function AA({message:e,theme:t}){return Ct("div",{role:"alert",css:gt("background:#fef2f2;border:1px solid #fecaca;border-left:3px solid ",t.color.error,";color:",t.color.error,";padding:",t.spacing.md," ",t.spacing.lg,";border-radius:",t.radius.md,";font-size:",t.typography.fontSizeBase,";line-height:1.5;display:flex;align-items:flex-start;gap:",t.spacing.sm,";",""),children:[xt("strong",{css:gt("font-weight:",t.typography.fontWeightBold,";",""),children:"✗"}),xt("span",{children:e})]})}function lA(e){const t=document.getElementById("mfm-root");return!!t&&(t===e||t.contains(e))}function cA(e){if(!e)return"";if(e.length<=1e3)return e;return e.slice(0,988)+"…[truncated]"}function dA(){const e=Ut(),{confirmState:t,dismissConfirm:n}=un();if(u.useEffect(()=>{if(!t)return;const e=e=>{"Escape"===e.key&&n()};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[t,n]),!t)return null;const{title:r,message:o,confirmLabel:i,cancelLabel:s,danger:a,onConfirm:A}=t;return xt("div",{role:"dialog","aria-label":r??"Confirm","aria-modal":"true",onClick:e=>{e.target===e.currentTarget&&n()},css:gt("position:absolute;inset:0;background:rgba(15, 23, 42, 0.5);z-index:",e.z.confirm,";display:flex;align-items:center;justify-content:center;padding:",e.spacing.xl,";",""),children:Ct("div",{css:gt("background:",e.color.bg,";border-radius:",e.radius.lg,";box-shadow:",e.shadow.lg,";padding:",e.spacing.xl,";max-width:360px;width:100%;display:flex;flex-direction:column;gap:",e.spacing.md,";",""),children:[r?xt("h3",{css:gt("margin:0;font-size:",e.typography.fontSizeLg,";font-weight:",e.typography.fontWeightBold,";color:",e.color.text,";",""),children:r}):null,xt("p",{css:gt("margin:0;color:",e.color.text,";font-size:",e.typography.fontSizeBase,";line-height:1.5;",""),children:o}),Ct("div",{css:gt("display:flex;justify-content:flex-end;gap:",e.spacing.md,";margin-top:",e.spacing.sm,";",""),children:[xt("button",{type:"button",onClick:n,css:gt("appearance:none;background:transparent;border:1px solid ",e.color.border,";color:",e.color.text,";font-family:inherit;font-size:",e.typography.fontSizeBase,";padding:",e.spacing.sm," ",e.spacing.lg,";border-radius:",e.radius.md,";cursor:pointer;&:hover{background:",e.color.surfaceBright,";}",""),children:s??"Cancel"}),xt("button",{type:"button",autoFocus:!0,onClick:()=>{n(),A()},css:gt("appearance:none;border:none;background:",a?e.color.error:e.color.primary,";color:#fff;font-family:inherit;font-weight:",e.typography.fontWeightSemibold,";font-size:",e.typography.fontSizeBase,";padding:",e.spacing.sm," ",e.spacing.lg,";border-radius:",e.radius.md,";cursor:pointer;&:hover{filter:brightness(0.95);}",""),children:i??"Confirm"})]})]})})}function uA(){const{analyticsEnabled:e}=tr(),{token:t,organisationId:n}=gn();return u.useEffect(()=>{rn.setEnabled(e)},[e]),u.useEffect(()=>{rn.setToken(t)},[t]),u.useEffect(()=>{rn.setOrganisationId(n)},[n]),null}function fA({clientType:e,version:t}={}){return Ct(Qt,{initialMode:"light",children:[xt(hA,{}),xt(Mt,{children:xt(dn,{clientType:e,version:t,children:xt(pn,{children:xt(yn,{children:xt(Un,{children:xt(Nn,{children:xt(er,{children:xt(Jn,{children:Ct(ir,{children:[xt(uA,{}),xt(So,{}),xt(pA,{})]})})})})})})})})})]})}function hA(){const e=Ut();return xt(pt,{styles:gt(":host,[data-mfm-mount]{all:initial;color:",e.color.text,";font-family:",e.typography.fontFamily,";font-size:",e.typography.fontSizeBase,";line-height:1.4;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;text-rendering:optimizeLegibility;}*,*::before,*::after{box-sizing:border-box;}::-webkit-scrollbar{width:8px;height:8px;}::-webkit-scrollbar-thumb{background:",e.color.border,";border-radius:",e.radius.pill,";}::-webkit-scrollbar-thumb:hover{background:",e.color.textDim,";}","")})}function pA(){const{setOpen:e,isInterceptEnabled:t,toggleIntercept:n,isSettingsOpen:r,openSettings:o,startSnipping:i,requestConfirm:s}=un(),{token:a,isTokenValidated:A,isValidating:l,isLoading:c,reloadMappings:d,deleteToken:u}=gn(),{debugRules:f,editRules:h}=Wn(),{globalDelay:p}=tr();if(!A&&(l||a))return Ct(Bt,{children:[xt(_o,{children:xt(bA,{children:xt(mA,{})})}),xt(qa,{})]});if(!a)return Ct(Bt,{children:[xt(_o,{children:Ct(bA,{children:[xt(pa,{}),xt(dA,{})]})}),xt(qa,{})]});const g=r||f.length>0||h.length>0||p.enabled;return Ct(Bt,{children:[Ct(_o,{children:[xt(Oo,{onSnip:i,onReload:d,onOpenSettings:o,onDeleteToken:()=>{s({title:"Delete token?",message:"Are you sure you want to delete token? API interception will stop once the token is removed.",confirmLabel:"Delete",danger:!0,onConfirm:u})},isInterceptEnabled:t,onToggleIntercept:()=>{t?s({title:"Disable interception?",message:"Once disabled, the widget will stop intercepting requests and disappear from the page. Please refresh the page after disabling it. You can re-enable it anytime from the MockForMe settings page via the extension icon in tray or the right-click menu. You can also re-enable it from inside Widget Settings → Whitelisted Hosts.",confirmLabel:"Disable",danger:!0,onConfirm:n}):n()},onClose:()=>e(!1),isSettingsActive:g,isReloading:c,isAuthenticated:!0}),xt(Po,{}),Ct(bA,{children:[xt(da,{}),xt(ga,{}),xt(ka,{}),xt(Ba,{}),xt(Ua,{}),xt(Na,{}),xt(dA,{}),xt(yA,{})]})]}),xt(qa,{})]})}var gA={name:"3kwpv8",styles:"flex:1;min-height:0;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:14px;padding:24px;text-align:center"};function mA(){const e=Ut();return Ct("div",{css:gA,children:[xt(yi,{size:26,color:e.color.primary,label:"Validating token"}),xt("div",{css:gt("font-size:",e.typography.fontSizeBase,";font-weight:600;color:",e.color.text,";",""),children:"Validating your token…"}),xt("div",{css:gt("font-size:12px;color:",e.color.textDim,";max-width:260px;line-height:1.5;",""),children:"Hang tight — we're verifying your session before loading the widget."})]})}function yA(){const{invalidatedMessage:e,acknowledgeInvalidation:t}=gn(),n=Ut();return null==e?null:xt(ri,{open:!0,hideClose:!0,title:"Token no longer valid",leadingDot:"live",onClose:()=>{},footer:xt("button",{type:"button",onClick:t,css:gt("appearance:none;border:none;border-radius:",n.radius.sm,";background:",n.color.primary,";color:#fff;font-size:",n.typography.fontSizeBase,";font-weight:",n.typography.fontWeightBold,";padding:8px 20px;cursor:pointer;&:hover{background:",n.color.primaryHover,";}",""),children:"OK"}),children:xt("p",{css:gt("margin:0;font-size:",n.typography.fontSizeBase,";line-height:1.5;color:",n.color.text,";",""),children:e})})}var wA={name:"4oq8x6",styles:"position:absolute;inset:0;pointer-events:none;z-index:1500;&:empty{display:none;}&>*{pointer-events:auto;}"},kA={name:"p72qif",styles:"flex:1;min-height:0;position:relative;display:flex;flex-direction:column;overflow:hidden"};function bA({children:e}){const{fullscreenSlotRef:t}=un();return Ct("div",{css:kA,children:[e,xt("div",{ref:t,"data-mfm-fullscreen-slot":!0,css:wA})]})}class vA extends u.Component{constructor(){super(...arguments),o(this,"state",{hasError:!1})}static getDerivedStateFromError(){return Or(),{hasError:!0}}componentDidCatch(e,t){try{this.props.onError(e,t)}catch{}}render(){return this.state.hasError?null:this.props.children}}const BA=(()=>{try{const e="file:///Users/sushilkumar/mockforme/shared/mockforme_widget/dist/chunks/widget-B8TRg0gv.js",t=e.lastIndexOf("/");return t>0?e.slice(0,t+1):e}catch{return""}})();function xA(e,t){return!(!BA||!function(){try{const e=typeof document<"u"&&(document.baseURI||document.location&&document.location.href)||"";return!!e&&!e.startsWith(BA)}catch{return!1}}()||!(e&&e.startsWith(BA)||t&&-1!==t.indexOf(BA)))}let CA=null;const EA="data-mfm-mount";function FA(e){return e||document.getElementById("mfm-root")||(document.body?document.body:null)}function SA(e,t){let n;"mfm-root"===e.id?n=e:(n=document.createElement("div"),n.id="mfm-root",e.appendChild(n)),n.style.cssText="all: initial; display: block;",function(e){try{rn.init(),rn.setClientType(e);const t=tn().read("MFM_TOKEN");t&&rn.setToken(t)}catch{}}(t.clientType);const r=["click","dblclick","mousedown","mouseup","mousemove","pointerdown","pointerup","pointermove","contextmenu","wheel","touchstart","touchend","touchmove"],o=e=>e.stopPropagation();for(const e of r){const t="wheel"===e||"touchstart"===e||"touchend"===e||"touchmove"===e;n.addEventListener(e,o,{passive:t})}const i=n.shadowRoot??n.attachShadow({mode:"open"});let s=i.querySelector(`[${EA}]`);s||(s=document.createElement("div"),s.setAttribute(EA,""),i.appendChild(s));const a=Ue({key:"mfm",container:i,prepend:!0}),A={run:()=>{}},l=F.createRoot(s);l.render(u.createElement(u.StrictMode,null,u.createElement(rt,{value:a},u.createElement(vA,{onError:e=>{setTimeout(()=>A.run(e),0)}},u.createElement(fA,{clientType:t.clientType,version:t.version})))));const c=e=>{const t=e.error;xA(e.filename,t?.stack)&&(Or(),e.preventDefault(),A.run(e.error))},d=e=>{const t=e.reason;xA(void 0,t?.stack??(t?String(t):void 0))&&(Or(),e.preventDefault(),A.run(e.reason))};window.addEventListener("error",c),window.addEventListener("unhandledrejection",d);const f=console.error;console.error=function(...e){if(!(jr>0)){if(BA)for(let t=0;t<e.length;t++){const n=e[t];if(-1!==((n&&"object"==typeof n&&"stack"in n?String(n.stack??""):"")||String(n)).indexOf(BA))return}f.apply(console,e)}};let h=!1,p=null;const g=e=>{if(!h){if(h=!0,window.removeEventListener("error",c),window.removeEventListener("unhandledrejection",d),console.error!==f)try{console.error=f}catch{}try{l.unmount()}catch{}try{n.remove()}catch{}CA=null;try{if(void 0!==e){const t=e,n=t&&"string"==typeof t.message?t.message:"string"==typeof e?e:String(e),r=t&&"string"==typeof t.stack?t.stack:"";Vr("widget_load_failed",{errorName:t&&"string"==typeof t.name?t.name:"Error",errorMessage:n,errorStack:r.slice(0,4e3),userAgent:typeof navigator<"u"?navigator.userAgent:"",url:typeof location<"u"?location.href:""})}else rn.track("widget_destroyed");Gr()}catch{}if(void 0!==e)try{p=function(){if(typeof document>"u"||!document.body)return{dismiss(){}};const e=document.createElement("div");e.id="mfm-error-snackbar",e.style.cssText=["all: initial","position: fixed","right: 16px","bottom: 16px","z-index: 2147483646"].join(";"),document.body.appendChild(e);const t=e.attachShadow({mode:"closed"}),n=document.createElement("div");n.style.cssText=["box-sizing: border-box","display: flex","align-items: center","gap: 10px","min-width: 280px","max-width: 380px","padding: 10px 12px","background: #1f2937","color: #f9fafb","border: 1px solid #374151","border-radius: 8px","box-shadow: 0 8px 24px rgba(0,0,0,0.25)",'font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',"font-size: 13px","line-height: 1.4"].join(";");const r=document.createElement("div");r.style.cssText=["flex: 1 1 auto","min-width: 0"].join(";");const o=document.createElement("div");o.textContent="MockForMe is unable to load.",o.style.cssText="font-weight: 500";const i=document.createElement("div");i.textContent="The issue has been reported.",i.style.cssText=["margin-top: 2px","color: #9ca3af","font-size: 12px"].join(";"),r.appendChild(o),r.appendChild(i);const s=document.createElement("button");s.type="button",s.setAttribute("aria-label","Dismiss"),s.textContent="×",s.style.cssText=["flex: 0 0 auto","width: 24px","height: 24px","padding: 0","background: transparent","color: #9ca3af","border: 0","border-radius: 4px","cursor: pointer","font-size: 18px","line-height: 1"].join(";");let a=!1;const A=()=>{if(!a){a=!0;try{e.remove()}catch{}}};return s.addEventListener("click",A),n.appendChild(r),n.appendChild(s),t.appendChild(n),{dismiss:A}}()}catch{}}};return A.run=g,{destroy(){if(g(),p){try{p.dismiss()}catch{}p=null}}}}const QA={run(e,t={}){if(CA)return CA;if(typeof document<"u"&&"loading"===document.readyState){let n=!1;const r=()=>{if(n)return;const r=FA(e);r&&(CA=SA(r,t))};return document.addEventListener("DOMContentLoaded",r,{once:!0}),{destroy(){n=!0,document.removeEventListener("DOMContentLoaded",r),CA&&CA.destroy()}}}const n=FA(e);return n?(CA=SA(n,t),CA):(console.warn("[MockForMeWidget] no mount target available"),{destroy(){}})}};typeof window<"u"&&(window.MockForMeWidget=QA),n.d(t,["M",0,QA])}};const t={};function n(r){const o=t[r];if(void 0!==o)return o.exports;const i=t[r]={exports:{}};return e[r](i,i.exports,n),i.exports}n.d=(e,t)=>{if(Array.isArray(t))for(var r=0;r<t.length;){var o=t[r++],i=t[r++];n.o(e,o)?0===i&&r++:0===i?Object.defineProperty(e,o,{enumerable:!0,value:t[r++]}):Object.defineProperty(e,o,{enumerable:!0,get:i})}else 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=>{Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};const r=()=>"undefined"!=typeof process&&null!=process.versions?.node,o=e=>{try{return e?e.toLowerCase():e}catch(e){return console.log(e),null}},i=(e,t)=>{const n=e.split("/"),r=t.split("/");if(n.length!==r.length)return!1;for(let e=0;e<n.length;e++){const t=n[e];if(t!==r[e]&&":any"!==t&&":"!==t.charAt(0))return!1}return!0},s=new Map;let a=[];function A(e){a=e}function l(){return a}function c(e,t="get"){const n=e=>e.startsWith("/")?e:`/${e}`,r=n(e),A=function(e,t){if(0===s.size)return null;for(const n of s.values())for(const r of n){if(o(r.apiMethod)!==o(t))continue;const n=r.apiEndpoint.startsWith("/")?r.apiEndpoint:`/${r.apiEndpoint}`;if(n===e||i(n,e)){const t={url:e,method:r.apiMethod,_ack:r._ack||null};return r._ri_&&(t._ri_=r._ri_),t}}return null}(r,t);if(A)return console.log(`[MockForMe] Flow Mock Match: ${t} ${e} -> ${A.url}`),A;for(const s of a)if(o(s.apiMethod)===o(t)){const o=n(s.apiEndpoint);if(o===r||i(o,r)){console.log(`[MockForMe] Match Found: ${t} ${e} -> ${s.apiEndpoint}`);const n={url:e,method:s.apiMethod,apiEndpoint:s.apiEndpoint,_ack:s._ack||null};return s._ri_&&(n._ri_=s._ri_),n}}return null}const d="JAVASCRIPT",u="mockforme",f="https://api.mockforme.com",h=`${f}/mockforme`,p=`${f}/gateway/3f4eae522b`;let g=null,m=null,y=null,w=[];function k({_o:e,mk:t,_mck:n,_rules:r}){g=e,m=t,y=n,w=r}function b(){return w}function v(){return`${h}/${g}/${m}`}function B(){return y}function x(e,t,n,r){fetch(p,{method:"GET",headers:{[u]:e,mfmver:"14.5.0","x-mfm-adaptor":t}}).then(e=>{if(!e.ok)throw e;return e.json()}).then(e=>{if(e){const{di:t,iv:r,_o:o,_mck:i,mk:s,r:a}=e,l=function({di:e,iv:t},n){var r;const o=function(e,t){const n=t.length;return e.split("").map((e,r)=>String.fromCharCode(e.charCodeAt(0)^t.charCodeAt(r%n))).join("")}((r=e,"undefined"!=typeof Buffer?Buffer.from(r,"base64").toString("utf8"):decodeURIComponent(escape(atob(r)))),n+t);return JSON.parse(o)}({di:t,iv:r},o);k({_o:o,mk:s,_mck:i,_rules:a}),l&&(A(l),n(l,{_o:o,mk:s,_mck:i,_rules:a}))}}).catch(e=>{console.error("Error in loading mocked APIs:",e),r(e)})}const C=`${f}/mockforme/mfm_op_3f4eae522b/manage`,E=e=>({[u]:e,mfmver:"14.5.0","Content-Type":"application/json"}),F=async e=>{let t=null;try{t=await e.json()}catch(e){}return{ok:!(!e.ok||!t||!0!==t.status&&"success"!==t.status&&1!==t.status),message:t&&t.message||(e.ok?"":`Request failed (${e.status})`),result:t?t.result:null}},S="MFM_INTERCEPTOR_RULES";let Q=[];const U=new Map;function T(){try{if("undefined"==typeof localStorage)return[];const e=localStorage.getItem(S);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>e&&e.enabled):[]}catch(e){return[]}}function I(e){Q=Array.isArray(e)?e.filter(e=>e&&e.enabled):[]}function _(e,t){if(!e||!t)return null;if(!Q.length&&(Q=T(),!Q.length))return null;const n=String(e).toUpperCase();return Q.find(e=>{if(!e.enabled||String(e.method).toUpperCase()!==n)return!1;if("PATH"===e.matchType)try{return new URL(e.url,"http://localhost").pathname===new URL(t,"http://localhost").pathname}catch(n){return e.url===t}return e.url===t})||null}function M({requestId:e,ruleId:t,request:n,response:r,timeoutMs:o=3e5}){return new Promise(i=>{const s=setTimeout(()=>{U.has(e)&&(U.delete(e),i({requestId:e,simulateTimeout:!1,delayMs:0,statusCode:r?.statusCode??200,headers:r?.headers||{},body:r?.body}))},o);U.set(e,{resolve:i,timer:s});try{"undefined"!=typeof window&&window.postMessage({type:"MFM_DEBUG_INTERCEPT_REQ",payload:{requestId:e,ruleId:t,request:n,response:r,timestamp:Date.now()}},"*")}catch(t){clearTimeout(s),U.delete(e),i({requestId:e,simulateTimeout:!1,delayMs:0,statusCode:r?.statusCode??200,headers:r?.headers||{},body:r?.body})}})}Q=T(),"undefined"!=typeof document&&"function"==typeof document.addEventListener&&document.addEventListener("mfm:rule-sync",e=>{const t=e&&e.detail;t&&"debugger"===t.kind&&I(t.payload?.rules||[])}),"undefined"!=typeof window&&"function"==typeof window.addEventListener&&window.addEventListener("storage",e=>{e.key===S&&(Q=T())});const H="MFM_REQUEST_EDITOR_RULES";let L=[];const D=new Map;function N(){try{if("undefined"==typeof localStorage)return[];const e=localStorage.getItem(H);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>e&&e.enabled):[]}catch(e){return[]}}function j(e){L=Array.isArray(e)?e.filter(e=>e&&e.enabled):[]}function O(e,t){if(!e||!t)return null;if(!L.length&&(L=N(),!L.length))return null;const n=String(e).toUpperCase();return L.find(e=>{if(!e.enabled||String(e.method).toUpperCase()!==n)return!1;if("PATH"===e.matchType)try{return new URL(e.url,"http://localhost").pathname===new URL(t,"http://localhost").pathname}catch(n){return e.url===t}return e.url===t})||null}function R(e,t,n){const r={};return Object.entries(t?.headers||{}).forEach(([e,t])=>{r[e]=String(t??"")}),{requestId:e,cancel:!1,headers:r,queryParams:n||{},body:"string"==typeof t?.body?t.body:null}}function P({requestId:e,ruleId:t,request:n,queryParams:r,timeoutMs:o=3e5}){return new Promise(i=>{const s=setTimeout(()=>{D.has(e)&&(D.delete(e),i(R(e,n,r)))},o);D.set(e,{resolve:i,timer:s});try{"undefined"!=typeof window&&window.postMessage({type:"MFM_REQUEST_EDIT_REQ",payload:{requestId:e,ruleId:t,request:n,queryParams:r,timestamp:Date.now()}},"*")}catch(t){clearTimeout(s),D.delete(e),i(R(e,n,r))}})}L=N(),"undefined"!=typeof document&&"function"==typeof document.addEventListener&&document.addEventListener("mfm:rule-sync",e=>{const t=e&&e.detail;t&&"editor"===t.kind&&j(t.payload?.rules||[])}),"undefined"!=typeof window&&"function"==typeof window.addEventListener&&window.addEventListener("storage",e=>{e.key===H&&(L=N())});const z="MFM_GLOBAL_DELAY";let K={enabled:!1,seconds:0},V=0;function G(){try{if("undefined"==typeof localStorage)return{enabled:!1,seconds:0};const e=localStorage.getItem(z);if(!e)return{enabled:!1,seconds:0};const t=JSON.parse(e);return t&&"object"==typeof t?{enabled:!!t.enabled&&Number.isFinite(t.seconds)&&t.seconds>0,seconds:Number.isFinite(t.seconds)?Number(t.seconds):0}:{enabled:!1,seconds:0}}catch(e){return{enabled:!1,seconds:0}}}function q(){const e=Date.now();return e-V>500&&(K=G(),V=e),K.enabled&&K.seconds>0?Math.round(1e3*K.seconds):0}K=G(),V=Date.now(),"undefined"!=typeof window&&"function"==typeof window.addEventListener&&window.addEventListener("storage",e=>{e.key===z&&(K=G(),V=Date.now())});var J,W,$=n(411);!function(e){e[e.NONE=0]="NONE",e[e.INFO=1]="INFO",e[e.WARN=2]="WARN",e[e.ERROR=3]="ERROR"}(J||(J={})),function(e){e.MFM_REQ_MAPPINGS="MFM_REQ_MAPPINGS",e.MFM_REQ_SAVED_MAPPINGS="MFM_REQ_SAVED_MAPPINGS",e.MFM_DEL_CLIENT_TOKEN="MFM_DEL_CLIENT_TOKEN",e.MFM_SUBMIT_TOKEN="MFM_SUBMIT_TOKEN",e.MFM_TOGGLE_INTERCEPTION="MFM_TOGGLE_INTERCEPTION",e.MFM_REQ_ALL_APIS="MFM_REQ_ALL_APIS",e.MFM_TOGGLE_API="MFM_TOGGLE_API",e.MFM_DEBUG_RULES_UPDATE="MFM_DEBUG_RULES_UPDATE",e.MFM_DEBUG_INTERCEPT_RES="MFM_DEBUG_INTERCEPT_RES",e.MFM_REQUEST_EDIT_RULES_UPDATE="MFM_REQUEST_EDIT_RULES_UPDATE",e.MFM_REQUEST_EDIT_ACK="MFM_REQUEST_EDIT_ACK",e.MFM_REQUEST_EDIT_RES="MFM_REQUEST_EDIT_RES",e.MFM_GLOBAL_DELAY_UPDATE="MFM_GLOBAL_DELAY_UPDATE",e.MFM_FLOW_MOCK_SET="MFM_FLOW_MOCK_SET",e.MFM_FLOW_MOCK_CLEAR="MFM_FLOW_MOCK_CLEAR",e.MFM_PING_SCREENSHOT="MFM_PING_SCREENSHOT",e.MFM_REQUEST_SCREENSHOT="MFM_REQUEST_SCREENSHOT",e.MFM_RES_MAPPINGS="MFM_RES_MAPPINGS",e.MFM_RES_ALL_APIS="MFM_RES_ALL_APIS",e.MFM_TOGGLE_API_RESULT="MFM_TOGGLE_API_RESULT",e.MFM_REQ="MFM_REQ",e.MFM_RES="MFM_RES",e.MFM_TOKEN_ERROR="MFM_TOKEN_ERROR",e.MFM_TOKEN_API_FAILED="MFM_TOKEN_API_FAILED",e.MFM_TOKEN_INVALIDATED="MFM_TOKEN_INVALIDATED",e.MFM_MOCK_DISABLED="MFM_MOCK_DISABLED",e.MFM_TOKEN_CLEARED="MFM_TOKEN_CLEARED",e.MFM_DEBUG_INTERCEPT_REQ="MFM_DEBUG_INTERCEPT_REQ",e.MFM_REQUEST_EDIT_REQ="MFM_REQUEST_EDIT_REQ",e.MFM_PONG_SCREENSHOT="MFM_PONG_SCREENSHOT",e.MFM_SCREENSHOT_RESULT="MFM_SCREENSHOT_RESULT",e.MFM_SCREENSHOT_ERROR="MFM_SCREENSHOT_ERROR",e.MFM_LOG_INFO="MFM_LOG_INFO",e.MFM_LOG_WARN="MFM_LOG_WARN",e.MFM_LOG_ERROR="MFM_LOG_ERROR"}(W||(W={}));const X="MFM_TOKEN",Y="MFM_CACHED_MAPPINGS",Z="MFM_INTERCEPTION_ENABLED",ee=new class{constructor(e={}){r()||(this.token=e.token||("undefined"!=typeof localStorage?localStorage.getItem(X):null),this.isAuthenticated=!!this.token,this.onAuthSuccess=e.onAuthSuccess||(()=>{}),this.mappings=e.mappings||[],this.rules=e.rules||[],this.widgetKey=e.widgetKey||null,this.tokenInvalidated=!1,this.setupMessageListeners())}get interceptionEnabled(){if(this.tokenInvalidated)return!1;if("undefined"==typeof localStorage)return!1!==this._interceptionEnabled;const e=localStorage.getItem(Z);return"false"!==e&&("true"===e||!1!==this._interceptionEnabled)}set interceptionEnabled(e){const t=!!e;this._interceptionEnabled=t,"undefined"!=typeof localStorage&&localStorage.setItem(Z,t?"true":"false")}setupMessageListeners(){"undefined"!=typeof window&&window.addEventListener("message",e=>{const{type:t,payload:n}=e.data||{};var r,o;if(t&&"string"==typeof t&&t.startsWith("MFM_"))switch(t){case W.MFM_REQ_MAPPINGS:this.refreshMappings();break;case W.MFM_REQ_SAVED_MAPPINGS:this.handleReqSavedMappings();break;case W.MFM_SUBMIT_TOKEN:this.handleTokenSubmission(n?.token);break;case W.MFM_DEL_CLIENT_TOKEN:this.handleTokenDeletion();break;case W.MFM_TOGGLE_INTERCEPTION:this.interceptionEnabled=!!n?.enabled;break;case W.MFM_REQ_ALL_APIS:this.handleReqAllApis();break;case W.MFM_TOGGLE_API:this.handleToggleApi(n?.apiId,n?.enabled);break;case W.MFM_DEBUG_RULES_UPDATE:I(n?.rules||[]);break;case W.MFM_DEBUG_INTERCEPT_RES:!function(e){if(!e||!e.requestId)return;const t=U.get(e.requestId);t&&(clearTimeout(t.timer),U.delete(e.requestId),t.resolve(e))}(n);break;case W.MFM_REQUEST_EDIT_RULES_UPDATE:j(n?.rules||[]);break;case W.MFM_REQUEST_EDIT_RES:!function(e){if(!e||!e.requestId)return;const t=D.get(e.requestId);t&&(clearTimeout(t.timer),D.delete(e.requestId),t.resolve(e))}(n);break;case W.MFM_GLOBAL_DELAY_UPDATE:!function(e){if(!e||"object"!=typeof e)return K={enabled:!1,seconds:0},void(V=Date.now());K={enabled:!!e.enabled&&Number.isFinite(e.seconds)&&e.seconds>0,seconds:Number.isFinite(e.seconds)?Number(e.seconds):0},V=Date.now()}(n);break;case W.MFM_FLOW_MOCK_SET:r=n?.runId,o=n?.apis||[],r&&s.set(String(r),Array.isArray(o)?o:[]);break;case W.MFM_FLOW_MOCK_CLEAR:!function(e){e&&s.delete(String(e))}(n?.runId)}})}init(){if("undefined"!=typeof document&&this.checkVisibility()){if("undefined"!=typeof window){const e=window.MockForMeWidget||$.M;e&&"function"==typeof e.run&&(e.run(null,{clientType:"NPM",version:"14.5.0"}),this.syncInterceptionToggleToWidget())}if(console.log("[MockForMe] Widget initialized"),this.token){const e=this.getSavedMappings(this.token,"JAVASCRIPT");e&&(this.mappings=e.mappings||[],this.rules=e.meta?._rules||[],this.onAuthSuccess(this.token,this.mappings,e.meta),this.updateMappings(this.mappings,e.meta))}}}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(X,e),this.refreshMappings())}handleTokenDeletion(){this.token=null,this.isAuthenticated=!1,"undefined"!=typeof localStorage&&(localStorage.removeItem(X),localStorage.removeItem(Y)),this.mappings=[],this.rules=[],this.onAuthSuccess(null,[],{_rules:[]}),this.updateMappings([],{_rules:[]})}handleReqAllApis(){this.token?(async e=>{if(!e)return{ok:!1,message:"Missing token",result:[]};const t=await fetch(`${C}/apis`,{method:"GET",headers:E(e)});return F(t)})(this.token).then(e=>{const t=e.ok&&Array.isArray(e.result)?e.result:[];this.sendMessage(W.MFM_RES_ALL_APIS,{apis:t})}).catch(()=>this.sendMessage(W.MFM_RES_ALL_APIS,{apis:[]})):this.sendMessage(W.MFM_RES_ALL_APIS,{apis:[]})}handleToggleApi(e,t){this.token&&e?(async(e,t,n)=>{if(!e)return{ok:!1,message:"Missing token",result:null};const r=await fetch(`${C}/api/${t}/toggle-state`,{method:"PUT",headers:E(e),body:JSON.stringify({enabled:!!n})});return F(r)})(this.token,e,t).then(n=>{this.sendMessage(W.MFM_TOGGLE_API_RESULT,{apiId:e,enabled:!!t,ok:!!n.ok,message:n.message||""}),n.ok&&this.refreshMappings()}).catch(()=>this.sendMessage(W.MFM_TOGGLE_API_RESULT,{apiId:e,enabled:!!t,ok:!1,message:"Failed to update the mock"})):this.sendMessage(W.MFM_TOGGLE_API_RESULT,{apiId:e,enabled:!!t,ok:!1,message:"Missing token"})}refreshMappings(){this.token&&x(this.token,"JAVASCRIPT",(e,t)=>{this.mappings=e||[],this.rules=t?._rules||[],this.tokenInvalidated=!1,this.saveMappings(e,t,this.token,"JAVASCRIPT"),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.token=null,this.isAuthenticated=!1,"undefined"!=typeof localStorage&&(localStorage.removeItem(X),localStorage.removeItem(Y)),this.mappings=[],this.rules=[],this.onAuthSuccess(null,[],{_rules:[]}),this.sendMessage(W.MFM_TOKEN_ERROR,{message:"Unauthorized: Invalid token"})):this.sendMessage(W.MFM_TOKEN_API_FAILED,{message:"Unable to reach the mappings service. Please try again."})})}saveMappings(e,t,n=this.token,r="JAVASCRIPT"){if("undefined"!=typeof localStorage)try{localStorage.setItem(Y,JSON.stringify({token:n,adaptor:r,mappings:e,meta:t,timestamp:Date.now()}))}catch(e){console.error("[MockForMe] Failed to save mappings to storage",e)}}handleReqSavedMappings(){const e=this.getSavedMappings(this.token,"JAVASCRIPT");e?(this.mappings=e.mappings||[],this.rules=e.meta?._rules||[],this.onAuthSuccess(this.token,this.mappings,e.meta),this.updateMappings(this.mappings,e.meta)):this.updateMappings([],{_rules:[]})}getSavedMappings(e=this.token,t="JAVASCRIPT"){if("undefined"==typeof localStorage)return null;try{const n=localStorage.getItem(Y);if(!n)return null;const r=JSON.parse(n);return r?.token&&e&&r.token!==e||r?.adaptor&&t&&r.adaptor!==t?null:r}catch(e){return null}}syncInterceptionToggleToWidget(){this.sendMessage(W.MFM_TOGGLE_INTERCEPTION,{enabled:this.interceptionEnabled})}updateMappings(e,t){this.sendMessage(W.MFM_RES_MAPPINGS,{apis:e.map(e=>({method:e.apiMethod,url:e.apiEndpoint})),rules:(t?._rules||[]).map(e=>{const t="object"==typeof e.rule&&null!==e.rule?e.rule:{},n={...e,...t},r=n.timingAction||{},o=r.activeAction||"MODIFY";let i="MODIFY";"delay"===o?i="DELAY":"delay_and_timeout"===o?i="TIMEOUT":"delay_and_redirect"===o&&(i="REDIRECT");const s={ruleName:n.ruleName||n._id||"Unnamed Rule",type:i,conditions:n.conditions||[],modificationActions:n.modificationActions||{}};return("MODIFY"!==i||r.activeAction)&&(s.timingAction=r),s}),token:this.token})}handleMockDisabled({apiMethod:e,apiEndpoint:t}={}){if(!t)return;const n=function(e,t){if(!t)return!1;const n=a.length,r=o(e||"");return a=a.filter(e=>!(o(e.apiMethod)===r&&e.apiEndpoint===t)),a.length!==n}(e,t),r=this.mappings.length;if(this.mappings=(this.mappings||[]).filter(n=>!((n.apiMethod||"").toLowerCase()===(e||"").toLowerCase()&&n.apiEndpoint===t)),!n&&this.mappings.length===r)return;this.updateMappings(this.mappings,{_rules:this.rules});const i=`${(e||"").toUpperCase()} ${t}`.trim();this.sendMessage(W.MFM_MOCK_DISABLED,{method:e,url:t,message:`${i} mock was disabled and has been removed.`})}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(": "),r=n.shift();r&&(t[r]=n.join(": "))}):t="function"==typeof e.entries?Object.fromEntries(e.entries()):e,Object.keys(t).reduce((e,n)=>(e[n.toLowerCase()]=t[n],e),{})};let r,o,i;if(void 0===t.status||null===t.status)r=void 0;else if("number"==typeof t.status)r=t.status;else{const e=Number(t.status);Number.isFinite(e)?r=e:(r=0,o=String(t.status))}t.aborted||"Aborted"===t.status?i="aborted":t.timeout||"Timeout"===t.status?i="timeout":"Cancelled"===t.status?i="cancelled":(t.error||"Error"===o)&&(i="error");const s=t.pending&&void 0===t.status?null:{statusCode:r,headers:n(t.responseHeaders),body:t.responseBody,endTime:(new Date).toISOString(),...o?{statusText:o}:{},...i?{errorReason:i,failed:!0}:{}},a={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:s,rule:t.rule,timestamp:t.pending&&t.startTime||Date.now(),...Number.isFinite(t.duration)?{duration:t.duration}:{}};if(t.pending)this.sendMessage(W.MFM_REQ,a);else if(this.sendMessage(W.MFM_RES,a),!this.tokenInvalidated&&a.response&&a.response.headers){const e=a.response.headers["mfm-invalid-token"];if("true"===e||!0===e){console.warn("[MockForMe] Invalid token detected from response headers"),this.tokenInvalidated=!0;let e="Your token is no longer valid. Please enter a valid token.";try{const n=t.responseBody,r="string"==typeof n?JSON.parse(n):n;r&&"string"==typeof r.message&&r.message.trim()&&(e=r.message.trim())}catch(e){}this.sendMessage(W.MFM_TOKEN_INVALIDATED,{message:e})}}}sendMessage(e,t){"undefined"!=typeof window&&window.postMessage({type:e,payload:t},"*")}};function te(e){const t=function(e,t){if(e)return"function"==typeof e.get?e.get(t):"string"==typeof e?((e,t)=>{const n=t.toLowerCase();return e.split(/\r?\n/).map(e=>{const t=e.indexOf(":");return t<0?null:[e.slice(0,t).trim().toLowerCase(),e.slice(t+1).trim()]}).filter(Boolean).find(([e])=>e===n)?.[1]})(e,t):((e,t)=>{const n=t.toLowerCase();for(const t of Object.keys(e||{}))if(t.toLowerCase()===n)return e[t]})(e,t)}(e,"mfm-mock-disabled");return"true"===t||!0===t}class ne{static match(e,t){if(!Array.isArray(t)||0===t.length)return!1;const{url:n,headers:r,queryParams:o,body:i}=e,s="undefined"!=typeof window?window.location.origin:globalThis.location?.origin||"http://localhost";for(const e of t){let t="";const{type:a,key:A,operator:l,value:c}=e;switch(a){case"URL":try{t=new URL(n,s).pathname}catch{t=n}break;case"QUERY_PARAM":if(o&&void 0!==o[A])t=String(o[A]);else try{t=new URL(n,s).searchParams.get(A)||""}catch{t=""}break;case"REQUEST_BODY":if(A){if("object"==typeof i&&null!==i)t=void 0!==i[A]?String(i[A]):"";else if("string"==typeof i)try{const e=JSON.parse(i);t=void 0!==e[A]?String(e[A]):""}catch{t=""}}else t="object"==typeof i?JSON.stringify(i):String(i||"");break;case"REQUEST_HEADER":if(A){const e=A?.toLowerCase();if(t="",r){const n=Object.keys(r).find(t=>t.toLowerCase()===e);t=n?String(r[n]):""}}else t=JSON.stringify(r||{});break;default:return!1}if(!this.evaluate(t,l,c))return!1}return!0}static evaluate(e,t,n){const r=t?.toLowerCase(),o=String(e),i=String(n);switch(r){case"contains":return o.includes(i);case"equal":case"equals":return o===i;case"regexp":try{let e=i;if(e.startsWith("/")&&e.lastIndexOf("/")>0){const t=e.lastIndexOf("/"),n=e.slice(1,t),r=e.slice(t+1);return new RegExp(n,r).test(o)}return new RegExp(e).test(o)}catch{return!1}default:return!1}}}class re{static async apply(e){if(!e||!e.activeAction)return{type:"passThrough",delay:0};const{activeAction:t,actions:n}=e,r=n?.[t];if(!r)return{type:"passThrough",delay:0};const o={type:"passThrough",delay:0},i=Number(r.value||0);switch(t){case"delay":o.delay=i,o.delay>0&&await new Promise(e=>setTimeout(e,1e3*o.delay));break;case"redirect":case"delay_and_redirect":o.type="redirect",o.delay=i,o.redirectUrl=r.redirectUrl,o.delay>0&&await new Promise(e=>setTimeout(e,1e3*o.delay));break;case"delay_and_timeout":o.type="timeout",o.delay=i,o.delay>0&&await new Promise(e=>setTimeout(e,1e3*o.delay))}return o}}class oe{static applyRequestModifications(e,t){if(!t)return e;let{url:n,method:r,headers:o,queryParams:i,body:s}={...e};o&&(o={...o}),i&&(i={...i});const{modifyQueryParams:a,modifyRequestBody:A,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),i&&delete i[t]}),Array.isArray(a.add)&&a.add.forEach(({key:t,value:n})=>{e.searchParams.set(t,n),i&&(i[t]=n)}),n=e.toString()}catch(e){console.error("[MockForMe] Failed to modify query params",e)}l?.enabled&&(o={...o},Array.isArray(l.remove)&&l.remove.forEach(e=>{const t=e.toLowerCase(),n=Object.keys(o).find(e=>e.toLowerCase()===t);n&&delete o[n]}),Array.isArray(l.add)&&l.add.forEach(({key:e,value:t})=>{o[e]=t}));const c=String(r||"GET").toUpperCase(),d="GET"===c||"HEAD"===c;if(A?.enabled&&!d)try{let e=null;if("string"==typeof s)try{e=JSON.parse(s)}catch{e={}}else if("object"==typeof s&&null!==s)try{e=JSON.parse(JSON.stringify(s))}catch{e={...s}}else(Array.isArray(A.add)&&A.add.length>0||Array.isArray(A.update)&&A.update.length>0)&&(e={});e&&(Array.isArray(A.remove)&&A.remove.forEach(t=>delete e[t]),Array.isArray(A.add)&&A.add.forEach(({key:t,value:n})=>e[t]=n),Array.isArray(A.update)&&A.update.forEach(({key:t,value:n})=>e[t]=n),s=JSON.stringify(e))}catch(e){console.error("[MockForMe] Failed to modify request body",e)}return{...e,url:n,headers:o,queryParams:i,body:s}}static applyResponseModifications(e,t){if(!t?.modifyResponseHeaders?.enabled)return e;const{modifyResponseHeaders:n}=t,r={...e};return Array.isArray(n.remove)&&n.remove.forEach(e=>{const t=e.toLowerCase(),n=Object.keys(r).find(e=>e.toLowerCase()===t);n&&delete r[n]}),Array.isArray(n.add)&&n.add.forEach(({key:e,value:t})=>{r[e]=t}),r}}class ie{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)&&ne.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,r=oe.applyRequestModifications(t,n.modificationActions);return{...await re.apply(n.timingAction),modifiedRequest:r,rule:n}}static applyResponseModifications(e,t){return oe.applyResponseModifications(e,t)}}class se{static apply({target:e=("undefined"!=typeof window?window:globalThis),originalFetch:t=e.fetch,ruleProvider:n=()=>[],mappingProvider:r=e=>null,onBeforeRequest:o=e=>{},onRuleMatch:i=async(e,t,n,r,o)=>null,onMockMatch:s=async(e,t,n,r,o)=>null,onOtherRequest:a=async(e,t,n,r)=>null,isEnabled:A=()=>!0,shouldBypassRequest:l=()=>!1}){t&&(e.fetch=async function(e,c={}){if(!A())return t(e,c);let d;try{const n="string"==typeof e?e:e.url,r=String(c.method||(e instanceof Request?e.method:"GET")).toUpperCase().trim(),i=Math.random().toString(36).substring(7);if(d={url:n,method:r,headers:c.headers||(e instanceof Request?e.headers:{}),body:c.body||(e instanceof Request?"{binary/stream}":null),requestId:i,queryParams:se.getQueryParams(n)},l(d))return t(e,c);o(d)}catch(n){return console.warn("[MockForMe] Fetch Interceptor Setup Error:",n),t(e,c)}try{const o=n(),A=ie.match(d,o);if(A){const n=await i(A,d,e,c,t);if(n)return n}const l=r(d);if(l){const n=await s(l,d,e,c,t);if(n)return n}const u=await a(d,e,c,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,c)})}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 ae{static apply({target:e=("undefined"!=typeof window?window:{}),OriginalXHR:t=e.XMLHttpRequest,ruleProvider:n=()=>[],mappingProvider:r=e=>null,onBeforeRequest:o=e=>{},onRuleMatch:i=(e,t,n,r)=>{r.call(n.proxy,t.body)},onMockMatch:s=(e,t,n,r)=>{r.call(n.proxy,t.body)},onOtherRequest:a=(e,t,n)=>{n.call(t.proxy,e.body)},isEnabled:A=()=>!0,shouldBypassRequest:l=()=>!1}){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,r={}){if(this._captured)return;this._captured=!0;const o=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}),o("readystatechange"),"Aborted"===e||r.aborted?o("abort"):0===e||"Error"===e||r.error?o("error"):"Timeout"===e||r.timeout?o("timeout"):o("load")}abort(){if(!this._isMocked||"function"!=typeof this._onAbort)return this._xhr.abort();this._onAbort()}open(e,t,n=!0,r=null,o=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,r,o)}setRequestHeader(e,t){return this._headers[e]=t,this._xhr.setRequestHeader(e,t)}send(e){if(!A())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:ae.getQueryParams(this._url)};if(l(t))return this._xhr.send(e);o(t);const c=n(),d=ie.match(t,c),u=e=>this._xhr.send(e);if(d)return this._isMocked=!0,i(d,t,this,u);const f=r(t);return f?(this._isMocked=!0,s(f,t,this,u)):(this._isMocked=!1,a(t,this,u))}})}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 Ae=[p,"https://api.mockforme.com/mockforme/httpRequestBulkMock/bulk_mock"];function le(e){try{const t="undefined"!=typeof window?window.location.origin:"http://localhost",n=new URL(e.url,t);return Ae.some(e=>{const r=new URL(e,t);return n.origin===r.origin&&n.pathname===r.pathname})}catch{return!1}}const ce=(e,t=null,n=d)=>{if(r())return;let o="string"==typeof e?e:e?.token,i="object"==typeof e?e?.widgetKey:null;if(n===d)try{o&&("undefined"!=typeof localStorage&&(localStorage.removeItem("mockforme-token"),localStorage.setItem("MFM_TOKEN",o)),ee.token=o,ee.isAuthenticated=!0),!o&&ee.token&&(o=ee.token),ee.onAuthSuccess=(e,t,n)=>{A(t),k(n),ee.updateMappings(t,n)},i?ee.setWidgetKey(i):ee.init()}catch(e){console.log("Error in showing mockforme widget",e)}t||={mappings:[],_o:null,mk:null,_mck:null,_rules:[]};const{mappings:s=[],_o:a,mk:f,_mck:h,_rules:p=[]}=t;return A(s),k({_o:a,mk:f,_mck:h,_rules:p}),{run:(e,t=()=>{})=>{if(function(e,t){if("undefined"!=typeof window){if(window._mfm_intercepted)return;window._mfm_intercepted=!0}const n=()=>ee.token||e;se.apply({isEnabled:()=>ee.interceptionEnabled,shouldBypassRequest:le,ruleProvider:()=>b(),mappingProvider:e=>{try{return c(new URL(e.url,window.location.origin).pathname,e.method)}catch{return null}},onRuleMatch:async(e,t,n,r,o)=>{const i=t.requestId||Math.random().toString(36).substring(7),s=Date.now();ee.addRequest("mocked",{...t,requestId:i,pending:!0,startTime:s,rule:e});const a=await ie.apply(e,t),{modifiedRequest:A,type:l,delay:c,redirectUrl:d}=a;if("timeout"!==l&&ee.addRequest("mocked",{...A,requestId:i,pending:!0,startTime:s,rule:e}),"timeout"===l){const t=Date.now()-s;throw ee.addRequest("mocked",{...A,requestId:i,status:"Aborted",pending:!1,duration:t,aborted:!0,rule:e}),new Error("Fetch timed out by rules")}if("redirect"===l&&!d)throw new Error("rules: Redirect missing URL");let u="redirect"===l?d:A.url,f={...r};A.headers&&(f.headers=A.headers),A.body&&(f.body=A.body);let h=null;if("redirect"===l){h=Math.random().toString(36).substring(7);const e={url:d,method:A.method,headers:f.headers||{},body:f.body,requestId:h,queryParams:se.getQueryParams(d),requestHeaders:f.headers||{},requestBody:f.body,pending:!0,startTime:Date.now()};ee.addRequest("mocked",e)}return o(u,f).then(async e=>{const t=Date.now()-s;let n=Object.fromEntries(e.headers.entries());if(a.rule.modificationActions?.modifyResponseHeaders?.enabled&&(n=ie.applyResponseModifications(n,a.rule.modificationActions)),"redirect"===l&&h){const t=e.clone(),r=t.headers.get("content-type")||"",o=Date.now()-s;try{let i;i=r.includes("application/json")?await t.json():await t.text(),ee.addRequest("mocked",{url:d,method:A.method,requestId:h,status:e.status,pending:!1,duration:o,responseHeaders:n,responseBody:i,requestHeaders:f.headers||{},requestBody:f.body})}catch(t){ee.addRequest("mocked",{url:d,method:A.method,requestId:h,status:e.status,pending:!1,duration:o,responseHeaders:n,requestHeaders:f.headers||{},requestBody:f.body})}}return ee.addRequest("mocked",{...A,requestId:i,status:e.status,pending:!1,duration:t,responseHeaders:n,rule:a.rule}),e}).catch(e=>{const t=Date.now()-s,n="AbortError"===e.name||e.message.includes("aborted");if(ee.addRequest("mocked",{...A,requestId:i,status:n?"Aborted":0,pending:!1,duration:t,rule:a.rule}),"redirect"===l&&h&&ee.addRequest("mocked",{url:d,method:A.method,requestId:h,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,r,o,i,s)=>{const a=r.requestId||Math.random().toString(36).substring(7),A=Date.now();ee.addRequest("mocked",{...r,requestId:a,pending:!0,startTime:A});const l=n(),c=new URL(r.url,window.location.origin).search;let d=`${v()}${e.url}${c}`,f={[u]:l,mfmver:"14.5.0","x-mfm-adaptor":t};const h=B();h&&e._ack&&(f["x-mfm-key"]=`${h}-${e._ack}`),e?._ri_&&(f._ri_=e._ri_);const p=o instanceof Request?o.headers:i.headers,g=new Headers(p||{});Object.entries(f).forEach(([e,t])=>g.set(e,t)),g.set("x-mfm-internal","true");let m=i.body;if(!m&&o instanceof Request){const e=o.clone();"GET"!==e.method&&"HEAD"!==e.method&&(m=await e.text())}const y={method:r.method,headers:g,credentials:o instanceof Request&&o.credentials||i.credentials||"include",mode:o instanceof Request&&o.mode||i.mode||"cors",signal:o instanceof Request&&o.signal||i.signal};return m&&(y.body=m),s(d,y).then(async t=>{const n=t.clone(),o=n.headers.get("content-type")||"",i=Date.now()-A;te(t.headers)&&ee.handleMockDisabled({apiMethod:e.method,apiEndpoint:e.apiEndpoint});const s=e=>(ee.addRequest("mocked",{...r,requestId:a,status:t.status,responseHeaders:Object.fromEntries(n.headers.entries()),responseBody:e,pending:!1,duration:i}),new Response("string"==typeof e?e:JSON.stringify(e),{status:t.status,headers:n.headers}));return o.includes("application/json")?n.json().then(s):n.text().then(s)}).catch(e=>{const t=Date.now()-A,n=e&&("AbortError"===e.name||String(e.message||"").toLowerCase().includes("abort"));if(ee.addRequest("mocked",{...r,requestId:a,status:n?"Aborted":0,pending:!1,duration:t,aborted:n}),n)throw e;return s(o,i)})},onOtherRequest:async(e,t,n,r)=>{const o=n?.headers||(t instanceof Request?t.headers:{});let i=!1;o instanceof Headers?i="true"===o.get("x-mfm-internal"):"object"==typeof o&&(i="true"===o["x-mfm-internal"]);const s=v();if(e.url.startsWith(s)&&(i=!0),"OPTIONS"===e.method||i)return r(t,n);const a=e.requestId,A=Date.now();ee.addRequest("other",{...e,requestId:a,pending:!0,startTime:A});const l=O(e.method,e.url),c=_(e.method,e.url);let d=t,u=n,f=e;if(l){const t={};try{new URL(e.url,"undefined"!=typeof window?window.location.origin:"http://localhost").searchParams.forEach((e,n)=>{t[n]=e})}catch(e){}const r=await P({requestId:a,ruleId:l.id,request:{method:e.method,url:e.url,headers:e.headers,body:e.body},queryParams:t});if(r.cancel){ee.addRequest("other",{...e,requestId:a,status:"Cancelled",pending:!1,duration:Date.now()-A,error:!0});const t=new Error("Request cancelled by MockForMe request editor");throw t.name="AbortError",t}let o=e.url;try{const t=new URL(e.url,"undefined"!=typeof window?window.location.origin:"http://localhost");[...t.searchParams.keys()].forEach(e=>t.searchParams.delete(e)),Object.entries(r.queryParams||{}).forEach(([e,n])=>{t.searchParams.set(e,String(n??""))}),o="string"==typeof e.url&&e.url.startsWith("/")?`${t.pathname}${t.search}`:t.href}catch(e){}const i=String(e.method||"GET").toUpperCase(),s="GET"!==i&&"HEAD"!==i;u={...n,method:e.method,headers:r.headers||{},body:s?null==r.body?void 0:r.body:void 0},d=o,f={...e,url:o,headers:r.headers||{},body:s?r.body:null}}const h=q();h>0&&await new Promise(e=>setTimeout(e,h));let p=null,g=null;try{p=await r(d,u)}catch(e){g=e}if(c){let t="",n=0,r={};if(p){try{t=await p.clone().text()}catch(e){}n=p.status,r=Object.fromEntries(p.headers.entries())}else g&&(t=g.message||"Network error",n=0);const o=await M({requestId:a,ruleId:c.id,request:{method:f.method,url:f.url,headers:f.headers,body:f.body},response:{statusCode:n,headers:r,body:t}});if(o.simulateTimeout){ee.addRequest("other",{...e,requestId:a,status:"Timeout",responseHeaders:{},pending:!1,duration:Date.now()-A,timeout:!0});const t=new Error("Network request failed (simulated by MockForMe debugger)");throw t.name="AbortError",t}o.delayMs>0&&await new Promise(e=>setTimeout(e,o.delayMs));const i=Number(o.statusCode),s=Number.isFinite(i)&&i>=200&&i<=599?i:n>=200?n:200,l=o.headers&&"object"==typeof o.headers?o.headers:r,d="string"==typeof o.body?o.body:null==o.body?"":JSON.stringify(o.body);ee.addRequest("other",{...e,requestId:a,status:s,responseHeaders:l,responseBody:d,pending:!1,duration:Date.now()-A});const u={};return Object.entries(l).forEach(([e,t])=>{const n=e.toLowerCase();"content-length"!==n&&"content-encoding"!==n&&"transfer-encoding"!==n&&(u[e]=t)}),new Response(d,{status:s,statusText:p?p.statusText:"",headers:new Headers(u)})}const m=Date.now()-A;if(g){const t="AbortError"===g.name||(g.message||"").includes("aborted"),n="TimeoutError"===g.name||(g.message||"").includes("timed out");throw ee.addRequest("other",{...e,requestId:a,status:t?"Aborted":n?"Timeout":"Error",pending:!1,duration:m,aborted:t,timeout:n,error:!t&&!n}),g}const y=Object.fromEntries(p.headers.entries());let w;try{const e=p.clone(),t=5e3,n=Symbol("body-timed-out"),r=await Promise.race([e.text(),new Promise(e=>setTimeout(()=>e(n),t))]);w=r===n?void 0:r}catch(e){w=void 0}return ee.addRequest("other",{...e,requestId:a,status:p.status,responseHeaders:y,responseBody:w,pending:!1,duration:m}),p}}),ae.apply({isEnabled:()=>ee.interceptionEnabled,shouldBypassRequest:le,ruleProvider:()=>b(),mappingProvider:e=>{try{return c(new URL(e.url,window.location.origin).pathname,e.method)}catch{return null}},onRuleMatch:async(e,t,n,r)=>{const o=t.requestId,i=Date.now();ee.addRequest("mocked",{...t,requestId:o,pending:!0,startTime:i,rule:e});const s=await ie.apply(e,t),{modifiedRequest:a,type:A,redirectUrl:l}=s;"timeout"!==A&&ee.addRequest("mocked",{...a,requestId:o,pending:!0,startTime:i,rule:e});let c=null;if("redirect"===A){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()};ee.addRequest("mocked",e)}const d=(e,t,r,d={})=>{const u=Date.now()-i;if(s.rule.modificationActions?.modifyResponseHeaders?.enabled){let e="string"==typeof r?Object.fromEntries(r.split("\r\n").filter(e=>e).map(e=>e.split(": "))):r;e=ie.applyResponseModifications(e,s.rule.modificationActions),r=e}ee.addRequest("mocked",{...a,requestId:o,status:e,responseBody:t,responseHeaders:r,pending:!1,duration:u,rule:s.rule,...d}),"redirect"===A&&c&&ee.addRequest("mocked",{url:l,method:a.method,requestId:c,status:e,responseBody:t,responseHeaders:r,pending:!1,duration:u,requestHeaders:a.headers||{},requestBody:a.body,...d}),n._capture(e,t,r,d)};if("timeout"===A)return d("Aborted","Timed out by rule",{},{aborted:!0}),void n._xhr.abort();if("redirect"===A){if(!l)return void d(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",()=>d("Aborted","Aborted",{},{aborted:!0}),{once:!0}),n._xhr.addEventListener("error",()=>d(0,"Error",{},{error:!0}),{once:!0}),n._xhr.addEventListener("timeout",()=>d("Timeout","Timeout",{},{timeout:!0}),{once:!0}),n._xhr.addEventListener("load",()=>d(n._xhr.status,n._xhr.responseText,n._xhr.getAllResponseHeaders()),{once:!0}),r(a.body)},onMockMatch:(e,r,o,i)=>{const s=r.requestId,a=Date.now(),A=n(),l=new URL(r.url,window.location.origin);let c=`${v()}${e.url}${l.search}`,d={[u]:A,mfmver:"14.5.0","x-mfm-adaptor":t};const f=B();f&&e._ack&&(d["x-mfm-key"]=`${f}-${e._ack}`),e?._ri_&&(d._ri_=e._ri_),d["x-mfm-internal"]="true";const h={...r.headers,...d};ee.addRequest("mocked",{...r,requestId:s,pending:!0,startTime:a});const p=(t,n,i,A={})=>{if(o._captured)return;const l=Date.now()-a;te(i)&&ee.handleMockDisabled({apiMethod:e.method,apiEndpoint:e.apiEndpoint}),ee.addRequest("mocked",{...r,requestId:s,status:t,responseBody:n,responseHeaders:i,pending:!1,duration:l,...A}),o._capture(t,n,i,A)};o._xhr.addEventListener("abort",()=>p("Aborted","Aborted",{},{aborted:!0}),{once:!0}),o._xhr.addEventListener("error",()=>p(0,"Error",{},{error:!0}),{once:!0}),o._xhr.addEventListener("timeout",()=>p("Timeout","Timeout",{},{timeout:!0}),{once:!0});const g=new window.XMLHttpRequest;g.open(r.method,c,!0);for(const e in h)g.setRequestHeader(e,h[e]);g.withCredentials=o.proxy.withCredentials,o._onAbort=()=>{try{g.abort()}catch(e){}p("Aborted","Aborted",{},{aborted:!0})},g.onload=()=>p(g.status,g.responseText,g.getAllResponseHeaders()),g.onerror=()=>p(0,"Network Error",{},{error:!0}),g.ontimeout=()=>p("Timeout","Request timed out",{},{timeout:!0}),g.send(r.body)},onOtherRequest:(e,t,n)=>{const r="true"===e.headers?.["x-mfm-internal"],o=v(),i=e.url.startsWith(o);if("OPTIONS"===e.method||r||i)return n(e.body);const s=Date.now();ee.addRequest("other",{...e,pending:!0,startTime:s});const a=O(e.method,e.url),A=_(e.method,e.url);let l=e;const c=(n,r,o,i={})=>{const a=Date.now()-s;ee.addRequest("other",{...e,status:n,responseBody:r,responseHeaders:o,pending:!1,duration:a,...i}),t._capture(n,r,o,i)};if(t._xhr.addEventListener("abort",()=>c("Aborted","Aborted",{},{aborted:!0}),{once:!0}),t._xhr.addEventListener("error",()=>c(0,"Error",{},{error:!0}),{once:!0}),t._xhr.addEventListener("timeout",()=>c("Timeout","Timeout",{},{timeout:!0}),{once:!0}),t._xhr.addEventListener("load",async()=>{const n=t._xhr.status,r=t._xhr.responseText,o=t._xhr.getAllResponseHeaders();if(A){const t={};"string"==typeof o&&o.split("\r\n").forEach(e=>{const n=e.indexOf(": ");n>0&&(t[e.slice(0,n)]=e.slice(n+2))});const i=await M({requestId:e.requestId,ruleId:A.id,request:{method:l.method,url:l.url,headers:l.headers,body:l.body},response:{statusCode:n,headers:t,body:r}});if(i.simulateTimeout)return void c("Timeout","Timeout (Debugger)",{},{timeout:!0});i.delayMs>0&&await new Promise(e=>setTimeout(e,i.delayMs));const s=Number(i.statusCode)||n,a=i.headers&&"object"==typeof i.headers?i.headers:t,d="string"==typeof i.body?i.body:null==i.body?"":JSON.stringify(i.body);return void c(s,d,a)}c(n,r,o)},{once:!0}),t._xhr.addEventListener("readystatechange",()=>{if(t._xhr.readyState>=2&&!t._captured){const n=t._xhr.status;if(n>0){const r=Date.now()-s;ee.addRequest("other",{...e,status:n,responseHeaders:t._xhr.getAllResponseHeaders(),pending:t._xhr.readyState<4,duration:r})}}}),a)return void(async()=>{const r={};try{new URL(e.url,"undefined"!=typeof window?window.location.origin:"http://localhost").searchParams.forEach((e,t)=>{r[t]=e})}catch(e){}const o=await P({requestId:e.requestId,ruleId:a.id,request:{method:e.method,url:e.url,headers:e.headers,body:e.body},queryParams:r});if(o.cancel){c("Cancelled","Cancelled by editor",{},{aborted:!0});try{t._xhr.abort()}catch(e){}return}let i=e.url;try{const t=new URL(e.url,"undefined"!=typeof window?window.location.origin:"http://localhost");[...t.searchParams.keys()].forEach(e=>t.searchParams.delete(e)),Object.entries(o.queryParams||{}).forEach(([e,n])=>{t.searchParams.set(e,String(n??""))}),i="string"==typeof e.url&&e.url.startsWith("/")?`${t.pathname}${t.search}`:t.href}catch(e){}if(i!==e.url)try{t._xhr.open(e.method,i,!0)}catch(e){}Object.entries(o.headers||{}).forEach(([e,n])=>{try{t._xhr.setRequestHeader(e,String(n??""))}catch(e){}}),l={...e,url:i,headers:o.headers||{},body:o.body};const s=String(e.method||"GET").toUpperCase(),A="GET"!==s&&"HEAD"!==s?null==o.body?null:o.body:null,d=q();d>0?setTimeout(()=>{try{n(A)}catch(e){}},d):n(A)})();const d=q();d>0?setTimeout(()=>{try{n(e.body)}catch(e){}},d):n(e.body)}})}(o,n),a&&f)ee.mappings=s,ee.rules=p,e?.(s,{_o:a,mk:f,_mck:h,_rules:p});else if(o){const t=ee.getSavedMappings(o,n);if(t&&Array.isArray(t.mappings))return ee.mappings=t.mappings,ee.rules=t.meta?._rules||[],A(t.mappings),k(t.meta),ee.updateMappings(t.mappings,t.meta),void e?.(t.mappings,t.meta);ee.updateMappings([],{_rules:[]}),e?.([],{_rules:[]})}},checkIfApiToBeMocked:c,getMappings:l,doFetchMappings:(e,t)=>{x(o||ee.token,n,(t,r)=>{ee.saveMappings(t,r,o||ee.token,n),ee.updateMappings(t,r),e?.(t,r)},t)},recheckWidgetVisibility:()=>{ee.init()}}},de=r();de||(globalThis.mockforme=ce);let ue=ce;de&&(ue=e=>({run:()=>{}}));const fe=ue;export{fe as mockforme};
|
|
20
|
+
`;function AA({message:e,theme:t}){return Ct("div",{role:"alert",css:gt("background:#fef2f2;border:1px solid #fecaca;border-left:3px solid ",t.color.error,";color:",t.color.error,";padding:",t.spacing.md," ",t.spacing.lg,";border-radius:",t.radius.md,";font-size:",t.typography.fontSizeBase,";line-height:1.5;display:flex;align-items:flex-start;gap:",t.spacing.sm,";",""),children:[xt("strong",{css:gt("font-weight:",t.typography.fontWeightBold,";",""),children:"✗"}),xt("span",{children:e})]})}function lA(e){const t=document.getElementById("mfm-root");return!!t&&(t===e||t.contains(e))}function cA(e){if(!e)return"";if(e.length<=1e3)return e;return e.slice(0,988)+"…[truncated]"}function dA(){const e=Ut(),{confirmState:t,dismissConfirm:n}=un();if(u.useEffect(()=>{if(!t)return;const e=e=>{"Escape"===e.key&&n()};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[t,n]),!t)return null;const{title:r,message:o,confirmLabel:i,cancelLabel:s,danger:a,onConfirm:A}=t;return xt("div",{role:"dialog","aria-label":r??"Confirm","aria-modal":"true",onClick:e=>{e.target===e.currentTarget&&n()},css:gt("position:absolute;inset:0;background:rgba(15, 23, 42, 0.5);z-index:",e.z.confirm,";display:flex;align-items:center;justify-content:center;padding:",e.spacing.xl,";",""),children:Ct("div",{css:gt("background:",e.color.bg,";border-radius:",e.radius.lg,";box-shadow:",e.shadow.lg,";padding:",e.spacing.xl,";max-width:360px;width:100%;display:flex;flex-direction:column;gap:",e.spacing.md,";",""),children:[r?xt("h3",{css:gt("margin:0;font-size:",e.typography.fontSizeLg,";font-weight:",e.typography.fontWeightBold,";color:",e.color.text,";",""),children:r}):null,xt("p",{css:gt("margin:0;color:",e.color.text,";font-size:",e.typography.fontSizeBase,";line-height:1.5;",""),children:o}),Ct("div",{css:gt("display:flex;justify-content:flex-end;gap:",e.spacing.md,";margin-top:",e.spacing.sm,";",""),children:[xt("button",{type:"button",onClick:n,css:gt("appearance:none;background:transparent;border:1px solid ",e.color.border,";color:",e.color.text,";font-family:inherit;font-size:",e.typography.fontSizeBase,";padding:",e.spacing.sm," ",e.spacing.lg,";border-radius:",e.radius.md,";cursor:pointer;&:hover{background:",e.color.surfaceBright,";}",""),children:s??"Cancel"}),xt("button",{type:"button",autoFocus:!0,onClick:()=>{n(),A()},css:gt("appearance:none;border:none;background:",a?e.color.error:e.color.primary,";color:#fff;font-family:inherit;font-weight:",e.typography.fontWeightSemibold,";font-size:",e.typography.fontSizeBase,";padding:",e.spacing.sm," ",e.spacing.lg,";border-radius:",e.radius.md,";cursor:pointer;&:hover{filter:brightness(0.95);}",""),children:i??"Confirm"})]})]})})}function uA(){const{analyticsEnabled:e}=tr(),{token:t,organisationId:n}=gn();return u.useEffect(()=>{rn.setEnabled(e)},[e]),u.useEffect(()=>{rn.setToken(t)},[t]),u.useEffect(()=>{rn.setOrganisationId(n)},[n]),null}function fA({clientType:e,version:t}={}){return Ct(Qt,{initialMode:"light",children:[xt(hA,{}),xt(Mt,{children:xt(dn,{clientType:e,version:t,children:xt(pn,{children:xt(yn,{children:xt(Un,{children:xt(Nn,{children:xt(er,{children:xt(Jn,{children:Ct(ir,{children:[xt(uA,{}),xt(So,{}),xt(pA,{})]})})})})})})})})})]})}function hA(){const e=Ut();return xt(pt,{styles:gt(":host,[data-mfm-mount]{all:initial;color:",e.color.text,";font-family:",e.typography.fontFamily,";font-size:",e.typography.fontSizeBase,";line-height:1.4;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;text-rendering:optimizeLegibility;}*,*::before,*::after{box-sizing:border-box;}::-webkit-scrollbar{width:8px;height:8px;}::-webkit-scrollbar-thumb{background:",e.color.border,";border-radius:",e.radius.pill,";}::-webkit-scrollbar-thumb:hover{background:",e.color.textDim,";}","")})}function pA(){const{setOpen:e,isInterceptEnabled:t,toggleIntercept:n,isSettingsOpen:r,openSettings:o,startSnipping:i,requestConfirm:s}=un(),{token:a,isTokenValidated:A,isValidating:l,isLoading:c,reloadMappings:d,deleteToken:u}=gn(),{debugRules:f,editRules:h}=Wn(),{globalDelay:p}=tr();if(!A&&(l||a))return Ct(Bt,{children:[xt(_o,{children:xt(bA,{children:xt(mA,{})})}),xt(qa,{})]});if(!a)return Ct(Bt,{children:[xt(_o,{children:Ct(bA,{children:[xt(pa,{}),xt(dA,{})]})}),xt(qa,{})]});const g=r||f.length>0||h.length>0||p.enabled;return Ct(Bt,{children:[Ct(_o,{children:[xt(Oo,{onSnip:i,onReload:d,onOpenSettings:o,onDeleteToken:()=>{s({title:"Delete token?",message:"Are you sure you want to delete token? API interception will stop once the token is removed.",confirmLabel:"Delete",danger:!0,onConfirm:u})},isInterceptEnabled:t,onToggleIntercept:()=>{t?s({title:"Disable interception?",message:"Once disabled, the widget will stop intercepting requests and disappear from the page. Please refresh the page after disabling it. You can re-enable it anytime from the MockForMe settings page via the extension icon in tray or the right-click menu. You can also re-enable it from inside Widget Settings → Whitelisted Hosts.",confirmLabel:"Disable",danger:!0,onConfirm:n}):n()},onClose:()=>e(!1),isSettingsActive:g,isReloading:c,isAuthenticated:!0}),xt(Po,{}),Ct(bA,{children:[xt(da,{}),xt(ga,{}),xt(ka,{}),xt(Ba,{}),xt(Ua,{}),xt(Na,{}),xt(dA,{}),xt(yA,{})]})]}),xt(qa,{})]})}var gA={name:"3kwpv8",styles:"flex:1;min-height:0;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:14px;padding:24px;text-align:center"};function mA(){const e=Ut();return Ct("div",{css:gA,children:[xt(yi,{size:26,color:e.color.primary,label:"Validating token"}),xt("div",{css:gt("font-size:",e.typography.fontSizeBase,";font-weight:600;color:",e.color.text,";",""),children:"Validating your token…"}),xt("div",{css:gt("font-size:12px;color:",e.color.textDim,";max-width:260px;line-height:1.5;",""),children:"Hang tight — we're verifying your session before loading the widget."})]})}function yA(){const{invalidatedMessage:e,acknowledgeInvalidation:t}=gn(),n=Ut();return null==e?null:xt(ri,{open:!0,hideClose:!0,title:"Token no longer valid",leadingDot:"live",onClose:()=>{},footer:xt("button",{type:"button",onClick:t,css:gt("appearance:none;border:none;border-radius:",n.radius.sm,";background:",n.color.primary,";color:#fff;font-size:",n.typography.fontSizeBase,";font-weight:",n.typography.fontWeightBold,";padding:8px 20px;cursor:pointer;&:hover{background:",n.color.primaryHover,";}",""),children:"OK"}),children:xt("p",{css:gt("margin:0;font-size:",n.typography.fontSizeBase,";line-height:1.5;color:",n.color.text,";",""),children:e})})}var wA={name:"4oq8x6",styles:"position:absolute;inset:0;pointer-events:none;z-index:1500;&:empty{display:none;}&>*{pointer-events:auto;}"},kA={name:"p72qif",styles:"flex:1;min-height:0;position:relative;display:flex;flex-direction:column;overflow:hidden"};function bA({children:e}){const{fullscreenSlotRef:t}=un();return Ct("div",{css:kA,children:[e,xt("div",{ref:t,"data-mfm-fullscreen-slot":!0,css:wA})]})}class vA extends u.Component{constructor(){super(...arguments),o(this,"state",{hasError:!1})}static getDerivedStateFromError(){return Or(),{hasError:!0}}componentDidCatch(e,t){try{this.props.onError(e,t)}catch{}}render(){return this.state.hasError?null:this.props.children}}const BA=(()=>{try{const e="file:///Users/sushilkumar/mockforme/shared/mockforme_widget/dist/chunks/widget-B8TRg0gv.js",t=e.lastIndexOf("/");return t>0?e.slice(0,t+1):e}catch{return""}})();function xA(e,t){return!(!BA||!function(){try{const e=typeof document<"u"&&(document.baseURI||document.location&&document.location.href)||"";return!!e&&!e.startsWith(BA)}catch{return!1}}()||!(e&&e.startsWith(BA)||t&&-1!==t.indexOf(BA)))}let CA=null;const EA="data-mfm-mount";function FA(e){return e||document.getElementById("mfm-root")||(document.body?document.body:null)}function SA(e,t){let n;"mfm-root"===e.id?n=e:(n=document.createElement("div"),n.id="mfm-root",e.appendChild(n)),n.style.cssText="all: initial; display: block;",function(e){try{rn.init(),rn.setClientType(e);const t=tn().read("MFM_TOKEN");t&&rn.setToken(t)}catch{}}(t.clientType);const r=["click","dblclick","mousedown","mouseup","mousemove","pointerdown","pointerup","pointermove","contextmenu","wheel","touchstart","touchend","touchmove"],o=e=>e.stopPropagation();for(const e of r){const t="wheel"===e||"touchstart"===e||"touchend"===e||"touchmove"===e;n.addEventListener(e,o,{passive:t})}const i=n.shadowRoot??n.attachShadow({mode:"open"});let s=i.querySelector(`[${EA}]`);s||(s=document.createElement("div"),s.setAttribute(EA,""),i.appendChild(s));const a=Ue({key:"mfm",container:i,prepend:!0}),A={run:()=>{}},l=F.createRoot(s);l.render(u.createElement(u.StrictMode,null,u.createElement(rt,{value:a},u.createElement(vA,{onError:e=>{setTimeout(()=>A.run(e),0)}},u.createElement(fA,{clientType:t.clientType,version:t.version})))));const c=e=>{const t=e.error;xA(e.filename,t?.stack)&&(Or(),e.preventDefault(),A.run(e.error))},d=e=>{const t=e.reason;xA(void 0,t?.stack??(t?String(t):void 0))&&(Or(),e.preventDefault(),A.run(e.reason))};window.addEventListener("error",c),window.addEventListener("unhandledrejection",d);const f=console.error;console.error=function(...e){if(!(jr>0)){if(BA)for(let t=0;t<e.length;t++){const n=e[t];if(-1!==((n&&"object"==typeof n&&"stack"in n?String(n.stack??""):"")||String(n)).indexOf(BA))return}f.apply(console,e)}};let h=!1,p=null;const g=e=>{if(!h){if(h=!0,window.removeEventListener("error",c),window.removeEventListener("unhandledrejection",d),console.error!==f)try{console.error=f}catch{}try{l.unmount()}catch{}try{n.remove()}catch{}CA=null;try{if(void 0!==e){const t=e,n=t&&"string"==typeof t.message?t.message:"string"==typeof e?e:String(e),r=t&&"string"==typeof t.stack?t.stack:"";Vr("widget_load_failed",{errorName:t&&"string"==typeof t.name?t.name:"Error",errorMessage:n,errorStack:r.slice(0,4e3),userAgent:typeof navigator<"u"?navigator.userAgent:"",url:typeof location<"u"?location.href:""})}else rn.track("widget_destroyed");Gr()}catch{}if(void 0!==e)try{p=function(){if(typeof document>"u"||!document.body)return{dismiss(){}};const e=document.createElement("div");e.id="mfm-error-snackbar",e.style.cssText=["all: initial","position: fixed","right: 16px","bottom: 16px","z-index: 2147483646"].join(";"),document.body.appendChild(e);const t=e.attachShadow({mode:"closed"}),n=document.createElement("div");n.style.cssText=["box-sizing: border-box","display: flex","align-items: center","gap: 10px","min-width: 280px","max-width: 380px","padding: 10px 12px","background: #1f2937","color: #f9fafb","border: 1px solid #374151","border-radius: 8px","box-shadow: 0 8px 24px rgba(0,0,0,0.25)",'font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',"font-size: 13px","line-height: 1.4"].join(";");const r=document.createElement("div");r.style.cssText=["flex: 1 1 auto","min-width: 0"].join(";");const o=document.createElement("div");o.textContent="MockForMe is unable to load.",o.style.cssText="font-weight: 500";const i=document.createElement("div");i.textContent="The issue has been reported.",i.style.cssText=["margin-top: 2px","color: #9ca3af","font-size: 12px"].join(";"),r.appendChild(o),r.appendChild(i);const s=document.createElement("button");s.type="button",s.setAttribute("aria-label","Dismiss"),s.textContent="×",s.style.cssText=["flex: 0 0 auto","width: 24px","height: 24px","padding: 0","background: transparent","color: #9ca3af","border: 0","border-radius: 4px","cursor: pointer","font-size: 18px","line-height: 1"].join(";");let a=!1;const A=()=>{if(!a){a=!0;try{e.remove()}catch{}}};return s.addEventListener("click",A),n.appendChild(r),n.appendChild(s),t.appendChild(n),{dismiss:A}}()}catch{}}};return A.run=g,{destroy(){if(g(),p){try{p.dismiss()}catch{}p=null}}}}const QA={run(e,t={}){if(CA)return CA;if(typeof document<"u"&&"loading"===document.readyState){let n=!1;const r=()=>{if(n)return;const r=FA(e);r&&(CA=SA(r,t))};return document.addEventListener("DOMContentLoaded",r,{once:!0}),{destroy(){n=!0,document.removeEventListener("DOMContentLoaded",r),CA&&CA.destroy()}}}const n=FA(e);return n?(CA=SA(n,t),CA):(console.warn("[MockForMeWidget] no mount target available"),{destroy(){}})}};typeof window<"u"&&(window.MockForMeWidget=QA),n.d(t,["M",0,QA])},435(e,t,n){n.d(t,{MockForMeWidget:()=>r.M});var r=n(411)}};const t={};function n(r){const o=t[r];if(void 0!==o)return o.exports;const i=t[r]={exports:{}};return e[r](i,i.exports,n),i.exports}n.d=(e,t)=>{if(Array.isArray(t))for(var r=0;r<t.length;){var o=t[r++],i=t[r++];n.o(e,o)?0===i&&r++:0===i?Object.defineProperty(e,o,{enumerable:!0,value:t[r++]}):Object.defineProperty(e,o,{enumerable:!0,get:i})}else 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=>{Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};const r=()=>"undefined"!=typeof process&&null!=process.versions?.node,o=e=>{try{return e?e.toLowerCase():e}catch(e){return console.log(e),null}},i=(e,t)=>{const n=e.split("/"),r=t.split("/");if(n.length!==r.length)return!1;for(let e=0;e<n.length;e++){const t=n[e];if(t!==r[e]&&":any"!==t&&":"!==t.charAt(0))return!1}return!0},s=new Map;let a=[];function A(e){a=e}function l(){return a}function c(e,t="get"){const n=e=>e.startsWith("/")?e:`/${e}`,r=n(e),A=function(e,t){if(0===s.size)return null;for(const n of s.values())for(const r of n){if(o(r.apiMethod)!==o(t))continue;const n=r.apiEndpoint.startsWith("/")?r.apiEndpoint:`/${r.apiEndpoint}`;if(n===e||i(n,e)){const t={url:e,method:r.apiMethod,_ack:r._ack||null};return r._ri_&&(t._ri_=r._ri_),t}}return null}(r,t);if(A)return console.log(`[MockForMe] Flow Mock Match: ${t} ${e} -> ${A.url}`),A;for(const s of a)if(o(s.apiMethod)===o(t)){const o=n(s.apiEndpoint);if(o===r||i(o,r)){console.log(`[MockForMe] Match Found: ${t} ${e} -> ${s.apiEndpoint}`);const n={url:e,method:s.apiMethod,apiEndpoint:s.apiEndpoint,_ack:s._ack||null};return s._ri_&&(n._ri_=s._ri_),n}}return null}const d="JAVASCRIPT",u="mockforme",f="https://api.mockforme.com",h=`${f}/mockforme`,p=`${f}/gateway/3f4eae522b`;let g=null,m=null,y=null,w=[];function k({_o:e,mk:t,_mck:n,_rules:r}){g=e,m=t,y=n,w=r}function b(){return w}function v(){return`${h}/${g}/${m}`}function B(){return y}function x(e,t,n,r){fetch(p,{method:"GET",headers:{[u]:e,mfmver:"14.5.1","x-mfm-adaptor":t}}).then(e=>{if(!e.ok)throw e;return e.json()}).then(e=>{if(e){const{di:t,iv:r,_o:o,_mck:i,mk:s,r:a}=e,l=function({di:e,iv:t},n){var r;const o=function(e,t){const n=t.length;return e.split("").map((e,r)=>String.fromCharCode(e.charCodeAt(0)^t.charCodeAt(r%n))).join("")}((r=e,"undefined"!=typeof Buffer?Buffer.from(r,"base64").toString("utf8"):decodeURIComponent(escape(atob(r)))),n+t);return JSON.parse(o)}({di:t,iv:r},o);k({_o:o,mk:s,_mck:i,_rules:a}),l&&(A(l),n(l,{_o:o,mk:s,_mck:i,_rules:a}))}}).catch(e=>{console.error("Error in loading mocked APIs:",e),r(e)})}const C=`${f}/mockforme/mfm_op_3f4eae522b/manage`,E=e=>({[u]:e,mfmver:"14.5.1","Content-Type":"application/json"}),F=async e=>{let t=null;try{t=await e.json()}catch(e){}return{ok:!(!e.ok||!t||!0!==t.status&&"success"!==t.status&&1!==t.status),message:t&&t.message||(e.ok?"":`Request failed (${e.status})`),result:t?t.result:null}},S="MFM_INTERCEPTOR_RULES";let Q=[];const U=new Map;function T(){try{if("undefined"==typeof localStorage)return[];const e=localStorage.getItem(S);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>e&&e.enabled):[]}catch(e){return[]}}function I(e){Q=Array.isArray(e)?e.filter(e=>e&&e.enabled):[]}function _(e,t){if(!e||!t)return null;if(!Q.length&&(Q=T(),!Q.length))return null;const n=String(e).toUpperCase();return Q.find(e=>{if(!e.enabled||String(e.method).toUpperCase()!==n)return!1;if("PATH"===e.matchType)try{return new URL(e.url,"http://localhost").pathname===new URL(t,"http://localhost").pathname}catch(n){return e.url===t}return e.url===t})||null}function M({requestId:e,ruleId:t,request:n,response:r,timeoutMs:o=3e5}){return new Promise(i=>{const s=setTimeout(()=>{U.has(e)&&(U.delete(e),i({requestId:e,simulateTimeout:!1,delayMs:0,statusCode:r?.statusCode??200,headers:r?.headers||{},body:r?.body}))},o);U.set(e,{resolve:i,timer:s});try{"undefined"!=typeof window&&window.postMessage({type:"MFM_DEBUG_INTERCEPT_REQ",payload:{requestId:e,ruleId:t,request:n,response:r,timestamp:Date.now()}},"*")}catch(t){clearTimeout(s),U.delete(e),i({requestId:e,simulateTimeout:!1,delayMs:0,statusCode:r?.statusCode??200,headers:r?.headers||{},body:r?.body})}})}Q=T(),"undefined"!=typeof document&&"function"==typeof document.addEventListener&&document.addEventListener("mfm:rule-sync",e=>{const t=e&&e.detail;t&&"debugger"===t.kind&&I(t.payload?.rules||[])}),"undefined"!=typeof window&&"function"==typeof window.addEventListener&&window.addEventListener("storage",e=>{e.key===S&&(Q=T())});const H="MFM_REQUEST_EDITOR_RULES";let L=[];const D=new Map;function N(){try{if("undefined"==typeof localStorage)return[];const e=localStorage.getItem(H);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>e&&e.enabled):[]}catch(e){return[]}}function j(e){L=Array.isArray(e)?e.filter(e=>e&&e.enabled):[]}function O(e,t){if(!e||!t)return null;if(!L.length&&(L=N(),!L.length))return null;const n=String(e).toUpperCase();return L.find(e=>{if(!e.enabled||String(e.method).toUpperCase()!==n)return!1;if("PATH"===e.matchType)try{return new URL(e.url,"http://localhost").pathname===new URL(t,"http://localhost").pathname}catch(n){return e.url===t}return e.url===t})||null}function R(e,t,n){const r={};return Object.entries(t?.headers||{}).forEach(([e,t])=>{r[e]=String(t??"")}),{requestId:e,cancel:!1,headers:r,queryParams:n||{},body:"string"==typeof t?.body?t.body:null}}function P({requestId:e,ruleId:t,request:n,queryParams:r,timeoutMs:o=3e5}){return new Promise(i=>{const s=setTimeout(()=>{D.has(e)&&(D.delete(e),i(R(e,n,r)))},o);D.set(e,{resolve:i,timer:s});try{"undefined"!=typeof window&&window.postMessage({type:"MFM_REQUEST_EDIT_REQ",payload:{requestId:e,ruleId:t,request:n,queryParams:r,timestamp:Date.now()}},"*")}catch(t){clearTimeout(s),D.delete(e),i(R(e,n,r))}})}L=N(),"undefined"!=typeof document&&"function"==typeof document.addEventListener&&document.addEventListener("mfm:rule-sync",e=>{const t=e&&e.detail;t&&"editor"===t.kind&&j(t.payload?.rules||[])}),"undefined"!=typeof window&&"function"==typeof window.addEventListener&&window.addEventListener("storage",e=>{e.key===H&&(L=N())});const z="MFM_GLOBAL_DELAY";let K={enabled:!1,seconds:0},V=0;function G(){try{if("undefined"==typeof localStorage)return{enabled:!1,seconds:0};const e=localStorage.getItem(z);if(!e)return{enabled:!1,seconds:0};const t=JSON.parse(e);return t&&"object"==typeof t?{enabled:!!t.enabled&&Number.isFinite(t.seconds)&&t.seconds>0,seconds:Number.isFinite(t.seconds)?Number(t.seconds):0}:{enabled:!1,seconds:0}}catch(e){return{enabled:!1,seconds:0}}}function q(){const e=Date.now();return e-V>500&&(K=G(),V=e),K.enabled&&K.seconds>0?Math.round(1e3*K.seconds):0}var J,W;K=G(),V=Date.now(),"undefined"!=typeof window&&"function"==typeof window.addEventListener&&window.addEventListener("storage",e=>{e.key===z&&(K=G(),V=Date.now())}),function(e){e[e.NONE=0]="NONE",e[e.INFO=1]="INFO",e[e.WARN=2]="WARN",e[e.ERROR=3]="ERROR"}(J||(J={})),function(e){e.MFM_REQ_MAPPINGS="MFM_REQ_MAPPINGS",e.MFM_REQ_SAVED_MAPPINGS="MFM_REQ_SAVED_MAPPINGS",e.MFM_DEL_CLIENT_TOKEN="MFM_DEL_CLIENT_TOKEN",e.MFM_SUBMIT_TOKEN="MFM_SUBMIT_TOKEN",e.MFM_TOGGLE_INTERCEPTION="MFM_TOGGLE_INTERCEPTION",e.MFM_REQ_ALL_APIS="MFM_REQ_ALL_APIS",e.MFM_TOGGLE_API="MFM_TOGGLE_API",e.MFM_DEBUG_RULES_UPDATE="MFM_DEBUG_RULES_UPDATE",e.MFM_DEBUG_INTERCEPT_RES="MFM_DEBUG_INTERCEPT_RES",e.MFM_REQUEST_EDIT_RULES_UPDATE="MFM_REQUEST_EDIT_RULES_UPDATE",e.MFM_REQUEST_EDIT_ACK="MFM_REQUEST_EDIT_ACK",e.MFM_REQUEST_EDIT_RES="MFM_REQUEST_EDIT_RES",e.MFM_GLOBAL_DELAY_UPDATE="MFM_GLOBAL_DELAY_UPDATE",e.MFM_FLOW_MOCK_SET="MFM_FLOW_MOCK_SET",e.MFM_FLOW_MOCK_CLEAR="MFM_FLOW_MOCK_CLEAR",e.MFM_PING_SCREENSHOT="MFM_PING_SCREENSHOT",e.MFM_REQUEST_SCREENSHOT="MFM_REQUEST_SCREENSHOT",e.MFM_RES_MAPPINGS="MFM_RES_MAPPINGS",e.MFM_RES_ALL_APIS="MFM_RES_ALL_APIS",e.MFM_TOGGLE_API_RESULT="MFM_TOGGLE_API_RESULT",e.MFM_REQ="MFM_REQ",e.MFM_RES="MFM_RES",e.MFM_TOKEN_ERROR="MFM_TOKEN_ERROR",e.MFM_TOKEN_API_FAILED="MFM_TOKEN_API_FAILED",e.MFM_TOKEN_INVALIDATED="MFM_TOKEN_INVALIDATED",e.MFM_MOCK_DISABLED="MFM_MOCK_DISABLED",e.MFM_TOKEN_CLEARED="MFM_TOKEN_CLEARED",e.MFM_DEBUG_INTERCEPT_REQ="MFM_DEBUG_INTERCEPT_REQ",e.MFM_REQUEST_EDIT_REQ="MFM_REQUEST_EDIT_REQ",e.MFM_PONG_SCREENSHOT="MFM_PONG_SCREENSHOT",e.MFM_SCREENSHOT_RESULT="MFM_SCREENSHOT_RESULT",e.MFM_SCREENSHOT_ERROR="MFM_SCREENSHOT_ERROR",e.MFM_LOG_INFO="MFM_LOG_INFO",e.MFM_LOG_WARN="MFM_LOG_WARN",e.MFM_LOG_ERROR="MFM_LOG_ERROR"}(W||(W={}));const $="MFM_TOKEN",X="MFM_CACHED_MAPPINGS",Y="MFM_INTERCEPTION_ENABLED",Z=new class{constructor(e={}){r()||(this.token=e.token||("undefined"!=typeof localStorage?localStorage.getItem($):null),this.isAuthenticated=!!this.token,this.onAuthSuccess=e.onAuthSuccess||(()=>{}),this.mappings=e.mappings||[],this.rules=e.rules||[],this.widgetKey=e.widgetKey||null,this.tokenInvalidated=!1,this.setupMessageListeners())}get interceptionEnabled(){if(this.tokenInvalidated)return!1;if("undefined"==typeof localStorage)return!1!==this._interceptionEnabled;const e=localStorage.getItem(Y);return"false"!==e&&("true"===e||!1!==this._interceptionEnabled)}set interceptionEnabled(e){const t=!!e;this._interceptionEnabled=t,"undefined"!=typeof localStorage&&localStorage.setItem(Y,t?"true":"false")}setupMessageListeners(){"undefined"!=typeof window&&window.addEventListener("message",e=>{const{type:t,payload:n}=e.data||{};var r,o;if(t&&"string"==typeof t&&t.startsWith("MFM_"))switch(t){case W.MFM_REQ_MAPPINGS:this.refreshMappings();break;case W.MFM_REQ_SAVED_MAPPINGS:this.handleReqSavedMappings();break;case W.MFM_SUBMIT_TOKEN:this.handleTokenSubmission(n?.token);break;case W.MFM_DEL_CLIENT_TOKEN:this.handleTokenDeletion();break;case W.MFM_TOGGLE_INTERCEPTION:this.interceptionEnabled=!!n?.enabled;break;case W.MFM_REQ_ALL_APIS:this.handleReqAllApis();break;case W.MFM_TOGGLE_API:this.handleToggleApi(n?.apiId,n?.enabled);break;case W.MFM_DEBUG_RULES_UPDATE:I(n?.rules||[]);break;case W.MFM_DEBUG_INTERCEPT_RES:!function(e){if(!e||!e.requestId)return;const t=U.get(e.requestId);t&&(clearTimeout(t.timer),U.delete(e.requestId),t.resolve(e))}(n);break;case W.MFM_REQUEST_EDIT_RULES_UPDATE:j(n?.rules||[]);break;case W.MFM_REQUEST_EDIT_RES:!function(e){if(!e||!e.requestId)return;const t=D.get(e.requestId);t&&(clearTimeout(t.timer),D.delete(e.requestId),t.resolve(e))}(n);break;case W.MFM_GLOBAL_DELAY_UPDATE:!function(e){if(!e||"object"!=typeof e)return K={enabled:!1,seconds:0},void(V=Date.now());K={enabled:!!e.enabled&&Number.isFinite(e.seconds)&&e.seconds>0,seconds:Number.isFinite(e.seconds)?Number(e.seconds):0},V=Date.now()}(n);break;case W.MFM_FLOW_MOCK_SET:r=n?.runId,o=n?.apis||[],r&&s.set(String(r),Array.isArray(o)?o:[]);break;case W.MFM_FLOW_MOCK_CLEAR:!function(e){e&&s.delete(String(e))}(n?.runId)}})}init(){if("undefined"!=typeof document&&this.checkVisibility()&&("undefined"!=typeof window&&Promise.resolve().then(n.bind(n,435)).then(e=>{const t=window.MockForMeWidget||e.MockForMeWidget;t&&"function"==typeof t.run&&(t.run(null,{clientType:"NPM",version:"14.5.1"}),this.syncInterceptionToggleToWidget())}).catch(e=>{console.error("[MockForMe] Failed to load mfm-widget",e)}),console.log("[MockForMe] Widget initialized"),this.token)){const e=this.getSavedMappings(this.token,"JAVASCRIPT");e&&(this.mappings=e.mappings||[],this.rules=e.meta?._rules||[],this.onAuthSuccess(this.token,this.mappings,e.meta),this.updateMappings(this.mappings,e.meta))}}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($,e),this.refreshMappings())}handleTokenDeletion(){this.token=null,this.isAuthenticated=!1,"undefined"!=typeof localStorage&&(localStorage.removeItem($),localStorage.removeItem(X)),this.mappings=[],this.rules=[],this.onAuthSuccess(null,[],{_rules:[]}),this.updateMappings([],{_rules:[]})}handleReqAllApis(){this.token?(async e=>{if(!e)return{ok:!1,message:"Missing token",result:[]};const t=await fetch(`${C}/apis`,{method:"GET",headers:E(e)});return F(t)})(this.token).then(e=>{const t=e.ok&&Array.isArray(e.result)?e.result:[];this.sendMessage(W.MFM_RES_ALL_APIS,{apis:t})}).catch(()=>this.sendMessage(W.MFM_RES_ALL_APIS,{apis:[]})):this.sendMessage(W.MFM_RES_ALL_APIS,{apis:[]})}handleToggleApi(e,t){this.token&&e?(async(e,t,n)=>{if(!e)return{ok:!1,message:"Missing token",result:null};const r=await fetch(`${C}/api/${t}/toggle-state`,{method:"PUT",headers:E(e),body:JSON.stringify({enabled:!!n})});return F(r)})(this.token,e,t).then(n=>{this.sendMessage(W.MFM_TOGGLE_API_RESULT,{apiId:e,enabled:!!t,ok:!!n.ok,message:n.message||""}),n.ok&&this.refreshMappings()}).catch(()=>this.sendMessage(W.MFM_TOGGLE_API_RESULT,{apiId:e,enabled:!!t,ok:!1,message:"Failed to update the mock"})):this.sendMessage(W.MFM_TOGGLE_API_RESULT,{apiId:e,enabled:!!t,ok:!1,message:"Missing token"})}refreshMappings(){this.token&&x(this.token,"JAVASCRIPT",(e,t)=>{this.mappings=e||[],this.rules=t?._rules||[],this.tokenInvalidated=!1,this.saveMappings(e,t,this.token,"JAVASCRIPT"),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.token=null,this.isAuthenticated=!1,"undefined"!=typeof localStorage&&(localStorage.removeItem($),localStorage.removeItem(X)),this.mappings=[],this.rules=[],this.onAuthSuccess(null,[],{_rules:[]}),this.sendMessage(W.MFM_TOKEN_ERROR,{message:"Unauthorized: Invalid token"})):this.sendMessage(W.MFM_TOKEN_API_FAILED,{message:"Unable to reach the mappings service. Please try again."})})}saveMappings(e,t,n=this.token,r="JAVASCRIPT"){if("undefined"!=typeof localStorage)try{localStorage.setItem(X,JSON.stringify({token:n,adaptor:r,mappings:e,meta:t,timestamp:Date.now()}))}catch(e){console.error("[MockForMe] Failed to save mappings to storage",e)}}handleReqSavedMappings(){const e=this.getSavedMappings(this.token,"JAVASCRIPT");e?(this.mappings=e.mappings||[],this.rules=e.meta?._rules||[],this.onAuthSuccess(this.token,this.mappings,e.meta),this.updateMappings(this.mappings,e.meta)):this.updateMappings([],{_rules:[]})}getSavedMappings(e=this.token,t="JAVASCRIPT"){if("undefined"==typeof localStorage)return null;try{const n=localStorage.getItem(X);if(!n)return null;const r=JSON.parse(n);return r?.token&&e&&r.token!==e||r?.adaptor&&t&&r.adaptor!==t?null:r}catch(e){return null}}syncInterceptionToggleToWidget(){this.sendMessage(W.MFM_TOGGLE_INTERCEPTION,{enabled:this.interceptionEnabled})}updateMappings(e,t){this.sendMessage(W.MFM_RES_MAPPINGS,{apis:e.map(e=>({method:e.apiMethod,url:e.apiEndpoint})),rules:(t?._rules||[]).map(e=>{const t="object"==typeof e.rule&&null!==e.rule?e.rule:{},n={...e,...t},r=n.timingAction||{},o=r.activeAction||"MODIFY";let i="MODIFY";"delay"===o?i="DELAY":"delay_and_timeout"===o?i="TIMEOUT":"delay_and_redirect"===o&&(i="REDIRECT");const s={ruleName:n.ruleName||n._id||"Unnamed Rule",type:i,conditions:n.conditions||[],modificationActions:n.modificationActions||{}};return("MODIFY"!==i||r.activeAction)&&(s.timingAction=r),s}),token:this.token})}handleMockDisabled({apiMethod:e,apiEndpoint:t}={}){if(!t)return;const n=function(e,t){if(!t)return!1;const n=a.length,r=o(e||"");return a=a.filter(e=>!(o(e.apiMethod)===r&&e.apiEndpoint===t)),a.length!==n}(e,t),r=this.mappings.length;if(this.mappings=(this.mappings||[]).filter(n=>!((n.apiMethod||"").toLowerCase()===(e||"").toLowerCase()&&n.apiEndpoint===t)),!n&&this.mappings.length===r)return;this.updateMappings(this.mappings,{_rules:this.rules});const i=`${(e||"").toUpperCase()} ${t}`.trim();this.sendMessage(W.MFM_MOCK_DISABLED,{method:e,url:t,message:`${i} mock was disabled and has been removed.`})}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(": "),r=n.shift();r&&(t[r]=n.join(": "))}):t="function"==typeof e.entries?Object.fromEntries(e.entries()):e,Object.keys(t).reduce((e,n)=>(e[n.toLowerCase()]=t[n],e),{})};let r,o,i;if(void 0===t.status||null===t.status)r=void 0;else if("number"==typeof t.status)r=t.status;else{const e=Number(t.status);Number.isFinite(e)?r=e:(r=0,o=String(t.status))}t.aborted||"Aborted"===t.status?i="aborted":t.timeout||"Timeout"===t.status?i="timeout":"Cancelled"===t.status?i="cancelled":(t.error||"Error"===o)&&(i="error");const s=t.pending&&void 0===t.status?null:{statusCode:r,headers:n(t.responseHeaders),body:t.responseBody,endTime:(new Date).toISOString(),...o?{statusText:o}:{},...i?{errorReason:i,failed:!0}:{}},a={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:s,rule:t.rule,timestamp:t.pending&&t.startTime||Date.now(),...Number.isFinite(t.duration)?{duration:t.duration}:{}};if(t.pending)this.sendMessage(W.MFM_REQ,a);else if(this.sendMessage(W.MFM_RES,a),!this.tokenInvalidated&&a.response&&a.response.headers){const e=a.response.headers["mfm-invalid-token"];if("true"===e||!0===e){console.warn("[MockForMe] Invalid token detected from response headers"),this.tokenInvalidated=!0;let e="Your token is no longer valid. Please enter a valid token.";try{const n=t.responseBody,r="string"==typeof n?JSON.parse(n):n;r&&"string"==typeof r.message&&r.message.trim()&&(e=r.message.trim())}catch(e){}this.sendMessage(W.MFM_TOKEN_INVALIDATED,{message:e})}}}sendMessage(e,t){"undefined"!=typeof window&&window.postMessage({type:e,payload:t},"*")}};function ee(e){const t=function(e,t){if(e)return"function"==typeof e.get?e.get(t):"string"==typeof e?((e,t)=>{const n=t.toLowerCase();return e.split(/\r?\n/).map(e=>{const t=e.indexOf(":");return t<0?null:[e.slice(0,t).trim().toLowerCase(),e.slice(t+1).trim()]}).filter(Boolean).find(([e])=>e===n)?.[1]})(e,t):((e,t)=>{const n=t.toLowerCase();for(const t of Object.keys(e||{}))if(t.toLowerCase()===n)return e[t]})(e,t)}(e,"mfm-mock-disabled");return"true"===t||!0===t}class te{static match(e,t){if(!Array.isArray(t)||0===t.length)return!1;const{url:n,headers:r,queryParams:o,body:i}=e,s="undefined"!=typeof window?window.location.origin:globalThis.location?.origin||"http://localhost";for(const e of t){let t="";const{type:a,key:A,operator:l,value:c}=e;switch(a){case"URL":try{t=new URL(n,s).pathname}catch{t=n}break;case"QUERY_PARAM":if(o&&void 0!==o[A])t=String(o[A]);else try{t=new URL(n,s).searchParams.get(A)||""}catch{t=""}break;case"REQUEST_BODY":if(A){if("object"==typeof i&&null!==i)t=void 0!==i[A]?String(i[A]):"";else if("string"==typeof i)try{const e=JSON.parse(i);t=void 0!==e[A]?String(e[A]):""}catch{t=""}}else t="object"==typeof i?JSON.stringify(i):String(i||"");break;case"REQUEST_HEADER":if(A){const e=A?.toLowerCase();if(t="",r){const n=Object.keys(r).find(t=>t.toLowerCase()===e);t=n?String(r[n]):""}}else t=JSON.stringify(r||{});break;default:return!1}if(!this.evaluate(t,l,c))return!1}return!0}static evaluate(e,t,n){const r=t?.toLowerCase(),o=String(e),i=String(n);switch(r){case"contains":return o.includes(i);case"equal":case"equals":return o===i;case"regexp":try{let e=i;if(e.startsWith("/")&&e.lastIndexOf("/")>0){const t=e.lastIndexOf("/"),n=e.slice(1,t),r=e.slice(t+1);return new RegExp(n,r).test(o)}return new RegExp(e).test(o)}catch{return!1}default:return!1}}}class ne{static async apply(e){if(!e||!e.activeAction)return{type:"passThrough",delay:0};const{activeAction:t,actions:n}=e,r=n?.[t];if(!r)return{type:"passThrough",delay:0};const o={type:"passThrough",delay:0},i=Number(r.value||0);switch(t){case"delay":o.delay=i,o.delay>0&&await new Promise(e=>setTimeout(e,1e3*o.delay));break;case"redirect":case"delay_and_redirect":o.type="redirect",o.delay=i,o.redirectUrl=r.redirectUrl,o.delay>0&&await new Promise(e=>setTimeout(e,1e3*o.delay));break;case"delay_and_timeout":o.type="timeout",o.delay=i,o.delay>0&&await new Promise(e=>setTimeout(e,1e3*o.delay))}return o}}class re{static applyRequestModifications(e,t){if(!t)return e;let{url:n,method:r,headers:o,queryParams:i,body:s}={...e};o&&(o={...o}),i&&(i={...i});const{modifyQueryParams:a,modifyRequestBody:A,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),i&&delete i[t]}),Array.isArray(a.add)&&a.add.forEach(({key:t,value:n})=>{e.searchParams.set(t,n),i&&(i[t]=n)}),n=e.toString()}catch(e){console.error("[MockForMe] Failed to modify query params",e)}l?.enabled&&(o={...o},Array.isArray(l.remove)&&l.remove.forEach(e=>{const t=e.toLowerCase(),n=Object.keys(o).find(e=>e.toLowerCase()===t);n&&delete o[n]}),Array.isArray(l.add)&&l.add.forEach(({key:e,value:t})=>{o[e]=t}));const c=String(r||"GET").toUpperCase(),d="GET"===c||"HEAD"===c;if(A?.enabled&&!d)try{let e=null;if("string"==typeof s)try{e=JSON.parse(s)}catch{e={}}else if("object"==typeof s&&null!==s)try{e=JSON.parse(JSON.stringify(s))}catch{e={...s}}else(Array.isArray(A.add)&&A.add.length>0||Array.isArray(A.update)&&A.update.length>0)&&(e={});e&&(Array.isArray(A.remove)&&A.remove.forEach(t=>delete e[t]),Array.isArray(A.add)&&A.add.forEach(({key:t,value:n})=>e[t]=n),Array.isArray(A.update)&&A.update.forEach(({key:t,value:n})=>e[t]=n),s=JSON.stringify(e))}catch(e){console.error("[MockForMe] Failed to modify request body",e)}return{...e,url:n,headers:o,queryParams:i,body:s}}static applyResponseModifications(e,t){if(!t?.modifyResponseHeaders?.enabled)return e;const{modifyResponseHeaders:n}=t,r={...e};return Array.isArray(n.remove)&&n.remove.forEach(e=>{const t=e.toLowerCase(),n=Object.keys(r).find(e=>e.toLowerCase()===t);n&&delete r[n]}),Array.isArray(n.add)&&n.add.forEach(({key:e,value:t})=>{r[e]=t}),r}}class oe{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)&&te.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,r=re.applyRequestModifications(t,n.modificationActions);return{...await ne.apply(n.timingAction),modifiedRequest:r,rule:n}}static applyResponseModifications(e,t){return re.applyResponseModifications(e,t)}}class ie{static apply({target:e=("undefined"!=typeof window?window:globalThis),originalFetch:t=e.fetch,ruleProvider:n=()=>[],mappingProvider:r=e=>null,onBeforeRequest:o=e=>{},onRuleMatch:i=async(e,t,n,r,o)=>null,onMockMatch:s=async(e,t,n,r,o)=>null,onOtherRequest:a=async(e,t,n,r)=>null,isEnabled:A=()=>!0,shouldBypassRequest:l=()=>!1}){t&&(e.fetch=async function(e,c={}){if(!A())return t(e,c);let d;try{const n="string"==typeof e?e:e.url,r=String(c.method||(e instanceof Request?e.method:"GET")).toUpperCase().trim(),i=Math.random().toString(36).substring(7);if(d={url:n,method:r,headers:c.headers||(e instanceof Request?e.headers:{}),body:c.body||(e instanceof Request?"{binary/stream}":null),requestId:i,queryParams:ie.getQueryParams(n)},l(d))return t(e,c);o(d)}catch(n){return console.warn("[MockForMe] Fetch Interceptor Setup Error:",n),t(e,c)}try{const o=n(),A=oe.match(d,o);if(A){const n=await i(A,d,e,c,t);if(n)return n}const l=r(d);if(l){const n=await s(l,d,e,c,t);if(n)return n}const u=await a(d,e,c,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,c)})}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 se{static apply({target:e=("undefined"!=typeof window?window:{}),OriginalXHR:t=e.XMLHttpRequest,ruleProvider:n=()=>[],mappingProvider:r=e=>null,onBeforeRequest:o=e=>{},onRuleMatch:i=(e,t,n,r)=>{r.call(n.proxy,t.body)},onMockMatch:s=(e,t,n,r)=>{r.call(n.proxy,t.body)},onOtherRequest:a=(e,t,n)=>{n.call(t.proxy,e.body)},isEnabled:A=()=>!0,shouldBypassRequest:l=()=>!1}){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,r={}){if(this._captured)return;this._captured=!0;const o=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}),o("readystatechange"),"Aborted"===e||r.aborted?o("abort"):0===e||"Error"===e||r.error?o("error"):"Timeout"===e||r.timeout?o("timeout"):o("load")}abort(){if(!this._isMocked||"function"!=typeof this._onAbort)return this._xhr.abort();this._onAbort()}open(e,t,n=!0,r=null,o=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,r,o)}setRequestHeader(e,t){return this._headers[e]=t,this._xhr.setRequestHeader(e,t)}send(e){if(!A())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:se.getQueryParams(this._url)};if(l(t))return this._xhr.send(e);o(t);const c=n(),d=oe.match(t,c),u=e=>this._xhr.send(e);if(d)return this._isMocked=!0,i(d,t,this,u);const f=r(t);return f?(this._isMocked=!0,s(f,t,this,u)):(this._isMocked=!1,a(t,this,u))}})}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 ae=[p,"https://api.mockforme.com/mockforme/httpRequestBulkMock/bulk_mock"];function Ae(e){try{const t="undefined"!=typeof window?window.location.origin:"http://localhost",n=new URL(e.url,t);return ae.some(e=>{const r=new URL(e,t);return n.origin===r.origin&&n.pathname===r.pathname})}catch{return!1}}const le=(e,t=null,n=d)=>{if(r())return;let o="string"==typeof e?e:e?.token,i="object"==typeof e?e?.widgetKey:null;if(n===d)try{o&&("undefined"!=typeof localStorage&&(localStorage.removeItem("mockforme-token"),localStorage.setItem("MFM_TOKEN",o)),Z.token=o,Z.isAuthenticated=!0),!o&&Z.token&&(o=Z.token),Z.onAuthSuccess=(e,t,n)=>{A(t),k(n),Z.updateMappings(t,n)},i?Z.setWidgetKey(i):Z.init()}catch(e){console.log("Error in showing mockforme widget",e)}t||={mappings:[],_o:null,mk:null,_mck:null,_rules:[]};const{mappings:s=[],_o:a,mk:f,_mck:h,_rules:p=[]}=t;return A(s),k({_o:a,mk:f,_mck:h,_rules:p}),{run:(e,t=()=>{})=>{if(function(e,t){if("undefined"!=typeof window){if(window._mfm_intercepted)return;window._mfm_intercepted=!0}const n=()=>Z.token||e;ie.apply({isEnabled:()=>Z.interceptionEnabled,shouldBypassRequest:Ae,ruleProvider:()=>b(),mappingProvider:e=>{try{return c(new URL(e.url,window.location.origin).pathname,e.method)}catch{return null}},onRuleMatch:async(e,t,n,r,o)=>{const i=t.requestId||Math.random().toString(36).substring(7),s=Date.now();Z.addRequest("mocked",{...t,requestId:i,pending:!0,startTime:s,rule:e});const a=await oe.apply(e,t),{modifiedRequest:A,type:l,delay:c,redirectUrl:d}=a;if("timeout"!==l&&Z.addRequest("mocked",{...A,requestId:i,pending:!0,startTime:s,rule:e}),"timeout"===l){const t=Date.now()-s;throw Z.addRequest("mocked",{...A,requestId:i,status:"Aborted",pending:!1,duration:t,aborted:!0,rule:e}),new Error("Fetch timed out by rules")}if("redirect"===l&&!d)throw new Error("rules: Redirect missing URL");let u="redirect"===l?d:A.url,f={...r};A.headers&&(f.headers=A.headers),A.body&&(f.body=A.body);let h=null;if("redirect"===l){h=Math.random().toString(36).substring(7);const e={url:d,method:A.method,headers:f.headers||{},body:f.body,requestId:h,queryParams:ie.getQueryParams(d),requestHeaders:f.headers||{},requestBody:f.body,pending:!0,startTime:Date.now()};Z.addRequest("mocked",e)}return o(u,f).then(async e=>{const t=Date.now()-s;let n=Object.fromEntries(e.headers.entries());if(a.rule.modificationActions?.modifyResponseHeaders?.enabled&&(n=oe.applyResponseModifications(n,a.rule.modificationActions)),"redirect"===l&&h){const t=e.clone(),r=t.headers.get("content-type")||"",o=Date.now()-s;try{let i;i=r.includes("application/json")?await t.json():await t.text(),Z.addRequest("mocked",{url:d,method:A.method,requestId:h,status:e.status,pending:!1,duration:o,responseHeaders:n,responseBody:i,requestHeaders:f.headers||{},requestBody:f.body})}catch(t){Z.addRequest("mocked",{url:d,method:A.method,requestId:h,status:e.status,pending:!1,duration:o,responseHeaders:n,requestHeaders:f.headers||{},requestBody:f.body})}}return Z.addRequest("mocked",{...A,requestId:i,status:e.status,pending:!1,duration:t,responseHeaders:n,rule:a.rule}),e}).catch(e=>{const t=Date.now()-s,n="AbortError"===e.name||e.message.includes("aborted");if(Z.addRequest("mocked",{...A,requestId:i,status:n?"Aborted":0,pending:!1,duration:t,rule:a.rule}),"redirect"===l&&h&&Z.addRequest("mocked",{url:d,method:A.method,requestId:h,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,r,o,i,s)=>{const a=r.requestId||Math.random().toString(36).substring(7),A=Date.now();Z.addRequest("mocked",{...r,requestId:a,pending:!0,startTime:A});const l=n(),c=new URL(r.url,window.location.origin).search;let d=`${v()}${e.url}${c}`,f={[u]:l,mfmver:"14.5.1","x-mfm-adaptor":t};const h=B();h&&e._ack&&(f["x-mfm-key"]=`${h}-${e._ack}`),e?._ri_&&(f._ri_=e._ri_);const p=o instanceof Request?o.headers:i.headers,g=new Headers(p||{});Object.entries(f).forEach(([e,t])=>g.set(e,t)),g.set("x-mfm-internal","true");let m=i.body;if(!m&&o instanceof Request){const e=o.clone();"GET"!==e.method&&"HEAD"!==e.method&&(m=await e.text())}const y={method:r.method,headers:g,credentials:o instanceof Request&&o.credentials||i.credentials||"include",mode:o instanceof Request&&o.mode||i.mode||"cors",signal:o instanceof Request&&o.signal||i.signal};return m&&(y.body=m),s(d,y).then(async t=>{const n=t.clone(),o=n.headers.get("content-type")||"",i=Date.now()-A;ee(t.headers)&&Z.handleMockDisabled({apiMethod:e.method,apiEndpoint:e.apiEndpoint});const s=e=>(Z.addRequest("mocked",{...r,requestId:a,status:t.status,responseHeaders:Object.fromEntries(n.headers.entries()),responseBody:e,pending:!1,duration:i}),new Response("string"==typeof e?e:JSON.stringify(e),{status:t.status,headers:n.headers}));return o.includes("application/json")?n.json().then(s):n.text().then(s)}).catch(e=>{const t=Date.now()-A,n=e&&("AbortError"===e.name||String(e.message||"").toLowerCase().includes("abort"));if(Z.addRequest("mocked",{...r,requestId:a,status:n?"Aborted":0,pending:!1,duration:t,aborted:n}),n)throw e;return s(o,i)})},onOtherRequest:async(e,t,n,r)=>{const o=n?.headers||(t instanceof Request?t.headers:{});let i=!1;o instanceof Headers?i="true"===o.get("x-mfm-internal"):"object"==typeof o&&(i="true"===o["x-mfm-internal"]);const s=v();if(e.url.startsWith(s)&&(i=!0),"OPTIONS"===e.method||i)return r(t,n);const a=e.requestId,A=Date.now();Z.addRequest("other",{...e,requestId:a,pending:!0,startTime:A});const l=O(e.method,e.url),c=_(e.method,e.url);let d=t,u=n,f=e;if(l){const t={};try{new URL(e.url,"undefined"!=typeof window?window.location.origin:"http://localhost").searchParams.forEach((e,n)=>{t[n]=e})}catch(e){}const r=await P({requestId:a,ruleId:l.id,request:{method:e.method,url:e.url,headers:e.headers,body:e.body},queryParams:t});if(r.cancel){Z.addRequest("other",{...e,requestId:a,status:"Cancelled",pending:!1,duration:Date.now()-A,error:!0});const t=new Error("Request cancelled by MockForMe request editor");throw t.name="AbortError",t}let o=e.url;try{const t=new URL(e.url,"undefined"!=typeof window?window.location.origin:"http://localhost");[...t.searchParams.keys()].forEach(e=>t.searchParams.delete(e)),Object.entries(r.queryParams||{}).forEach(([e,n])=>{t.searchParams.set(e,String(n??""))}),o="string"==typeof e.url&&e.url.startsWith("/")?`${t.pathname}${t.search}`:t.href}catch(e){}const i=String(e.method||"GET").toUpperCase(),s="GET"!==i&&"HEAD"!==i;u={...n,method:e.method,headers:r.headers||{},body:s?null==r.body?void 0:r.body:void 0},d=o,f={...e,url:o,headers:r.headers||{},body:s?r.body:null}}const h=q();h>0&&await new Promise(e=>setTimeout(e,h));let p=null,g=null;try{p=await r(d,u)}catch(e){g=e}if(c){let t="",n=0,r={};if(p){try{t=await p.clone().text()}catch(e){}n=p.status,r=Object.fromEntries(p.headers.entries())}else g&&(t=g.message||"Network error",n=0);const o=await M({requestId:a,ruleId:c.id,request:{method:f.method,url:f.url,headers:f.headers,body:f.body},response:{statusCode:n,headers:r,body:t}});if(o.simulateTimeout){Z.addRequest("other",{...e,requestId:a,status:"Timeout",responseHeaders:{},pending:!1,duration:Date.now()-A,timeout:!0});const t=new Error("Network request failed (simulated by MockForMe debugger)");throw t.name="AbortError",t}o.delayMs>0&&await new Promise(e=>setTimeout(e,o.delayMs));const i=Number(o.statusCode),s=Number.isFinite(i)&&i>=200&&i<=599?i:n>=200?n:200,l=o.headers&&"object"==typeof o.headers?o.headers:r,d="string"==typeof o.body?o.body:null==o.body?"":JSON.stringify(o.body);Z.addRequest("other",{...e,requestId:a,status:s,responseHeaders:l,responseBody:d,pending:!1,duration:Date.now()-A});const u={};return Object.entries(l).forEach(([e,t])=>{const n=e.toLowerCase();"content-length"!==n&&"content-encoding"!==n&&"transfer-encoding"!==n&&(u[e]=t)}),new Response(d,{status:s,statusText:p?p.statusText:"",headers:new Headers(u)})}const m=Date.now()-A;if(g){const t="AbortError"===g.name||(g.message||"").includes("aborted"),n="TimeoutError"===g.name||(g.message||"").includes("timed out");throw Z.addRequest("other",{...e,requestId:a,status:t?"Aborted":n?"Timeout":"Error",pending:!1,duration:m,aborted:t,timeout:n,error:!t&&!n}),g}const y=Object.fromEntries(p.headers.entries());let w;try{const e=p.clone(),t=5e3,n=Symbol("body-timed-out"),r=await Promise.race([e.text(),new Promise(e=>setTimeout(()=>e(n),t))]);w=r===n?void 0:r}catch(e){w=void 0}return Z.addRequest("other",{...e,requestId:a,status:p.status,responseHeaders:y,responseBody:w,pending:!1,duration:m}),p}}),se.apply({isEnabled:()=>Z.interceptionEnabled,shouldBypassRequest:Ae,ruleProvider:()=>b(),mappingProvider:e=>{try{return c(new URL(e.url,window.location.origin).pathname,e.method)}catch{return null}},onRuleMatch:async(e,t,n,r)=>{const o=t.requestId,i=Date.now();Z.addRequest("mocked",{...t,requestId:o,pending:!0,startTime:i,rule:e});const s=await oe.apply(e,t),{modifiedRequest:a,type:A,redirectUrl:l}=s;"timeout"!==A&&Z.addRequest("mocked",{...a,requestId:o,pending:!0,startTime:i,rule:e});let c=null;if("redirect"===A){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()};Z.addRequest("mocked",e)}const d=(e,t,r,d={})=>{const u=Date.now()-i;if(s.rule.modificationActions?.modifyResponseHeaders?.enabled){let e="string"==typeof r?Object.fromEntries(r.split("\r\n").filter(e=>e).map(e=>e.split(": "))):r;e=oe.applyResponseModifications(e,s.rule.modificationActions),r=e}Z.addRequest("mocked",{...a,requestId:o,status:e,responseBody:t,responseHeaders:r,pending:!1,duration:u,rule:s.rule,...d}),"redirect"===A&&c&&Z.addRequest("mocked",{url:l,method:a.method,requestId:c,status:e,responseBody:t,responseHeaders:r,pending:!1,duration:u,requestHeaders:a.headers||{},requestBody:a.body,...d}),n._capture(e,t,r,d)};if("timeout"===A)return d("Aborted","Timed out by rule",{},{aborted:!0}),void n._xhr.abort();if("redirect"===A){if(!l)return void d(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",()=>d("Aborted","Aborted",{},{aborted:!0}),{once:!0}),n._xhr.addEventListener("error",()=>d(0,"Error",{},{error:!0}),{once:!0}),n._xhr.addEventListener("timeout",()=>d("Timeout","Timeout",{},{timeout:!0}),{once:!0}),n._xhr.addEventListener("load",()=>d(n._xhr.status,n._xhr.responseText,n._xhr.getAllResponseHeaders()),{once:!0}),r(a.body)},onMockMatch:(e,r,o,i)=>{const s=r.requestId,a=Date.now(),A=n(),l=new URL(r.url,window.location.origin);let c=`${v()}${e.url}${l.search}`,d={[u]:A,mfmver:"14.5.1","x-mfm-adaptor":t};const f=B();f&&e._ack&&(d["x-mfm-key"]=`${f}-${e._ack}`),e?._ri_&&(d._ri_=e._ri_),d["x-mfm-internal"]="true";const h={...r.headers,...d};Z.addRequest("mocked",{...r,requestId:s,pending:!0,startTime:a});const p=(t,n,i,A={})=>{if(o._captured)return;const l=Date.now()-a;ee(i)&&Z.handleMockDisabled({apiMethod:e.method,apiEndpoint:e.apiEndpoint}),Z.addRequest("mocked",{...r,requestId:s,status:t,responseBody:n,responseHeaders:i,pending:!1,duration:l,...A}),o._capture(t,n,i,A)};o._xhr.addEventListener("abort",()=>p("Aborted","Aborted",{},{aborted:!0}),{once:!0}),o._xhr.addEventListener("error",()=>p(0,"Error",{},{error:!0}),{once:!0}),o._xhr.addEventListener("timeout",()=>p("Timeout","Timeout",{},{timeout:!0}),{once:!0});const g=new window.XMLHttpRequest;g.open(r.method,c,!0);for(const e in h)g.setRequestHeader(e,h[e]);g.withCredentials=o.proxy.withCredentials,o._onAbort=()=>{try{g.abort()}catch(e){}p("Aborted","Aborted",{},{aborted:!0})},g.onload=()=>p(g.status,g.responseText,g.getAllResponseHeaders()),g.onerror=()=>p(0,"Network Error",{},{error:!0}),g.ontimeout=()=>p("Timeout","Request timed out",{},{timeout:!0}),g.send(r.body)},onOtherRequest:(e,t,n)=>{const r="true"===e.headers?.["x-mfm-internal"],o=v(),i=e.url.startsWith(o);if("OPTIONS"===e.method||r||i)return n(e.body);const s=Date.now();Z.addRequest("other",{...e,pending:!0,startTime:s});const a=O(e.method,e.url),A=_(e.method,e.url);let l=e;const c=(n,r,o,i={})=>{const a=Date.now()-s;Z.addRequest("other",{...e,status:n,responseBody:r,responseHeaders:o,pending:!1,duration:a,...i}),t._capture(n,r,o,i)};if(t._xhr.addEventListener("abort",()=>c("Aborted","Aborted",{},{aborted:!0}),{once:!0}),t._xhr.addEventListener("error",()=>c(0,"Error",{},{error:!0}),{once:!0}),t._xhr.addEventListener("timeout",()=>c("Timeout","Timeout",{},{timeout:!0}),{once:!0}),t._xhr.addEventListener("load",async()=>{const n=t._xhr.status,r=t._xhr.responseText,o=t._xhr.getAllResponseHeaders();if(A){const t={};"string"==typeof o&&o.split("\r\n").forEach(e=>{const n=e.indexOf(": ");n>0&&(t[e.slice(0,n)]=e.slice(n+2))});const i=await M({requestId:e.requestId,ruleId:A.id,request:{method:l.method,url:l.url,headers:l.headers,body:l.body},response:{statusCode:n,headers:t,body:r}});if(i.simulateTimeout)return void c("Timeout","Timeout (Debugger)",{},{timeout:!0});i.delayMs>0&&await new Promise(e=>setTimeout(e,i.delayMs));const s=Number(i.statusCode)||n,a=i.headers&&"object"==typeof i.headers?i.headers:t,d="string"==typeof i.body?i.body:null==i.body?"":JSON.stringify(i.body);return void c(s,d,a)}c(n,r,o)},{once:!0}),t._xhr.addEventListener("readystatechange",()=>{if(t._xhr.readyState>=2&&!t._captured){const n=t._xhr.status;if(n>0){const r=Date.now()-s;Z.addRequest("other",{...e,status:n,responseHeaders:t._xhr.getAllResponseHeaders(),pending:t._xhr.readyState<4,duration:r})}}}),a)return void(async()=>{const r={};try{new URL(e.url,"undefined"!=typeof window?window.location.origin:"http://localhost").searchParams.forEach((e,t)=>{r[t]=e})}catch(e){}const o=await P({requestId:e.requestId,ruleId:a.id,request:{method:e.method,url:e.url,headers:e.headers,body:e.body},queryParams:r});if(o.cancel){c("Cancelled","Cancelled by editor",{},{aborted:!0});try{t._xhr.abort()}catch(e){}return}let i=e.url;try{const t=new URL(e.url,"undefined"!=typeof window?window.location.origin:"http://localhost");[...t.searchParams.keys()].forEach(e=>t.searchParams.delete(e)),Object.entries(o.queryParams||{}).forEach(([e,n])=>{t.searchParams.set(e,String(n??""))}),i="string"==typeof e.url&&e.url.startsWith("/")?`${t.pathname}${t.search}`:t.href}catch(e){}if(i!==e.url)try{t._xhr.open(e.method,i,!0)}catch(e){}Object.entries(o.headers||{}).forEach(([e,n])=>{try{t._xhr.setRequestHeader(e,String(n??""))}catch(e){}}),l={...e,url:i,headers:o.headers||{},body:o.body};const s=String(e.method||"GET").toUpperCase(),A="GET"!==s&&"HEAD"!==s?null==o.body?null:o.body:null,d=q();d>0?setTimeout(()=>{try{n(A)}catch(e){}},d):n(A)})();const d=q();d>0?setTimeout(()=>{try{n(e.body)}catch(e){}},d):n(e.body)}})}(o,n),a&&f)Z.mappings=s,Z.rules=p,e?.(s,{_o:a,mk:f,_mck:h,_rules:p});else if(o){const t=Z.getSavedMappings(o,n);if(t&&Array.isArray(t.mappings))return Z.mappings=t.mappings,Z.rules=t.meta?._rules||[],A(t.mappings),k(t.meta),Z.updateMappings(t.mappings,t.meta),void e?.(t.mappings,t.meta);Z.updateMappings([],{_rules:[]}),e?.([],{_rules:[]})}},checkIfApiToBeMocked:c,getMappings:l,doFetchMappings:(e,t)=>{x(o||Z.token,n,(t,r)=>{Z.saveMappings(t,r,o||Z.token,n),Z.updateMappings(t,r),e?.(t,r)},t)},recheckWidgetVisibility:()=>{Z.init()}}},ce=r();ce||(globalThis.mockforme=le);let de=le;ce&&(de=e=>({run:()=>{}}));const ue=de;export{ue as mockforme};
|
|
@@ -17,4 +17,4 @@
|
|
|
17
17
|
0% { transform: translateX(-100%) scaleX(0.4); }
|
|
18
18
|
50% { transform: translateX(20%) scaleX(0.6); }
|
|
19
19
|
100% { transform: translateX(100%) scaleX(0.4); }
|
|
20
|
-
`;function AA({message:e,theme:t}){return Ct("div",{role:"alert",css:gt("background:#fef2f2;border:1px solid #fecaca;border-left:3px solid ",t.color.error,";color:",t.color.error,";padding:",t.spacing.md," ",t.spacing.lg,";border-radius:",t.radius.md,";font-size:",t.typography.fontSizeBase,";line-height:1.5;display:flex;align-items:flex-start;gap:",t.spacing.sm,";",""),children:[xt("strong",{css:gt("font-weight:",t.typography.fontWeightBold,";",""),children:"✗"}),xt("span",{children:e})]})}function lA(e){const t=document.getElementById("mfm-root");return!!t&&(t===e||t.contains(e))}function cA(e){if(!e)return"";if(e.length<=1e3)return e;return e.slice(0,988)+"…[truncated]"}function dA(){const e=Ut(),{confirmState:t,dismissConfirm:n}=un();if(u.useEffect(()=>{if(!t)return;const e=e=>{"Escape"===e.key&&n()};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[t,n]),!t)return null;const{title:r,message:o,confirmLabel:i,cancelLabel:s,danger:a,onConfirm:A}=t;return xt("div",{role:"dialog","aria-label":r??"Confirm","aria-modal":"true",onClick:e=>{e.target===e.currentTarget&&n()},css:gt("position:absolute;inset:0;background:rgba(15, 23, 42, 0.5);z-index:",e.z.confirm,";display:flex;align-items:center;justify-content:center;padding:",e.spacing.xl,";",""),children:Ct("div",{css:gt("background:",e.color.bg,";border-radius:",e.radius.lg,";box-shadow:",e.shadow.lg,";padding:",e.spacing.xl,";max-width:360px;width:100%;display:flex;flex-direction:column;gap:",e.spacing.md,";",""),children:[r?xt("h3",{css:gt("margin:0;font-size:",e.typography.fontSizeLg,";font-weight:",e.typography.fontWeightBold,";color:",e.color.text,";",""),children:r}):null,xt("p",{css:gt("margin:0;color:",e.color.text,";font-size:",e.typography.fontSizeBase,";line-height:1.5;",""),children:o}),Ct("div",{css:gt("display:flex;justify-content:flex-end;gap:",e.spacing.md,";margin-top:",e.spacing.sm,";",""),children:[xt("button",{type:"button",onClick:n,css:gt("appearance:none;background:transparent;border:1px solid ",e.color.border,";color:",e.color.text,";font-family:inherit;font-size:",e.typography.fontSizeBase,";padding:",e.spacing.sm," ",e.spacing.lg,";border-radius:",e.radius.md,";cursor:pointer;&:hover{background:",e.color.surfaceBright,";}",""),children:s??"Cancel"}),xt("button",{type:"button",autoFocus:!0,onClick:()=>{n(),A()},css:gt("appearance:none;border:none;background:",a?e.color.error:e.color.primary,";color:#fff;font-family:inherit;font-weight:",e.typography.fontWeightSemibold,";font-size:",e.typography.fontSizeBase,";padding:",e.spacing.sm," ",e.spacing.lg,";border-radius:",e.radius.md,";cursor:pointer;&:hover{filter:brightness(0.95);}",""),children:i??"Confirm"})]})]})})}function uA(){const{analyticsEnabled:e}=tr(),{token:t,organisationId:n}=gn();return u.useEffect(()=>{rn.setEnabled(e)},[e]),u.useEffect(()=>{rn.setToken(t)},[t]),u.useEffect(()=>{rn.setOrganisationId(n)},[n]),null}function fA({clientType:e,version:t}={}){return Ct(Qt,{initialMode:"light",children:[xt(hA,{}),xt(Mt,{children:xt(dn,{clientType:e,version:t,children:xt(pn,{children:xt(yn,{children:xt(Un,{children:xt(Nn,{children:xt(er,{children:xt(Jn,{children:Ct(ir,{children:[xt(uA,{}),xt(So,{}),xt(pA,{})]})})})})})})})})})]})}function hA(){const e=Ut();return xt(pt,{styles:gt(":host,[data-mfm-mount]{all:initial;color:",e.color.text,";font-family:",e.typography.fontFamily,";font-size:",e.typography.fontSizeBase,";line-height:1.4;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;text-rendering:optimizeLegibility;}*,*::before,*::after{box-sizing:border-box;}::-webkit-scrollbar{width:8px;height:8px;}::-webkit-scrollbar-thumb{background:",e.color.border,";border-radius:",e.radius.pill,";}::-webkit-scrollbar-thumb:hover{background:",e.color.textDim,";}","")})}function pA(){const{setOpen:e,isInterceptEnabled:t,toggleIntercept:n,isSettingsOpen:r,openSettings:o,startSnipping:i,requestConfirm:s}=un(),{token:a,isTokenValidated:A,isValidating:l,isLoading:c,reloadMappings:d,deleteToken:u}=gn(),{debugRules:f,editRules:h}=Wn(),{globalDelay:p}=tr();if(!A&&(l||a))return Ct(Bt,{children:[xt(_o,{children:xt(bA,{children:xt(mA,{})})}),xt(qa,{})]});if(!a)return Ct(Bt,{children:[xt(_o,{children:Ct(bA,{children:[xt(pa,{}),xt(dA,{})]})}),xt(qa,{})]});const g=r||f.length>0||h.length>0||p.enabled;return Ct(Bt,{children:[Ct(_o,{children:[xt(Oo,{onSnip:i,onReload:d,onOpenSettings:o,onDeleteToken:()=>{s({title:"Delete token?",message:"Are you sure you want to delete token? API interception will stop once the token is removed.",confirmLabel:"Delete",danger:!0,onConfirm:u})},isInterceptEnabled:t,onToggleIntercept:()=>{t?s({title:"Disable interception?",message:"Once disabled, the widget will stop intercepting requests and disappear from the page. Please refresh the page after disabling it. You can re-enable it anytime from the MockForMe settings page via the extension icon in tray or the right-click menu. You can also re-enable it from inside Widget Settings → Whitelisted Hosts.",confirmLabel:"Disable",danger:!0,onConfirm:n}):n()},onClose:()=>e(!1),isSettingsActive:g,isReloading:c,isAuthenticated:!0}),xt(Po,{}),Ct(bA,{children:[xt(da,{}),xt(ga,{}),xt(ka,{}),xt(Ba,{}),xt(Ua,{}),xt(Na,{}),xt(dA,{}),xt(yA,{})]})]}),xt(qa,{})]})}var gA={name:"3kwpv8",styles:"flex:1;min-height:0;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:14px;padding:24px;text-align:center"};function mA(){const e=Ut();return Ct("div",{css:gA,children:[xt(yi,{size:26,color:e.color.primary,label:"Validating token"}),xt("div",{css:gt("font-size:",e.typography.fontSizeBase,";font-weight:600;color:",e.color.text,";",""),children:"Validating your token…"}),xt("div",{css:gt("font-size:12px;color:",e.color.textDim,";max-width:260px;line-height:1.5;",""),children:"Hang tight — we're verifying your session before loading the widget."})]})}function yA(){const{invalidatedMessage:e,acknowledgeInvalidation:t}=gn(),n=Ut();return null==e?null:xt(ri,{open:!0,hideClose:!0,title:"Token no longer valid",leadingDot:"live",onClose:()=>{},footer:xt("button",{type:"button",onClick:t,css:gt("appearance:none;border:none;border-radius:",n.radius.sm,";background:",n.color.primary,";color:#fff;font-size:",n.typography.fontSizeBase,";font-weight:",n.typography.fontWeightBold,";padding:8px 20px;cursor:pointer;&:hover{background:",n.color.primaryHover,";}",""),children:"OK"}),children:xt("p",{css:gt("margin:0;font-size:",n.typography.fontSizeBase,";line-height:1.5;color:",n.color.text,";",""),children:e})})}var wA={name:"4oq8x6",styles:"position:absolute;inset:0;pointer-events:none;z-index:1500;&:empty{display:none;}&>*{pointer-events:auto;}"},kA={name:"p72qif",styles:"flex:1;min-height:0;position:relative;display:flex;flex-direction:column;overflow:hidden"};function bA({children:e}){const{fullscreenSlotRef:t}=un();return Ct("div",{css:kA,children:[e,xt("div",{ref:t,"data-mfm-fullscreen-slot":!0,css:wA})]})}class vA extends u.Component{constructor(){super(...arguments),o(this,"state",{hasError:!1})}static getDerivedStateFromError(){return Or(),{hasError:!0}}componentDidCatch(e,t){try{this.props.onError(e,t)}catch{}}render(){return this.state.hasError?null:this.props.children}}const BA=(()=>{try{const e="file:///Users/sushilkumar/mockforme/shared/mockforme_widget/dist/chunks/widget-B8TRg0gv.js",t=e.lastIndexOf("/");return t>0?e.slice(0,t+1):e}catch{return""}})();function xA(e,t){return!(!BA||!function(){try{const e=typeof document<"u"&&(document.baseURI||document.location&&document.location.href)||"";return!!e&&!e.startsWith(BA)}catch{return!1}}()||!(e&&e.startsWith(BA)||t&&-1!==t.indexOf(BA)))}let CA=null;const EA="data-mfm-mount";function FA(e){return e||document.getElementById("mfm-root")||(document.body?document.body:null)}function SA(e,t){let n;"mfm-root"===e.id?n=e:(n=document.createElement("div"),n.id="mfm-root",e.appendChild(n)),n.style.cssText="all: initial; display: block;",function(e){try{rn.init(),rn.setClientType(e);const t=tn().read("MFM_TOKEN");t&&rn.setToken(t)}catch{}}(t.clientType);const r=["click","dblclick","mousedown","mouseup","mousemove","pointerdown","pointerup","pointermove","contextmenu","wheel","touchstart","touchend","touchmove"],o=e=>e.stopPropagation();for(const e of r){const t="wheel"===e||"touchstart"===e||"touchend"===e||"touchmove"===e;n.addEventListener(e,o,{passive:t})}const i=n.shadowRoot??n.attachShadow({mode:"open"});let s=i.querySelector(`[${EA}]`);s||(s=document.createElement("div"),s.setAttribute(EA,""),i.appendChild(s));const a=Ue({key:"mfm",container:i,prepend:!0}),A={run:()=>{}},l=F.createRoot(s);l.render(u.createElement(u.StrictMode,null,u.createElement(rt,{value:a},u.createElement(vA,{onError:e=>{setTimeout(()=>A.run(e),0)}},u.createElement(fA,{clientType:t.clientType,version:t.version})))));const c=e=>{const t=e.error;xA(e.filename,t?.stack)&&(Or(),e.preventDefault(),A.run(e.error))},d=e=>{const t=e.reason;xA(void 0,t?.stack??(t?String(t):void 0))&&(Or(),e.preventDefault(),A.run(e.reason))};window.addEventListener("error",c),window.addEventListener("unhandledrejection",d);const f=console.error;console.error=function(...e){if(!(jr>0)){if(BA)for(let t=0;t<e.length;t++){const n=e[t];if(-1!==((n&&"object"==typeof n&&"stack"in n?String(n.stack??""):"")||String(n)).indexOf(BA))return}f.apply(console,e)}};let h=!1,p=null;const g=e=>{if(!h){if(h=!0,window.removeEventListener("error",c),window.removeEventListener("unhandledrejection",d),console.error!==f)try{console.error=f}catch{}try{l.unmount()}catch{}try{n.remove()}catch{}CA=null;try{if(void 0!==e){const t=e,n=t&&"string"==typeof t.message?t.message:"string"==typeof e?e:String(e),r=t&&"string"==typeof t.stack?t.stack:"";Vr("widget_load_failed",{errorName:t&&"string"==typeof t.name?t.name:"Error",errorMessage:n,errorStack:r.slice(0,4e3),userAgent:typeof navigator<"u"?navigator.userAgent:"",url:typeof location<"u"?location.href:""})}else rn.track("widget_destroyed");Gr()}catch{}if(void 0!==e)try{p=function(){if(typeof document>"u"||!document.body)return{dismiss(){}};const e=document.createElement("div");e.id="mfm-error-snackbar",e.style.cssText=["all: initial","position: fixed","right: 16px","bottom: 16px","z-index: 2147483646"].join(";"),document.body.appendChild(e);const t=e.attachShadow({mode:"closed"}),n=document.createElement("div");n.style.cssText=["box-sizing: border-box","display: flex","align-items: center","gap: 10px","min-width: 280px","max-width: 380px","padding: 10px 12px","background: #1f2937","color: #f9fafb","border: 1px solid #374151","border-radius: 8px","box-shadow: 0 8px 24px rgba(0,0,0,0.25)",'font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',"font-size: 13px","line-height: 1.4"].join(";");const r=document.createElement("div");r.style.cssText=["flex: 1 1 auto","min-width: 0"].join(";");const o=document.createElement("div");o.textContent="MockForMe is unable to load.",o.style.cssText="font-weight: 500";const i=document.createElement("div");i.textContent="The issue has been reported.",i.style.cssText=["margin-top: 2px","color: #9ca3af","font-size: 12px"].join(";"),r.appendChild(o),r.appendChild(i);const s=document.createElement("button");s.type="button",s.setAttribute("aria-label","Dismiss"),s.textContent="×",s.style.cssText=["flex: 0 0 auto","width: 24px","height: 24px","padding: 0","background: transparent","color: #9ca3af","border: 0","border-radius: 4px","cursor: pointer","font-size: 18px","line-height: 1"].join(";");let a=!1;const A=()=>{if(!a){a=!0;try{e.remove()}catch{}}};return s.addEventListener("click",A),n.appendChild(r),n.appendChild(s),t.appendChild(n),{dismiss:A}}()}catch{}}};return A.run=g,{destroy(){if(g(),p){try{p.dismiss()}catch{}p=null}}}}const QA={run(e,t={}){if(CA)return CA;if(typeof document<"u"&&"loading"===document.readyState){let n=!1;const r=()=>{if(n)return;const r=FA(e);r&&(CA=SA(r,t))};return document.addEventListener("DOMContentLoaded",r,{once:!0}),{destroy(){n=!0,document.removeEventListener("DOMContentLoaded",r),CA&&CA.destroy()}}}const n=FA(e);return n?(CA=SA(n,t),CA):(console.warn("[MockForMeWidget] no mount target available"),{destroy(){}})}};typeof window<"u"&&(window.MockForMeWidget=QA),n.d(t,["M",0,QA])}};const t={};function n(r){const o=t[r];if(void 0!==o)return o.exports;const i=t[r]={exports:{}};return e[r](i,i.exports,n),i.exports}n.d=(e,t)=>{if(Array.isArray(t))for(var r=0;r<t.length;){var o=t[r++],i=t[r++];n.o(e,o)?0===i&&r++:0===i?Object.defineProperty(e,o,{enumerable:!0,value:t[r++]}):Object.defineProperty(e,o,{enumerable:!0,get:i})}else 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=>{Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};let r={};n.d(r,{mockforme:()=>he});const o=()=>"undefined"!=typeof process&&null!=process.versions?.node,i=e=>{try{return e?e.toLowerCase():e}catch(e){return console.log(e),null}},s=(e,t)=>{const n=e.split("/"),r=t.split("/");if(n.length!==r.length)return!1;for(let e=0;e<n.length;e++){const t=n[e];if(t!==r[e]&&":any"!==t&&":"!==t.charAt(0))return!1}return!0},a=new Map;let A=[];function l(e){A=e}function c(){return A}function d(e,t="get"){const n=e=>e.startsWith("/")?e:`/${e}`,r=n(e),o=function(e,t){if(0===a.size)return null;for(const n of a.values())for(const r of n){if(i(r.apiMethod)!==i(t))continue;const n=r.apiEndpoint.startsWith("/")?r.apiEndpoint:`/${r.apiEndpoint}`;if(n===e||s(n,e)){const t={url:e,method:r.apiMethod,_ack:r._ack||null};return r._ri_&&(t._ri_=r._ri_),t}}return null}(r,t);if(o)return console.log(`[MockForMe] Flow Mock Match: ${t} ${e} -> ${o.url}`),o;for(const o of A)if(i(o.apiMethod)===i(t)){const i=n(o.apiEndpoint);if(i===r||s(i,r)){console.log(`[MockForMe] Match Found: ${t} ${e} -> ${o.apiEndpoint}`);const n={url:e,method:o.apiMethod,apiEndpoint:o.apiEndpoint,_ack:o._ack||null};return o._ri_&&(n._ri_=o._ri_),n}}return null}const u="JAVASCRIPT",f="mockforme",h="https://api.mockforme.com",p=`${h}/mockforme`,g=`${h}/gateway/3f4eae522b`;let m=null,y=null,w=null,k=[];function b({_o:e,mk:t,_mck:n,_rules:r}){m=e,y=t,w=n,k=r}function v(){return k}function B(){return`${p}/${m}/${y}`}function x(){return w}function C(e,t,n,r){fetch(g,{method:"GET",headers:{[f]:e,mfmver:"14.5.0","x-mfm-adaptor":t}}).then(e=>{if(!e.ok)throw e;return e.json()}).then(e=>{if(e){const{di:t,iv:r,_o:o,_mck:i,mk:s,r:a}=e,A=function({di:e,iv:t},n){var r;const o=function(e,t){const n=t.length;return e.split("").map((e,r)=>String.fromCharCode(e.charCodeAt(0)^t.charCodeAt(r%n))).join("")}((r=e,"undefined"!=typeof Buffer?Buffer.from(r,"base64").toString("utf8"):decodeURIComponent(escape(atob(r)))),n+t);return JSON.parse(o)}({di:t,iv:r},o);b({_o:o,mk:s,_mck:i,_rules:a}),A&&(l(A),n(A,{_o:o,mk:s,_mck:i,_rules:a}))}}).catch(e=>{console.error("Error in loading mocked APIs:",e),r(e)})}const E=`${h}/mockforme/mfm_op_3f4eae522b/manage`,F=e=>({[f]:e,mfmver:"14.5.0","Content-Type":"application/json"}),S=async e=>{let t=null;try{t=await e.json()}catch(e){}return{ok:!(!e.ok||!t||!0!==t.status&&"success"!==t.status&&1!==t.status),message:t&&t.message||(e.ok?"":`Request failed (${e.status})`),result:t?t.result:null}},Q="MFM_INTERCEPTOR_RULES";let U=[];const T=new Map;function I(){try{if("undefined"==typeof localStorage)return[];const e=localStorage.getItem(Q);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>e&&e.enabled):[]}catch(e){return[]}}function _(e){U=Array.isArray(e)?e.filter(e=>e&&e.enabled):[]}function M(e,t){if(!e||!t)return null;if(!U.length&&(U=I(),!U.length))return null;const n=String(e).toUpperCase();return U.find(e=>{if(!e.enabled||String(e.method).toUpperCase()!==n)return!1;if("PATH"===e.matchType)try{return new URL(e.url,"http://localhost").pathname===new URL(t,"http://localhost").pathname}catch(n){return e.url===t}return e.url===t})||null}function H({requestId:e,ruleId:t,request:n,response:r,timeoutMs:o=3e5}){return new Promise(i=>{const s=setTimeout(()=>{T.has(e)&&(T.delete(e),i({requestId:e,simulateTimeout:!1,delayMs:0,statusCode:r?.statusCode??200,headers:r?.headers||{},body:r?.body}))},o);T.set(e,{resolve:i,timer:s});try{"undefined"!=typeof window&&window.postMessage({type:"MFM_DEBUG_INTERCEPT_REQ",payload:{requestId:e,ruleId:t,request:n,response:r,timestamp:Date.now()}},"*")}catch(t){clearTimeout(s),T.delete(e),i({requestId:e,simulateTimeout:!1,delayMs:0,statusCode:r?.statusCode??200,headers:r?.headers||{},body:r?.body})}})}U=I(),"undefined"!=typeof document&&"function"==typeof document.addEventListener&&document.addEventListener("mfm:rule-sync",e=>{const t=e&&e.detail;t&&"debugger"===t.kind&&_(t.payload?.rules||[])}),"undefined"!=typeof window&&"function"==typeof window.addEventListener&&window.addEventListener("storage",e=>{e.key===Q&&(U=I())});const L="MFM_REQUEST_EDITOR_RULES";let D=[];const N=new Map;function j(){try{if("undefined"==typeof localStorage)return[];const e=localStorage.getItem(L);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>e&&e.enabled):[]}catch(e){return[]}}function O(e){D=Array.isArray(e)?e.filter(e=>e&&e.enabled):[]}function R(e,t){if(!e||!t)return null;if(!D.length&&(D=j(),!D.length))return null;const n=String(e).toUpperCase();return D.find(e=>{if(!e.enabled||String(e.method).toUpperCase()!==n)return!1;if("PATH"===e.matchType)try{return new URL(e.url,"http://localhost").pathname===new URL(t,"http://localhost").pathname}catch(n){return e.url===t}return e.url===t})||null}function P(e,t,n){const r={};return Object.entries(t?.headers||{}).forEach(([e,t])=>{r[e]=String(t??"")}),{requestId:e,cancel:!1,headers:r,queryParams:n||{},body:"string"==typeof t?.body?t.body:null}}function z({requestId:e,ruleId:t,request:n,queryParams:r,timeoutMs:o=3e5}){return new Promise(i=>{const s=setTimeout(()=>{N.has(e)&&(N.delete(e),i(P(e,n,r)))},o);N.set(e,{resolve:i,timer:s});try{"undefined"!=typeof window&&window.postMessage({type:"MFM_REQUEST_EDIT_REQ",payload:{requestId:e,ruleId:t,request:n,queryParams:r,timestamp:Date.now()}},"*")}catch(t){clearTimeout(s),N.delete(e),i(P(e,n,r))}})}D=j(),"undefined"!=typeof document&&"function"==typeof document.addEventListener&&document.addEventListener("mfm:rule-sync",e=>{const t=e&&e.detail;t&&"editor"===t.kind&&O(t.payload?.rules||[])}),"undefined"!=typeof window&&"function"==typeof window.addEventListener&&window.addEventListener("storage",e=>{e.key===L&&(D=j())});const K="MFM_GLOBAL_DELAY";let V={enabled:!1,seconds:0},G=0;function q(){try{if("undefined"==typeof localStorage)return{enabled:!1,seconds:0};const e=localStorage.getItem(K);if(!e)return{enabled:!1,seconds:0};const t=JSON.parse(e);return t&&"object"==typeof t?{enabled:!!t.enabled&&Number.isFinite(t.seconds)&&t.seconds>0,seconds:Number.isFinite(t.seconds)?Number(t.seconds):0}:{enabled:!1,seconds:0}}catch(e){return{enabled:!1,seconds:0}}}function J(){const e=Date.now();return e-G>500&&(V=q(),G=e),V.enabled&&V.seconds>0?Math.round(1e3*V.seconds):0}V=q(),G=Date.now(),"undefined"!=typeof window&&"function"==typeof window.addEventListener&&window.addEventListener("storage",e=>{e.key===K&&(V=q(),G=Date.now())});var W,$,X=n(411);!function(e){e[e.NONE=0]="NONE",e[e.INFO=1]="INFO",e[e.WARN=2]="WARN",e[e.ERROR=3]="ERROR"}(W||(W={})),function(e){e.MFM_REQ_MAPPINGS="MFM_REQ_MAPPINGS",e.MFM_REQ_SAVED_MAPPINGS="MFM_REQ_SAVED_MAPPINGS",e.MFM_DEL_CLIENT_TOKEN="MFM_DEL_CLIENT_TOKEN",e.MFM_SUBMIT_TOKEN="MFM_SUBMIT_TOKEN",e.MFM_TOGGLE_INTERCEPTION="MFM_TOGGLE_INTERCEPTION",e.MFM_REQ_ALL_APIS="MFM_REQ_ALL_APIS",e.MFM_TOGGLE_API="MFM_TOGGLE_API",e.MFM_DEBUG_RULES_UPDATE="MFM_DEBUG_RULES_UPDATE",e.MFM_DEBUG_INTERCEPT_RES="MFM_DEBUG_INTERCEPT_RES",e.MFM_REQUEST_EDIT_RULES_UPDATE="MFM_REQUEST_EDIT_RULES_UPDATE",e.MFM_REQUEST_EDIT_ACK="MFM_REQUEST_EDIT_ACK",e.MFM_REQUEST_EDIT_RES="MFM_REQUEST_EDIT_RES",e.MFM_GLOBAL_DELAY_UPDATE="MFM_GLOBAL_DELAY_UPDATE",e.MFM_FLOW_MOCK_SET="MFM_FLOW_MOCK_SET",e.MFM_FLOW_MOCK_CLEAR="MFM_FLOW_MOCK_CLEAR",e.MFM_PING_SCREENSHOT="MFM_PING_SCREENSHOT",e.MFM_REQUEST_SCREENSHOT="MFM_REQUEST_SCREENSHOT",e.MFM_RES_MAPPINGS="MFM_RES_MAPPINGS",e.MFM_RES_ALL_APIS="MFM_RES_ALL_APIS",e.MFM_TOGGLE_API_RESULT="MFM_TOGGLE_API_RESULT",e.MFM_REQ="MFM_REQ",e.MFM_RES="MFM_RES",e.MFM_TOKEN_ERROR="MFM_TOKEN_ERROR",e.MFM_TOKEN_API_FAILED="MFM_TOKEN_API_FAILED",e.MFM_TOKEN_INVALIDATED="MFM_TOKEN_INVALIDATED",e.MFM_MOCK_DISABLED="MFM_MOCK_DISABLED",e.MFM_TOKEN_CLEARED="MFM_TOKEN_CLEARED",e.MFM_DEBUG_INTERCEPT_REQ="MFM_DEBUG_INTERCEPT_REQ",e.MFM_REQUEST_EDIT_REQ="MFM_REQUEST_EDIT_REQ",e.MFM_PONG_SCREENSHOT="MFM_PONG_SCREENSHOT",e.MFM_SCREENSHOT_RESULT="MFM_SCREENSHOT_RESULT",e.MFM_SCREENSHOT_ERROR="MFM_SCREENSHOT_ERROR",e.MFM_LOG_INFO="MFM_LOG_INFO",e.MFM_LOG_WARN="MFM_LOG_WARN",e.MFM_LOG_ERROR="MFM_LOG_ERROR"}($||($={}));const Y="MFM_TOKEN",Z="MFM_CACHED_MAPPINGS",ee="MFM_INTERCEPTION_ENABLED",te=new class{constructor(e={}){o()||(this.token=e.token||("undefined"!=typeof localStorage?localStorage.getItem(Y):null),this.isAuthenticated=!!this.token,this.onAuthSuccess=e.onAuthSuccess||(()=>{}),this.mappings=e.mappings||[],this.rules=e.rules||[],this.widgetKey=e.widgetKey||null,this.tokenInvalidated=!1,this.setupMessageListeners())}get interceptionEnabled(){if(this.tokenInvalidated)return!1;if("undefined"==typeof localStorage)return!1!==this._interceptionEnabled;const e=localStorage.getItem(ee);return"false"!==e&&("true"===e||!1!==this._interceptionEnabled)}set interceptionEnabled(e){const t=!!e;this._interceptionEnabled=t,"undefined"!=typeof localStorage&&localStorage.setItem(ee,t?"true":"false")}setupMessageListeners(){"undefined"!=typeof window&&window.addEventListener("message",e=>{const{type:t,payload:n}=e.data||{};var r,o;if(t&&"string"==typeof t&&t.startsWith("MFM_"))switch(t){case $.MFM_REQ_MAPPINGS:this.refreshMappings();break;case $.MFM_REQ_SAVED_MAPPINGS:this.handleReqSavedMappings();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;break;case $.MFM_REQ_ALL_APIS:this.handleReqAllApis();break;case $.MFM_TOGGLE_API:this.handleToggleApi(n?.apiId,n?.enabled);break;case $.MFM_DEBUG_RULES_UPDATE:_(n?.rules||[]);break;case $.MFM_DEBUG_INTERCEPT_RES:!function(e){if(!e||!e.requestId)return;const t=T.get(e.requestId);t&&(clearTimeout(t.timer),T.delete(e.requestId),t.resolve(e))}(n);break;case $.MFM_REQUEST_EDIT_RULES_UPDATE:O(n?.rules||[]);break;case $.MFM_REQUEST_EDIT_RES:!function(e){if(!e||!e.requestId)return;const t=N.get(e.requestId);t&&(clearTimeout(t.timer),N.delete(e.requestId),t.resolve(e))}(n);break;case $.MFM_GLOBAL_DELAY_UPDATE:!function(e){if(!e||"object"!=typeof e)return V={enabled:!1,seconds:0},void(G=Date.now());V={enabled:!!e.enabled&&Number.isFinite(e.seconds)&&e.seconds>0,seconds:Number.isFinite(e.seconds)?Number(e.seconds):0},G=Date.now()}(n);break;case $.MFM_FLOW_MOCK_SET:r=n?.runId,o=n?.apis||[],r&&a.set(String(r),Array.isArray(o)?o:[]);break;case $.MFM_FLOW_MOCK_CLEAR:!function(e){e&&a.delete(String(e))}(n?.runId)}})}init(){if("undefined"!=typeof document&&this.checkVisibility()){if("undefined"!=typeof window){const e=window.MockForMeWidget||X.M;e&&"function"==typeof e.run&&(e.run(null,{clientType:"NPM",version:"14.5.0"}),this.syncInterceptionToggleToWidget())}if(console.log("[MockForMe] Widget initialized"),this.token){const e=this.getSavedMappings(this.token,"JAVASCRIPT");e&&(this.mappings=e.mappings||[],this.rules=e.meta?._rules||[],this.onAuthSuccess(this.token,this.mappings,e.meta),this.updateMappings(this.mappings,e.meta))}}}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(Y,e),this.refreshMappings())}handleTokenDeletion(){this.token=null,this.isAuthenticated=!1,"undefined"!=typeof localStorage&&(localStorage.removeItem(Y),localStorage.removeItem(Z)),this.mappings=[],this.rules=[],this.onAuthSuccess(null,[],{_rules:[]}),this.updateMappings([],{_rules:[]})}handleReqAllApis(){this.token?(async e=>{if(!e)return{ok:!1,message:"Missing token",result:[]};const t=await fetch(`${E}/apis`,{method:"GET",headers:F(e)});return S(t)})(this.token).then(e=>{const t=e.ok&&Array.isArray(e.result)?e.result:[];this.sendMessage($.MFM_RES_ALL_APIS,{apis:t})}).catch(()=>this.sendMessage($.MFM_RES_ALL_APIS,{apis:[]})):this.sendMessage($.MFM_RES_ALL_APIS,{apis:[]})}handleToggleApi(e,t){this.token&&e?(async(e,t,n)=>{if(!e)return{ok:!1,message:"Missing token",result:null};const r=await fetch(`${E}/api/${t}/toggle-state`,{method:"PUT",headers:F(e),body:JSON.stringify({enabled:!!n})});return S(r)})(this.token,e,t).then(n=>{this.sendMessage($.MFM_TOGGLE_API_RESULT,{apiId:e,enabled:!!t,ok:!!n.ok,message:n.message||""}),n.ok&&this.refreshMappings()}).catch(()=>this.sendMessage($.MFM_TOGGLE_API_RESULT,{apiId:e,enabled:!!t,ok:!1,message:"Failed to update the mock"})):this.sendMessage($.MFM_TOGGLE_API_RESULT,{apiId:e,enabled:!!t,ok:!1,message:"Missing token"})}refreshMappings(){this.token&&C(this.token,"JAVASCRIPT",(e,t)=>{this.mappings=e||[],this.rules=t?._rules||[],this.tokenInvalidated=!1,this.saveMappings(e,t,this.token,"JAVASCRIPT"),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.token=null,this.isAuthenticated=!1,"undefined"!=typeof localStorage&&(localStorage.removeItem(Y),localStorage.removeItem(Z)),this.mappings=[],this.rules=[],this.onAuthSuccess(null,[],{_rules:[]}),this.sendMessage($.MFM_TOKEN_ERROR,{message:"Unauthorized: Invalid token"})):this.sendMessage($.MFM_TOKEN_API_FAILED,{message:"Unable to reach the mappings service. Please try again."})})}saveMappings(e,t,n=this.token,r="JAVASCRIPT"){if("undefined"!=typeof localStorage)try{localStorage.setItem(Z,JSON.stringify({token:n,adaptor:r,mappings:e,meta:t,timestamp:Date.now()}))}catch(e){console.error("[MockForMe] Failed to save mappings to storage",e)}}handleReqSavedMappings(){const e=this.getSavedMappings(this.token,"JAVASCRIPT");e?(this.mappings=e.mappings||[],this.rules=e.meta?._rules||[],this.onAuthSuccess(this.token,this.mappings,e.meta),this.updateMappings(this.mappings,e.meta)):this.updateMappings([],{_rules:[]})}getSavedMappings(e=this.token,t="JAVASCRIPT"){if("undefined"==typeof localStorage)return null;try{const n=localStorage.getItem(Z);if(!n)return null;const r=JSON.parse(n);return r?.token&&e&&r.token!==e||r?.adaptor&&t&&r.adaptor!==t?null:r}catch(e){return null}}syncInterceptionToggleToWidget(){this.sendMessage($.MFM_TOGGLE_INTERCEPTION,{enabled:this.interceptionEnabled})}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="object"==typeof e.rule&&null!==e.rule?e.rule:{},n={...e,...t},r=n.timingAction||{},o=r.activeAction||"MODIFY";let i="MODIFY";"delay"===o?i="DELAY":"delay_and_timeout"===o?i="TIMEOUT":"delay_and_redirect"===o&&(i="REDIRECT");const s={ruleName:n.ruleName||n._id||"Unnamed Rule",type:i,conditions:n.conditions||[],modificationActions:n.modificationActions||{}};return("MODIFY"!==i||r.activeAction)&&(s.timingAction=r),s}),token:this.token})}handleMockDisabled({apiMethod:e,apiEndpoint:t}={}){if(!t)return;const n=function(e,t){if(!t)return!1;const n=A.length,r=i(e||"");return A=A.filter(e=>!(i(e.apiMethod)===r&&e.apiEndpoint===t)),A.length!==n}(e,t),r=this.mappings.length;if(this.mappings=(this.mappings||[]).filter(n=>!((n.apiMethod||"").toLowerCase()===(e||"").toLowerCase()&&n.apiEndpoint===t)),!n&&this.mappings.length===r)return;this.updateMappings(this.mappings,{_rules:this.rules});const o=`${(e||"").toUpperCase()} ${t}`.trim();this.sendMessage($.MFM_MOCK_DISABLED,{method:e,url:t,message:`${o} mock was disabled and has been removed.`})}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(": "),r=n.shift();r&&(t[r]=n.join(": "))}):t="function"==typeof e.entries?Object.fromEntries(e.entries()):e,Object.keys(t).reduce((e,n)=>(e[n.toLowerCase()]=t[n],e),{})};let r,o,i;if(void 0===t.status||null===t.status)r=void 0;else if("number"==typeof t.status)r=t.status;else{const e=Number(t.status);Number.isFinite(e)?r=e:(r=0,o=String(t.status))}t.aborted||"Aborted"===t.status?i="aborted":t.timeout||"Timeout"===t.status?i="timeout":"Cancelled"===t.status?i="cancelled":(t.error||"Error"===o)&&(i="error");const s=t.pending&&void 0===t.status?null:{statusCode:r,headers:n(t.responseHeaders),body:t.responseBody,endTime:(new Date).toISOString(),...o?{statusText:o}:{},...i?{errorReason:i,failed:!0}:{}},a={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:s,rule:t.rule,timestamp:t.pending&&t.startTime||Date.now(),...Number.isFinite(t.duration)?{duration:t.duration}:{}};if(t.pending)this.sendMessage($.MFM_REQ,a);else if(this.sendMessage($.MFM_RES,a),!this.tokenInvalidated&&a.response&&a.response.headers){const e=a.response.headers["mfm-invalid-token"];if("true"===e||!0===e){console.warn("[MockForMe] Invalid token detected from response headers"),this.tokenInvalidated=!0;let e="Your token is no longer valid. Please enter a valid token.";try{const n=t.responseBody,r="string"==typeof n?JSON.parse(n):n;r&&"string"==typeof r.message&&r.message.trim()&&(e=r.message.trim())}catch(e){}this.sendMessage($.MFM_TOKEN_INVALIDATED,{message:e})}}}sendMessage(e,t){"undefined"!=typeof window&&window.postMessage({type:e,payload:t},"*")}};function ne(e){const t=function(e,t){if(e)return"function"==typeof e.get?e.get(t):"string"==typeof e?((e,t)=>{const n=t.toLowerCase();return e.split(/\r?\n/).map(e=>{const t=e.indexOf(":");return t<0?null:[e.slice(0,t).trim().toLowerCase(),e.slice(t+1).trim()]}).filter(Boolean).find(([e])=>e===n)?.[1]})(e,t):((e,t)=>{const n=t.toLowerCase();for(const t of Object.keys(e||{}))if(t.toLowerCase()===n)return e[t]})(e,t)}(e,"mfm-mock-disabled");return"true"===t||!0===t}class re{static match(e,t){if(!Array.isArray(t)||0===t.length)return!1;const{url:n,headers:r,queryParams:o,body:i}=e,s="undefined"!=typeof window?window.location.origin:globalThis.location?.origin||"http://localhost";for(const e of t){let t="";const{type:a,key:A,operator:l,value:c}=e;switch(a){case"URL":try{t=new URL(n,s).pathname}catch{t=n}break;case"QUERY_PARAM":if(o&&void 0!==o[A])t=String(o[A]);else try{t=new URL(n,s).searchParams.get(A)||""}catch{t=""}break;case"REQUEST_BODY":if(A){if("object"==typeof i&&null!==i)t=void 0!==i[A]?String(i[A]):"";else if("string"==typeof i)try{const e=JSON.parse(i);t=void 0!==e[A]?String(e[A]):""}catch{t=""}}else t="object"==typeof i?JSON.stringify(i):String(i||"");break;case"REQUEST_HEADER":if(A){const e=A?.toLowerCase();if(t="",r){const n=Object.keys(r).find(t=>t.toLowerCase()===e);t=n?String(r[n]):""}}else t=JSON.stringify(r||{});break;default:return!1}if(!this.evaluate(t,l,c))return!1}return!0}static evaluate(e,t,n){const r=t?.toLowerCase(),o=String(e),i=String(n);switch(r){case"contains":return o.includes(i);case"equal":case"equals":return o===i;case"regexp":try{let e=i;if(e.startsWith("/")&&e.lastIndexOf("/")>0){const t=e.lastIndexOf("/"),n=e.slice(1,t),r=e.slice(t+1);return new RegExp(n,r).test(o)}return new RegExp(e).test(o)}catch{return!1}default:return!1}}}class oe{static async apply(e){if(!e||!e.activeAction)return{type:"passThrough",delay:0};const{activeAction:t,actions:n}=e,r=n?.[t];if(!r)return{type:"passThrough",delay:0};const o={type:"passThrough",delay:0},i=Number(r.value||0);switch(t){case"delay":o.delay=i,o.delay>0&&await new Promise(e=>setTimeout(e,1e3*o.delay));break;case"redirect":case"delay_and_redirect":o.type="redirect",o.delay=i,o.redirectUrl=r.redirectUrl,o.delay>0&&await new Promise(e=>setTimeout(e,1e3*o.delay));break;case"delay_and_timeout":o.type="timeout",o.delay=i,o.delay>0&&await new Promise(e=>setTimeout(e,1e3*o.delay))}return o}}class ie{static applyRequestModifications(e,t){if(!t)return e;let{url:n,method:r,headers:o,queryParams:i,body:s}={...e};o&&(o={...o}),i&&(i={...i});const{modifyQueryParams:a,modifyRequestBody:A,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),i&&delete i[t]}),Array.isArray(a.add)&&a.add.forEach(({key:t,value:n})=>{e.searchParams.set(t,n),i&&(i[t]=n)}),n=e.toString()}catch(e){console.error("[MockForMe] Failed to modify query params",e)}l?.enabled&&(o={...o},Array.isArray(l.remove)&&l.remove.forEach(e=>{const t=e.toLowerCase(),n=Object.keys(o).find(e=>e.toLowerCase()===t);n&&delete o[n]}),Array.isArray(l.add)&&l.add.forEach(({key:e,value:t})=>{o[e]=t}));const c=String(r||"GET").toUpperCase(),d="GET"===c||"HEAD"===c;if(A?.enabled&&!d)try{let e=null;if("string"==typeof s)try{e=JSON.parse(s)}catch{e={}}else if("object"==typeof s&&null!==s)try{e=JSON.parse(JSON.stringify(s))}catch{e={...s}}else(Array.isArray(A.add)&&A.add.length>0||Array.isArray(A.update)&&A.update.length>0)&&(e={});e&&(Array.isArray(A.remove)&&A.remove.forEach(t=>delete e[t]),Array.isArray(A.add)&&A.add.forEach(({key:t,value:n})=>e[t]=n),Array.isArray(A.update)&&A.update.forEach(({key:t,value:n})=>e[t]=n),s=JSON.stringify(e))}catch(e){console.error("[MockForMe] Failed to modify request body",e)}return{...e,url:n,headers:o,queryParams:i,body:s}}static applyResponseModifications(e,t){if(!t?.modifyResponseHeaders?.enabled)return e;const{modifyResponseHeaders:n}=t,r={...e};return Array.isArray(n.remove)&&n.remove.forEach(e=>{const t=e.toLowerCase(),n=Object.keys(r).find(e=>e.toLowerCase()===t);n&&delete r[n]}),Array.isArray(n.add)&&n.add.forEach(({key:e,value:t})=>{r[e]=t}),r}}class se{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)&&re.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,r=ie.applyRequestModifications(t,n.modificationActions);return{...await oe.apply(n.timingAction),modifiedRequest:r,rule:n}}static applyResponseModifications(e,t){return ie.applyResponseModifications(e,t)}}class ae{static apply({target:e=("undefined"!=typeof window?window:globalThis),originalFetch:t=e.fetch,ruleProvider:n=()=>[],mappingProvider:r=e=>null,onBeforeRequest:o=e=>{},onRuleMatch:i=async(e,t,n,r,o)=>null,onMockMatch:s=async(e,t,n,r,o)=>null,onOtherRequest:a=async(e,t,n,r)=>null,isEnabled:A=()=>!0,shouldBypassRequest:l=()=>!1}){t&&(e.fetch=async function(e,c={}){if(!A())return t(e,c);let d;try{const n="string"==typeof e?e:e.url,r=String(c.method||(e instanceof Request?e.method:"GET")).toUpperCase().trim(),i=Math.random().toString(36).substring(7);if(d={url:n,method:r,headers:c.headers||(e instanceof Request?e.headers:{}),body:c.body||(e instanceof Request?"{binary/stream}":null),requestId:i,queryParams:ae.getQueryParams(n)},l(d))return t(e,c);o(d)}catch(n){return console.warn("[MockForMe] Fetch Interceptor Setup Error:",n),t(e,c)}try{const o=n(),A=se.match(d,o);if(A){const n=await i(A,d,e,c,t);if(n)return n}const l=r(d);if(l){const n=await s(l,d,e,c,t);if(n)return n}const u=await a(d,e,c,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,c)})}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 Ae{static apply({target:e=("undefined"!=typeof window?window:{}),OriginalXHR:t=e.XMLHttpRequest,ruleProvider:n=()=>[],mappingProvider:r=e=>null,onBeforeRequest:o=e=>{},onRuleMatch:i=(e,t,n,r)=>{r.call(n.proxy,t.body)},onMockMatch:s=(e,t,n,r)=>{r.call(n.proxy,t.body)},onOtherRequest:a=(e,t,n)=>{n.call(t.proxy,e.body)},isEnabled:A=()=>!0,shouldBypassRequest:l=()=>!1}){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,r={}){if(this._captured)return;this._captured=!0;const o=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}),o("readystatechange"),"Aborted"===e||r.aborted?o("abort"):0===e||"Error"===e||r.error?o("error"):"Timeout"===e||r.timeout?o("timeout"):o("load")}abort(){if(!this._isMocked||"function"!=typeof this._onAbort)return this._xhr.abort();this._onAbort()}open(e,t,n=!0,r=null,o=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,r,o)}setRequestHeader(e,t){return this._headers[e]=t,this._xhr.setRequestHeader(e,t)}send(e){if(!A())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:Ae.getQueryParams(this._url)};if(l(t))return this._xhr.send(e);o(t);const c=n(),d=se.match(t,c),u=e=>this._xhr.send(e);if(d)return this._isMocked=!0,i(d,t,this,u);const f=r(t);return f?(this._isMocked=!0,s(f,t,this,u)):(this._isMocked=!1,a(t,this,u))}})}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 le=[g,"https://api.mockforme.com/mockforme/httpRequestBulkMock/bulk_mock"];function ce(e){try{const t="undefined"!=typeof window?window.location.origin:"http://localhost",n=new URL(e.url,t);return le.some(e=>{const r=new URL(e,t);return n.origin===r.origin&&n.pathname===r.pathname})}catch{return!1}}const de=(e,t=null,n=u)=>{if(o())return;let r="string"==typeof e?e:e?.token,i="object"==typeof e?e?.widgetKey:null;if(n===u)try{r&&("undefined"!=typeof localStorage&&(localStorage.removeItem("mockforme-token"),localStorage.setItem("MFM_TOKEN",r)),te.token=r,te.isAuthenticated=!0),!r&&te.token&&(r=te.token),te.onAuthSuccess=(e,t,n)=>{l(t),b(n),te.updateMappings(t,n)},i?te.setWidgetKey(i):te.init()}catch(e){console.log("Error in showing mockforme widget",e)}t||={mappings:[],_o:null,mk:null,_mck:null,_rules:[]};const{mappings:s=[],_o:a,mk:A,_mck:h,_rules:p=[]}=t;return l(s),b({_o:a,mk:A,_mck:h,_rules:p}),{run:(e,t=()=>{})=>{if(function(e,t){if("undefined"!=typeof window){if(window._mfm_intercepted)return;window._mfm_intercepted=!0}const n=()=>te.token||e;ae.apply({isEnabled:()=>te.interceptionEnabled,shouldBypassRequest:ce,ruleProvider:()=>v(),mappingProvider:e=>{try{return d(new URL(e.url,window.location.origin).pathname,e.method)}catch{return null}},onRuleMatch:async(e,t,n,r,o)=>{const i=t.requestId||Math.random().toString(36).substring(7),s=Date.now();te.addRequest("mocked",{...t,requestId:i,pending:!0,startTime:s,rule:e});const a=await se.apply(e,t),{modifiedRequest:A,type:l,delay:c,redirectUrl:d}=a;if("timeout"!==l&&te.addRequest("mocked",{...A,requestId:i,pending:!0,startTime:s,rule:e}),"timeout"===l){const t=Date.now()-s;throw te.addRequest("mocked",{...A,requestId:i,status:"Aborted",pending:!1,duration:t,aborted:!0,rule:e}),new Error("Fetch timed out by rules")}if("redirect"===l&&!d)throw new Error("rules: Redirect missing URL");let u="redirect"===l?d:A.url,f={...r};A.headers&&(f.headers=A.headers),A.body&&(f.body=A.body);let h=null;if("redirect"===l){h=Math.random().toString(36).substring(7);const e={url:d,method:A.method,headers:f.headers||{},body:f.body,requestId:h,queryParams:ae.getQueryParams(d),requestHeaders:f.headers||{},requestBody:f.body,pending:!0,startTime:Date.now()};te.addRequest("mocked",e)}return o(u,f).then(async e=>{const t=Date.now()-s;let n=Object.fromEntries(e.headers.entries());if(a.rule.modificationActions?.modifyResponseHeaders?.enabled&&(n=se.applyResponseModifications(n,a.rule.modificationActions)),"redirect"===l&&h){const t=e.clone(),r=t.headers.get("content-type")||"",o=Date.now()-s;try{let i;i=r.includes("application/json")?await t.json():await t.text(),te.addRequest("mocked",{url:d,method:A.method,requestId:h,status:e.status,pending:!1,duration:o,responseHeaders:n,responseBody:i,requestHeaders:f.headers||{},requestBody:f.body})}catch(t){te.addRequest("mocked",{url:d,method:A.method,requestId:h,status:e.status,pending:!1,duration:o,responseHeaders:n,requestHeaders:f.headers||{},requestBody:f.body})}}return te.addRequest("mocked",{...A,requestId:i,status:e.status,pending:!1,duration:t,responseHeaders:n,rule:a.rule}),e}).catch(e=>{const t=Date.now()-s,n="AbortError"===e.name||e.message.includes("aborted");if(te.addRequest("mocked",{...A,requestId:i,status:n?"Aborted":0,pending:!1,duration:t,rule:a.rule}),"redirect"===l&&h&&te.addRequest("mocked",{url:d,method:A.method,requestId:h,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,r,o,i,s)=>{const a=r.requestId||Math.random().toString(36).substring(7),A=Date.now();te.addRequest("mocked",{...r,requestId:a,pending:!0,startTime:A});const l=n(),c=new URL(r.url,window.location.origin).search;let d=`${B()}${e.url}${c}`,u={[f]:l,mfmver:"14.5.0","x-mfm-adaptor":t};const h=x();h&&e._ack&&(u["x-mfm-key"]=`${h}-${e._ack}`),e?._ri_&&(u._ri_=e._ri_);const p=o instanceof Request?o.headers:i.headers,g=new Headers(p||{});Object.entries(u).forEach(([e,t])=>g.set(e,t)),g.set("x-mfm-internal","true");let m=i.body;if(!m&&o instanceof Request){const e=o.clone();"GET"!==e.method&&"HEAD"!==e.method&&(m=await e.text())}const y={method:r.method,headers:g,credentials:o instanceof Request&&o.credentials||i.credentials||"include",mode:o instanceof Request&&o.mode||i.mode||"cors",signal:o instanceof Request&&o.signal||i.signal};return m&&(y.body=m),s(d,y).then(async t=>{const n=t.clone(),o=n.headers.get("content-type")||"",i=Date.now()-A;ne(t.headers)&&te.handleMockDisabled({apiMethod:e.method,apiEndpoint:e.apiEndpoint});const s=e=>(te.addRequest("mocked",{...r,requestId:a,status:t.status,responseHeaders:Object.fromEntries(n.headers.entries()),responseBody:e,pending:!1,duration:i}),new Response("string"==typeof e?e:JSON.stringify(e),{status:t.status,headers:n.headers}));return o.includes("application/json")?n.json().then(s):n.text().then(s)}).catch(e=>{const t=Date.now()-A,n=e&&("AbortError"===e.name||String(e.message||"").toLowerCase().includes("abort"));if(te.addRequest("mocked",{...r,requestId:a,status:n?"Aborted":0,pending:!1,duration:t,aborted:n}),n)throw e;return s(o,i)})},onOtherRequest:async(e,t,n,r)=>{const o=n?.headers||(t instanceof Request?t.headers:{});let i=!1;o instanceof Headers?i="true"===o.get("x-mfm-internal"):"object"==typeof o&&(i="true"===o["x-mfm-internal"]);const s=B();if(e.url.startsWith(s)&&(i=!0),"OPTIONS"===e.method||i)return r(t,n);const a=e.requestId,A=Date.now();te.addRequest("other",{...e,requestId:a,pending:!0,startTime:A});const l=R(e.method,e.url),c=M(e.method,e.url);let d=t,u=n,f=e;if(l){const t={};try{new URL(e.url,"undefined"!=typeof window?window.location.origin:"http://localhost").searchParams.forEach((e,n)=>{t[n]=e})}catch(e){}const r=await z({requestId:a,ruleId:l.id,request:{method:e.method,url:e.url,headers:e.headers,body:e.body},queryParams:t});if(r.cancel){te.addRequest("other",{...e,requestId:a,status:"Cancelled",pending:!1,duration:Date.now()-A,error:!0});const t=new Error("Request cancelled by MockForMe request editor");throw t.name="AbortError",t}let o=e.url;try{const t=new URL(e.url,"undefined"!=typeof window?window.location.origin:"http://localhost");[...t.searchParams.keys()].forEach(e=>t.searchParams.delete(e)),Object.entries(r.queryParams||{}).forEach(([e,n])=>{t.searchParams.set(e,String(n??""))}),o="string"==typeof e.url&&e.url.startsWith("/")?`${t.pathname}${t.search}`:t.href}catch(e){}const i=String(e.method||"GET").toUpperCase(),s="GET"!==i&&"HEAD"!==i;u={...n,method:e.method,headers:r.headers||{},body:s?null==r.body?void 0:r.body:void 0},d=o,f={...e,url:o,headers:r.headers||{},body:s?r.body:null}}const h=J();h>0&&await new Promise(e=>setTimeout(e,h));let p=null,g=null;try{p=await r(d,u)}catch(e){g=e}if(c){let t="",n=0,r={};if(p){try{t=await p.clone().text()}catch(e){}n=p.status,r=Object.fromEntries(p.headers.entries())}else g&&(t=g.message||"Network error",n=0);const o=await H({requestId:a,ruleId:c.id,request:{method:f.method,url:f.url,headers:f.headers,body:f.body},response:{statusCode:n,headers:r,body:t}});if(o.simulateTimeout){te.addRequest("other",{...e,requestId:a,status:"Timeout",responseHeaders:{},pending:!1,duration:Date.now()-A,timeout:!0});const t=new Error("Network request failed (simulated by MockForMe debugger)");throw t.name="AbortError",t}o.delayMs>0&&await new Promise(e=>setTimeout(e,o.delayMs));const i=Number(o.statusCode),s=Number.isFinite(i)&&i>=200&&i<=599?i:n>=200?n:200,l=o.headers&&"object"==typeof o.headers?o.headers:r,d="string"==typeof o.body?o.body:null==o.body?"":JSON.stringify(o.body);te.addRequest("other",{...e,requestId:a,status:s,responseHeaders:l,responseBody:d,pending:!1,duration:Date.now()-A});const u={};return Object.entries(l).forEach(([e,t])=>{const n=e.toLowerCase();"content-length"!==n&&"content-encoding"!==n&&"transfer-encoding"!==n&&(u[e]=t)}),new Response(d,{status:s,statusText:p?p.statusText:"",headers:new Headers(u)})}const m=Date.now()-A;if(g){const t="AbortError"===g.name||(g.message||"").includes("aborted"),n="TimeoutError"===g.name||(g.message||"").includes("timed out");throw te.addRequest("other",{...e,requestId:a,status:t?"Aborted":n?"Timeout":"Error",pending:!1,duration:m,aborted:t,timeout:n,error:!t&&!n}),g}const y=Object.fromEntries(p.headers.entries());let w;try{const e=p.clone(),t=5e3,n=Symbol("body-timed-out"),r=await Promise.race([e.text(),new Promise(e=>setTimeout(()=>e(n),t))]);w=r===n?void 0:r}catch(e){w=void 0}return te.addRequest("other",{...e,requestId:a,status:p.status,responseHeaders:y,responseBody:w,pending:!1,duration:m}),p}}),Ae.apply({isEnabled:()=>te.interceptionEnabled,shouldBypassRequest:ce,ruleProvider:()=>v(),mappingProvider:e=>{try{return d(new URL(e.url,window.location.origin).pathname,e.method)}catch{return null}},onRuleMatch:async(e,t,n,r)=>{const o=t.requestId,i=Date.now();te.addRequest("mocked",{...t,requestId:o,pending:!0,startTime:i,rule:e});const s=await se.apply(e,t),{modifiedRequest:a,type:A,redirectUrl:l}=s;"timeout"!==A&&te.addRequest("mocked",{...a,requestId:o,pending:!0,startTime:i,rule:e});let c=null;if("redirect"===A){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()};te.addRequest("mocked",e)}const d=(e,t,r,d={})=>{const u=Date.now()-i;if(s.rule.modificationActions?.modifyResponseHeaders?.enabled){let e="string"==typeof r?Object.fromEntries(r.split("\r\n").filter(e=>e).map(e=>e.split(": "))):r;e=se.applyResponseModifications(e,s.rule.modificationActions),r=e}te.addRequest("mocked",{...a,requestId:o,status:e,responseBody:t,responseHeaders:r,pending:!1,duration:u,rule:s.rule,...d}),"redirect"===A&&c&&te.addRequest("mocked",{url:l,method:a.method,requestId:c,status:e,responseBody:t,responseHeaders:r,pending:!1,duration:u,requestHeaders:a.headers||{},requestBody:a.body,...d}),n._capture(e,t,r,d)};if("timeout"===A)return d("Aborted","Timed out by rule",{},{aborted:!0}),void n._xhr.abort();if("redirect"===A){if(!l)return void d(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",()=>d("Aborted","Aborted",{},{aborted:!0}),{once:!0}),n._xhr.addEventListener("error",()=>d(0,"Error",{},{error:!0}),{once:!0}),n._xhr.addEventListener("timeout",()=>d("Timeout","Timeout",{},{timeout:!0}),{once:!0}),n._xhr.addEventListener("load",()=>d(n._xhr.status,n._xhr.responseText,n._xhr.getAllResponseHeaders()),{once:!0}),r(a.body)},onMockMatch:(e,r,o,i)=>{const s=r.requestId,a=Date.now(),A=n(),l=new URL(r.url,window.location.origin);let c=`${B()}${e.url}${l.search}`,d={[f]:A,mfmver:"14.5.0","x-mfm-adaptor":t};const u=x();u&&e._ack&&(d["x-mfm-key"]=`${u}-${e._ack}`),e?._ri_&&(d._ri_=e._ri_),d["x-mfm-internal"]="true";const h={...r.headers,...d};te.addRequest("mocked",{...r,requestId:s,pending:!0,startTime:a});const p=(t,n,i,A={})=>{if(o._captured)return;const l=Date.now()-a;ne(i)&&te.handleMockDisabled({apiMethod:e.method,apiEndpoint:e.apiEndpoint}),te.addRequest("mocked",{...r,requestId:s,status:t,responseBody:n,responseHeaders:i,pending:!1,duration:l,...A}),o._capture(t,n,i,A)};o._xhr.addEventListener("abort",()=>p("Aborted","Aborted",{},{aborted:!0}),{once:!0}),o._xhr.addEventListener("error",()=>p(0,"Error",{},{error:!0}),{once:!0}),o._xhr.addEventListener("timeout",()=>p("Timeout","Timeout",{},{timeout:!0}),{once:!0});const g=new window.XMLHttpRequest;g.open(r.method,c,!0);for(const e in h)g.setRequestHeader(e,h[e]);g.withCredentials=o.proxy.withCredentials,o._onAbort=()=>{try{g.abort()}catch(e){}p("Aborted","Aborted",{},{aborted:!0})},g.onload=()=>p(g.status,g.responseText,g.getAllResponseHeaders()),g.onerror=()=>p(0,"Network Error",{},{error:!0}),g.ontimeout=()=>p("Timeout","Request timed out",{},{timeout:!0}),g.send(r.body)},onOtherRequest:(e,t,n)=>{const r="true"===e.headers?.["x-mfm-internal"],o=B(),i=e.url.startsWith(o);if("OPTIONS"===e.method||r||i)return n(e.body);const s=Date.now();te.addRequest("other",{...e,pending:!0,startTime:s});const a=R(e.method,e.url),A=M(e.method,e.url);let l=e;const c=(n,r,o,i={})=>{const a=Date.now()-s;te.addRequest("other",{...e,status:n,responseBody:r,responseHeaders:o,pending:!1,duration:a,...i}),t._capture(n,r,o,i)};if(t._xhr.addEventListener("abort",()=>c("Aborted","Aborted",{},{aborted:!0}),{once:!0}),t._xhr.addEventListener("error",()=>c(0,"Error",{},{error:!0}),{once:!0}),t._xhr.addEventListener("timeout",()=>c("Timeout","Timeout",{},{timeout:!0}),{once:!0}),t._xhr.addEventListener("load",async()=>{const n=t._xhr.status,r=t._xhr.responseText,o=t._xhr.getAllResponseHeaders();if(A){const t={};"string"==typeof o&&o.split("\r\n").forEach(e=>{const n=e.indexOf(": ");n>0&&(t[e.slice(0,n)]=e.slice(n+2))});const i=await H({requestId:e.requestId,ruleId:A.id,request:{method:l.method,url:l.url,headers:l.headers,body:l.body},response:{statusCode:n,headers:t,body:r}});if(i.simulateTimeout)return void c("Timeout","Timeout (Debugger)",{},{timeout:!0});i.delayMs>0&&await new Promise(e=>setTimeout(e,i.delayMs));const s=Number(i.statusCode)||n,a=i.headers&&"object"==typeof i.headers?i.headers:t,d="string"==typeof i.body?i.body:null==i.body?"":JSON.stringify(i.body);return void c(s,d,a)}c(n,r,o)},{once:!0}),t._xhr.addEventListener("readystatechange",()=>{if(t._xhr.readyState>=2&&!t._captured){const n=t._xhr.status;if(n>0){const r=Date.now()-s;te.addRequest("other",{...e,status:n,responseHeaders:t._xhr.getAllResponseHeaders(),pending:t._xhr.readyState<4,duration:r})}}}),a)return void(async()=>{const r={};try{new URL(e.url,"undefined"!=typeof window?window.location.origin:"http://localhost").searchParams.forEach((e,t)=>{r[t]=e})}catch(e){}const o=await z({requestId:e.requestId,ruleId:a.id,request:{method:e.method,url:e.url,headers:e.headers,body:e.body},queryParams:r});if(o.cancel){c("Cancelled","Cancelled by editor",{},{aborted:!0});try{t._xhr.abort()}catch(e){}return}let i=e.url;try{const t=new URL(e.url,"undefined"!=typeof window?window.location.origin:"http://localhost");[...t.searchParams.keys()].forEach(e=>t.searchParams.delete(e)),Object.entries(o.queryParams||{}).forEach(([e,n])=>{t.searchParams.set(e,String(n??""))}),i="string"==typeof e.url&&e.url.startsWith("/")?`${t.pathname}${t.search}`:t.href}catch(e){}if(i!==e.url)try{t._xhr.open(e.method,i,!0)}catch(e){}Object.entries(o.headers||{}).forEach(([e,n])=>{try{t._xhr.setRequestHeader(e,String(n??""))}catch(e){}}),l={...e,url:i,headers:o.headers||{},body:o.body};const s=String(e.method||"GET").toUpperCase(),A="GET"!==s&&"HEAD"!==s?null==o.body?null:o.body:null,d=J();d>0?setTimeout(()=>{try{n(A)}catch(e){}},d):n(A)})();const d=J();d>0?setTimeout(()=>{try{n(e.body)}catch(e){}},d):n(e.body)}})}(r,n),a&&A)te.mappings=s,te.rules=p,e?.(s,{_o:a,mk:A,_mck:h,_rules:p});else if(r){const t=te.getSavedMappings(r,n);if(t&&Array.isArray(t.mappings))return te.mappings=t.mappings,te.rules=t.meta?._rules||[],l(t.mappings),b(t.meta),te.updateMappings(t.mappings,t.meta),void e?.(t.mappings,t.meta);te.updateMappings([],{_rules:[]}),e?.([],{_rules:[]})}},checkIfApiToBeMocked:d,getMappings:c,doFetchMappings:(e,t)=>{C(r||te.token,n,(t,o)=>{te.saveMappings(t,o,r||te.token,n),te.updateMappings(t,o),e?.(t,o)},t)},recheckWidgetVisibility:()=>{te.init()}}},ue=o();ue||(globalThis.mockforme=de);let fe=de;ue&&(fe=e=>({run:()=>{}}));const he=fe;return r=r.mockforme,r})());
|
|
20
|
+
`;function AA({message:e,theme:t}){return Ct("div",{role:"alert",css:gt("background:#fef2f2;border:1px solid #fecaca;border-left:3px solid ",t.color.error,";color:",t.color.error,";padding:",t.spacing.md," ",t.spacing.lg,";border-radius:",t.radius.md,";font-size:",t.typography.fontSizeBase,";line-height:1.5;display:flex;align-items:flex-start;gap:",t.spacing.sm,";",""),children:[xt("strong",{css:gt("font-weight:",t.typography.fontWeightBold,";",""),children:"✗"}),xt("span",{children:e})]})}function lA(e){const t=document.getElementById("mfm-root");return!!t&&(t===e||t.contains(e))}function cA(e){if(!e)return"";if(e.length<=1e3)return e;return e.slice(0,988)+"…[truncated]"}function dA(){const e=Ut(),{confirmState:t,dismissConfirm:n}=un();if(u.useEffect(()=>{if(!t)return;const e=e=>{"Escape"===e.key&&n()};return document.addEventListener("keydown",e),()=>document.removeEventListener("keydown",e)},[t,n]),!t)return null;const{title:r,message:o,confirmLabel:i,cancelLabel:s,danger:a,onConfirm:A}=t;return xt("div",{role:"dialog","aria-label":r??"Confirm","aria-modal":"true",onClick:e=>{e.target===e.currentTarget&&n()},css:gt("position:absolute;inset:0;background:rgba(15, 23, 42, 0.5);z-index:",e.z.confirm,";display:flex;align-items:center;justify-content:center;padding:",e.spacing.xl,";",""),children:Ct("div",{css:gt("background:",e.color.bg,";border-radius:",e.radius.lg,";box-shadow:",e.shadow.lg,";padding:",e.spacing.xl,";max-width:360px;width:100%;display:flex;flex-direction:column;gap:",e.spacing.md,";",""),children:[r?xt("h3",{css:gt("margin:0;font-size:",e.typography.fontSizeLg,";font-weight:",e.typography.fontWeightBold,";color:",e.color.text,";",""),children:r}):null,xt("p",{css:gt("margin:0;color:",e.color.text,";font-size:",e.typography.fontSizeBase,";line-height:1.5;",""),children:o}),Ct("div",{css:gt("display:flex;justify-content:flex-end;gap:",e.spacing.md,";margin-top:",e.spacing.sm,";",""),children:[xt("button",{type:"button",onClick:n,css:gt("appearance:none;background:transparent;border:1px solid ",e.color.border,";color:",e.color.text,";font-family:inherit;font-size:",e.typography.fontSizeBase,";padding:",e.spacing.sm," ",e.spacing.lg,";border-radius:",e.radius.md,";cursor:pointer;&:hover{background:",e.color.surfaceBright,";}",""),children:s??"Cancel"}),xt("button",{type:"button",autoFocus:!0,onClick:()=>{n(),A()},css:gt("appearance:none;border:none;background:",a?e.color.error:e.color.primary,";color:#fff;font-family:inherit;font-weight:",e.typography.fontWeightSemibold,";font-size:",e.typography.fontSizeBase,";padding:",e.spacing.sm," ",e.spacing.lg,";border-radius:",e.radius.md,";cursor:pointer;&:hover{filter:brightness(0.95);}",""),children:i??"Confirm"})]})]})})}function uA(){const{analyticsEnabled:e}=tr(),{token:t,organisationId:n}=gn();return u.useEffect(()=>{rn.setEnabled(e)},[e]),u.useEffect(()=>{rn.setToken(t)},[t]),u.useEffect(()=>{rn.setOrganisationId(n)},[n]),null}function fA({clientType:e,version:t}={}){return Ct(Qt,{initialMode:"light",children:[xt(hA,{}),xt(Mt,{children:xt(dn,{clientType:e,version:t,children:xt(pn,{children:xt(yn,{children:xt(Un,{children:xt(Nn,{children:xt(er,{children:xt(Jn,{children:Ct(ir,{children:[xt(uA,{}),xt(So,{}),xt(pA,{})]})})})})})})})})})]})}function hA(){const e=Ut();return xt(pt,{styles:gt(":host,[data-mfm-mount]{all:initial;color:",e.color.text,";font-family:",e.typography.fontFamily,";font-size:",e.typography.fontSizeBase,";line-height:1.4;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;text-rendering:optimizeLegibility;}*,*::before,*::after{box-sizing:border-box;}::-webkit-scrollbar{width:8px;height:8px;}::-webkit-scrollbar-thumb{background:",e.color.border,";border-radius:",e.radius.pill,";}::-webkit-scrollbar-thumb:hover{background:",e.color.textDim,";}","")})}function pA(){const{setOpen:e,isInterceptEnabled:t,toggleIntercept:n,isSettingsOpen:r,openSettings:o,startSnipping:i,requestConfirm:s}=un(),{token:a,isTokenValidated:A,isValidating:l,isLoading:c,reloadMappings:d,deleteToken:u}=gn(),{debugRules:f,editRules:h}=Wn(),{globalDelay:p}=tr();if(!A&&(l||a))return Ct(Bt,{children:[xt(_o,{children:xt(bA,{children:xt(mA,{})})}),xt(qa,{})]});if(!a)return Ct(Bt,{children:[xt(_o,{children:Ct(bA,{children:[xt(pa,{}),xt(dA,{})]})}),xt(qa,{})]});const g=r||f.length>0||h.length>0||p.enabled;return Ct(Bt,{children:[Ct(_o,{children:[xt(Oo,{onSnip:i,onReload:d,onOpenSettings:o,onDeleteToken:()=>{s({title:"Delete token?",message:"Are you sure you want to delete token? API interception will stop once the token is removed.",confirmLabel:"Delete",danger:!0,onConfirm:u})},isInterceptEnabled:t,onToggleIntercept:()=>{t?s({title:"Disable interception?",message:"Once disabled, the widget will stop intercepting requests and disappear from the page. Please refresh the page after disabling it. You can re-enable it anytime from the MockForMe settings page via the extension icon in tray or the right-click menu. You can also re-enable it from inside Widget Settings → Whitelisted Hosts.",confirmLabel:"Disable",danger:!0,onConfirm:n}):n()},onClose:()=>e(!1),isSettingsActive:g,isReloading:c,isAuthenticated:!0}),xt(Po,{}),Ct(bA,{children:[xt(da,{}),xt(ga,{}),xt(ka,{}),xt(Ba,{}),xt(Ua,{}),xt(Na,{}),xt(dA,{}),xt(yA,{})]})]}),xt(qa,{})]})}var gA={name:"3kwpv8",styles:"flex:1;min-height:0;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:14px;padding:24px;text-align:center"};function mA(){const e=Ut();return Ct("div",{css:gA,children:[xt(yi,{size:26,color:e.color.primary,label:"Validating token"}),xt("div",{css:gt("font-size:",e.typography.fontSizeBase,";font-weight:600;color:",e.color.text,";",""),children:"Validating your token…"}),xt("div",{css:gt("font-size:12px;color:",e.color.textDim,";max-width:260px;line-height:1.5;",""),children:"Hang tight — we're verifying your session before loading the widget."})]})}function yA(){const{invalidatedMessage:e,acknowledgeInvalidation:t}=gn(),n=Ut();return null==e?null:xt(ri,{open:!0,hideClose:!0,title:"Token no longer valid",leadingDot:"live",onClose:()=>{},footer:xt("button",{type:"button",onClick:t,css:gt("appearance:none;border:none;border-radius:",n.radius.sm,";background:",n.color.primary,";color:#fff;font-size:",n.typography.fontSizeBase,";font-weight:",n.typography.fontWeightBold,";padding:8px 20px;cursor:pointer;&:hover{background:",n.color.primaryHover,";}",""),children:"OK"}),children:xt("p",{css:gt("margin:0;font-size:",n.typography.fontSizeBase,";line-height:1.5;color:",n.color.text,";",""),children:e})})}var wA={name:"4oq8x6",styles:"position:absolute;inset:0;pointer-events:none;z-index:1500;&:empty{display:none;}&>*{pointer-events:auto;}"},kA={name:"p72qif",styles:"flex:1;min-height:0;position:relative;display:flex;flex-direction:column;overflow:hidden"};function bA({children:e}){const{fullscreenSlotRef:t}=un();return Ct("div",{css:kA,children:[e,xt("div",{ref:t,"data-mfm-fullscreen-slot":!0,css:wA})]})}class vA extends u.Component{constructor(){super(...arguments),o(this,"state",{hasError:!1})}static getDerivedStateFromError(){return Or(),{hasError:!0}}componentDidCatch(e,t){try{this.props.onError(e,t)}catch{}}render(){return this.state.hasError?null:this.props.children}}const BA=(()=>{try{const e="file:///Users/sushilkumar/mockforme/shared/mockforme_widget/dist/chunks/widget-B8TRg0gv.js",t=e.lastIndexOf("/");return t>0?e.slice(0,t+1):e}catch{return""}})();function xA(e,t){return!(!BA||!function(){try{const e=typeof document<"u"&&(document.baseURI||document.location&&document.location.href)||"";return!!e&&!e.startsWith(BA)}catch{return!1}}()||!(e&&e.startsWith(BA)||t&&-1!==t.indexOf(BA)))}let CA=null;const EA="data-mfm-mount";function FA(e){return e||document.getElementById("mfm-root")||(document.body?document.body:null)}function SA(e,t){let n;"mfm-root"===e.id?n=e:(n=document.createElement("div"),n.id="mfm-root",e.appendChild(n)),n.style.cssText="all: initial; display: block;",function(e){try{rn.init(),rn.setClientType(e);const t=tn().read("MFM_TOKEN");t&&rn.setToken(t)}catch{}}(t.clientType);const r=["click","dblclick","mousedown","mouseup","mousemove","pointerdown","pointerup","pointermove","contextmenu","wheel","touchstart","touchend","touchmove"],o=e=>e.stopPropagation();for(const e of r){const t="wheel"===e||"touchstart"===e||"touchend"===e||"touchmove"===e;n.addEventListener(e,o,{passive:t})}const i=n.shadowRoot??n.attachShadow({mode:"open"});let s=i.querySelector(`[${EA}]`);s||(s=document.createElement("div"),s.setAttribute(EA,""),i.appendChild(s));const a=Ue({key:"mfm",container:i,prepend:!0}),A={run:()=>{}},l=F.createRoot(s);l.render(u.createElement(u.StrictMode,null,u.createElement(rt,{value:a},u.createElement(vA,{onError:e=>{setTimeout(()=>A.run(e),0)}},u.createElement(fA,{clientType:t.clientType,version:t.version})))));const c=e=>{const t=e.error;xA(e.filename,t?.stack)&&(Or(),e.preventDefault(),A.run(e.error))},d=e=>{const t=e.reason;xA(void 0,t?.stack??(t?String(t):void 0))&&(Or(),e.preventDefault(),A.run(e.reason))};window.addEventListener("error",c),window.addEventListener("unhandledrejection",d);const f=console.error;console.error=function(...e){if(!(jr>0)){if(BA)for(let t=0;t<e.length;t++){const n=e[t];if(-1!==((n&&"object"==typeof n&&"stack"in n?String(n.stack??""):"")||String(n)).indexOf(BA))return}f.apply(console,e)}};let h=!1,p=null;const g=e=>{if(!h){if(h=!0,window.removeEventListener("error",c),window.removeEventListener("unhandledrejection",d),console.error!==f)try{console.error=f}catch{}try{l.unmount()}catch{}try{n.remove()}catch{}CA=null;try{if(void 0!==e){const t=e,n=t&&"string"==typeof t.message?t.message:"string"==typeof e?e:String(e),r=t&&"string"==typeof t.stack?t.stack:"";Vr("widget_load_failed",{errorName:t&&"string"==typeof t.name?t.name:"Error",errorMessage:n,errorStack:r.slice(0,4e3),userAgent:typeof navigator<"u"?navigator.userAgent:"",url:typeof location<"u"?location.href:""})}else rn.track("widget_destroyed");Gr()}catch{}if(void 0!==e)try{p=function(){if(typeof document>"u"||!document.body)return{dismiss(){}};const e=document.createElement("div");e.id="mfm-error-snackbar",e.style.cssText=["all: initial","position: fixed","right: 16px","bottom: 16px","z-index: 2147483646"].join(";"),document.body.appendChild(e);const t=e.attachShadow({mode:"closed"}),n=document.createElement("div");n.style.cssText=["box-sizing: border-box","display: flex","align-items: center","gap: 10px","min-width: 280px","max-width: 380px","padding: 10px 12px","background: #1f2937","color: #f9fafb","border: 1px solid #374151","border-radius: 8px","box-shadow: 0 8px 24px rgba(0,0,0,0.25)",'font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',"font-size: 13px","line-height: 1.4"].join(";");const r=document.createElement("div");r.style.cssText=["flex: 1 1 auto","min-width: 0"].join(";");const o=document.createElement("div");o.textContent="MockForMe is unable to load.",o.style.cssText="font-weight: 500";const i=document.createElement("div");i.textContent="The issue has been reported.",i.style.cssText=["margin-top: 2px","color: #9ca3af","font-size: 12px"].join(";"),r.appendChild(o),r.appendChild(i);const s=document.createElement("button");s.type="button",s.setAttribute("aria-label","Dismiss"),s.textContent="×",s.style.cssText=["flex: 0 0 auto","width: 24px","height: 24px","padding: 0","background: transparent","color: #9ca3af","border: 0","border-radius: 4px","cursor: pointer","font-size: 18px","line-height: 1"].join(";");let a=!1;const A=()=>{if(!a){a=!0;try{e.remove()}catch{}}};return s.addEventListener("click",A),n.appendChild(r),n.appendChild(s),t.appendChild(n),{dismiss:A}}()}catch{}}};return A.run=g,{destroy(){if(g(),p){try{p.dismiss()}catch{}p=null}}}}const QA={run(e,t={}){if(CA)return CA;if(typeof document<"u"&&"loading"===document.readyState){let n=!1;const r=()=>{if(n)return;const r=FA(e);r&&(CA=SA(r,t))};return document.addEventListener("DOMContentLoaded",r,{once:!0}),{destroy(){n=!0,document.removeEventListener("DOMContentLoaded",r),CA&&CA.destroy()}}}const n=FA(e);return n?(CA=SA(n,t),CA):(console.warn("[MockForMeWidget] no mount target available"),{destroy(){}})}};typeof window<"u"&&(window.MockForMeWidget=QA),n.d(t,["M",0,QA])},435(e,t,n){n.d(t,{MockForMeWidget:()=>r.M});var r=n(411)}};const t={};function n(r){const o=t[r];if(void 0!==o)return o.exports;const i=t[r]={exports:{}};return e[r](i,i.exports,n),i.exports}n.d=(e,t)=>{if(Array.isArray(t))for(var r=0;r<t.length;){var o=t[r++],i=t[r++];n.o(e,o)?0===i&&r++:0===i?Object.defineProperty(e,o,{enumerable:!0,value:t[r++]}):Object.defineProperty(e,o,{enumerable:!0,get:i})}else 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=>{Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};let r={};n.d(r,{mockforme:()=>fe});const o=()=>"undefined"!=typeof process&&null!=process.versions?.node,i=e=>{try{return e?e.toLowerCase():e}catch(e){return console.log(e),null}},s=(e,t)=>{const n=e.split("/"),r=t.split("/");if(n.length!==r.length)return!1;for(let e=0;e<n.length;e++){const t=n[e];if(t!==r[e]&&":any"!==t&&":"!==t.charAt(0))return!1}return!0},a=new Map;let A=[];function l(e){A=e}function c(){return A}function d(e,t="get"){const n=e=>e.startsWith("/")?e:`/${e}`,r=n(e),o=function(e,t){if(0===a.size)return null;for(const n of a.values())for(const r of n){if(i(r.apiMethod)!==i(t))continue;const n=r.apiEndpoint.startsWith("/")?r.apiEndpoint:`/${r.apiEndpoint}`;if(n===e||s(n,e)){const t={url:e,method:r.apiMethod,_ack:r._ack||null};return r._ri_&&(t._ri_=r._ri_),t}}return null}(r,t);if(o)return console.log(`[MockForMe] Flow Mock Match: ${t} ${e} -> ${o.url}`),o;for(const o of A)if(i(o.apiMethod)===i(t)){const i=n(o.apiEndpoint);if(i===r||s(i,r)){console.log(`[MockForMe] Match Found: ${t} ${e} -> ${o.apiEndpoint}`);const n={url:e,method:o.apiMethod,apiEndpoint:o.apiEndpoint,_ack:o._ack||null};return o._ri_&&(n._ri_=o._ri_),n}}return null}const u="JAVASCRIPT",f="mockforme",h="https://api.mockforme.com",p=`${h}/mockforme`,g=`${h}/gateway/3f4eae522b`;let m=null,y=null,w=null,k=[];function b({_o:e,mk:t,_mck:n,_rules:r}){m=e,y=t,w=n,k=r}function v(){return k}function B(){return`${p}/${m}/${y}`}function x(){return w}function C(e,t,n,r){fetch(g,{method:"GET",headers:{[f]:e,mfmver:"14.5.1","x-mfm-adaptor":t}}).then(e=>{if(!e.ok)throw e;return e.json()}).then(e=>{if(e){const{di:t,iv:r,_o:o,_mck:i,mk:s,r:a}=e,A=function({di:e,iv:t},n){var r;const o=function(e,t){const n=t.length;return e.split("").map((e,r)=>String.fromCharCode(e.charCodeAt(0)^t.charCodeAt(r%n))).join("")}((r=e,"undefined"!=typeof Buffer?Buffer.from(r,"base64").toString("utf8"):decodeURIComponent(escape(atob(r)))),n+t);return JSON.parse(o)}({di:t,iv:r},o);b({_o:o,mk:s,_mck:i,_rules:a}),A&&(l(A),n(A,{_o:o,mk:s,_mck:i,_rules:a}))}}).catch(e=>{console.error("Error in loading mocked APIs:",e),r(e)})}const E=`${h}/mockforme/mfm_op_3f4eae522b/manage`,F=e=>({[f]:e,mfmver:"14.5.1","Content-Type":"application/json"}),S=async e=>{let t=null;try{t=await e.json()}catch(e){}return{ok:!(!e.ok||!t||!0!==t.status&&"success"!==t.status&&1!==t.status),message:t&&t.message||(e.ok?"":`Request failed (${e.status})`),result:t?t.result:null}},Q="MFM_INTERCEPTOR_RULES";let U=[];const T=new Map;function I(){try{if("undefined"==typeof localStorage)return[];const e=localStorage.getItem(Q);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>e&&e.enabled):[]}catch(e){return[]}}function _(e){U=Array.isArray(e)?e.filter(e=>e&&e.enabled):[]}function M(e,t){if(!e||!t)return null;if(!U.length&&(U=I(),!U.length))return null;const n=String(e).toUpperCase();return U.find(e=>{if(!e.enabled||String(e.method).toUpperCase()!==n)return!1;if("PATH"===e.matchType)try{return new URL(e.url,"http://localhost").pathname===new URL(t,"http://localhost").pathname}catch(n){return e.url===t}return e.url===t})||null}function H({requestId:e,ruleId:t,request:n,response:r,timeoutMs:o=3e5}){return new Promise(i=>{const s=setTimeout(()=>{T.has(e)&&(T.delete(e),i({requestId:e,simulateTimeout:!1,delayMs:0,statusCode:r?.statusCode??200,headers:r?.headers||{},body:r?.body}))},o);T.set(e,{resolve:i,timer:s});try{"undefined"!=typeof window&&window.postMessage({type:"MFM_DEBUG_INTERCEPT_REQ",payload:{requestId:e,ruleId:t,request:n,response:r,timestamp:Date.now()}},"*")}catch(t){clearTimeout(s),T.delete(e),i({requestId:e,simulateTimeout:!1,delayMs:0,statusCode:r?.statusCode??200,headers:r?.headers||{},body:r?.body})}})}U=I(),"undefined"!=typeof document&&"function"==typeof document.addEventListener&&document.addEventListener("mfm:rule-sync",e=>{const t=e&&e.detail;t&&"debugger"===t.kind&&_(t.payload?.rules||[])}),"undefined"!=typeof window&&"function"==typeof window.addEventListener&&window.addEventListener("storage",e=>{e.key===Q&&(U=I())});const L="MFM_REQUEST_EDITOR_RULES";let D=[];const N=new Map;function j(){try{if("undefined"==typeof localStorage)return[];const e=localStorage.getItem(L);if(!e)return[];const t=JSON.parse(e);return Array.isArray(t)?t.filter(e=>e&&e.enabled):[]}catch(e){return[]}}function O(e){D=Array.isArray(e)?e.filter(e=>e&&e.enabled):[]}function R(e,t){if(!e||!t)return null;if(!D.length&&(D=j(),!D.length))return null;const n=String(e).toUpperCase();return D.find(e=>{if(!e.enabled||String(e.method).toUpperCase()!==n)return!1;if("PATH"===e.matchType)try{return new URL(e.url,"http://localhost").pathname===new URL(t,"http://localhost").pathname}catch(n){return e.url===t}return e.url===t})||null}function P(e,t,n){const r={};return Object.entries(t?.headers||{}).forEach(([e,t])=>{r[e]=String(t??"")}),{requestId:e,cancel:!1,headers:r,queryParams:n||{},body:"string"==typeof t?.body?t.body:null}}function z({requestId:e,ruleId:t,request:n,queryParams:r,timeoutMs:o=3e5}){return new Promise(i=>{const s=setTimeout(()=>{N.has(e)&&(N.delete(e),i(P(e,n,r)))},o);N.set(e,{resolve:i,timer:s});try{"undefined"!=typeof window&&window.postMessage({type:"MFM_REQUEST_EDIT_REQ",payload:{requestId:e,ruleId:t,request:n,queryParams:r,timestamp:Date.now()}},"*")}catch(t){clearTimeout(s),N.delete(e),i(P(e,n,r))}})}D=j(),"undefined"!=typeof document&&"function"==typeof document.addEventListener&&document.addEventListener("mfm:rule-sync",e=>{const t=e&&e.detail;t&&"editor"===t.kind&&O(t.payload?.rules||[])}),"undefined"!=typeof window&&"function"==typeof window.addEventListener&&window.addEventListener("storage",e=>{e.key===L&&(D=j())});const K="MFM_GLOBAL_DELAY";let V={enabled:!1,seconds:0},G=0;function q(){try{if("undefined"==typeof localStorage)return{enabled:!1,seconds:0};const e=localStorage.getItem(K);if(!e)return{enabled:!1,seconds:0};const t=JSON.parse(e);return t&&"object"==typeof t?{enabled:!!t.enabled&&Number.isFinite(t.seconds)&&t.seconds>0,seconds:Number.isFinite(t.seconds)?Number(t.seconds):0}:{enabled:!1,seconds:0}}catch(e){return{enabled:!1,seconds:0}}}function J(){const e=Date.now();return e-G>500&&(V=q(),G=e),V.enabled&&V.seconds>0?Math.round(1e3*V.seconds):0}var W,$;V=q(),G=Date.now(),"undefined"!=typeof window&&"function"==typeof window.addEventListener&&window.addEventListener("storage",e=>{e.key===K&&(V=q(),G=Date.now())}),function(e){e[e.NONE=0]="NONE",e[e.INFO=1]="INFO",e[e.WARN=2]="WARN",e[e.ERROR=3]="ERROR"}(W||(W={})),function(e){e.MFM_REQ_MAPPINGS="MFM_REQ_MAPPINGS",e.MFM_REQ_SAVED_MAPPINGS="MFM_REQ_SAVED_MAPPINGS",e.MFM_DEL_CLIENT_TOKEN="MFM_DEL_CLIENT_TOKEN",e.MFM_SUBMIT_TOKEN="MFM_SUBMIT_TOKEN",e.MFM_TOGGLE_INTERCEPTION="MFM_TOGGLE_INTERCEPTION",e.MFM_REQ_ALL_APIS="MFM_REQ_ALL_APIS",e.MFM_TOGGLE_API="MFM_TOGGLE_API",e.MFM_DEBUG_RULES_UPDATE="MFM_DEBUG_RULES_UPDATE",e.MFM_DEBUG_INTERCEPT_RES="MFM_DEBUG_INTERCEPT_RES",e.MFM_REQUEST_EDIT_RULES_UPDATE="MFM_REQUEST_EDIT_RULES_UPDATE",e.MFM_REQUEST_EDIT_ACK="MFM_REQUEST_EDIT_ACK",e.MFM_REQUEST_EDIT_RES="MFM_REQUEST_EDIT_RES",e.MFM_GLOBAL_DELAY_UPDATE="MFM_GLOBAL_DELAY_UPDATE",e.MFM_FLOW_MOCK_SET="MFM_FLOW_MOCK_SET",e.MFM_FLOW_MOCK_CLEAR="MFM_FLOW_MOCK_CLEAR",e.MFM_PING_SCREENSHOT="MFM_PING_SCREENSHOT",e.MFM_REQUEST_SCREENSHOT="MFM_REQUEST_SCREENSHOT",e.MFM_RES_MAPPINGS="MFM_RES_MAPPINGS",e.MFM_RES_ALL_APIS="MFM_RES_ALL_APIS",e.MFM_TOGGLE_API_RESULT="MFM_TOGGLE_API_RESULT",e.MFM_REQ="MFM_REQ",e.MFM_RES="MFM_RES",e.MFM_TOKEN_ERROR="MFM_TOKEN_ERROR",e.MFM_TOKEN_API_FAILED="MFM_TOKEN_API_FAILED",e.MFM_TOKEN_INVALIDATED="MFM_TOKEN_INVALIDATED",e.MFM_MOCK_DISABLED="MFM_MOCK_DISABLED",e.MFM_TOKEN_CLEARED="MFM_TOKEN_CLEARED",e.MFM_DEBUG_INTERCEPT_REQ="MFM_DEBUG_INTERCEPT_REQ",e.MFM_REQUEST_EDIT_REQ="MFM_REQUEST_EDIT_REQ",e.MFM_PONG_SCREENSHOT="MFM_PONG_SCREENSHOT",e.MFM_SCREENSHOT_RESULT="MFM_SCREENSHOT_RESULT",e.MFM_SCREENSHOT_ERROR="MFM_SCREENSHOT_ERROR",e.MFM_LOG_INFO="MFM_LOG_INFO",e.MFM_LOG_WARN="MFM_LOG_WARN",e.MFM_LOG_ERROR="MFM_LOG_ERROR"}($||($={}));const X="MFM_TOKEN",Y="MFM_CACHED_MAPPINGS",Z="MFM_INTERCEPTION_ENABLED",ee=new class{constructor(e={}){o()||(this.token=e.token||("undefined"!=typeof localStorage?localStorage.getItem(X):null),this.isAuthenticated=!!this.token,this.onAuthSuccess=e.onAuthSuccess||(()=>{}),this.mappings=e.mappings||[],this.rules=e.rules||[],this.widgetKey=e.widgetKey||null,this.tokenInvalidated=!1,this.setupMessageListeners())}get interceptionEnabled(){if(this.tokenInvalidated)return!1;if("undefined"==typeof localStorage)return!1!==this._interceptionEnabled;const e=localStorage.getItem(Z);return"false"!==e&&("true"===e||!1!==this._interceptionEnabled)}set interceptionEnabled(e){const t=!!e;this._interceptionEnabled=t,"undefined"!=typeof localStorage&&localStorage.setItem(Z,t?"true":"false")}setupMessageListeners(){"undefined"!=typeof window&&window.addEventListener("message",e=>{const{type:t,payload:n}=e.data||{};var r,o;if(t&&"string"==typeof t&&t.startsWith("MFM_"))switch(t){case $.MFM_REQ_MAPPINGS:this.refreshMappings();break;case $.MFM_REQ_SAVED_MAPPINGS:this.handleReqSavedMappings();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;break;case $.MFM_REQ_ALL_APIS:this.handleReqAllApis();break;case $.MFM_TOGGLE_API:this.handleToggleApi(n?.apiId,n?.enabled);break;case $.MFM_DEBUG_RULES_UPDATE:_(n?.rules||[]);break;case $.MFM_DEBUG_INTERCEPT_RES:!function(e){if(!e||!e.requestId)return;const t=T.get(e.requestId);t&&(clearTimeout(t.timer),T.delete(e.requestId),t.resolve(e))}(n);break;case $.MFM_REQUEST_EDIT_RULES_UPDATE:O(n?.rules||[]);break;case $.MFM_REQUEST_EDIT_RES:!function(e){if(!e||!e.requestId)return;const t=N.get(e.requestId);t&&(clearTimeout(t.timer),N.delete(e.requestId),t.resolve(e))}(n);break;case $.MFM_GLOBAL_DELAY_UPDATE:!function(e){if(!e||"object"!=typeof e)return V={enabled:!1,seconds:0},void(G=Date.now());V={enabled:!!e.enabled&&Number.isFinite(e.seconds)&&e.seconds>0,seconds:Number.isFinite(e.seconds)?Number(e.seconds):0},G=Date.now()}(n);break;case $.MFM_FLOW_MOCK_SET:r=n?.runId,o=n?.apis||[],r&&a.set(String(r),Array.isArray(o)?o:[]);break;case $.MFM_FLOW_MOCK_CLEAR:!function(e){e&&a.delete(String(e))}(n?.runId)}})}init(){if("undefined"!=typeof document&&this.checkVisibility()&&("undefined"!=typeof window&&Promise.resolve().then(n.bind(n,435)).then(e=>{const t=window.MockForMeWidget||e.MockForMeWidget;t&&"function"==typeof t.run&&(t.run(null,{clientType:"NPM",version:"14.5.1"}),this.syncInterceptionToggleToWidget())}).catch(e=>{console.error("[MockForMe] Failed to load mfm-widget",e)}),console.log("[MockForMe] Widget initialized"),this.token)){const e=this.getSavedMappings(this.token,"JAVASCRIPT");e&&(this.mappings=e.mappings||[],this.rules=e.meta?._rules||[],this.onAuthSuccess(this.token,this.mappings,e.meta),this.updateMappings(this.mappings,e.meta))}}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(X,e),this.refreshMappings())}handleTokenDeletion(){this.token=null,this.isAuthenticated=!1,"undefined"!=typeof localStorage&&(localStorage.removeItem(X),localStorage.removeItem(Y)),this.mappings=[],this.rules=[],this.onAuthSuccess(null,[],{_rules:[]}),this.updateMappings([],{_rules:[]})}handleReqAllApis(){this.token?(async e=>{if(!e)return{ok:!1,message:"Missing token",result:[]};const t=await fetch(`${E}/apis`,{method:"GET",headers:F(e)});return S(t)})(this.token).then(e=>{const t=e.ok&&Array.isArray(e.result)?e.result:[];this.sendMessage($.MFM_RES_ALL_APIS,{apis:t})}).catch(()=>this.sendMessage($.MFM_RES_ALL_APIS,{apis:[]})):this.sendMessage($.MFM_RES_ALL_APIS,{apis:[]})}handleToggleApi(e,t){this.token&&e?(async(e,t,n)=>{if(!e)return{ok:!1,message:"Missing token",result:null};const r=await fetch(`${E}/api/${t}/toggle-state`,{method:"PUT",headers:F(e),body:JSON.stringify({enabled:!!n})});return S(r)})(this.token,e,t).then(n=>{this.sendMessage($.MFM_TOGGLE_API_RESULT,{apiId:e,enabled:!!t,ok:!!n.ok,message:n.message||""}),n.ok&&this.refreshMappings()}).catch(()=>this.sendMessage($.MFM_TOGGLE_API_RESULT,{apiId:e,enabled:!!t,ok:!1,message:"Failed to update the mock"})):this.sendMessage($.MFM_TOGGLE_API_RESULT,{apiId:e,enabled:!!t,ok:!1,message:"Missing token"})}refreshMappings(){this.token&&C(this.token,"JAVASCRIPT",(e,t)=>{this.mappings=e||[],this.rules=t?._rules||[],this.tokenInvalidated=!1,this.saveMappings(e,t,this.token,"JAVASCRIPT"),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.token=null,this.isAuthenticated=!1,"undefined"!=typeof localStorage&&(localStorage.removeItem(X),localStorage.removeItem(Y)),this.mappings=[],this.rules=[],this.onAuthSuccess(null,[],{_rules:[]}),this.sendMessage($.MFM_TOKEN_ERROR,{message:"Unauthorized: Invalid token"})):this.sendMessage($.MFM_TOKEN_API_FAILED,{message:"Unable to reach the mappings service. Please try again."})})}saveMappings(e,t,n=this.token,r="JAVASCRIPT"){if("undefined"!=typeof localStorage)try{localStorage.setItem(Y,JSON.stringify({token:n,adaptor:r,mappings:e,meta:t,timestamp:Date.now()}))}catch(e){console.error("[MockForMe] Failed to save mappings to storage",e)}}handleReqSavedMappings(){const e=this.getSavedMappings(this.token,"JAVASCRIPT");e?(this.mappings=e.mappings||[],this.rules=e.meta?._rules||[],this.onAuthSuccess(this.token,this.mappings,e.meta),this.updateMappings(this.mappings,e.meta)):this.updateMappings([],{_rules:[]})}getSavedMappings(e=this.token,t="JAVASCRIPT"){if("undefined"==typeof localStorage)return null;try{const n=localStorage.getItem(Y);if(!n)return null;const r=JSON.parse(n);return r?.token&&e&&r.token!==e||r?.adaptor&&t&&r.adaptor!==t?null:r}catch(e){return null}}syncInterceptionToggleToWidget(){this.sendMessage($.MFM_TOGGLE_INTERCEPTION,{enabled:this.interceptionEnabled})}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="object"==typeof e.rule&&null!==e.rule?e.rule:{},n={...e,...t},r=n.timingAction||{},o=r.activeAction||"MODIFY";let i="MODIFY";"delay"===o?i="DELAY":"delay_and_timeout"===o?i="TIMEOUT":"delay_and_redirect"===o&&(i="REDIRECT");const s={ruleName:n.ruleName||n._id||"Unnamed Rule",type:i,conditions:n.conditions||[],modificationActions:n.modificationActions||{}};return("MODIFY"!==i||r.activeAction)&&(s.timingAction=r),s}),token:this.token})}handleMockDisabled({apiMethod:e,apiEndpoint:t}={}){if(!t)return;const n=function(e,t){if(!t)return!1;const n=A.length,r=i(e||"");return A=A.filter(e=>!(i(e.apiMethod)===r&&e.apiEndpoint===t)),A.length!==n}(e,t),r=this.mappings.length;if(this.mappings=(this.mappings||[]).filter(n=>!((n.apiMethod||"").toLowerCase()===(e||"").toLowerCase()&&n.apiEndpoint===t)),!n&&this.mappings.length===r)return;this.updateMappings(this.mappings,{_rules:this.rules});const o=`${(e||"").toUpperCase()} ${t}`.trim();this.sendMessage($.MFM_MOCK_DISABLED,{method:e,url:t,message:`${o} mock was disabled and has been removed.`})}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(": "),r=n.shift();r&&(t[r]=n.join(": "))}):t="function"==typeof e.entries?Object.fromEntries(e.entries()):e,Object.keys(t).reduce((e,n)=>(e[n.toLowerCase()]=t[n],e),{})};let r,o,i;if(void 0===t.status||null===t.status)r=void 0;else if("number"==typeof t.status)r=t.status;else{const e=Number(t.status);Number.isFinite(e)?r=e:(r=0,o=String(t.status))}t.aborted||"Aborted"===t.status?i="aborted":t.timeout||"Timeout"===t.status?i="timeout":"Cancelled"===t.status?i="cancelled":(t.error||"Error"===o)&&(i="error");const s=t.pending&&void 0===t.status?null:{statusCode:r,headers:n(t.responseHeaders),body:t.responseBody,endTime:(new Date).toISOString(),...o?{statusText:o}:{},...i?{errorReason:i,failed:!0}:{}},a={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:s,rule:t.rule,timestamp:t.pending&&t.startTime||Date.now(),...Number.isFinite(t.duration)?{duration:t.duration}:{}};if(t.pending)this.sendMessage($.MFM_REQ,a);else if(this.sendMessage($.MFM_RES,a),!this.tokenInvalidated&&a.response&&a.response.headers){const e=a.response.headers["mfm-invalid-token"];if("true"===e||!0===e){console.warn("[MockForMe] Invalid token detected from response headers"),this.tokenInvalidated=!0;let e="Your token is no longer valid. Please enter a valid token.";try{const n=t.responseBody,r="string"==typeof n?JSON.parse(n):n;r&&"string"==typeof r.message&&r.message.trim()&&(e=r.message.trim())}catch(e){}this.sendMessage($.MFM_TOKEN_INVALIDATED,{message:e})}}}sendMessage(e,t){"undefined"!=typeof window&&window.postMessage({type:e,payload:t},"*")}};function te(e){const t=function(e,t){if(e)return"function"==typeof e.get?e.get(t):"string"==typeof e?((e,t)=>{const n=t.toLowerCase();return e.split(/\r?\n/).map(e=>{const t=e.indexOf(":");return t<0?null:[e.slice(0,t).trim().toLowerCase(),e.slice(t+1).trim()]}).filter(Boolean).find(([e])=>e===n)?.[1]})(e,t):((e,t)=>{const n=t.toLowerCase();for(const t of Object.keys(e||{}))if(t.toLowerCase()===n)return e[t]})(e,t)}(e,"mfm-mock-disabled");return"true"===t||!0===t}class ne{static match(e,t){if(!Array.isArray(t)||0===t.length)return!1;const{url:n,headers:r,queryParams:o,body:i}=e,s="undefined"!=typeof window?window.location.origin:globalThis.location?.origin||"http://localhost";for(const e of t){let t="";const{type:a,key:A,operator:l,value:c}=e;switch(a){case"URL":try{t=new URL(n,s).pathname}catch{t=n}break;case"QUERY_PARAM":if(o&&void 0!==o[A])t=String(o[A]);else try{t=new URL(n,s).searchParams.get(A)||""}catch{t=""}break;case"REQUEST_BODY":if(A){if("object"==typeof i&&null!==i)t=void 0!==i[A]?String(i[A]):"";else if("string"==typeof i)try{const e=JSON.parse(i);t=void 0!==e[A]?String(e[A]):""}catch{t=""}}else t="object"==typeof i?JSON.stringify(i):String(i||"");break;case"REQUEST_HEADER":if(A){const e=A?.toLowerCase();if(t="",r){const n=Object.keys(r).find(t=>t.toLowerCase()===e);t=n?String(r[n]):""}}else t=JSON.stringify(r||{});break;default:return!1}if(!this.evaluate(t,l,c))return!1}return!0}static evaluate(e,t,n){const r=t?.toLowerCase(),o=String(e),i=String(n);switch(r){case"contains":return o.includes(i);case"equal":case"equals":return o===i;case"regexp":try{let e=i;if(e.startsWith("/")&&e.lastIndexOf("/")>0){const t=e.lastIndexOf("/"),n=e.slice(1,t),r=e.slice(t+1);return new RegExp(n,r).test(o)}return new RegExp(e).test(o)}catch{return!1}default:return!1}}}class re{static async apply(e){if(!e||!e.activeAction)return{type:"passThrough",delay:0};const{activeAction:t,actions:n}=e,r=n?.[t];if(!r)return{type:"passThrough",delay:0};const o={type:"passThrough",delay:0},i=Number(r.value||0);switch(t){case"delay":o.delay=i,o.delay>0&&await new Promise(e=>setTimeout(e,1e3*o.delay));break;case"redirect":case"delay_and_redirect":o.type="redirect",o.delay=i,o.redirectUrl=r.redirectUrl,o.delay>0&&await new Promise(e=>setTimeout(e,1e3*o.delay));break;case"delay_and_timeout":o.type="timeout",o.delay=i,o.delay>0&&await new Promise(e=>setTimeout(e,1e3*o.delay))}return o}}class oe{static applyRequestModifications(e,t){if(!t)return e;let{url:n,method:r,headers:o,queryParams:i,body:s}={...e};o&&(o={...o}),i&&(i={...i});const{modifyQueryParams:a,modifyRequestBody:A,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),i&&delete i[t]}),Array.isArray(a.add)&&a.add.forEach(({key:t,value:n})=>{e.searchParams.set(t,n),i&&(i[t]=n)}),n=e.toString()}catch(e){console.error("[MockForMe] Failed to modify query params",e)}l?.enabled&&(o={...o},Array.isArray(l.remove)&&l.remove.forEach(e=>{const t=e.toLowerCase(),n=Object.keys(o).find(e=>e.toLowerCase()===t);n&&delete o[n]}),Array.isArray(l.add)&&l.add.forEach(({key:e,value:t})=>{o[e]=t}));const c=String(r||"GET").toUpperCase(),d="GET"===c||"HEAD"===c;if(A?.enabled&&!d)try{let e=null;if("string"==typeof s)try{e=JSON.parse(s)}catch{e={}}else if("object"==typeof s&&null!==s)try{e=JSON.parse(JSON.stringify(s))}catch{e={...s}}else(Array.isArray(A.add)&&A.add.length>0||Array.isArray(A.update)&&A.update.length>0)&&(e={});e&&(Array.isArray(A.remove)&&A.remove.forEach(t=>delete e[t]),Array.isArray(A.add)&&A.add.forEach(({key:t,value:n})=>e[t]=n),Array.isArray(A.update)&&A.update.forEach(({key:t,value:n})=>e[t]=n),s=JSON.stringify(e))}catch(e){console.error("[MockForMe] Failed to modify request body",e)}return{...e,url:n,headers:o,queryParams:i,body:s}}static applyResponseModifications(e,t){if(!t?.modifyResponseHeaders?.enabled)return e;const{modifyResponseHeaders:n}=t,r={...e};return Array.isArray(n.remove)&&n.remove.forEach(e=>{const t=e.toLowerCase(),n=Object.keys(r).find(e=>e.toLowerCase()===t);n&&delete r[n]}),Array.isArray(n.add)&&n.add.forEach(({key:e,value:t})=>{r[e]=t}),r}}class ie{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)&&ne.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,r=oe.applyRequestModifications(t,n.modificationActions);return{...await re.apply(n.timingAction),modifiedRequest:r,rule:n}}static applyResponseModifications(e,t){return oe.applyResponseModifications(e,t)}}class se{static apply({target:e=("undefined"!=typeof window?window:globalThis),originalFetch:t=e.fetch,ruleProvider:n=()=>[],mappingProvider:r=e=>null,onBeforeRequest:o=e=>{},onRuleMatch:i=async(e,t,n,r,o)=>null,onMockMatch:s=async(e,t,n,r,o)=>null,onOtherRequest:a=async(e,t,n,r)=>null,isEnabled:A=()=>!0,shouldBypassRequest:l=()=>!1}){t&&(e.fetch=async function(e,c={}){if(!A())return t(e,c);let d;try{const n="string"==typeof e?e:e.url,r=String(c.method||(e instanceof Request?e.method:"GET")).toUpperCase().trim(),i=Math.random().toString(36).substring(7);if(d={url:n,method:r,headers:c.headers||(e instanceof Request?e.headers:{}),body:c.body||(e instanceof Request?"{binary/stream}":null),requestId:i,queryParams:se.getQueryParams(n)},l(d))return t(e,c);o(d)}catch(n){return console.warn("[MockForMe] Fetch Interceptor Setup Error:",n),t(e,c)}try{const o=n(),A=ie.match(d,o);if(A){const n=await i(A,d,e,c,t);if(n)return n}const l=r(d);if(l){const n=await s(l,d,e,c,t);if(n)return n}const u=await a(d,e,c,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,c)})}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 ae{static apply({target:e=("undefined"!=typeof window?window:{}),OriginalXHR:t=e.XMLHttpRequest,ruleProvider:n=()=>[],mappingProvider:r=e=>null,onBeforeRequest:o=e=>{},onRuleMatch:i=(e,t,n,r)=>{r.call(n.proxy,t.body)},onMockMatch:s=(e,t,n,r)=>{r.call(n.proxy,t.body)},onOtherRequest:a=(e,t,n)=>{n.call(t.proxy,e.body)},isEnabled:A=()=>!0,shouldBypassRequest:l=()=>!1}){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,r={}){if(this._captured)return;this._captured=!0;const o=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}),o("readystatechange"),"Aborted"===e||r.aborted?o("abort"):0===e||"Error"===e||r.error?o("error"):"Timeout"===e||r.timeout?o("timeout"):o("load")}abort(){if(!this._isMocked||"function"!=typeof this._onAbort)return this._xhr.abort();this._onAbort()}open(e,t,n=!0,r=null,o=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,r,o)}setRequestHeader(e,t){return this._headers[e]=t,this._xhr.setRequestHeader(e,t)}send(e){if(!A())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:ae.getQueryParams(this._url)};if(l(t))return this._xhr.send(e);o(t);const c=n(),d=ie.match(t,c),u=e=>this._xhr.send(e);if(d)return this._isMocked=!0,i(d,t,this,u);const f=r(t);return f?(this._isMocked=!0,s(f,t,this,u)):(this._isMocked=!1,a(t,this,u))}})}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 Ae=[g,"https://api.mockforme.com/mockforme/httpRequestBulkMock/bulk_mock"];function le(e){try{const t="undefined"!=typeof window?window.location.origin:"http://localhost",n=new URL(e.url,t);return Ae.some(e=>{const r=new URL(e,t);return n.origin===r.origin&&n.pathname===r.pathname})}catch{return!1}}const ce=(e,t=null,n=u)=>{if(o())return;let r="string"==typeof e?e:e?.token,i="object"==typeof e?e?.widgetKey:null;if(n===u)try{r&&("undefined"!=typeof localStorage&&(localStorage.removeItem("mockforme-token"),localStorage.setItem("MFM_TOKEN",r)),ee.token=r,ee.isAuthenticated=!0),!r&&ee.token&&(r=ee.token),ee.onAuthSuccess=(e,t,n)=>{l(t),b(n),ee.updateMappings(t,n)},i?ee.setWidgetKey(i):ee.init()}catch(e){console.log("Error in showing mockforme widget",e)}t||={mappings:[],_o:null,mk:null,_mck:null,_rules:[]};const{mappings:s=[],_o:a,mk:A,_mck:h,_rules:p=[]}=t;return l(s),b({_o:a,mk:A,_mck:h,_rules:p}),{run:(e,t=()=>{})=>{if(function(e,t){if("undefined"!=typeof window){if(window._mfm_intercepted)return;window._mfm_intercepted=!0}const n=()=>ee.token||e;se.apply({isEnabled:()=>ee.interceptionEnabled,shouldBypassRequest:le,ruleProvider:()=>v(),mappingProvider:e=>{try{return d(new URL(e.url,window.location.origin).pathname,e.method)}catch{return null}},onRuleMatch:async(e,t,n,r,o)=>{const i=t.requestId||Math.random().toString(36).substring(7),s=Date.now();ee.addRequest("mocked",{...t,requestId:i,pending:!0,startTime:s,rule:e});const a=await ie.apply(e,t),{modifiedRequest:A,type:l,delay:c,redirectUrl:d}=a;if("timeout"!==l&&ee.addRequest("mocked",{...A,requestId:i,pending:!0,startTime:s,rule:e}),"timeout"===l){const t=Date.now()-s;throw ee.addRequest("mocked",{...A,requestId:i,status:"Aborted",pending:!1,duration:t,aborted:!0,rule:e}),new Error("Fetch timed out by rules")}if("redirect"===l&&!d)throw new Error("rules: Redirect missing URL");let u="redirect"===l?d:A.url,f={...r};A.headers&&(f.headers=A.headers),A.body&&(f.body=A.body);let h=null;if("redirect"===l){h=Math.random().toString(36).substring(7);const e={url:d,method:A.method,headers:f.headers||{},body:f.body,requestId:h,queryParams:se.getQueryParams(d),requestHeaders:f.headers||{},requestBody:f.body,pending:!0,startTime:Date.now()};ee.addRequest("mocked",e)}return o(u,f).then(async e=>{const t=Date.now()-s;let n=Object.fromEntries(e.headers.entries());if(a.rule.modificationActions?.modifyResponseHeaders?.enabled&&(n=ie.applyResponseModifications(n,a.rule.modificationActions)),"redirect"===l&&h){const t=e.clone(),r=t.headers.get("content-type")||"",o=Date.now()-s;try{let i;i=r.includes("application/json")?await t.json():await t.text(),ee.addRequest("mocked",{url:d,method:A.method,requestId:h,status:e.status,pending:!1,duration:o,responseHeaders:n,responseBody:i,requestHeaders:f.headers||{},requestBody:f.body})}catch(t){ee.addRequest("mocked",{url:d,method:A.method,requestId:h,status:e.status,pending:!1,duration:o,responseHeaders:n,requestHeaders:f.headers||{},requestBody:f.body})}}return ee.addRequest("mocked",{...A,requestId:i,status:e.status,pending:!1,duration:t,responseHeaders:n,rule:a.rule}),e}).catch(e=>{const t=Date.now()-s,n="AbortError"===e.name||e.message.includes("aborted");if(ee.addRequest("mocked",{...A,requestId:i,status:n?"Aborted":0,pending:!1,duration:t,rule:a.rule}),"redirect"===l&&h&&ee.addRequest("mocked",{url:d,method:A.method,requestId:h,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,r,o,i,s)=>{const a=r.requestId||Math.random().toString(36).substring(7),A=Date.now();ee.addRequest("mocked",{...r,requestId:a,pending:!0,startTime:A});const l=n(),c=new URL(r.url,window.location.origin).search;let d=`${B()}${e.url}${c}`,u={[f]:l,mfmver:"14.5.1","x-mfm-adaptor":t};const h=x();h&&e._ack&&(u["x-mfm-key"]=`${h}-${e._ack}`),e?._ri_&&(u._ri_=e._ri_);const p=o instanceof Request?o.headers:i.headers,g=new Headers(p||{});Object.entries(u).forEach(([e,t])=>g.set(e,t)),g.set("x-mfm-internal","true");let m=i.body;if(!m&&o instanceof Request){const e=o.clone();"GET"!==e.method&&"HEAD"!==e.method&&(m=await e.text())}const y={method:r.method,headers:g,credentials:o instanceof Request&&o.credentials||i.credentials||"include",mode:o instanceof Request&&o.mode||i.mode||"cors",signal:o instanceof Request&&o.signal||i.signal};return m&&(y.body=m),s(d,y).then(async t=>{const n=t.clone(),o=n.headers.get("content-type")||"",i=Date.now()-A;te(t.headers)&&ee.handleMockDisabled({apiMethod:e.method,apiEndpoint:e.apiEndpoint});const s=e=>(ee.addRequest("mocked",{...r,requestId:a,status:t.status,responseHeaders:Object.fromEntries(n.headers.entries()),responseBody:e,pending:!1,duration:i}),new Response("string"==typeof e?e:JSON.stringify(e),{status:t.status,headers:n.headers}));return o.includes("application/json")?n.json().then(s):n.text().then(s)}).catch(e=>{const t=Date.now()-A,n=e&&("AbortError"===e.name||String(e.message||"").toLowerCase().includes("abort"));if(ee.addRequest("mocked",{...r,requestId:a,status:n?"Aborted":0,pending:!1,duration:t,aborted:n}),n)throw e;return s(o,i)})},onOtherRequest:async(e,t,n,r)=>{const o=n?.headers||(t instanceof Request?t.headers:{});let i=!1;o instanceof Headers?i="true"===o.get("x-mfm-internal"):"object"==typeof o&&(i="true"===o["x-mfm-internal"]);const s=B();if(e.url.startsWith(s)&&(i=!0),"OPTIONS"===e.method||i)return r(t,n);const a=e.requestId,A=Date.now();ee.addRequest("other",{...e,requestId:a,pending:!0,startTime:A});const l=R(e.method,e.url),c=M(e.method,e.url);let d=t,u=n,f=e;if(l){const t={};try{new URL(e.url,"undefined"!=typeof window?window.location.origin:"http://localhost").searchParams.forEach((e,n)=>{t[n]=e})}catch(e){}const r=await z({requestId:a,ruleId:l.id,request:{method:e.method,url:e.url,headers:e.headers,body:e.body},queryParams:t});if(r.cancel){ee.addRequest("other",{...e,requestId:a,status:"Cancelled",pending:!1,duration:Date.now()-A,error:!0});const t=new Error("Request cancelled by MockForMe request editor");throw t.name="AbortError",t}let o=e.url;try{const t=new URL(e.url,"undefined"!=typeof window?window.location.origin:"http://localhost");[...t.searchParams.keys()].forEach(e=>t.searchParams.delete(e)),Object.entries(r.queryParams||{}).forEach(([e,n])=>{t.searchParams.set(e,String(n??""))}),o="string"==typeof e.url&&e.url.startsWith("/")?`${t.pathname}${t.search}`:t.href}catch(e){}const i=String(e.method||"GET").toUpperCase(),s="GET"!==i&&"HEAD"!==i;u={...n,method:e.method,headers:r.headers||{},body:s?null==r.body?void 0:r.body:void 0},d=o,f={...e,url:o,headers:r.headers||{},body:s?r.body:null}}const h=J();h>0&&await new Promise(e=>setTimeout(e,h));let p=null,g=null;try{p=await r(d,u)}catch(e){g=e}if(c){let t="",n=0,r={};if(p){try{t=await p.clone().text()}catch(e){}n=p.status,r=Object.fromEntries(p.headers.entries())}else g&&(t=g.message||"Network error",n=0);const o=await H({requestId:a,ruleId:c.id,request:{method:f.method,url:f.url,headers:f.headers,body:f.body},response:{statusCode:n,headers:r,body:t}});if(o.simulateTimeout){ee.addRequest("other",{...e,requestId:a,status:"Timeout",responseHeaders:{},pending:!1,duration:Date.now()-A,timeout:!0});const t=new Error("Network request failed (simulated by MockForMe debugger)");throw t.name="AbortError",t}o.delayMs>0&&await new Promise(e=>setTimeout(e,o.delayMs));const i=Number(o.statusCode),s=Number.isFinite(i)&&i>=200&&i<=599?i:n>=200?n:200,l=o.headers&&"object"==typeof o.headers?o.headers:r,d="string"==typeof o.body?o.body:null==o.body?"":JSON.stringify(o.body);ee.addRequest("other",{...e,requestId:a,status:s,responseHeaders:l,responseBody:d,pending:!1,duration:Date.now()-A});const u={};return Object.entries(l).forEach(([e,t])=>{const n=e.toLowerCase();"content-length"!==n&&"content-encoding"!==n&&"transfer-encoding"!==n&&(u[e]=t)}),new Response(d,{status:s,statusText:p?p.statusText:"",headers:new Headers(u)})}const m=Date.now()-A;if(g){const t="AbortError"===g.name||(g.message||"").includes("aborted"),n="TimeoutError"===g.name||(g.message||"").includes("timed out");throw ee.addRequest("other",{...e,requestId:a,status:t?"Aborted":n?"Timeout":"Error",pending:!1,duration:m,aborted:t,timeout:n,error:!t&&!n}),g}const y=Object.fromEntries(p.headers.entries());let w;try{const e=p.clone(),t=5e3,n=Symbol("body-timed-out"),r=await Promise.race([e.text(),new Promise(e=>setTimeout(()=>e(n),t))]);w=r===n?void 0:r}catch(e){w=void 0}return ee.addRequest("other",{...e,requestId:a,status:p.status,responseHeaders:y,responseBody:w,pending:!1,duration:m}),p}}),ae.apply({isEnabled:()=>ee.interceptionEnabled,shouldBypassRequest:le,ruleProvider:()=>v(),mappingProvider:e=>{try{return d(new URL(e.url,window.location.origin).pathname,e.method)}catch{return null}},onRuleMatch:async(e,t,n,r)=>{const o=t.requestId,i=Date.now();ee.addRequest("mocked",{...t,requestId:o,pending:!0,startTime:i,rule:e});const s=await ie.apply(e,t),{modifiedRequest:a,type:A,redirectUrl:l}=s;"timeout"!==A&&ee.addRequest("mocked",{...a,requestId:o,pending:!0,startTime:i,rule:e});let c=null;if("redirect"===A){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()};ee.addRequest("mocked",e)}const d=(e,t,r,d={})=>{const u=Date.now()-i;if(s.rule.modificationActions?.modifyResponseHeaders?.enabled){let e="string"==typeof r?Object.fromEntries(r.split("\r\n").filter(e=>e).map(e=>e.split(": "))):r;e=ie.applyResponseModifications(e,s.rule.modificationActions),r=e}ee.addRequest("mocked",{...a,requestId:o,status:e,responseBody:t,responseHeaders:r,pending:!1,duration:u,rule:s.rule,...d}),"redirect"===A&&c&&ee.addRequest("mocked",{url:l,method:a.method,requestId:c,status:e,responseBody:t,responseHeaders:r,pending:!1,duration:u,requestHeaders:a.headers||{},requestBody:a.body,...d}),n._capture(e,t,r,d)};if("timeout"===A)return d("Aborted","Timed out by rule",{},{aborted:!0}),void n._xhr.abort();if("redirect"===A){if(!l)return void d(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",()=>d("Aborted","Aborted",{},{aborted:!0}),{once:!0}),n._xhr.addEventListener("error",()=>d(0,"Error",{},{error:!0}),{once:!0}),n._xhr.addEventListener("timeout",()=>d("Timeout","Timeout",{},{timeout:!0}),{once:!0}),n._xhr.addEventListener("load",()=>d(n._xhr.status,n._xhr.responseText,n._xhr.getAllResponseHeaders()),{once:!0}),r(a.body)},onMockMatch:(e,r,o,i)=>{const s=r.requestId,a=Date.now(),A=n(),l=new URL(r.url,window.location.origin);let c=`${B()}${e.url}${l.search}`,d={[f]:A,mfmver:"14.5.1","x-mfm-adaptor":t};const u=x();u&&e._ack&&(d["x-mfm-key"]=`${u}-${e._ack}`),e?._ri_&&(d._ri_=e._ri_),d["x-mfm-internal"]="true";const h={...r.headers,...d};ee.addRequest("mocked",{...r,requestId:s,pending:!0,startTime:a});const p=(t,n,i,A={})=>{if(o._captured)return;const l=Date.now()-a;te(i)&&ee.handleMockDisabled({apiMethod:e.method,apiEndpoint:e.apiEndpoint}),ee.addRequest("mocked",{...r,requestId:s,status:t,responseBody:n,responseHeaders:i,pending:!1,duration:l,...A}),o._capture(t,n,i,A)};o._xhr.addEventListener("abort",()=>p("Aborted","Aborted",{},{aborted:!0}),{once:!0}),o._xhr.addEventListener("error",()=>p(0,"Error",{},{error:!0}),{once:!0}),o._xhr.addEventListener("timeout",()=>p("Timeout","Timeout",{},{timeout:!0}),{once:!0});const g=new window.XMLHttpRequest;g.open(r.method,c,!0);for(const e in h)g.setRequestHeader(e,h[e]);g.withCredentials=o.proxy.withCredentials,o._onAbort=()=>{try{g.abort()}catch(e){}p("Aborted","Aborted",{},{aborted:!0})},g.onload=()=>p(g.status,g.responseText,g.getAllResponseHeaders()),g.onerror=()=>p(0,"Network Error",{},{error:!0}),g.ontimeout=()=>p("Timeout","Request timed out",{},{timeout:!0}),g.send(r.body)},onOtherRequest:(e,t,n)=>{const r="true"===e.headers?.["x-mfm-internal"],o=B(),i=e.url.startsWith(o);if("OPTIONS"===e.method||r||i)return n(e.body);const s=Date.now();ee.addRequest("other",{...e,pending:!0,startTime:s});const a=R(e.method,e.url),A=M(e.method,e.url);let l=e;const c=(n,r,o,i={})=>{const a=Date.now()-s;ee.addRequest("other",{...e,status:n,responseBody:r,responseHeaders:o,pending:!1,duration:a,...i}),t._capture(n,r,o,i)};if(t._xhr.addEventListener("abort",()=>c("Aborted","Aborted",{},{aborted:!0}),{once:!0}),t._xhr.addEventListener("error",()=>c(0,"Error",{},{error:!0}),{once:!0}),t._xhr.addEventListener("timeout",()=>c("Timeout","Timeout",{},{timeout:!0}),{once:!0}),t._xhr.addEventListener("load",async()=>{const n=t._xhr.status,r=t._xhr.responseText,o=t._xhr.getAllResponseHeaders();if(A){const t={};"string"==typeof o&&o.split("\r\n").forEach(e=>{const n=e.indexOf(": ");n>0&&(t[e.slice(0,n)]=e.slice(n+2))});const i=await H({requestId:e.requestId,ruleId:A.id,request:{method:l.method,url:l.url,headers:l.headers,body:l.body},response:{statusCode:n,headers:t,body:r}});if(i.simulateTimeout)return void c("Timeout","Timeout (Debugger)",{},{timeout:!0});i.delayMs>0&&await new Promise(e=>setTimeout(e,i.delayMs));const s=Number(i.statusCode)||n,a=i.headers&&"object"==typeof i.headers?i.headers:t,d="string"==typeof i.body?i.body:null==i.body?"":JSON.stringify(i.body);return void c(s,d,a)}c(n,r,o)},{once:!0}),t._xhr.addEventListener("readystatechange",()=>{if(t._xhr.readyState>=2&&!t._captured){const n=t._xhr.status;if(n>0){const r=Date.now()-s;ee.addRequest("other",{...e,status:n,responseHeaders:t._xhr.getAllResponseHeaders(),pending:t._xhr.readyState<4,duration:r})}}}),a)return void(async()=>{const r={};try{new URL(e.url,"undefined"!=typeof window?window.location.origin:"http://localhost").searchParams.forEach((e,t)=>{r[t]=e})}catch(e){}const o=await z({requestId:e.requestId,ruleId:a.id,request:{method:e.method,url:e.url,headers:e.headers,body:e.body},queryParams:r});if(o.cancel){c("Cancelled","Cancelled by editor",{},{aborted:!0});try{t._xhr.abort()}catch(e){}return}let i=e.url;try{const t=new URL(e.url,"undefined"!=typeof window?window.location.origin:"http://localhost");[...t.searchParams.keys()].forEach(e=>t.searchParams.delete(e)),Object.entries(o.queryParams||{}).forEach(([e,n])=>{t.searchParams.set(e,String(n??""))}),i="string"==typeof e.url&&e.url.startsWith("/")?`${t.pathname}${t.search}`:t.href}catch(e){}if(i!==e.url)try{t._xhr.open(e.method,i,!0)}catch(e){}Object.entries(o.headers||{}).forEach(([e,n])=>{try{t._xhr.setRequestHeader(e,String(n??""))}catch(e){}}),l={...e,url:i,headers:o.headers||{},body:o.body};const s=String(e.method||"GET").toUpperCase(),A="GET"!==s&&"HEAD"!==s?null==o.body?null:o.body:null,d=J();d>0?setTimeout(()=>{try{n(A)}catch(e){}},d):n(A)})();const d=J();d>0?setTimeout(()=>{try{n(e.body)}catch(e){}},d):n(e.body)}})}(r,n),a&&A)ee.mappings=s,ee.rules=p,e?.(s,{_o:a,mk:A,_mck:h,_rules:p});else if(r){const t=ee.getSavedMappings(r,n);if(t&&Array.isArray(t.mappings))return ee.mappings=t.mappings,ee.rules=t.meta?._rules||[],l(t.mappings),b(t.meta),ee.updateMappings(t.mappings,t.meta),void e?.(t.mappings,t.meta);ee.updateMappings([],{_rules:[]}),e?.([],{_rules:[]})}},checkIfApiToBeMocked:d,getMappings:c,doFetchMappings:(e,t)=>{C(r||ee.token,n,(t,o)=>{ee.saveMappings(t,o,r||ee.token,n),ee.updateMappings(t,o),e?.(t,o)},t)},recheckWidgetVisibility:()=>{ee.init()}}},de=o();de||(globalThis.mockforme=ce);let ue=ce;de&&(ue=e=>({run:()=>{}}));const fe=ue;return r=r.mockforme,r})());
|
|
@@ -1 +1 @@
|
|
|
1
|
-
(()=>{var e={583(e,t,r){const o=r(896),s=r(928),n=r(857),a=r(982),i=r(519).version,c=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/gm;function l(e){console.log(`[dotenv@${i}][DEBUG] ${e}`)}function p(e){console.log(`[dotenv@${i}] ${e}`)}function u(e){return e&&e.DOTENV_KEY&&e.DOTENV_KEY.length>0?e.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:""}function h(e,t){let r;try{r=new URL(t)}catch(e){if("ERR_INVALID_URL"===e.code){const e=new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");throw e.code="INVALID_DOTENV_KEY",e}throw e}const o=r.password;if(!o){const e=new Error("INVALID_DOTENV_KEY: Missing key part");throw e.code="INVALID_DOTENV_KEY",e}const s=r.searchParams.get("environment");if(!s){const e=new Error("INVALID_DOTENV_KEY: Missing environment part");throw e.code="INVALID_DOTENV_KEY",e}const n=`DOTENV_VAULT_${s.toUpperCase()}`,a=e.parsed[n];if(!a){const e=new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${n} in your .env.vault file.`);throw e.code="NOT_FOUND_DOTENV_ENVIRONMENT",e}return{ciphertext:a,key:o}}function d(e){let t=null;if(e&&e.path&&e.path.length>0)if(Array.isArray(e.path))for(const r of e.path)o.existsSync(r)&&(t=r.endsWith(".vault")?r:`${r}.vault`);else t=e.path.endsWith(".vault")?e.path:`${e.path}.vault`;else t=s.resolve(process.cwd(),".env.vault");return o.existsSync(t)?t:null}function f(e){return"~"===e[0]?s.join(n.homedir(),e.slice(1)):e}const y={configDotenv:function(e){const t=s.resolve(process.cwd(),".env");let r="utf8";const n=Boolean(e&&e.debug),a=!e||!("quiet"in e)||e.quiet;e&&e.encoding?r=e.encoding:n&&l("No encoding is specified. UTF-8 is used by default");let i,c=[t];if(e&&e.path)if(Array.isArray(e.path)){c=[];for(const t of e.path)c.push(f(t))}else c=[f(e.path)];const u={};for(const t of c)try{const s=y.parse(o.readFileSync(t,{encoding:r}));y.populate(u,s,e)}catch(e){n&&l(`Failed to load ${t} ${e.message}`),i=e}let h=process.env;if(e&&null!=e.processEnv&&(h=e.processEnv),y.populate(h,u,e),n||!a){const e=Object.keys(u).length,t=[];for(const e of c)try{const r=s.relative(process.cwd(),e);t.push(r)}catch(t){n&&l(`Failed to load ${e} ${t.message}`),i=t}p(`injecting env (${e}) from ${t.join(",")}`)}return i?{parsed:u,error:i}:{parsed:u}},_configVault:function(e){const t=Boolean(e&&e.debug),r=!e||!("quiet"in e)||e.quiet;!t&&r||p("Loading env from encrypted .env.vault");const o=y._parseVault(e);let s=process.env;return e&&null!=e.processEnv&&(s=e.processEnv),y.populate(s,o,e),{parsed:o}},_parseVault:function(e){const t=d(e=e||{});e.path=t;const r=y.configDotenv(e);if(!r.parsed){const e=new Error(`MISSING_DATA: Cannot parse ${t} for an unknown reason`);throw e.code="MISSING_DATA",e}const o=u(e).split(","),s=o.length;let n;for(let e=0;e<s;e++)try{const t=h(r,o[e].trim());n=y.decrypt(t.ciphertext,t.key);break}catch(t){if(e+1>=s)throw t}return y.parse(n)},config:function(e){if(0===u(e).length)return y.configDotenv(e);const t=d(e);return t?y._configVault(e):(r=`You set DOTENV_KEY but you are missing a .env.vault file at ${t}. Did you forget to build it?`,console.log(`[dotenv@${i}][WARN] ${r}`),y.configDotenv(e));var r},decrypt:function(e,t){const r=Buffer.from(t.slice(-64),"hex");let o=Buffer.from(e,"base64");const s=o.subarray(0,12),n=o.subarray(-16);o=o.subarray(12,-16);try{const e=a.createDecipheriv("aes-256-gcm",r,s);return e.setAuthTag(n),`${e.update(o)}${e.final()}`}catch(e){const t=e instanceof RangeError,r="Invalid key length"===e.message,o="Unsupported state or unable to authenticate data"===e.message;if(t||r){const e=new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw e.code="INVALID_DOTENV_KEY",e}if(o){const e=new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");throw e.code="DECRYPTION_FAILED",e}throw e}},parse:function(e){const t={};let r,o=e.toString();for(o=o.replace(/\r\n?/gm,"\n");null!=(r=c.exec(o));){const e=r[1];let o=r[2]||"";o=o.trim();const s=o[0];o=o.replace(/^(['"`])([\s\S]*)\1$/gm,"$2"),'"'===s&&(o=o.replace(/\\n/g,"\n"),o=o.replace(/\\r/g,"\r")),t[e]=o}return t},populate:function(e,t,r={}){const o=Boolean(r&&r.debug),s=Boolean(r&&r.override);if("object"!=typeof t){const e=new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");throw e.code="OBJECT_REQUIRED",e}for(const r of Object.keys(t))Object.prototype.hasOwnProperty.call(e,r)?(!0===s&&(e[r]=t[r]),o&&l(!0===s?`"${r}" is already defined and WAS overwritten`:`"${r}" is already defined and was NOT overwritten`)):e[r]=t[r]}};e.exports.configDotenv=y.configDotenv,e.exports._configVault=y._configVault,e.exports._parseVault=y._parseVault,e.exports.config=y.config,e.exports.decrypt=y.decrypt,e.exports.parse=y.parse,e.exports.populate=y.populate,e.exports=y},982(e){"use strict";e.exports=require("crypto")},896(e){"use strict";e.exports=require("fs")},857(e){"use strict";e.exports=require("os")},928(e){"use strict";e.exports=require("path")},519(e){"use strict";e.exports={version:"16.6.1"}}};const t={};function r(o){const s=t[o];if(void 0!==s)return s.exports;const n=t[o]={exports:{}};return e[o](n,n.exports,r),n.exports}r.n=e=>{const t=e&&e.__esModule?()=>e.default:()=>e;return r.d(t,{a:t}),t},r.d=(e,t)=>{if(Array.isArray(t))for(var o=0;o<t.length;){var s=t[o++],n=t[o++];r.o(e,s)?0===n&&o++:0===n?Object.defineProperty(e,s,{enumerable:!0,value:t[o++]}):Object.defineProperty(e,s,{enumerable:!0,get:n})}else for(var s in t)r.o(t,s)&&!r.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:t[s]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};let o={};(()=>{"use strict";r.r(o),r.d(o,{mockforme:()=>_});const e=require("http");var t=r.n(e);const s=require("https");var n=r.n(s);const a=require("child_process");var i=r(583),c=r.n(i);const l=e=>{try{return e?e.toLowerCase():e}catch(e){return console.log(e),null}},p=(e,t)=>{const r=e.split("/"),o=t.split("/");if(r.length!==o.length)return!1;for(let e=0;e<r.length;e++){const t=r[e];if(t!==o[e]&&":any"!==t&&":"!==t.charAt(0))return!1}return!0},u=(e,t=null,r=2)=>{try{return JSON.stringify(e,t,r)}catch(e){return null}};class h{static match(e,t){if(!Array.isArray(t)||0===t.length)return!1;const{url:r,headers:o,queryParams:s,body:n}=e,a="undefined"!=typeof window?window.location.origin:globalThis.location?.origin||"http://localhost";for(const e of t){let t="";const{type:i,key:c,operator:l,value:p}=e;switch(i){case"URL":try{t=new URL(r,a).pathname}catch{t=r}break;case"QUERY_PARAM":if(s&&void 0!==s[c])t=String(s[c]);else try{t=new URL(r,a).searchParams.get(c)||""}catch{t=""}break;case"REQUEST_BODY":if(c){if("object"==typeof n&&null!==n)t=void 0!==n[c]?String(n[c]):"";else if("string"==typeof n)try{const e=JSON.parse(n);t=void 0!==e[c]?String(e[c]):""}catch{t=""}}else t="object"==typeof n?JSON.stringify(n):String(n||"");break;case"REQUEST_HEADER":if(c){const e=c?.toLowerCase();if(t="",o){const r=Object.keys(o).find(t=>t.toLowerCase()===e);t=r?String(o[r]):""}}else t=JSON.stringify(o||{});break;default:return!1}if(!this.evaluate(t,l,p))return!1}return!0}static evaluate(e,t,r){const o=t?.toLowerCase(),s=String(e),n=String(r);switch(o){case"contains":return s.includes(n);case"equal":case"equals":return s===n;case"regexp":try{let e=n;if(e.startsWith("/")&&e.lastIndexOf("/")>0){const t=e.lastIndexOf("/"),r=e.slice(1,t),o=e.slice(t+1);return new RegExp(r,o).test(s)}return new RegExp(e).test(s)}catch{return!1}default:return!1}}}class d{static async apply(e){if(!e||!e.activeAction)return{type:"passThrough",delay:0};const{activeAction:t,actions:r}=e,o=r?.[t];if(!o)return{type:"passThrough",delay:0};const s={type:"passThrough",delay:0},n=Number(o.value||0);switch(t){case"delay":s.delay=n,s.delay>0&&await new Promise(e=>setTimeout(e,1e3*s.delay));break;case"redirect":case"delay_and_redirect":s.type="redirect",s.delay=n,s.redirectUrl=o.redirectUrl,s.delay>0&&await new Promise(e=>setTimeout(e,1e3*s.delay));break;case"delay_and_timeout":s.type="timeout",s.delay=n,s.delay>0&&await new Promise(e=>setTimeout(e,1e3*s.delay))}return s}}class f{static applyRequestModifications(e,t){if(!t)return e;let{url:r,method:o,headers:s,queryParams:n,body:a}={...e};s&&(s={...s}),n&&(n={...n});const{modifyQueryParams:i,modifyRequestBody:c,modifyRequestHeaders:l}=t;if(i?.enabled)try{const e=new URL(r,"undefined"!=typeof window?window.location.href:"http://localhost");Array.isArray(i.remove)&&i.remove.forEach(t=>{e.searchParams.delete(t),n&&delete n[t]}),Array.isArray(i.add)&&i.add.forEach(({key:t,value:r})=>{e.searchParams.set(t,r),n&&(n[t]=r)}),r=e.toString()}catch(e){console.error("[MockForMe] Failed to modify query params",e)}l?.enabled&&(s={...s},Array.isArray(l.remove)&&l.remove.forEach(e=>{const t=e.toLowerCase(),r=Object.keys(s).find(e=>e.toLowerCase()===t);r&&delete s[r]}),Array.isArray(l.add)&&l.add.forEach(({key:e,value:t})=>{s[e]=t}));const p=String(o||"GET").toUpperCase(),u="GET"===p||"HEAD"===p;if(c?.enabled&&!u)try{let e=null;if("string"==typeof a)try{e=JSON.parse(a)}catch{e={}}else if("object"==typeof a&&null!==a)try{e=JSON.parse(JSON.stringify(a))}catch{e={...a}}else(Array.isArray(c.add)&&c.add.length>0||Array.isArray(c.update)&&c.update.length>0)&&(e={});e&&(Array.isArray(c.remove)&&c.remove.forEach(t=>delete e[t]),Array.isArray(c.add)&&c.add.forEach(({key:t,value:r})=>e[t]=r),Array.isArray(c.update)&&c.update.forEach(({key:t,value:r})=>e[t]=r),a=JSON.stringify(e))}catch(e){console.error("[MockForMe] Failed to modify request body",e)}return{...e,url:r,headers:s,queryParams:n,body:a}}static applyResponseModifications(e,t){if(!t?.modifyResponseHeaders?.enabled)return e;const{modifyResponseHeaders:r}=t,o={...e};return Array.isArray(r.remove)&&r.remove.forEach(e=>{const t=e.toLowerCase(),r=Object.keys(o).find(e=>e.toLowerCase()===t);r&&delete o[r]}),Array.isArray(r.add)&&r.add.forEach(({key:e,value:t})=>{o[e]=t}),o}}class y{static match(e,t){if(!Array.isArray(t)||0===t.length)return null;for(const r of t){const t=r.rule||r;if(t.conditions&&Array.isArray(t.conditions)&&h.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 r=e.rule||e,o=f.applyRequestModifications(t,r.modificationActions);return{...await d.apply(r.timingAction),modifiedRequest:o,rule:r}}static applyResponseModifications(e,t){return f.applyResponseModifications(e,t)}}c().config("../../.env");const m="https://api.mockforme.com",g=`${m}/mockforme`,E="mfmver",v="4.2.7";let w=`${m}/gateway/3f4eae522b`,A=null;class b{constructor(e){this.token=e,this.apiMappings=[],this.rules=[],this.isReady=!1,this.originalHttpRequest=t().request,this.originalHttpGet=t().get,this.originalHttpsRequest=n().request,this.originalHttpsGet=n().get,this.originalFetch=globalThis.fetch,this.fetchApiMappings(),this.setupInterceptor()}checkIsErrorInFetchMappings(e){try{const t=JSON.parse(e);if(0==t?.status)throw new Error(t?.message||"Failed to fetch mockforme mappings")}catch(e){throw new Error(e.message||"Failed to fetch mockforme mappings")}}fetchApiMappings(){this.apiMappings=[],this.rules=[],this.isReady=!1;try{const e=`curl -s -H "mockforme: ${this.token}" "${w}"`,t=(0,a.execSync)(e,{encoding:"utf8"});if(t&&this.checkIsErrorInFetchMappings(t),!t)throw new Error("Failed to fetch mockforme mappings: No response");{const{di:e,iv:r,_o:o,_mck:s,mk:n,r:a}=JSON.parse(t);this.organisationId=o,this.memberKey=n,this.memberCacheKey=s;const i=function({di:e,iv:t},r){var o;const s=function(e,t){const r=t.length;return e.split("").map((e,o)=>String.fromCharCode(e.charCodeAt(0)^t.charCodeAt(o%r))).join("")}((o=e,"undefined"!=typeof Buffer?Buffer.from(o,"base64").toString("utf8"):decodeURIComponent(escape(atob(o)))),r+t);return JSON.parse(s)}({di:e,iv:r},o);i&&(this.apiMappings=i),a&&(this.rules=a)}this.isReady=!0}catch(e){console.error("[mockforme] Failed to fetch mappings:",e.message)}}getProxyUrl(){return`${g}/${this.organisationId}/${this.memberKey}`}checkRules(e){return y.match(e,this.rules)}async applyRuleBehavior(e,t){return await y.apply(e,t)}interceptFetch(e,t){const r=(t.method||"GET").toUpperCase(),o=this.apiMappings.find(t=>{const o=l(t.apiMethod)===l(r),s=t.apiEndpoint===e.pathname||p(t.apiEndpoint,e.pathname);return o&&s});if(o){console.log("[mockforme] [api intercepted]: ",o);const r={mockforme:this.token,[E]:v},s=o?._ack||null;this.memberCacheKey&&s&&(r["x-mfm-key"]=`${this.memberCacheKey}-${s}`);let n=`${this.getProxyUrl()}${e.pathname}`;return e.search&&(n+=e.search),{url:n,init:{...t,headers:{...t.headers,...r}}}}return{url:e.href,init:t}}setupInterceptor(){const e=this;globalThis.fetch=async function(t,r={}){if(!e.isReady)return e.originalFetch(t,r);const o=t instanceof Request?new URL(t.url):new URL(t,"http://localhost"),s={url:o.href,method:(r.method||"GET").toUpperCase(),headers:r.headers||{},queryParams:Object.fromEntries(o.searchParams.entries())},n=e.checkRules(s);if(n){console.log("[mockforme] [fetch] [rule matched]: ",u(n));try{const t=await e.applyRuleBehavior(n,s),{modifiedRequest:o,type:a,redirectUrl:i}=t;return"redirect"===a?e.originalFetch(i,{...r,method:o.method,headers:o.headers,body:o.body}):e.originalFetch(o.url,{...r,method:o.method,headers:o.headers,body:o.body})}catch(e){throw e}}const{url:a,init:i}=e.interceptFetch(o,r);try{const t=await e.originalFetch(a,i);if(!t.ok)throw new Error(`[mockforme] Proxy fetch failed: ${t.status} ${t.statusText}`);return t}catch(e){throw e}};const r=(t,r)=>async function(...o){let s=o[0];if("string"==typeof s&&(s=new URL(s)),!e.isReady)return t.apply(null,[s,...o.slice(1)]);const n={url:s.href||s.url||`http://${s.hostname}${s.path}`,method:(s.method||"GET").toUpperCase(),headers:s.headers||{}},a=e.checkRules(n);if(a){console.log(`[mockforme] [${r}] [rule matched]: `,u(a));try{const r=await e.applyRuleBehavior(a,n),{modifiedRequest:i,type:c,redirectUrl:l}=r;if("passThrough"===c){const e={...s};try{const t=new URL(i.url);e.hostname=t.hostname,e.path=t.pathname+t.search,e.port=t.port,e.protocol=t.protocol}catch(e){}return i.headers&&(e.headers=i.headers),i.method&&(e.method=i.method),t.apply(null,[e,...o.slice(1)])}}catch(e){throw e}}const i=e.interceptRequest(s);try{return t.apply(null,[i,...o.slice(1)])}catch(e){throw e}};t().request=r(this.originalHttpRequest,"http.request"),n().request=r(this.originalHttpsRequest,"https.request"),t().get=r(this.originalHttpGet,"http.get"),n().get=r(this.originalHttpsGet,"https.get")}interceptRequest(e){const t=this.apiMappings.find(t=>{if(l(t.apiMethod)===l(e.method))return t.apiEndpoint===e.path||p(t.apiEndpoint,e.path)});if(t){console.log("[mockforme] [matched request]: ",t,e);const r={mockforme:this.token,[E]:v},o=t?._ack||null;this.memberCacheKey&&o&&(r["x-mfm-key"]=`${this.memberCacheKey}-${o}`);let s=`${this.getProxyUrl()}${e.path}`;e.search&&(s+=e.search);const n=new URL(s);return{...e,hostname:n.hostname,path:n.pathname,headers:{...e.headers,...r}}}return e}run(e){e&&e(this.apiMappings,{_rules:this.rules})}}function _(e){return A?(A.token=e,A.fetchApiMappings()):A=new b(e),A}})(),module.exports=o})();
|
|
1
|
+
(()=>{var e={583(e,t,r){const o=r(896),s=r(928),n=r(857),a=r(982),i=r(519).version,c=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/gm;function l(e){console.log(`[dotenv@${i}][DEBUG] ${e}`)}function p(e){console.log(`[dotenv@${i}] ${e}`)}function u(e){return e&&e.DOTENV_KEY&&e.DOTENV_KEY.length>0?e.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:""}function h(e,t){let r;try{r=new URL(t)}catch(e){if("ERR_INVALID_URL"===e.code){const e=new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");throw e.code="INVALID_DOTENV_KEY",e}throw e}const o=r.password;if(!o){const e=new Error("INVALID_DOTENV_KEY: Missing key part");throw e.code="INVALID_DOTENV_KEY",e}const s=r.searchParams.get("environment");if(!s){const e=new Error("INVALID_DOTENV_KEY: Missing environment part");throw e.code="INVALID_DOTENV_KEY",e}const n=`DOTENV_VAULT_${s.toUpperCase()}`,a=e.parsed[n];if(!a){const e=new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${n} in your .env.vault file.`);throw e.code="NOT_FOUND_DOTENV_ENVIRONMENT",e}return{ciphertext:a,key:o}}function d(e){let t=null;if(e&&e.path&&e.path.length>0)if(Array.isArray(e.path))for(const r of e.path)o.existsSync(r)&&(t=r.endsWith(".vault")?r:`${r}.vault`);else t=e.path.endsWith(".vault")?e.path:`${e.path}.vault`;else t=s.resolve(process.cwd(),".env.vault");return o.existsSync(t)?t:null}function f(e){return"~"===e[0]?s.join(n.homedir(),e.slice(1)):e}const y={configDotenv:function(e){const t=s.resolve(process.cwd(),".env");let r="utf8";const n=Boolean(e&&e.debug),a=!e||!("quiet"in e)||e.quiet;e&&e.encoding?r=e.encoding:n&&l("No encoding is specified. UTF-8 is used by default");let i,c=[t];if(e&&e.path)if(Array.isArray(e.path)){c=[];for(const t of e.path)c.push(f(t))}else c=[f(e.path)];const u={};for(const t of c)try{const s=y.parse(o.readFileSync(t,{encoding:r}));y.populate(u,s,e)}catch(e){n&&l(`Failed to load ${t} ${e.message}`),i=e}let h=process.env;if(e&&null!=e.processEnv&&(h=e.processEnv),y.populate(h,u,e),n||!a){const e=Object.keys(u).length,t=[];for(const e of c)try{const r=s.relative(process.cwd(),e);t.push(r)}catch(t){n&&l(`Failed to load ${e} ${t.message}`),i=t}p(`injecting env (${e}) from ${t.join(",")}`)}return i?{parsed:u,error:i}:{parsed:u}},_configVault:function(e){const t=Boolean(e&&e.debug),r=!e||!("quiet"in e)||e.quiet;!t&&r||p("Loading env from encrypted .env.vault");const o=y._parseVault(e);let s=process.env;return e&&null!=e.processEnv&&(s=e.processEnv),y.populate(s,o,e),{parsed:o}},_parseVault:function(e){const t=d(e=e||{});e.path=t;const r=y.configDotenv(e);if(!r.parsed){const e=new Error(`MISSING_DATA: Cannot parse ${t} for an unknown reason`);throw e.code="MISSING_DATA",e}const o=u(e).split(","),s=o.length;let n;for(let e=0;e<s;e++)try{const t=h(r,o[e].trim());n=y.decrypt(t.ciphertext,t.key);break}catch(t){if(e+1>=s)throw t}return y.parse(n)},config:function(e){if(0===u(e).length)return y.configDotenv(e);const t=d(e);return t?y._configVault(e):(r=`You set DOTENV_KEY but you are missing a .env.vault file at ${t}. Did you forget to build it?`,console.log(`[dotenv@${i}][WARN] ${r}`),y.configDotenv(e));var r},decrypt:function(e,t){const r=Buffer.from(t.slice(-64),"hex");let o=Buffer.from(e,"base64");const s=o.subarray(0,12),n=o.subarray(-16);o=o.subarray(12,-16);try{const e=a.createDecipheriv("aes-256-gcm",r,s);return e.setAuthTag(n),`${e.update(o)}${e.final()}`}catch(e){const t=e instanceof RangeError,r="Invalid key length"===e.message,o="Unsupported state or unable to authenticate data"===e.message;if(t||r){const e=new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw e.code="INVALID_DOTENV_KEY",e}if(o){const e=new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");throw e.code="DECRYPTION_FAILED",e}throw e}},parse:function(e){const t={};let r,o=e.toString();for(o=o.replace(/\r\n?/gm,"\n");null!=(r=c.exec(o));){const e=r[1];let o=r[2]||"";o=o.trim();const s=o[0];o=o.replace(/^(['"`])([\s\S]*)\1$/gm,"$2"),'"'===s&&(o=o.replace(/\\n/g,"\n"),o=o.replace(/\\r/g,"\r")),t[e]=o}return t},populate:function(e,t,r={}){const o=Boolean(r&&r.debug),s=Boolean(r&&r.override);if("object"!=typeof t){const e=new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");throw e.code="OBJECT_REQUIRED",e}for(const r of Object.keys(t))Object.prototype.hasOwnProperty.call(e,r)?(!0===s&&(e[r]=t[r]),o&&l(!0===s?`"${r}" is already defined and WAS overwritten`:`"${r}" is already defined and was NOT overwritten`)):e[r]=t[r]}};e.exports.configDotenv=y.configDotenv,e.exports._configVault=y._configVault,e.exports._parseVault=y._parseVault,e.exports.config=y.config,e.exports.decrypt=y.decrypt,e.exports.parse=y.parse,e.exports.populate=y.populate,e.exports=y},982(e){"use strict";e.exports=require("crypto")},896(e){"use strict";e.exports=require("fs")},857(e){"use strict";e.exports=require("os")},928(e){"use strict";e.exports=require("path")},519(e){"use strict";e.exports={version:"16.6.1"}}};const t={};function r(o){const s=t[o];if(void 0!==s)return s.exports;const n=t[o]={exports:{}};return e[o](n,n.exports,r),n.exports}r.n=e=>{const t=e&&e.__esModule?()=>e.default:()=>e;return r.d(t,{a:t}),t},r.d=(e,t)=>{if(Array.isArray(t))for(var o=0;o<t.length;){var s=t[o++],n=t[o++];r.o(e,s)?0===n&&o++:0===n?Object.defineProperty(e,s,{enumerable:!0,value:t[o++]}):Object.defineProperty(e,s,{enumerable:!0,get:n})}else for(var s in t)r.o(t,s)&&!r.o(e,s)&&Object.defineProperty(e,s,{enumerable:!0,get:t[s]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};let o={};(()=>{"use strict";r.r(o),r.d(o,{mockforme:()=>_});const e=require("http");var t=r.n(e);const s=require("https");var n=r.n(s);const a=require("child_process");var i=r(583),c=r.n(i);const l=e=>{try{return e?e.toLowerCase():e}catch(e){return console.log(e),null}},p=(e,t)=>{const r=e.split("/"),o=t.split("/");if(r.length!==o.length)return!1;for(let e=0;e<r.length;e++){const t=r[e];if(t!==o[e]&&":any"!==t&&":"!==t.charAt(0))return!1}return!0},u=(e,t=null,r=2)=>{try{return JSON.stringify(e,t,r)}catch(e){return null}};class h{static match(e,t){if(!Array.isArray(t)||0===t.length)return!1;const{url:r,headers:o,queryParams:s,body:n}=e,a="undefined"!=typeof window?window.location.origin:globalThis.location?.origin||"http://localhost";for(const e of t){let t="";const{type:i,key:c,operator:l,value:p}=e;switch(i){case"URL":try{t=new URL(r,a).pathname}catch{t=r}break;case"QUERY_PARAM":if(s&&void 0!==s[c])t=String(s[c]);else try{t=new URL(r,a).searchParams.get(c)||""}catch{t=""}break;case"REQUEST_BODY":if(c){if("object"==typeof n&&null!==n)t=void 0!==n[c]?String(n[c]):"";else if("string"==typeof n)try{const e=JSON.parse(n);t=void 0!==e[c]?String(e[c]):""}catch{t=""}}else t="object"==typeof n?JSON.stringify(n):String(n||"");break;case"REQUEST_HEADER":if(c){const e=c?.toLowerCase();if(t="",o){const r=Object.keys(o).find(t=>t.toLowerCase()===e);t=r?String(o[r]):""}}else t=JSON.stringify(o||{});break;default:return!1}if(!this.evaluate(t,l,p))return!1}return!0}static evaluate(e,t,r){const o=t?.toLowerCase(),s=String(e),n=String(r);switch(o){case"contains":return s.includes(n);case"equal":case"equals":return s===n;case"regexp":try{let e=n;if(e.startsWith("/")&&e.lastIndexOf("/")>0){const t=e.lastIndexOf("/"),r=e.slice(1,t),o=e.slice(t+1);return new RegExp(r,o).test(s)}return new RegExp(e).test(s)}catch{return!1}default:return!1}}}class d{static async apply(e){if(!e||!e.activeAction)return{type:"passThrough",delay:0};const{activeAction:t,actions:r}=e,o=r?.[t];if(!o)return{type:"passThrough",delay:0};const s={type:"passThrough",delay:0},n=Number(o.value||0);switch(t){case"delay":s.delay=n,s.delay>0&&await new Promise(e=>setTimeout(e,1e3*s.delay));break;case"redirect":case"delay_and_redirect":s.type="redirect",s.delay=n,s.redirectUrl=o.redirectUrl,s.delay>0&&await new Promise(e=>setTimeout(e,1e3*s.delay));break;case"delay_and_timeout":s.type="timeout",s.delay=n,s.delay>0&&await new Promise(e=>setTimeout(e,1e3*s.delay))}return s}}class f{static applyRequestModifications(e,t){if(!t)return e;let{url:r,method:o,headers:s,queryParams:n,body:a}={...e};s&&(s={...s}),n&&(n={...n});const{modifyQueryParams:i,modifyRequestBody:c,modifyRequestHeaders:l}=t;if(i?.enabled)try{const e=new URL(r,"undefined"!=typeof window?window.location.href:"http://localhost");Array.isArray(i.remove)&&i.remove.forEach(t=>{e.searchParams.delete(t),n&&delete n[t]}),Array.isArray(i.add)&&i.add.forEach(({key:t,value:r})=>{e.searchParams.set(t,r),n&&(n[t]=r)}),r=e.toString()}catch(e){console.error("[MockForMe] Failed to modify query params",e)}l?.enabled&&(s={...s},Array.isArray(l.remove)&&l.remove.forEach(e=>{const t=e.toLowerCase(),r=Object.keys(s).find(e=>e.toLowerCase()===t);r&&delete s[r]}),Array.isArray(l.add)&&l.add.forEach(({key:e,value:t})=>{s[e]=t}));const p=String(o||"GET").toUpperCase(),u="GET"===p||"HEAD"===p;if(c?.enabled&&!u)try{let e=null;if("string"==typeof a)try{e=JSON.parse(a)}catch{e={}}else if("object"==typeof a&&null!==a)try{e=JSON.parse(JSON.stringify(a))}catch{e={...a}}else(Array.isArray(c.add)&&c.add.length>0||Array.isArray(c.update)&&c.update.length>0)&&(e={});e&&(Array.isArray(c.remove)&&c.remove.forEach(t=>delete e[t]),Array.isArray(c.add)&&c.add.forEach(({key:t,value:r})=>e[t]=r),Array.isArray(c.update)&&c.update.forEach(({key:t,value:r})=>e[t]=r),a=JSON.stringify(e))}catch(e){console.error("[MockForMe] Failed to modify request body",e)}return{...e,url:r,headers:s,queryParams:n,body:a}}static applyResponseModifications(e,t){if(!t?.modifyResponseHeaders?.enabled)return e;const{modifyResponseHeaders:r}=t,o={...e};return Array.isArray(r.remove)&&r.remove.forEach(e=>{const t=e.toLowerCase(),r=Object.keys(o).find(e=>e.toLowerCase()===t);r&&delete o[r]}),Array.isArray(r.add)&&r.add.forEach(({key:e,value:t})=>{o[e]=t}),o}}class y{static match(e,t){if(!Array.isArray(t)||0===t.length)return null;for(const r of t){const t=r.rule||r;if(t.conditions&&Array.isArray(t.conditions)&&h.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 r=e.rule||e,o=f.applyRequestModifications(t,r.modificationActions);return{...await d.apply(r.timingAction),modifiedRequest:o,rule:r}}static applyResponseModifications(e,t){return f.applyResponseModifications(e,t)}}c().config({path:"../../.env"});const m="https://api.mockforme.com",g=`${m}/mockforme`,E="mfmver",v="4.2.7";let w=`${m}/gateway/3f4eae522b`,A=null;class b{constructor(e){this.token=e,this.apiMappings=[],this.rules=[],this.isReady=!1,this.originalHttpRequest=t().request,this.originalHttpGet=t().get,this.originalHttpsRequest=n().request,this.originalHttpsGet=n().get,this.originalFetch=globalThis.fetch,this.fetchApiMappings(),this.setupInterceptor()}checkIsErrorInFetchMappings(e){try{const t=JSON.parse(e);if(0==t?.status)throw new Error(t?.message||"Failed to fetch mockforme mappings")}catch(e){throw new Error(e.message||"Failed to fetch mockforme mappings")}}fetchApiMappings(){this.apiMappings=[],this.rules=[],this.isReady=!1;try{const e=`curl -s -H "mockforme: ${this.token}" "${w}"`,t=(0,a.execSync)(e,{encoding:"utf8"});if(t&&this.checkIsErrorInFetchMappings(t),!t)throw new Error("Failed to fetch mockforme mappings: No response");{const{di:e,iv:r,_o:o,_mck:s,mk:n,r:a}=JSON.parse(t);this.organisationId=o,this.memberKey=n,this.memberCacheKey=s;const i=function({di:e,iv:t},r){var o;const s=function(e,t){const r=t.length;return e.split("").map((e,o)=>String.fromCharCode(e.charCodeAt(0)^t.charCodeAt(o%r))).join("")}((o=e,"undefined"!=typeof Buffer?Buffer.from(o,"base64").toString("utf8"):decodeURIComponent(escape(atob(o)))),r+t);return JSON.parse(s)}({di:e,iv:r},o);i&&(this.apiMappings=i),a&&(this.rules=a)}this.isReady=!0}catch(e){console.error("[mockforme] Failed to fetch mappings:",e.message)}}getProxyUrl(){return`${g}/${this.organisationId}/${this.memberKey}`}checkRules(e){return y.match(e,this.rules)}async applyRuleBehavior(e,t){return await y.apply(e,t)}interceptFetch(e,t){const r=(t.method||"GET").toUpperCase(),o=this.apiMappings.find(t=>{const o=l(t.apiMethod)===l(r),s=t.apiEndpoint===e.pathname||p(t.apiEndpoint,e.pathname);return o&&s});if(o){console.log("[mockforme] [api intercepted]: ",o);const r={mockforme:this.token,[E]:v},s=o?._ack||null;this.memberCacheKey&&s&&(r["x-mfm-key"]=`${this.memberCacheKey}-${s}`);let n=`${this.getProxyUrl()}${e.pathname}`;return e.search&&(n+=e.search),{url:n,init:{...t,headers:{...t.headers,...r}}}}return{url:e.href,init:t}}setupInterceptor(){const e=this;globalThis.fetch=async function(t,r={}){if(!e.isReady)return e.originalFetch(t,r);const o=t instanceof Request?new URL(t.url):new URL(t,"http://localhost"),s={url:o.href,method:(r.method||"GET").toUpperCase(),headers:r.headers||{},queryParams:Object.fromEntries(o.searchParams.entries())},n=e.checkRules(s);if(n){console.log("[mockforme] [fetch] [rule matched]: ",u(n));try{const t=await e.applyRuleBehavior(n,s),{modifiedRequest:o,type:a,redirectUrl:i}=t;return"redirect"===a?e.originalFetch(i,{...r,method:o.method,headers:o.headers,body:o.body}):e.originalFetch(o.url,{...r,method:o.method,headers:o.headers,body:o.body})}catch(e){throw e}}const{url:a,init:i}=e.interceptFetch(o,r);try{const t=await e.originalFetch(a,i);if(!t.ok)throw new Error(`[mockforme] Proxy fetch failed: ${t.status} ${t.statusText}`);return t}catch(e){throw e}};const r=(t,r)=>async function(...o){let s=o[0];if("string"==typeof s&&(s=new URL(s)),!e.isReady)return t.apply(null,[s,...o.slice(1)]);const n={url:s.href||s.url||`http://${s.hostname}${s.path}`,method:(s.method||"GET").toUpperCase(),headers:s.headers||{}},a=e.checkRules(n);if(a){console.log(`[mockforme] [${r}] [rule matched]: `,u(a));try{const r=await e.applyRuleBehavior(a,n),{modifiedRequest:i,type:c,redirectUrl:l}=r;if("passThrough"===c){const e={...s};try{const t=new URL(i.url);e.hostname=t.hostname,e.path=t.pathname+t.search,e.port=t.port,e.protocol=t.protocol}catch(e){}return i.headers&&(e.headers=i.headers),i.method&&(e.method=i.method),t.apply(null,[e,...o.slice(1)])}}catch(e){throw e}}const i=e.interceptRequest(s);try{return t.apply(null,[i,...o.slice(1)])}catch(e){throw e}};t().request=r(this.originalHttpRequest,"http.request"),n().request=r(this.originalHttpsRequest,"https.request"),t().get=r(this.originalHttpGet,"http.get"),n().get=r(this.originalHttpsGet,"https.get")}interceptRequest(e){const t=this.apiMappings.find(t=>{if(l(t.apiMethod)===l(e.method))return t.apiEndpoint===e.path||p(t.apiEndpoint,e.path)});if(t){console.log("[mockforme] [matched request]: ",t,e);const r={mockforme:this.token,[E]:v},o=t?._ack||null;this.memberCacheKey&&o&&(r["x-mfm-key"]=`${this.memberCacheKey}-${o}`);let s=`${this.getProxyUrl()}${e.path}`;e.search&&(s+=e.search);const n=new URL(s);return{...e,hostname:n.hostname,path:n.pathname,headers:{...e.headers,...r}}}return e}run(e){e&&e(this.apiMappings,{_rules:this.rules})}}function _(e){return A?(A.token=e,A.fetchApiMappings()):A=new b(e),A}})(),module.exports=o})();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createRequire as e}from"node:module";const t=e(import.meta.url);import{default as r}from"http";import{default as o}from"https";import{execSync as s}from"child_process";var n={583(e,t,r){const o=r(896),s=r(928),n=r(857),a=r(982),i=r(519).version,c=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/gm;function l(e){console.log(`[dotenv@${i}][DEBUG] ${e}`)}function p(e){console.log(`[dotenv@${i}] ${e}`)}function h(e){return e&&e.DOTENV_KEY&&e.DOTENV_KEY.length>0?e.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:""}function u(e,t){let r;try{r=new URL(t)}catch(e){if("ERR_INVALID_URL"===e.code){const e=new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");throw e.code="INVALID_DOTENV_KEY",e}throw e}const o=r.password;if(!o){const e=new Error("INVALID_DOTENV_KEY: Missing key part");throw e.code="INVALID_DOTENV_KEY",e}const s=r.searchParams.get("environment");if(!s){const e=new Error("INVALID_DOTENV_KEY: Missing environment part");throw e.code="INVALID_DOTENV_KEY",e}const n=`DOTENV_VAULT_${s.toUpperCase()}`,a=e.parsed[n];if(!a){const e=new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${n} in your .env.vault file.`);throw e.code="NOT_FOUND_DOTENV_ENVIRONMENT",e}return{ciphertext:a,key:o}}function d(e){let t=null;if(e&&e.path&&e.path.length>0)if(Array.isArray(e.path))for(const r of e.path)o.existsSync(r)&&(t=r.endsWith(".vault")?r:`${r}.vault`);else t=e.path.endsWith(".vault")?e.path:`${e.path}.vault`;else t=s.resolve(process.cwd(),".env.vault");return o.existsSync(t)?t:null}function f(e){return"~"===e[0]?s.join(n.homedir(),e.slice(1)):e}const y={configDotenv:function(e){const t=s.resolve(process.cwd(),".env");let r="utf8";const n=Boolean(e&&e.debug),a=!e||!("quiet"in e)||e.quiet;e&&e.encoding?r=e.encoding:n&&l("No encoding is specified. UTF-8 is used by default");let i,c=[t];if(e&&e.path)if(Array.isArray(e.path)){c=[];for(const t of e.path)c.push(f(t))}else c=[f(e.path)];const h={};for(const t of c)try{const s=y.parse(o.readFileSync(t,{encoding:r}));y.populate(h,s,e)}catch(e){n&&l(`Failed to load ${t} ${e.message}`),i=e}let u=process.env;if(e&&null!=e.processEnv&&(u=e.processEnv),y.populate(u,h,e),n||!a){const e=Object.keys(h).length,t=[];for(const e of c)try{const r=s.relative(process.cwd(),e);t.push(r)}catch(t){n&&l(`Failed to load ${e} ${t.message}`),i=t}p(`injecting env (${e}) from ${t.join(",")}`)}return i?{parsed:h,error:i}:{parsed:h}},_configVault:function(e){const t=Boolean(e&&e.debug),r=!e||!("quiet"in e)||e.quiet;!t&&r||p("Loading env from encrypted .env.vault");const o=y._parseVault(e);let s=process.env;return e&&null!=e.processEnv&&(s=e.processEnv),y.populate(s,o,e),{parsed:o}},_parseVault:function(e){const t=d(e=e||{});e.path=t;const r=y.configDotenv(e);if(!r.parsed){const e=new Error(`MISSING_DATA: Cannot parse ${t} for an unknown reason`);throw e.code="MISSING_DATA",e}const o=h(e).split(","),s=o.length;let n;for(let e=0;e<s;e++)try{const t=u(r,o[e].trim());n=y.decrypt(t.ciphertext,t.key);break}catch(t){if(e+1>=s)throw t}return y.parse(n)},config:function(e){if(0===h(e).length)return y.configDotenv(e);const t=d(e);return t?y._configVault(e):(r=`You set DOTENV_KEY but you are missing a .env.vault file at ${t}. Did you forget to build it?`,console.log(`[dotenv@${i}][WARN] ${r}`),y.configDotenv(e));var r},decrypt:function(e,t){const r=Buffer.from(t.slice(-64),"hex");let o=Buffer.from(e,"base64");const s=o.subarray(0,12),n=o.subarray(-16);o=o.subarray(12,-16);try{const e=a.createDecipheriv("aes-256-gcm",r,s);return e.setAuthTag(n),`${e.update(o)}${e.final()}`}catch(e){const t=e instanceof RangeError,r="Invalid key length"===e.message,o="Unsupported state or unable to authenticate data"===e.message;if(t||r){const e=new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw e.code="INVALID_DOTENV_KEY",e}if(o){const e=new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");throw e.code="DECRYPTION_FAILED",e}throw e}},parse:function(e){const t={};let r,o=e.toString();for(o=o.replace(/\r\n?/gm,"\n");null!=(r=c.exec(o));){const e=r[1];let o=r[2]||"";o=o.trim();const s=o[0];o=o.replace(/^(['"`])([\s\S]*)\1$/gm,"$2"),'"'===s&&(o=o.replace(/\\n/g,"\n"),o=o.replace(/\\r/g,"\r")),t[e]=o}return t},populate:function(e,t,r={}){const o=Boolean(r&&r.debug),s=Boolean(r&&r.override);if("object"!=typeof t){const e=new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");throw e.code="OBJECT_REQUIRED",e}for(const r of Object.keys(t))Object.prototype.hasOwnProperty.call(e,r)?(!0===s&&(e[r]=t[r]),o&&l(!0===s?`"${r}" is already defined and WAS overwritten`:`"${r}" is already defined and was NOT overwritten`)):e[r]=t[r]}};e.exports.configDotenv=y.configDotenv,e.exports._configVault=y._configVault,e.exports._parseVault=y._parseVault,e.exports.config=y.config,e.exports.decrypt=y.decrypt,e.exports.parse=y.parse,e.exports.populate=y.populate,e.exports=y},982(e){e.exports=t("crypto")},896(e){e.exports=t("fs")},857(e){e.exports=t("os")},928(e){e.exports=t("path")},519(e){e.exports={version:"16.6.1"}}};const a={};function i(e){const t=a[e];if(void 0!==t)return t.exports;const r=a[e]={exports:{}};return n[e](r,r.exports,i),r.exports}i.n=e=>{const t=e&&e.__esModule?()=>e.default:()=>e;return i.d(t,{a:t}),t},i.d=(e,t)=>{if(Array.isArray(t))for(var r=0;r<t.length;){var o=t[r++],s=t[r++];i.o(e,o)?0===s&&r++:0===s?Object.defineProperty(e,o,{enumerable:!0,value:t[r++]}):Object.defineProperty(e,o,{enumerable:!0,get:s})}else for(var o in t)i.o(t,o)&&!i.o(e,o)&&Object.defineProperty(e,o,{enumerable:!0,get:t[o]})},i.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var c=i(583),l=i.n(c);const p=e=>{try{return e?e.toLowerCase():e}catch(e){return console.log(e),null}},h=(e,t)=>{const r=e.split("/"),o=t.split("/");if(r.length!==o.length)return!1;for(let e=0;e<r.length;e++){const t=r[e];if(t!==o[e]&&":any"!==t&&":"!==t.charAt(0))return!1}return!0},u=(e,t=null,r=2)=>{try{return JSON.stringify(e,t,r)}catch(e){return null}};class d{static match(e,t){if(!Array.isArray(t)||0===t.length)return!1;const{url:r,headers:o,queryParams:s,body:n}=e,a="undefined"!=typeof window?window.location.origin:globalThis.location?.origin||"http://localhost";for(const e of t){let t="";const{type:i,key:c,operator:l,value:p}=e;switch(i){case"URL":try{t=new URL(r,a).pathname}catch{t=r}break;case"QUERY_PARAM":if(s&&void 0!==s[c])t=String(s[c]);else try{t=new URL(r,a).searchParams.get(c)||""}catch{t=""}break;case"REQUEST_BODY":if(c){if("object"==typeof n&&null!==n)t=void 0!==n[c]?String(n[c]):"";else if("string"==typeof n)try{const e=JSON.parse(n);t=void 0!==e[c]?String(e[c]):""}catch{t=""}}else t="object"==typeof n?JSON.stringify(n):String(n||"");break;case"REQUEST_HEADER":if(c){const e=c?.toLowerCase();if(t="",o){const r=Object.keys(o).find(t=>t.toLowerCase()===e);t=r?String(o[r]):""}}else t=JSON.stringify(o||{});break;default:return!1}if(!this.evaluate(t,l,p))return!1}return!0}static evaluate(e,t,r){const o=t?.toLowerCase(),s=String(e),n=String(r);switch(o){case"contains":return s.includes(n);case"equal":case"equals":return s===n;case"regexp":try{let e=n;if(e.startsWith("/")&&e.lastIndexOf("/")>0){const t=e.lastIndexOf("/"),r=e.slice(1,t),o=e.slice(t+1);return new RegExp(r,o).test(s)}return new RegExp(e).test(s)}catch{return!1}default:return!1}}}class f{static async apply(e){if(!e||!e.activeAction)return{type:"passThrough",delay:0};const{activeAction:t,actions:r}=e,o=r?.[t];if(!o)return{type:"passThrough",delay:0};const s={type:"passThrough",delay:0},n=Number(o.value||0);switch(t){case"delay":s.delay=n,s.delay>0&&await new Promise(e=>setTimeout(e,1e3*s.delay));break;case"redirect":case"delay_and_redirect":s.type="redirect",s.delay=n,s.redirectUrl=o.redirectUrl,s.delay>0&&await new Promise(e=>setTimeout(e,1e3*s.delay));break;case"delay_and_timeout":s.type="timeout",s.delay=n,s.delay>0&&await new Promise(e=>setTimeout(e,1e3*s.delay))}return s}}class y{static applyRequestModifications(e,t){if(!t)return e;let{url:r,method:o,headers:s,queryParams:n,body:a}={...e};s&&(s={...s}),n&&(n={...n});const{modifyQueryParams:i,modifyRequestBody:c,modifyRequestHeaders:l}=t;if(i?.enabled)try{const e=new URL(r,"undefined"!=typeof window?window.location.href:"http://localhost");Array.isArray(i.remove)&&i.remove.forEach(t=>{e.searchParams.delete(t),n&&delete n[t]}),Array.isArray(i.add)&&i.add.forEach(({key:t,value:r})=>{e.searchParams.set(t,r),n&&(n[t]=r)}),r=e.toString()}catch(e){console.error("[MockForMe] Failed to modify query params",e)}l?.enabled&&(s={...s},Array.isArray(l.remove)&&l.remove.forEach(e=>{const t=e.toLowerCase(),r=Object.keys(s).find(e=>e.toLowerCase()===t);r&&delete s[r]}),Array.isArray(l.add)&&l.add.forEach(({key:e,value:t})=>{s[e]=t}));const p=String(o||"GET").toUpperCase(),h="GET"===p||"HEAD"===p;if(c?.enabled&&!h)try{let e=null;if("string"==typeof a)try{e=JSON.parse(a)}catch{e={}}else if("object"==typeof a&&null!==a)try{e=JSON.parse(JSON.stringify(a))}catch{e={...a}}else(Array.isArray(c.add)&&c.add.length>0||Array.isArray(c.update)&&c.update.length>0)&&(e={});e&&(Array.isArray(c.remove)&&c.remove.forEach(t=>delete e[t]),Array.isArray(c.add)&&c.add.forEach(({key:t,value:r})=>e[t]=r),Array.isArray(c.update)&&c.update.forEach(({key:t,value:r})=>e[t]=r),a=JSON.stringify(e))}catch(e){console.error("[MockForMe] Failed to modify request body",e)}return{...e,url:r,headers:s,queryParams:n,body:a}}static applyResponseModifications(e,t){if(!t?.modifyResponseHeaders?.enabled)return e;const{modifyResponseHeaders:r}=t,o={...e};return Array.isArray(r.remove)&&r.remove.forEach(e=>{const t=e.toLowerCase(),r=Object.keys(o).find(e=>e.toLowerCase()===t);r&&delete o[r]}),Array.isArray(r.add)&&r.add.forEach(({key:e,value:t})=>{o[e]=t}),o}}class m{static match(e,t){if(!Array.isArray(t)||0===t.length)return null;for(const r of t){const t=r.rule||r;if(t.conditions&&Array.isArray(t.conditions)&&d.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 r=e.rule||e,o=y.applyRequestModifications(t,r.modificationActions);return{...await f.apply(r.timingAction),modifiedRequest:o,rule:r}}static applyResponseModifications(e,t){return y.applyResponseModifications(e,t)}}l().config("../../.env");const g="https://api.mockforme.com",E=`${g}/mockforme`,v="mfmver",w="4.2.7";let A=`${g}/gateway/3f4eae522b`,b=null;class _{constructor(e){this.token=e,this.apiMappings=[],this.rules=[],this.isReady=!1,this.originalHttpRequest=r.request,this.originalHttpGet=r.get,this.originalHttpsRequest=o.request,this.originalHttpsGet=o.get,this.originalFetch=globalThis.fetch,this.fetchApiMappings(),this.setupInterceptor()}checkIsErrorInFetchMappings(e){try{const t=JSON.parse(e);if(0==t?.status)throw new Error(t?.message||"Failed to fetch mockforme mappings")}catch(e){throw new Error(e.message||"Failed to fetch mockforme mappings")}}fetchApiMappings(){this.apiMappings=[],this.rules=[],this.isReady=!1;try{const e=`curl -s -H "mockforme: ${this.token}" "${A}"`,t=s(e,{encoding:"utf8"});if(t&&this.checkIsErrorInFetchMappings(t),!t)throw new Error("Failed to fetch mockforme mappings: No response");{const{di:e,iv:r,_o:o,_mck:s,mk:n,r:a}=JSON.parse(t);this.organisationId=o,this.memberKey=n,this.memberCacheKey=s;const i=function({di:e,iv:t},r){var o;const s=function(e,t){const r=t.length;return e.split("").map((e,o)=>String.fromCharCode(e.charCodeAt(0)^t.charCodeAt(o%r))).join("")}((o=e,"undefined"!=typeof Buffer?Buffer.from(o,"base64").toString("utf8"):decodeURIComponent(escape(atob(o)))),r+t);return JSON.parse(s)}({di:e,iv:r},o);i&&(this.apiMappings=i),a&&(this.rules=a)}this.isReady=!0}catch(e){console.error("[mockforme] Failed to fetch mappings:",e.message)}}getProxyUrl(){return`${E}/${this.organisationId}/${this.memberKey}`}checkRules(e){return m.match(e,this.rules)}async applyRuleBehavior(e,t){return await m.apply(e,t)}interceptFetch(e,t){const r=(t.method||"GET").toUpperCase(),o=this.apiMappings.find(t=>{const o=p(t.apiMethod)===p(r),s=t.apiEndpoint===e.pathname||h(t.apiEndpoint,e.pathname);return o&&s});if(o){console.log("[mockforme] [api intercepted]: ",o);const r={mockforme:this.token,[v]:w},s=o?._ack||null;this.memberCacheKey&&s&&(r["x-mfm-key"]=`${this.memberCacheKey}-${s}`);let n=`${this.getProxyUrl()}${e.pathname}`;return e.search&&(n+=e.search),{url:n,init:{...t,headers:{...t.headers,...r}}}}return{url:e.href,init:t}}setupInterceptor(){const e=this;globalThis.fetch=async function(t,r={}){if(!e.isReady)return e.originalFetch(t,r);const o=t instanceof Request?new URL(t.url):new URL(t,"http://localhost"),s={url:o.href,method:(r.method||"GET").toUpperCase(),headers:r.headers||{},queryParams:Object.fromEntries(o.searchParams.entries())},n=e.checkRules(s);if(n){console.log("[mockforme] [fetch] [rule matched]: ",u(n));try{const t=await e.applyRuleBehavior(n,s),{modifiedRequest:o,type:a,redirectUrl:i}=t;return"redirect"===a?e.originalFetch(i,{...r,method:o.method,headers:o.headers,body:o.body}):e.originalFetch(o.url,{...r,method:o.method,headers:o.headers,body:o.body})}catch(e){throw e}}const{url:a,init:i}=e.interceptFetch(o,r);try{const t=await e.originalFetch(a,i);if(!t.ok)throw new Error(`[mockforme] Proxy fetch failed: ${t.status} ${t.statusText}`);return t}catch(e){throw e}};const t=(t,r)=>async function(...o){let s=o[0];if("string"==typeof s&&(s=new URL(s)),!e.isReady)return t.apply(null,[s,...o.slice(1)]);const n={url:s.href||s.url||`http://${s.hostname}${s.path}`,method:(s.method||"GET").toUpperCase(),headers:s.headers||{}},a=e.checkRules(n);if(a){console.log(`[mockforme] [${r}] [rule matched]: `,u(a));try{const r=await e.applyRuleBehavior(a,n),{modifiedRequest:i,type:c,redirectUrl:l}=r;if("passThrough"===c){const e={...s};try{const t=new URL(i.url);e.hostname=t.hostname,e.path=t.pathname+t.search,e.port=t.port,e.protocol=t.protocol}catch(e){}return i.headers&&(e.headers=i.headers),i.method&&(e.method=i.method),t.apply(null,[e,...o.slice(1)])}}catch(e){throw e}}const i=e.interceptRequest(s);try{return t.apply(null,[i,...o.slice(1)])}catch(e){throw e}};r.request=t(this.originalHttpRequest,"http.request"),o.request=t(this.originalHttpsRequest,"https.request"),r.get=t(this.originalHttpGet,"http.get"),o.get=t(this.originalHttpsGet,"https.get")}interceptRequest(e){const t=this.apiMappings.find(t=>{if(p(t.apiMethod)===p(e.method))return t.apiEndpoint===e.path||h(t.apiEndpoint,e.path)});if(t){console.log("[mockforme] [matched request]: ",t,e);const r={mockforme:this.token,[v]:w},o=t?._ack||null;this.memberCacheKey&&o&&(r["x-mfm-key"]=`${this.memberCacheKey}-${o}`);let s=`${this.getProxyUrl()}${e.path}`;e.search&&(s+=e.search);const n=new URL(s);return{...e,hostname:n.hostname,path:n.pathname,headers:{...e.headers,...r}}}return e}run(e){e&&e(this.apiMappings,{_rules:this.rules})}}function R(e){return b?(b.token=e,b.fetchApiMappings()):b=new _(e),b}export{R as mockforme};
|
|
1
|
+
import{createRequire as e}from"node:module";const t=e(import.meta.url);import{default as r}from"http";import{default as o}from"https";import{execSync as s}from"child_process";var n={583(e,t,r){const o=r(896),s=r(928),n=r(857),a=r(982),i=r(519).version,c=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/gm;function l(e){console.log(`[dotenv@${i}][DEBUG] ${e}`)}function p(e){console.log(`[dotenv@${i}] ${e}`)}function h(e){return e&&e.DOTENV_KEY&&e.DOTENV_KEY.length>0?e.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:""}function u(e,t){let r;try{r=new URL(t)}catch(e){if("ERR_INVALID_URL"===e.code){const e=new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");throw e.code="INVALID_DOTENV_KEY",e}throw e}const o=r.password;if(!o){const e=new Error("INVALID_DOTENV_KEY: Missing key part");throw e.code="INVALID_DOTENV_KEY",e}const s=r.searchParams.get("environment");if(!s){const e=new Error("INVALID_DOTENV_KEY: Missing environment part");throw e.code="INVALID_DOTENV_KEY",e}const n=`DOTENV_VAULT_${s.toUpperCase()}`,a=e.parsed[n];if(!a){const e=new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${n} in your .env.vault file.`);throw e.code="NOT_FOUND_DOTENV_ENVIRONMENT",e}return{ciphertext:a,key:o}}function d(e){let t=null;if(e&&e.path&&e.path.length>0)if(Array.isArray(e.path))for(const r of e.path)o.existsSync(r)&&(t=r.endsWith(".vault")?r:`${r}.vault`);else t=e.path.endsWith(".vault")?e.path:`${e.path}.vault`;else t=s.resolve(process.cwd(),".env.vault");return o.existsSync(t)?t:null}function f(e){return"~"===e[0]?s.join(n.homedir(),e.slice(1)):e}const y={configDotenv:function(e){const t=s.resolve(process.cwd(),".env");let r="utf8";const n=Boolean(e&&e.debug),a=!e||!("quiet"in e)||e.quiet;e&&e.encoding?r=e.encoding:n&&l("No encoding is specified. UTF-8 is used by default");let i,c=[t];if(e&&e.path)if(Array.isArray(e.path)){c=[];for(const t of e.path)c.push(f(t))}else c=[f(e.path)];const h={};for(const t of c)try{const s=y.parse(o.readFileSync(t,{encoding:r}));y.populate(h,s,e)}catch(e){n&&l(`Failed to load ${t} ${e.message}`),i=e}let u=process.env;if(e&&null!=e.processEnv&&(u=e.processEnv),y.populate(u,h,e),n||!a){const e=Object.keys(h).length,t=[];for(const e of c)try{const r=s.relative(process.cwd(),e);t.push(r)}catch(t){n&&l(`Failed to load ${e} ${t.message}`),i=t}p(`injecting env (${e}) from ${t.join(",")}`)}return i?{parsed:h,error:i}:{parsed:h}},_configVault:function(e){const t=Boolean(e&&e.debug),r=!e||!("quiet"in e)||e.quiet;!t&&r||p("Loading env from encrypted .env.vault");const o=y._parseVault(e);let s=process.env;return e&&null!=e.processEnv&&(s=e.processEnv),y.populate(s,o,e),{parsed:o}},_parseVault:function(e){const t=d(e=e||{});e.path=t;const r=y.configDotenv(e);if(!r.parsed){const e=new Error(`MISSING_DATA: Cannot parse ${t} for an unknown reason`);throw e.code="MISSING_DATA",e}const o=h(e).split(","),s=o.length;let n;for(let e=0;e<s;e++)try{const t=u(r,o[e].trim());n=y.decrypt(t.ciphertext,t.key);break}catch(t){if(e+1>=s)throw t}return y.parse(n)},config:function(e){if(0===h(e).length)return y.configDotenv(e);const t=d(e);return t?y._configVault(e):(r=`You set DOTENV_KEY but you are missing a .env.vault file at ${t}. Did you forget to build it?`,console.log(`[dotenv@${i}][WARN] ${r}`),y.configDotenv(e));var r},decrypt:function(e,t){const r=Buffer.from(t.slice(-64),"hex");let o=Buffer.from(e,"base64");const s=o.subarray(0,12),n=o.subarray(-16);o=o.subarray(12,-16);try{const e=a.createDecipheriv("aes-256-gcm",r,s);return e.setAuthTag(n),`${e.update(o)}${e.final()}`}catch(e){const t=e instanceof RangeError,r="Invalid key length"===e.message,o="Unsupported state or unable to authenticate data"===e.message;if(t||r){const e=new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw e.code="INVALID_DOTENV_KEY",e}if(o){const e=new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");throw e.code="DECRYPTION_FAILED",e}throw e}},parse:function(e){const t={};let r,o=e.toString();for(o=o.replace(/\r\n?/gm,"\n");null!=(r=c.exec(o));){const e=r[1];let o=r[2]||"";o=o.trim();const s=o[0];o=o.replace(/^(['"`])([\s\S]*)\1$/gm,"$2"),'"'===s&&(o=o.replace(/\\n/g,"\n"),o=o.replace(/\\r/g,"\r")),t[e]=o}return t},populate:function(e,t,r={}){const o=Boolean(r&&r.debug),s=Boolean(r&&r.override);if("object"!=typeof t){const e=new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");throw e.code="OBJECT_REQUIRED",e}for(const r of Object.keys(t))Object.prototype.hasOwnProperty.call(e,r)?(!0===s&&(e[r]=t[r]),o&&l(!0===s?`"${r}" is already defined and WAS overwritten`:`"${r}" is already defined and was NOT overwritten`)):e[r]=t[r]}};e.exports.configDotenv=y.configDotenv,e.exports._configVault=y._configVault,e.exports._parseVault=y._parseVault,e.exports.config=y.config,e.exports.decrypt=y.decrypt,e.exports.parse=y.parse,e.exports.populate=y.populate,e.exports=y},982(e){e.exports=t("crypto")},896(e){e.exports=t("fs")},857(e){e.exports=t("os")},928(e){e.exports=t("path")},519(e){e.exports={version:"16.6.1"}}};const a={};function i(e){const t=a[e];if(void 0!==t)return t.exports;const r=a[e]={exports:{}};return n[e](r,r.exports,i),r.exports}i.n=e=>{const t=e&&e.__esModule?()=>e.default:()=>e;return i.d(t,{a:t}),t},i.d=(e,t)=>{if(Array.isArray(t))for(var r=0;r<t.length;){var o=t[r++],s=t[r++];i.o(e,o)?0===s&&r++:0===s?Object.defineProperty(e,o,{enumerable:!0,value:t[r++]}):Object.defineProperty(e,o,{enumerable:!0,get:s})}else for(var o in t)i.o(t,o)&&!i.o(e,o)&&Object.defineProperty(e,o,{enumerable:!0,get:t[o]})},i.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var c=i(583),l=i.n(c);const p=e=>{try{return e?e.toLowerCase():e}catch(e){return console.log(e),null}},h=(e,t)=>{const r=e.split("/"),o=t.split("/");if(r.length!==o.length)return!1;for(let e=0;e<r.length;e++){const t=r[e];if(t!==o[e]&&":any"!==t&&":"!==t.charAt(0))return!1}return!0},u=(e,t=null,r=2)=>{try{return JSON.stringify(e,t,r)}catch(e){return null}};class d{static match(e,t){if(!Array.isArray(t)||0===t.length)return!1;const{url:r,headers:o,queryParams:s,body:n}=e,a="undefined"!=typeof window?window.location.origin:globalThis.location?.origin||"http://localhost";for(const e of t){let t="";const{type:i,key:c,operator:l,value:p}=e;switch(i){case"URL":try{t=new URL(r,a).pathname}catch{t=r}break;case"QUERY_PARAM":if(s&&void 0!==s[c])t=String(s[c]);else try{t=new URL(r,a).searchParams.get(c)||""}catch{t=""}break;case"REQUEST_BODY":if(c){if("object"==typeof n&&null!==n)t=void 0!==n[c]?String(n[c]):"";else if("string"==typeof n)try{const e=JSON.parse(n);t=void 0!==e[c]?String(e[c]):""}catch{t=""}}else t="object"==typeof n?JSON.stringify(n):String(n||"");break;case"REQUEST_HEADER":if(c){const e=c?.toLowerCase();if(t="",o){const r=Object.keys(o).find(t=>t.toLowerCase()===e);t=r?String(o[r]):""}}else t=JSON.stringify(o||{});break;default:return!1}if(!this.evaluate(t,l,p))return!1}return!0}static evaluate(e,t,r){const o=t?.toLowerCase(),s=String(e),n=String(r);switch(o){case"contains":return s.includes(n);case"equal":case"equals":return s===n;case"regexp":try{let e=n;if(e.startsWith("/")&&e.lastIndexOf("/")>0){const t=e.lastIndexOf("/"),r=e.slice(1,t),o=e.slice(t+1);return new RegExp(r,o).test(s)}return new RegExp(e).test(s)}catch{return!1}default:return!1}}}class f{static async apply(e){if(!e||!e.activeAction)return{type:"passThrough",delay:0};const{activeAction:t,actions:r}=e,o=r?.[t];if(!o)return{type:"passThrough",delay:0};const s={type:"passThrough",delay:0},n=Number(o.value||0);switch(t){case"delay":s.delay=n,s.delay>0&&await new Promise(e=>setTimeout(e,1e3*s.delay));break;case"redirect":case"delay_and_redirect":s.type="redirect",s.delay=n,s.redirectUrl=o.redirectUrl,s.delay>0&&await new Promise(e=>setTimeout(e,1e3*s.delay));break;case"delay_and_timeout":s.type="timeout",s.delay=n,s.delay>0&&await new Promise(e=>setTimeout(e,1e3*s.delay))}return s}}class y{static applyRequestModifications(e,t){if(!t)return e;let{url:r,method:o,headers:s,queryParams:n,body:a}={...e};s&&(s={...s}),n&&(n={...n});const{modifyQueryParams:i,modifyRequestBody:c,modifyRequestHeaders:l}=t;if(i?.enabled)try{const e=new URL(r,"undefined"!=typeof window?window.location.href:"http://localhost");Array.isArray(i.remove)&&i.remove.forEach(t=>{e.searchParams.delete(t),n&&delete n[t]}),Array.isArray(i.add)&&i.add.forEach(({key:t,value:r})=>{e.searchParams.set(t,r),n&&(n[t]=r)}),r=e.toString()}catch(e){console.error("[MockForMe] Failed to modify query params",e)}l?.enabled&&(s={...s},Array.isArray(l.remove)&&l.remove.forEach(e=>{const t=e.toLowerCase(),r=Object.keys(s).find(e=>e.toLowerCase()===t);r&&delete s[r]}),Array.isArray(l.add)&&l.add.forEach(({key:e,value:t})=>{s[e]=t}));const p=String(o||"GET").toUpperCase(),h="GET"===p||"HEAD"===p;if(c?.enabled&&!h)try{let e=null;if("string"==typeof a)try{e=JSON.parse(a)}catch{e={}}else if("object"==typeof a&&null!==a)try{e=JSON.parse(JSON.stringify(a))}catch{e={...a}}else(Array.isArray(c.add)&&c.add.length>0||Array.isArray(c.update)&&c.update.length>0)&&(e={});e&&(Array.isArray(c.remove)&&c.remove.forEach(t=>delete e[t]),Array.isArray(c.add)&&c.add.forEach(({key:t,value:r})=>e[t]=r),Array.isArray(c.update)&&c.update.forEach(({key:t,value:r})=>e[t]=r),a=JSON.stringify(e))}catch(e){console.error("[MockForMe] Failed to modify request body",e)}return{...e,url:r,headers:s,queryParams:n,body:a}}static applyResponseModifications(e,t){if(!t?.modifyResponseHeaders?.enabled)return e;const{modifyResponseHeaders:r}=t,o={...e};return Array.isArray(r.remove)&&r.remove.forEach(e=>{const t=e.toLowerCase(),r=Object.keys(o).find(e=>e.toLowerCase()===t);r&&delete o[r]}),Array.isArray(r.add)&&r.add.forEach(({key:e,value:t})=>{o[e]=t}),o}}class m{static match(e,t){if(!Array.isArray(t)||0===t.length)return null;for(const r of t){const t=r.rule||r;if(t.conditions&&Array.isArray(t.conditions)&&d.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 r=e.rule||e,o=y.applyRequestModifications(t,r.modificationActions);return{...await f.apply(r.timingAction),modifiedRequest:o,rule:r}}static applyResponseModifications(e,t){return y.applyResponseModifications(e,t)}}l().config({path:"../../.env"});const g="https://api.mockforme.com",E=`${g}/mockforme`,v="mfmver",w="4.2.7";let A=`${g}/gateway/3f4eae522b`,b=null;class _{constructor(e){this.token=e,this.apiMappings=[],this.rules=[],this.isReady=!1,this.originalHttpRequest=r.request,this.originalHttpGet=r.get,this.originalHttpsRequest=o.request,this.originalHttpsGet=o.get,this.originalFetch=globalThis.fetch,this.fetchApiMappings(),this.setupInterceptor()}checkIsErrorInFetchMappings(e){try{const t=JSON.parse(e);if(0==t?.status)throw new Error(t?.message||"Failed to fetch mockforme mappings")}catch(e){throw new Error(e.message||"Failed to fetch mockforme mappings")}}fetchApiMappings(){this.apiMappings=[],this.rules=[],this.isReady=!1;try{const e=`curl -s -H "mockforme: ${this.token}" "${A}"`,t=s(e,{encoding:"utf8"});if(t&&this.checkIsErrorInFetchMappings(t),!t)throw new Error("Failed to fetch mockforme mappings: No response");{const{di:e,iv:r,_o:o,_mck:s,mk:n,r:a}=JSON.parse(t);this.organisationId=o,this.memberKey=n,this.memberCacheKey=s;const i=function({di:e,iv:t},r){var o;const s=function(e,t){const r=t.length;return e.split("").map((e,o)=>String.fromCharCode(e.charCodeAt(0)^t.charCodeAt(o%r))).join("")}((o=e,"undefined"!=typeof Buffer?Buffer.from(o,"base64").toString("utf8"):decodeURIComponent(escape(atob(o)))),r+t);return JSON.parse(s)}({di:e,iv:r},o);i&&(this.apiMappings=i),a&&(this.rules=a)}this.isReady=!0}catch(e){console.error("[mockforme] Failed to fetch mappings:",e.message)}}getProxyUrl(){return`${E}/${this.organisationId}/${this.memberKey}`}checkRules(e){return m.match(e,this.rules)}async applyRuleBehavior(e,t){return await m.apply(e,t)}interceptFetch(e,t){const r=(t.method||"GET").toUpperCase(),o=this.apiMappings.find(t=>{const o=p(t.apiMethod)===p(r),s=t.apiEndpoint===e.pathname||h(t.apiEndpoint,e.pathname);return o&&s});if(o){console.log("[mockforme] [api intercepted]: ",o);const r={mockforme:this.token,[v]:w},s=o?._ack||null;this.memberCacheKey&&s&&(r["x-mfm-key"]=`${this.memberCacheKey}-${s}`);let n=`${this.getProxyUrl()}${e.pathname}`;return e.search&&(n+=e.search),{url:n,init:{...t,headers:{...t.headers,...r}}}}return{url:e.href,init:t}}setupInterceptor(){const e=this;globalThis.fetch=async function(t,r={}){if(!e.isReady)return e.originalFetch(t,r);const o=t instanceof Request?new URL(t.url):new URL(t,"http://localhost"),s={url:o.href,method:(r.method||"GET").toUpperCase(),headers:r.headers||{},queryParams:Object.fromEntries(o.searchParams.entries())},n=e.checkRules(s);if(n){console.log("[mockforme] [fetch] [rule matched]: ",u(n));try{const t=await e.applyRuleBehavior(n,s),{modifiedRequest:o,type:a,redirectUrl:i}=t;return"redirect"===a?e.originalFetch(i,{...r,method:o.method,headers:o.headers,body:o.body}):e.originalFetch(o.url,{...r,method:o.method,headers:o.headers,body:o.body})}catch(e){throw e}}const{url:a,init:i}=e.interceptFetch(o,r);try{const t=await e.originalFetch(a,i);if(!t.ok)throw new Error(`[mockforme] Proxy fetch failed: ${t.status} ${t.statusText}`);return t}catch(e){throw e}};const t=(t,r)=>async function(...o){let s=o[0];if("string"==typeof s&&(s=new URL(s)),!e.isReady)return t.apply(null,[s,...o.slice(1)]);const n={url:s.href||s.url||`http://${s.hostname}${s.path}`,method:(s.method||"GET").toUpperCase(),headers:s.headers||{}},a=e.checkRules(n);if(a){console.log(`[mockforme] [${r}] [rule matched]: `,u(a));try{const r=await e.applyRuleBehavior(a,n),{modifiedRequest:i,type:c,redirectUrl:l}=r;if("passThrough"===c){const e={...s};try{const t=new URL(i.url);e.hostname=t.hostname,e.path=t.pathname+t.search,e.port=t.port,e.protocol=t.protocol}catch(e){}return i.headers&&(e.headers=i.headers),i.method&&(e.method=i.method),t.apply(null,[e,...o.slice(1)])}}catch(e){throw e}}const i=e.interceptRequest(s);try{return t.apply(null,[i,...o.slice(1)])}catch(e){throw e}};r.request=t(this.originalHttpRequest,"http.request"),o.request=t(this.originalHttpsRequest,"https.request"),r.get=t(this.originalHttpGet,"http.get"),o.get=t(this.originalHttpsGet,"https.get")}interceptRequest(e){const t=this.apiMappings.find(t=>{if(p(t.apiMethod)===p(e.method))return t.apiEndpoint===e.path||h(t.apiEndpoint,e.path)});if(t){console.log("[mockforme] [matched request]: ",t,e);const r={mockforme:this.token,[v]:w},o=t?._ack||null;this.memberCacheKey&&o&&(r["x-mfm-key"]=`${this.memberCacheKey}-${o}`);let s=`${this.getProxyUrl()}${e.path}`;e.search&&(s+=e.search);const n=new URL(s);return{...e,hostname:n.hostname,path:n.pathname,headers:{...e.headers,...r}}}return e}run(e){e&&e(this.apiMappings,{_rules:this.rules})}}function R(e){return b?(b.token=e,b.fetchApiMappings()):b=new _(e),b}export{R as mockforme};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "mockforme",
|
|
3
|
-
"version": "14.5.
|
|
3
|
+
"version": "14.5.1",
|
|
4
4
|
"description": "MockForMe is a fast and simple mock API solution for CSR and SSR apps. Create mock APIs in 2 minutes with support for delays, conditional responses, public URLs, random data, variables, Faker, and postFunctions — all designed to boost developer productivity.",
|
|
5
5
|
"main": "dist/mockforme.client.cjs.js",
|
|
6
6
|
"module": "dist/mockforme.client.esm.js",
|