mockforme 8.2.0 → 10.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/mockforme.client.cjs.js +2 -1
- package/dist/mockforme.client.cjs.js.LICENSE.txt +20 -0
- package/dist/mockforme.client.esm.js +2 -1
- package/dist/mockforme.client.esm.js.LICENSE.txt +20 -0
- package/dist/mockforme.client.umd.js +2 -1
- package/dist/mockforme.client.umd.js.LICENSE.txt +20 -0
- package/dist/mockforme.server.cjs.js +1 -1
- package/dist/mockforme.server.esm.js +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/*!
|
|
2
|
+
* html2canvas 1.4.1 <https://html2canvas.hertzen.com>
|
|
3
|
+
* Copyright (c) 2022 Niklas von Hertzen <https://hertzen.com>
|
|
4
|
+
* Released under MIT License
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
/*! *****************************************************************************
|
|
8
|
+
Copyright (c) Microsoft Corporation.
|
|
9
|
+
|
|
10
|
+
Permission to use, copy, modify, and/or distribute this software for any
|
|
11
|
+
purpose with or without fee is hereby granted.
|
|
12
|
+
|
|
13
|
+
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
|
|
14
|
+
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
|
|
15
|
+
AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
|
|
16
|
+
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
|
|
17
|
+
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
|
|
18
|
+
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
|
|
19
|
+
PERFORMANCE OF THIS SOFTWARE.
|
|
20
|
+
***************************************************************************** */
|
|
@@ -1 +1 @@
|
|
|
1
|
-
(()=>{var e={56:e=>{"use strict";e.exports=JSON.parse('{"name":"dotenv","version":"16.5.0","description":"Loads environment variables from .env file","main":"lib/main.js","types":"lib/main.d.ts","exports":{".":{"types":"./lib/main.d.ts","require":"./lib/main.js","default":"./lib/main.js"},"./config":"./config.js","./config.js":"./config.js","./lib/env-options":"./lib/env-options.js","./lib/env-options.js":"./lib/env-options.js","./lib/cli-options":"./lib/cli-options.js","./lib/cli-options.js":"./lib/cli-options.js","./package.json":"./package.json"},"scripts":{"dts-check":"tsc --project tests/types/tsconfig.json","lint":"standard","pretest":"npm run lint && npm run dts-check","test":"tap run --allow-empty-coverage --disable-coverage --timeout=60000","test:coverage":"tap run --show-full-coverage --timeout=60000 --coverage-report=lcov","prerelease":"npm test","release":"standard-version"},"repository":{"type":"git","url":"git://github.com/motdotla/dotenv.git"},"homepage":"https://github.com/motdotla/dotenv#readme","funding":"https://dotenvx.com","keywords":["dotenv","env",".env","environment","variables","config","settings"],"readmeFilename":"README.md","license":"BSD-2-Clause","devDependencies":{"@types/node":"^18.11.3","decache":"^4.6.2","sinon":"^14.0.1","standard":"^17.0.0","standard-version":"^9.5.0","tap":"^19.2.0","typescript":"^4.8.4"},"engines":{"node":">=12"},"browser":{"fs":false}}')},857:e=>{"use strict";e.exports=require("os")},896:e=>{"use strict";e.exports=require("fs")},928:e=>{"use strict";e.exports=require("path")},982:e=>{"use strict";e.exports=require("crypto")},998:(e,t,r)=>{const o=r(896),s=r(928),n=r(857),a=r(982),i=r(56).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){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 h(e){return"~"===e[0]?s.join(n.homedir(),e.slice(1)):e}const f={configDotenv:function(e){const t=s.resolve(process.cwd(),".env");let r="utf8";const n=Boolean(e&&e.debug);e&&e.encoding?r=e.encoding:n&&l("No encoding is specified. UTF-8 is used by default");let a,i=[t];if(e&&e.path)if(Array.isArray(e.path)){i=[];for(const t of e.path)i.push(h(t))}else i=[h(e.path)];const c={};for(const t of i)try{const s=f.parse(o.readFileSync(t,{encoding:r}));f.populate(c,s,e)}catch(e){n&&l(`Failed to load ${t} ${e.message}`),a=e}let p=process.env;return e&&null!=e.processEnv&&(p=e.processEnv),f.populate(p,c,e),a?{parsed:c,error:a}:{parsed:c}},_configVault:function(e){Boolean(e&&e.debug)&&l("Loading env from encrypted .env.vault");const t=f._parseVault(e);let r=process.env;return e&&null!=e.processEnv&&(r=e.processEnv),f.populate(r,t,e),{parsed:t}},_parseVault:function(e){const t=d(e),r=f.configDotenv({path:t});if(!r.parsed){const e=new Error(`MISSING_DATA: Cannot parse ${t} for an unknown reason`);throw e.code="MISSING_DATA",e}const o=p(e).split(","),s=o.length;let n;for(let e=0;e<s;e++)try{const t=u(r,o[e].trim());n=f.decrypt(t.ciphertext,t.key);break}catch(t){if(e+1>=s)throw t}return f.parse(n)},config:function(e){if(0===p(e).length)return f.configDotenv(e);const t=d(e);return t?f._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}`),f.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=f.configDotenv,e.exports._configVault=f._configVault,e.exports._parseVault=f._parseVault,e.exports.config=f.config,e.exports.decrypt=f.decrypt,e.exports.parse=f.parse,e.exports.populate=f.populate,e.exports=f}},t={};function r(o){var s=t[o];if(void 0!==s)return s.exports;var n=t[o]={exports:{}};return e[o](n,n.exports,r),n.exports}r.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return r.d(t,{a:t}),t},r.d=(e,t)=>{for(var o in t)r.o(t,o)&&!r.o(e,o)&&Object.defineProperty(e,o,{enumerable:!0,get:t[o]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var 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(998),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)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 h{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)&&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=f.applyRequestModifications(t,r.modificationActions);return{...await h.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`,v="mfmver",E="8.2.0";let w=`${m}/gateway/3f4eae522b`,b=null;class A{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,[v]:E},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,[v]:E},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 b?(b.token=e,b.fetchApiMappings()):b=new A(e),b}})(),module.exports=o})();
|
|
1
|
+
(()=>{var e={56:e=>{"use strict";e.exports=JSON.parse('{"name":"dotenv","version":"16.5.0","description":"Loads environment variables from .env file","main":"lib/main.js","types":"lib/main.d.ts","exports":{".":{"types":"./lib/main.d.ts","require":"./lib/main.js","default":"./lib/main.js"},"./config":"./config.js","./config.js":"./config.js","./lib/env-options":"./lib/env-options.js","./lib/env-options.js":"./lib/env-options.js","./lib/cli-options":"./lib/cli-options.js","./lib/cli-options.js":"./lib/cli-options.js","./package.json":"./package.json"},"scripts":{"dts-check":"tsc --project tests/types/tsconfig.json","lint":"standard","pretest":"npm run lint && npm run dts-check","test":"tap run --allow-empty-coverage --disable-coverage --timeout=60000","test:coverage":"tap run --show-full-coverage --timeout=60000 --coverage-report=lcov","prerelease":"npm test","release":"standard-version"},"repository":{"type":"git","url":"git://github.com/motdotla/dotenv.git"},"homepage":"https://github.com/motdotla/dotenv#readme","funding":"https://dotenvx.com","keywords":["dotenv","env",".env","environment","variables","config","settings"],"readmeFilename":"README.md","license":"BSD-2-Clause","devDependencies":{"@types/node":"^18.11.3","decache":"^4.6.2","sinon":"^14.0.1","standard":"^17.0.0","standard-version":"^9.5.0","tap":"^19.2.0","typescript":"^4.8.4"},"engines":{"node":">=12"},"browser":{"fs":false}}')},857:e=>{"use strict";e.exports=require("os")},896:e=>{"use strict";e.exports=require("fs")},928:e=>{"use strict";e.exports=require("path")},982:e=>{"use strict";e.exports=require("crypto")},998:(e,t,r)=>{const o=r(896),s=r(928),n=r(857),a=r(982),i=r(56).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){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 h(e){return"~"===e[0]?s.join(n.homedir(),e.slice(1)):e}const f={configDotenv:function(e){const t=s.resolve(process.cwd(),".env");let r="utf8";const n=Boolean(e&&e.debug);e&&e.encoding?r=e.encoding:n&&l("No encoding is specified. UTF-8 is used by default");let a,i=[t];if(e&&e.path)if(Array.isArray(e.path)){i=[];for(const t of e.path)i.push(h(t))}else i=[h(e.path)];const c={};for(const t of i)try{const s=f.parse(o.readFileSync(t,{encoding:r}));f.populate(c,s,e)}catch(e){n&&l(`Failed to load ${t} ${e.message}`),a=e}let p=process.env;return e&&null!=e.processEnv&&(p=e.processEnv),f.populate(p,c,e),a?{parsed:c,error:a}:{parsed:c}},_configVault:function(e){Boolean(e&&e.debug)&&l("Loading env from encrypted .env.vault");const t=f._parseVault(e);let r=process.env;return e&&null!=e.processEnv&&(r=e.processEnv),f.populate(r,t,e),{parsed:t}},_parseVault:function(e){const t=d(e),r=f.configDotenv({path:t});if(!r.parsed){const e=new Error(`MISSING_DATA: Cannot parse ${t} for an unknown reason`);throw e.code="MISSING_DATA",e}const o=p(e).split(","),s=o.length;let n;for(let e=0;e<s;e++)try{const t=u(r,o[e].trim());n=f.decrypt(t.ciphertext,t.key);break}catch(t){if(e+1>=s)throw t}return f.parse(n)},config:function(e){if(0===p(e).length)return f.configDotenv(e);const t=d(e);return t?f._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}`),f.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=f.configDotenv,e.exports._configVault=f._configVault,e.exports._parseVault=f._parseVault,e.exports.config=f.config,e.exports.decrypt=f.decrypt,e.exports.parse=f.parse,e.exports.populate=f.populate,e.exports=f}},t={};function r(o){var s=t[o];if(void 0!==s)return s.exports;var n=t[o]={exports:{}};return e[o](n,n.exports,r),n.exports}r.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return r.d(t,{a:t}),t},r.d=(e,t)=>{for(var o in t)r.o(t,o)&&!r.o(e,o)&&Object.defineProperty(e,o,{enumerable:!0,get:t[o]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var 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(998),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)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 h{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)&&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=f.applyRequestModifications(t,r.modificationActions);return{...await h.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`,v="mfmver",E="9.0.0";let w=`${m}/gateway/3f4eae522b`,b=null;class A{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,[v]:E},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,[v]:E},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 b?(b.token=e,b.fetchApiMappings()):b=new A(e),b}})(),module.exports=o})();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{createRequire as e}from"node:module";var t={56:e=>{e.exports=JSON.parse('{"name":"dotenv","version":"16.5.0","description":"Loads environment variables from .env file","main":"lib/main.js","types":"lib/main.d.ts","exports":{".":{"types":"./lib/main.d.ts","require":"./lib/main.js","default":"./lib/main.js"},"./config":"./config.js","./config.js":"./config.js","./lib/env-options":"./lib/env-options.js","./lib/env-options.js":"./lib/env-options.js","./lib/cli-options":"./lib/cli-options.js","./lib/cli-options.js":"./lib/cli-options.js","./package.json":"./package.json"},"scripts":{"dts-check":"tsc --project tests/types/tsconfig.json","lint":"standard","pretest":"npm run lint && npm run dts-check","test":"tap run --allow-empty-coverage --disable-coverage --timeout=60000","test:coverage":"tap run --show-full-coverage --timeout=60000 --coverage-report=lcov","prerelease":"npm test","release":"standard-version"},"repository":{"type":"git","url":"git://github.com/motdotla/dotenv.git"},"homepage":"https://github.com/motdotla/dotenv#readme","funding":"https://dotenvx.com","keywords":["dotenv","env",".env","environment","variables","config","settings"],"readmeFilename":"README.md","license":"BSD-2-Clause","devDependencies":{"@types/node":"^18.11.3","decache":"^4.6.2","sinon":"^14.0.1","standard":"^17.0.0","standard-version":"^9.5.0","tap":"^19.2.0","typescript":"^4.8.4"},"engines":{"node":">=12"},"browser":{"fs":false}}')},857:t=>{t.exports=e(import.meta.url)("os")},896:t=>{t.exports=e(import.meta.url)("fs")},928:t=>{t.exports=e(import.meta.url)("path")},982:t=>{t.exports=e(import.meta.url)("crypto")},998:(e,t,r)=>{const o=r(896),s=r(928),n=r(857),a=r(982),i=r(56).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){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 d(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 h(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 u(e){return"~"===e[0]?s.join(n.homedir(),e.slice(1)):e}const f={configDotenv:function(e){const t=s.resolve(process.cwd(),".env");let r="utf8";const n=Boolean(e&&e.debug);e&&e.encoding?r=e.encoding:n&&l("No encoding is specified. UTF-8 is used by default");let a,i=[t];if(e&&e.path)if(Array.isArray(e.path)){i=[];for(const t of e.path)i.push(u(t))}else i=[u(e.path)];const c={};for(const t of i)try{const s=f.parse(o.readFileSync(t,{encoding:r}));f.populate(c,s,e)}catch(e){n&&l(`Failed to load ${t} ${e.message}`),a=e}let p=process.env;return e&&null!=e.processEnv&&(p=e.processEnv),f.populate(p,c,e),a?{parsed:c,error:a}:{parsed:c}},_configVault:function(e){Boolean(e&&e.debug)&&l("Loading env from encrypted .env.vault");const t=f._parseVault(e);let r=process.env;return e&&null!=e.processEnv&&(r=e.processEnv),f.populate(r,t,e),{parsed:t}},_parseVault:function(e){const t=h(e),r=f.configDotenv({path:t});if(!r.parsed){const e=new Error(`MISSING_DATA: Cannot parse ${t} for an unknown reason`);throw e.code="MISSING_DATA",e}const o=p(e).split(","),s=o.length;let n;for(let e=0;e<s;e++)try{const t=d(r,o[e].trim());n=f.decrypt(t.ciphertext,t.key);break}catch(t){if(e+1>=s)throw t}return f.parse(n)},config:function(e){if(0===p(e).length)return f.configDotenv(e);const t=h(e);return t?f._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}`),f.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=f.configDotenv,e.exports._configVault=f._configVault,e.exports._parseVault=f._parseVault,e.exports.config=f.config,e.exports.decrypt=f.decrypt,e.exports.parse=f.parse,e.exports.populate=f.populate,e.exports=f}},r={};function o(e){var s=r[e];if(void 0!==s)return s.exports;var n=r[e]={exports:{}};return t[e](n,n.exports,o),n.exports}o.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return o.d(t,{a:t}),t},o.d=(e,t)=>{for(var r in t)o.o(t,r)&&!o.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},o.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);const s=e(import.meta.url)("http");var n=o.n(s);const a=e(import.meta.url)("https");var i=o.n(a);const c=e(import.meta.url)("child_process");var l=o(998),p=o.n(l);const d=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)return!1}return!0},u=(e,t=null,r=2)=>{try{return JSON.stringify(e,t,r)}catch(e){return null}};class f{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 m{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(),d="GET"===p||"HEAD"===p;if(c?.enabled&&!d)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 g{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)&&f.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 m.apply(r.timingAction),modifiedRequest:o,rule:r}}static applyResponseModifications(e,t){return y.applyResponseModifications(e,t)}}p().config("../../.env");const v="https://api.mockforme.com",E=`${v}/mockforme`,w="mfmver",b="8.2.0";let A=`${v}/gateway/3f4eae522b`,k=null;class _{constructor(e){this.token=e,this.apiMappings=[],this.rules=[],this.isReady=!1,this.originalHttpRequest=n().request,this.originalHttpGet=n().get,this.originalHttpsRequest=i().request,this.originalHttpsGet=i().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=(0,c.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`${E}/${this.organisationId}/${this.memberKey}`}checkRules(e){return g.match(e,this.rules)}async applyRuleBehavior(e,t){return await g.apply(e,t)}interceptFetch(e,t){const r=(t.method||"GET").toUpperCase(),o=this.apiMappings.find((t=>{const o=d(t.apiMethod)===d(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,[w]:b},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}};n().request=t(this.originalHttpRequest,"http.request"),i().request=t(this.originalHttpsRequest,"https.request"),n().get=t(this.originalHttpGet,"http.get"),i().get=t(this.originalHttpsGet,"https.get")}interceptRequest(e){const t=this.apiMappings.find((t=>{if(d(t.apiMethod)===d(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,[w]:b},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 k?(k.token=e,k.fetchApiMappings()):k=new _(e),k}export{R as mockforme};
|
|
1
|
+
import{createRequire as e}from"node:module";var t={56:e=>{e.exports=JSON.parse('{"name":"dotenv","version":"16.5.0","description":"Loads environment variables from .env file","main":"lib/main.js","types":"lib/main.d.ts","exports":{".":{"types":"./lib/main.d.ts","require":"./lib/main.js","default":"./lib/main.js"},"./config":"./config.js","./config.js":"./config.js","./lib/env-options":"./lib/env-options.js","./lib/env-options.js":"./lib/env-options.js","./lib/cli-options":"./lib/cli-options.js","./lib/cli-options.js":"./lib/cli-options.js","./package.json":"./package.json"},"scripts":{"dts-check":"tsc --project tests/types/tsconfig.json","lint":"standard","pretest":"npm run lint && npm run dts-check","test":"tap run --allow-empty-coverage --disable-coverage --timeout=60000","test:coverage":"tap run --show-full-coverage --timeout=60000 --coverage-report=lcov","prerelease":"npm test","release":"standard-version"},"repository":{"type":"git","url":"git://github.com/motdotla/dotenv.git"},"homepage":"https://github.com/motdotla/dotenv#readme","funding":"https://dotenvx.com","keywords":["dotenv","env",".env","environment","variables","config","settings"],"readmeFilename":"README.md","license":"BSD-2-Clause","devDependencies":{"@types/node":"^18.11.3","decache":"^4.6.2","sinon":"^14.0.1","standard":"^17.0.0","standard-version":"^9.5.0","tap":"^19.2.0","typescript":"^4.8.4"},"engines":{"node":">=12"},"browser":{"fs":false}}')},857:t=>{t.exports=e(import.meta.url)("os")},896:t=>{t.exports=e(import.meta.url)("fs")},928:t=>{t.exports=e(import.meta.url)("path")},982:t=>{t.exports=e(import.meta.url)("crypto")},998:(e,t,r)=>{const o=r(896),s=r(928),n=r(857),a=r(982),i=r(56).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){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 d(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 h(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 u(e){return"~"===e[0]?s.join(n.homedir(),e.slice(1)):e}const f={configDotenv:function(e){const t=s.resolve(process.cwd(),".env");let r="utf8";const n=Boolean(e&&e.debug);e&&e.encoding?r=e.encoding:n&&l("No encoding is specified. UTF-8 is used by default");let a,i=[t];if(e&&e.path)if(Array.isArray(e.path)){i=[];for(const t of e.path)i.push(u(t))}else i=[u(e.path)];const c={};for(const t of i)try{const s=f.parse(o.readFileSync(t,{encoding:r}));f.populate(c,s,e)}catch(e){n&&l(`Failed to load ${t} ${e.message}`),a=e}let p=process.env;return e&&null!=e.processEnv&&(p=e.processEnv),f.populate(p,c,e),a?{parsed:c,error:a}:{parsed:c}},_configVault:function(e){Boolean(e&&e.debug)&&l("Loading env from encrypted .env.vault");const t=f._parseVault(e);let r=process.env;return e&&null!=e.processEnv&&(r=e.processEnv),f.populate(r,t,e),{parsed:t}},_parseVault:function(e){const t=h(e),r=f.configDotenv({path:t});if(!r.parsed){const e=new Error(`MISSING_DATA: Cannot parse ${t} for an unknown reason`);throw e.code="MISSING_DATA",e}const o=p(e).split(","),s=o.length;let n;for(let e=0;e<s;e++)try{const t=d(r,o[e].trim());n=f.decrypt(t.ciphertext,t.key);break}catch(t){if(e+1>=s)throw t}return f.parse(n)},config:function(e){if(0===p(e).length)return f.configDotenv(e);const t=h(e);return t?f._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}`),f.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=f.configDotenv,e.exports._configVault=f._configVault,e.exports._parseVault=f._parseVault,e.exports.config=f.config,e.exports.decrypt=f.decrypt,e.exports.parse=f.parse,e.exports.populate=f.populate,e.exports=f}},r={};function o(e){var s=r[e];if(void 0!==s)return s.exports;var n=r[e]={exports:{}};return t[e](n,n.exports,o),n.exports}o.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return o.d(t,{a:t}),t},o.d=(e,t)=>{for(var r in t)o.o(t,r)&&!o.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},o.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);const s=e(import.meta.url)("http");var n=o.n(s);const a=e(import.meta.url)("https");var i=o.n(a);const c=e(import.meta.url)("child_process");var l=o(998),p=o.n(l);const d=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)return!1}return!0},u=(e,t=null,r=2)=>{try{return JSON.stringify(e,t,r)}catch(e){return null}};class f{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 m{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(),d="GET"===p||"HEAD"===p;if(c?.enabled&&!d)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 g{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)&&f.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 m.apply(r.timingAction),modifiedRequest:o,rule:r}}static applyResponseModifications(e,t){return y.applyResponseModifications(e,t)}}p().config("../../.env");const v="https://api.mockforme.com",E=`${v}/mockforme`,w="mfmver",b="9.0.0";let A=`${v}/gateway/3f4eae522b`,k=null;class _{constructor(e){this.token=e,this.apiMappings=[],this.rules=[],this.isReady=!1,this.originalHttpRequest=n().request,this.originalHttpGet=n().get,this.originalHttpsRequest=i().request,this.originalHttpsGet=i().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=(0,c.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`${E}/${this.organisationId}/${this.memberKey}`}checkRules(e){return g.match(e,this.rules)}async applyRuleBehavior(e,t){return await g.apply(e,t)}interceptFetch(e,t){const r=(t.method||"GET").toUpperCase(),o=this.apiMappings.find((t=>{const o=d(t.apiMethod)===d(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,[w]:b},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}};n().request=t(this.originalHttpRequest,"http.request"),i().request=t(this.originalHttpsRequest,"https.request"),n().get=t(this.originalHttpGet,"http.get"),i().get=t(this.originalHttpsGet,"https.get")}interceptRequest(e){const t=this.apiMappings.find((t=>{if(d(t.apiMethod)===d(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,[w]:b},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 k?(k.token=e,k.fetchApiMappings()):k=new _(e),k}export{R as mockforme};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "mockforme",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "10.0.0",
|
|
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",
|