local-traffic 0.0.84 → 0.0.86

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
@@ -5,7 +5,7 @@ That is a secure http/2 (or insecure http1.1) reverse-proxy installed on your ma
5
5
  - with 0 transitive dependency
6
6
  - with 1 install step
7
7
  - with a startup time of a few milliseconds
8
- - with one 46kb index.js file
8
+ - with one 58kb index.js file
9
9
 
10
10
  How simple is that ?
11
11
 
@@ -49,7 +49,7 @@ npx local-traffic
49
49
  4. Go to [http://localhost:8080/my-static-webapp/index.html](http://localhost:8080/my-static-webapp/index.html) with your browser (given your project name is my-static-webapp, but I am not 100% sure)
50
50
  5. Go to [http://localhost:8080/logs/](http://localhost:8080/logs/) to watch the request logs
51
51
  6. Go to [http://localhost:8080/config/](http://localhost:8080/config/) to change the config in a web editor
52
- 7. You can use the [http://localhost:8080/recorder/](recorder) to turn your proxy into a mock server.
52
+ 7. You can use the [http://localhost:8080/recorder/](recorder) to turn your proxy into a mock server. There is a user interface and also an API (documented [here](#recorder-api))
53
53
  8. From the web config editor, create a SSL keypair and start working with a self signed SSL certificate right away
54
54
  9. Your page will use /jquery-local/jquery.js instead of the CDN asset, and will serve the file from your hard drive
55
55
  10. Your server now proxies the mapping that you have configured
@@ -90,7 +90,47 @@ All boolean settings default to false when unspecified.
90
90
  - `dontTranslateLocationHeader`: (`boolean`) when getting a response location header, in case `replaceResponseBodyUrls` does not change the URL, change the origin to the proxy anyway
91
91
  - `dontUseHttp2Downstream`: (`boolean`) force calling downstream services in http1.1 only (to save some time)
92
92
  - `simpleLogs`: (`boolean`) disable colored logs for text terminals
93
+ - `logAccessInTerminal`: (`boolean`) write an access log in the terminal on each call (defaults to false)
93
94
  - `websocket`: (`boolean`) true to activate websocket connections proxying via sockets. Required for logs UI.
94
95
  - `disableWebSecurity`: (`boolean`) true for easygoing values in cross origin requests or content security policy headers
95
96
  - `connectTimeout`: (`number`) max time before aborting the connection (defaults to 3000ms)
96
97
  - `socketTimeout`: (`number`) max time waiting for a response (defaults to 3000ms)
98
+
99
+ ## recorder API
100
+
101
+ (>= 0.0.86)
102
+ The recorder can be used programmatically with an API.
103
+ This can be used if someone needs to automatically record mocks during instance provisioning
104
+ (when the machine boots up using a cloud provider for example)
105
+
106
+ The API always matches the route targetting `recorder://`.
107
+
108
+ ### post, put
109
+
110
+ Arguments :
111
+ | parameter | Type | Description | Defaults|
112
+ | ------------- | ------------------------ | ---------------------------- | --------|
113
+ | mode | "proxy" or "mock" | server mode | "proxy" |
114
+ | strict | boolean | errors when no mock is found | false |
115
+ | autoRecord | boolean | adds mocks from server | false |
116
+ | mocks | {uniqueHash,response}[] | mocks definition | [] |
117
+
118
+ The recorder webapp can take care of the mocks by itself,
119
+ so `autoRecord` is only necessary when using local-traffic headless or without human
120
+ intervention
121
+
122
+ ### delete
123
+
124
+ The mock config will be reset to empty :
125
+ - `autoRecord` will be set to false
126
+ - `mocks` will be purged
127
+
128
+ ### get
129
+
130
+ Retrieves the current mock configuration.
131
+ use `Content-Type: application/json` to use the API mode.
132
+
133
+ ```bash
134
+ $ curl https://localhost:8443/recorder/ -XGET -k -H'Content-Type: application/json'
135
+ {"mocks":[],"strict":false,"autoRecord":false}
136
+ ```
@@ -1,2 +1,2 @@
1
1
  #!/usr/bin/env node
2
- "use strict";var e,t=this&&this.__awaiter||function(e,t,n,o){return new(n||(n=Promise))((function(s,r){function i(e){try{l(o.next(e))}catch(e){r(e)}}function a(e){try{l(o.throw(e))}catch(e){r(e)}}function l(e){var t;e.done?s(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}l((o=o.apply(e,t||[])).next())}))},n=this&&this.__rest||function(e,t){var n={};for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(n[o]=e[o]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var s=0;for(o=Object.getOwnPropertySymbols(e);s<o.length;s++)t.indexOf(o[s])<0&&Object.prototype.propertyIsEnumerable.call(e,o[s])&&(n[o[s]]=e[o[s]])}return n};Object.defineProperty(exports,"__esModule",{value:!0}),exports.update=exports.serve=exports.determineMapping=exports.send=exports.cleanEntropy=exports.replaceTextUsingMapping=exports.replaceBody=exports.acknowledgeWebsocket=exports.readWebsocketBuffer=exports.createWebsocketBufferFrom=exports.websocketServe=exports.quickStatus=exports.errorListener=exports.load=exports.start=void 0;const o=require("http2"),s=require("http"),r=require("https"),i=require("url"),a=require("fs"),l=require("zlib"),d=require("path"),c=require("crypto"),u=require("process"),p=require("os");var m,g,h,f;!function(e){e[e.ERROR=124]="ERROR",e[e.INFO=93]="INFO",e[e.WARNING=172]="WARNING"}(m||(m={})),function(e){e.INBOUND="↘️ ",e.PORT="☎️ ",e.OUTBOUND="↗️ ",e.RULES="🔗",e.MOCKS="🌐",e.REWRITE="✒️ ",e.RESTART="🔄",e.WEBSOCKET="☄️ ",e.COLORED="✨",e.SHIELD="🛡️ ",e.NO="⛔",e.ERROR_1="❌",e.ERROR_2="⛈️ ",e.ERROR_3="☢️ ",e.ERROR_4="⁉️ ",e.ERROR_5="⚡",e.ERROR_6="☠️ "}(g||(g={})),function(e){e.INBOUND="INBOUND",e.OUTBOUND="OUTBOUND"}(h||(h={})),function(e){e.PROXY="proxy",e.MOCK="mock"}(f||(f={}));const b=(0,d.resolve)((0,p.homedir)(),".local-traffic.json"),y=(0,d.resolve)((0,u.cwd)(),u.argv.slice(-1)[0].endsWith(".json")?u.argv.slice(-1)[0]:b),v=()=>{var e,t;return null!==(t=null===(e=u.hrtime.bigint)||void 0===e?void 0:e.call(u.hrtime))&&void 0!==t?t:(()=>{const e=(0,u.hrtime)();return 1e3*e[0]+e[1]/1e6})()},O=e=>e===m.ERROR?"error":e===m.WARNING?"warning":"info",w=function(e,t,n,o){var s,r,i,a,l;const d=(null===(s=null==e?void 0:e.config)||void 0===s?void 0:s.simpleLogs)||(null===(r=null==e?void 0:e.logsListeners)||void 0===r?void 0:r.length)?t.replace(/⎸/g,"|").replace(/⎹/g,"|").replace(/\u001b\[[^m]*m/g,"").replace(new RegExp(g.INBOUND,"g"),"inbound:").replace(new RegExp(g.PORT,"g"),"port:").replace(new RegExp(g.OUTBOUND,"g"),"outbound:").replace(new RegExp(g.RULES,"g"),"rules:").replace(new RegExp(g.NO,"g"),"").replace(new RegExp(g.REWRITE,"g"),"+rewrite").replace(new RegExp(g.WEBSOCKET,"g"),"websocket").replace(new RegExp(g.SHIELD,"g"),"web-security").replace(/\|+/g,"|"):t;console.log(`${(e=>{const t=new Date;return`${e?"":""}${`${t.getHours()}`.padStart(2,"0")}${e?":":":"}${`${t.getMinutes()}`.padStart(2,"0")}${e?":":":"}${`${t.getSeconds()}`.padStart(2,"0")}${e?"":""}`})(null===(i=null==e?void 0:e.config)||void 0===i?void 0:i.simpleLogs)} ${(null===(a=null==e?void 0:e.config)||void 0===a?void 0:a.simpleLogs)?d:n?`[48;5;${n}m⎸ ${u.stdout.isTTY&&o||""} ${t.padEnd(40)} ⎹`:t}`),null===(l=null==e?void 0:e.notifyLogsListeners)||void 0===l||l.call(e,{event:d,level:O(n)})},R=(e,t)=>{const n=Array(4).fill(0).map((()=>t?Math.floor(256*Math.random()):0)),o=e.split("").map(((e,t)=>e.charCodeAt(0)^n[3&t])),s=e.length,r=t?128:0,i=e.length<126?Buffer.from(Uint8Array.from([129,r+s]).buffer):e.length<65535?Buffer.concat([Buffer.from(Uint8Array.from([129,126|r]).buffer),Buffer.from(Uint8Array.from([s>>8]).buffer),Buffer.from(Uint8Array.from([255&s]).buffer)]):Buffer.concat([Buffer.from(Uint8Array.from([129,127|r]).buffer),Buffer.concat(Number(s).toString(16).padStart(16,"0").match(/.{2}/g).map((e=>parseInt(e,16))).map((e=>Buffer.from(Uint8Array.from([e]).buffer))))]),a=Buffer.from(Int8Array.from(n).buffer),l=Buffer.from(Int8Array.from(o).buffer);return Buffer.concat(t?[i,a,l]:[i,l])};exports.createWebsocketBufferFrom=R;const k=(e,t)=>{var n;if(!t&&0==(1&e.readUInt8(0)))return{payloadLength:0,mask:[0,0,0,0],body:""};const o=t?0:e.readUInt8(1),s=o>>7,r=127&o,i=t?t.payloadLength:127!==r?r:e.readUInt8(2)<<8+e.readUInt8(3),a=t?t.mask:s?Array(4).fill(0).map(((t,n)=>e.readUInt8(n+4))):[0,0,0,0],l=t?0:s?8:4,d=Array(e.length-l).fill(0).map(((t,n)=>String.fromCharCode(e.readUInt8(n+l)^a[3&n]))).join("");return{payloadLength:i,mask:a,body:(null!==(n=null==t?void 0:t.body)&&void 0!==n?n:"").concat(d)}};exports.readWebsocketBuffer=k;const E=(e,t)=>{const n=(0,c.createHash)("sha1");n.update(t+"258EAFA5-E914-47DA-95CA-C5AB0DC85B11");const o=n.digest("base64");e.allowHalfOpen=!0,e.write(`HTTP/1.1 101 Switching Protocols\r\ndate: ${(new Date).toUTCString()}\r\nconnection: upgrade\r\nupgrade: websocket\r\nserver: local\r\nsec-websocket-accept: ${o}\r\n\r\n`)};exports.acknowledgeWebsocket=E;const S=function(e){return q(e,this.configListeners)},$=function(e){const{response:t}=e,o=n(e,["response"]);return Promise.all([q(e,this.logsListeners.filter((e=>e.wantsResponseMessage))),q(o,this.logsListeners.filter((e=>!e.wantsResponseMessage)))])},q=(e,t)=>{if(!t.length)return;const n=JSON.stringify(e),o=new Set(t.map((e=>e.wantsMask))),s=o.has(!1)&&R(n,!1),r=o.has(!0)&&R(n,!0),i=e=>{e.stream.errored&&e.stream.destroy()};t.forEach((e=>{e.stream.closed||e.stream.errored||(e.wantsMask?e.stream.write(r,"ascii",(()=>i(e))):e.stream.write(s,"ascii",(()=>i(e))))}))},x=function(){this.log(`⎸${g.PORT} ${this.config.port.toString().padStart(5)} ⎸${g.OUTBOUND} ${this.config.dontUseHttp2Downstream?"H1.1":"H/2 "}${this.config.replaceRequestBodyUrls?g.REWRITE:" "}⎹⎸${g.INBOUND} ${this.config.ssl?"H/2 ":"H1.1"}${this.config.replaceResponseBodyUrls?g.REWRITE:" "}⎹⎸${this.mode===f.PROXY?`${g.RULES}${Object.keys(this.config.mapping).length.toString().padStart(3)}`:`${g.MOCKS}${this.mocks.size.toString().padStart(3)}`}⎹⎸${this.config.websocket?g.WEBSOCKET:g.NO}⎹⎸${this.config.simpleLogs?g.NO:g.COLORED}⎹⎸${this.config.disableWebSecurity?g.NO:g.SHIELD}⎹`),this.notifyConfigListeners(this.config)};exports.quickStatus=x;const B=(e,t,n,o,s)=>`${U(128163,"error",e.message)}\n<p>An error happened while trying to proxy a remote exchange</p>\n<div class="alert alert-warning" role="alert">\n&#x24D8;&nbsp;This is not an error from the downstream service.\n</div>\n<div class="alert alert-danger" role="alert">\n<pre><code>${e.stack||`<i>${e.name} : ${e.message}</i>`}${e.errno?`<br/>(code : ${e.errno})`:""}</code></pre>\n</div>\nMore information about the request :\n<table class="table">\n<tbody>\n<tr>\n<td>server mode</td>\n<td>${t}</td>\n</tr>\n<tr>\n<td>phase</td>\n<td>${n}</td>\n</tr>\n<tr>\n<td>requested URL</td>\n<td>${o}</td>\n</tr>\n<tr>\n<td>downstream URL</td>\n<td>${s||"&lt;no-target-url&gt;"}</td>\n</tr>\n</tbody>\n</table>\n</div></body></html>`,N=(e,t,n)=>`<table id="table-access" class="table table-striped" style="display: block; width: 100%; overflow-y: auto">\n<thead>\n<tr>\n<th scope="col"${!0===n.captureResponseBody?' style="min-width: 120px"':""}>...</th>\n<th scope="col">Date</th>\n<th scope="col">Level</th>\n<th scope="col">Protocol</th>\n<th scope="col">Method</th>\n<th scope="col">Status</th>\n<th scope="col">Duration</th>\n<th scope="col">Upstream Path</th>\n<th scope="col">Downstream Path</th>\n</tr>\n</thead>\n<tbody id="access">\n</tbody>\n</table>\n<table id="table-proxy" class="table table-striped" style="display: none; width: 100%; overflow-y: auto">\n<thead>\n<tr>\n<th scope="col">Date</th>\n<th scope="col">Level</th>\n<th scope="col">Message</th>\n</tr>\n</thead>\n<tbody id="proxy">\n</tbody>\n</table>\n<script type="text/javascript">\nfunction start() {\ndocument.getElementById('table-access').style.height =\n(document.documentElement.clientHeight - 150) + 'px';\nconst socket = new WebSocket("ws${t.ssl?"s":""}://${e}/local-traffic-logs${n.captureResponseBody?"?wantsResponseMessage=true":""}");\nsocket.onmessage = function(event) {\nlet data = event.data\nlet uniqueHash;\ntry {\nconst { uniqueHash: uniqueHash1, ...data1 } = JSON.parse(event.data);\ndata = data1;\nuniqueHash = uniqueHash1;\n} catch(e) { }\nif (document.getElementById('mock-mode')?.checked) return;\nif (${!0===n.captureResponseBody} && \ndata?.downstreamPath?.startsWith('recorder://') &&\n!data?.upstreamPath?.endsWith('?forceLogInRecorderPage=true'))\nreturn;\nconst time = new Date().toISOString().split('T')[1].replace('Z', '');\nconst actions = getActionsHtmlText(uniqueHash, data.response);\nif(data.statusCode && uniqueHash) {\nconst color = getColorFromStatusCode(data.statusCode);\nconst statusCodeColumn = document.querySelector("#event-" + data.randomId + " .statusCode");\nif (statusCodeColumn)\nstatusCodeColumn.innerHTML = '<span class="badge bg-' + color + '">' + data.statusCode + '</span>';\n\nconst durationColumn = document.querySelector("#event-" + data.randomId + " .duration");\nif (durationColumn) {\nconst duration = data.duration > 10000 ? Math.floor(data.duration / 1000) + 's' :\ndata.duration + 'ms';\ndurationColumn.innerHTML = duration;\n}\n\nconst protocolColumn = document.querySelector("#event-" + data.randomId + " .protocol");\nif (protocolColumn) {\nprotocolColumn.innerHTML = data.protocol;\n}\n\nconst replayColumn = document.querySelector("#event-" + data.randomId + " .replay");\nif (replayColumn) {\nreplayColumn.innerHTML = actions;\n}\n} else if (uniqueHash) {\naddNewRequest(data.randomId, actions, time, data.level, data.protocol, data.method, \n'<span class="badge bg-secondary">...</span>', '&#x23F1;',\ndata.upstreamPath, data.downstreamPath);\n} else if(data.event) {\ndocument.getElementById("proxy")\n.insertAdjacentHTML('afterbegin', '<tr><td scope="col">' + time + '</td>' +\n'<td scope="col">' + (data.level || 'info')+ '</td>' + \n'<td scope="col">' + data.event + '</td></tr>');\n}\ncleanup();\n};\nsocket.onerror = function(error) {\nconsole.log(\`[error] \${JSON.stringify(error)}\`);\nsetTimeout(start, 5000);\n};\n};\nfunction show(id) {\n[...document.querySelectorAll('table')].forEach((table, index) => {\ntable.style.display = index === id ? 'block': 'none'\n});\n[...document.querySelectorAll('.navbar-nav .nav-item .nav-link')].forEach((link, index) => {\nif (index === id) { link.classList.add('active') } else link.classList.remove('active');\n});\n}\nfunction remove(event) {\nevent.target.closest('tr').remove();\nif (window.updateState) window.updateState();\n}\nfunction cleanup() {\nconst currentLimit = parseInt(document.getElementById('limit').value)\nfor (let table of ['access', 'proxy']) {\nwhile (currentLimit && document.getElementById(table).childNodes.length && \ndocument.getElementById(table).childNodes.length > currentLimit) {\n[...document.getElementById(table).childNodes].slice(-1)[0].remove();\n}\n}\n}\nfunction replay(event) {\nconst uniqueHash = event.target.dataset.uniquehash;\nconst { method, url, headers, body } = JSON.parse(atob(uniqueHash));\nfetch(url, {\nmethod,\nheaders,\nbody: !body || !body.length ? undefined : atob(body)\n});\n}\nfunction getActionsHtmlText(uniqueHash, response) {\nconst edit = ${!0===n.captureResponseBody} && uniqueHash\n? '<button data-response="' + btoa(JSON.stringify(response ?? {})) +\n'" data-uniquehash="' + uniqueHash + \n'" data-bs-toggle="modal" data-bs-target="#edit-request" type="button" ' +\n'class="btn btn-primary">&#x1F4DD;</button>'\n: ''\nconst remove = ${!0===n.captureResponseBody} && uniqueHash\n? '<button onclick="javascript:remove(event)" type="button" ' +\n'class="btn btn-primary">&#x274C;</button>'\n: ''\nconst replay = ${!1===n.captureResponseBody} && uniqueHash ? '<button data-response="' + \nbtoa(JSON.stringify(response ?? {})) +\n'" data-uniquehash="' + uniqueHash + '" onclick="javascript:replay(event)" ' +\n'type="button" class="btn btn-primary">&#x1F501;</button>' : '';\nreturn edit + replay + remove\n}\nfunction addNewRequest(\nrandomId, actions, time, level, protocol, method, \nstatusCode, duration, upstreamPath, downstreamPath\n) {\ndocument.getElementById("access")\n.insertAdjacentHTML('afterbegin', '<tr id="event-' + randomId + '">' +\n'<td scope="col" class="replay">' + actions + '</td>' +\n'<td scope="col">' + time + '</td>' +\n'<td scope="col">' + (level || 'info')+ '</td>' + \n'<td scope="col" class="protocol">' + protocol + '</td>' + \n'<td scope="col" class="method">' + method + '</td>' + \n'<td scope="col" class="statusCode">' + statusCode + '</td>' +\n'<td scope="col" class="duration text-end">' + duration + '</td>' +\n'<td scope="col" class="upstream-path">' + upstreamPath + '</td>' + \n'<td scope="col">' + downstreamPath + '</td>' + \n'</tr>');\n}\nfunction getColorFromStatusCode(statusCode) {\nreturn Math.floor(statusCode / 100) === 1 ? "info" :\nMath.floor(statusCode / 100) === 2 ? "success" :\nMath.floor(statusCode / 100) === 3 ? "dark" :\nMath.floor(statusCode / 100) === 4 ? "warning" :\nMath.floor(statusCode / 100) === 5 ? "danger" :\n"secondary";\n}\nwindow.addEventListener("DOMContentLoaded", start);\n<\/script>`,L={logs:(e,t)=>D(`${U(128250,"logs","")}\n<nav class="navbar navbar-expand-lg navbar-dark bg-primary nav-fill">\n<div class="container-fluid">\n<ul class="navbar-nav">\n<li class="nav-item">\n<a class="nav-link active" aria-current="page" href="javascript:show(0)">Access</a>\n</li>\n<li class="nav-item">\n<a class="nav-link" href="javascript:show(1)">Proxy</a>\n</li>\n</ul>\n<span class="navbar-text">\nLimit : <select id="limit" onchange="javascript:cleanup()"><option value="-1">0 (clear)</option><option value="10">10</option>\n<option value="50">50</option><option value="100">100</option><option value="200">200</option>\n<option selected="selected" value="500">500</option><option value="0">Infinity (discouraged)</option>\n</select> rows\n</span>\n</div>\n</nav>\n${N(e,t.config,{captureResponseBody:!1})}\n</body></html>`),config:(e,t)=>D(`${U(127899,"config","")}\n<link href="${A}jsoneditor/dist/jsoneditor.min.css" rel="stylesheet" type="text/css">\n<script src="${A}jsoneditor/dist/jsoneditor.min.js"><\/script>\n<script src="${A}node-forge/dist/forge.min.js"><\/script>\n<div id="ssl-modal" class="modal" tabindex="-1" role="dialog">\n<div class="modal-dialog" role="document">\n<div class="modal-content">\n<div class="modal-header">\n<h5 class="modal-title">SSL keypair generation in progress</h5>\n</div>\n<div class="modal-body">\n<p>Wait a few seconds or move your mouse to increase the entropy.</p>\n</div>\n</div>\n</div>\n</div>\n<div id="jsoneditor" style="width: 400px; height: 400px;"></div>\n<script>\n// create the editor\nconst container = document.getElementById("jsoneditor")\nconst options = {mode: "code", allowSchemaSuggestions: true, schema: {\ntype: "object",\nproperties: {\n${Object.entries(Object.assign(Object.assign({},P),{ssl:{cert:"",key:""}})).map((([e,t])=>`${e}: {type: "${"number"==typeof t?"integer":"string"==typeof t?"string":"boolean"==typeof t?"boolean":"object"}"}`)).join(",\n")}\n},\nrequired: [],\nadditionalProperties: false\n}}\n\nfunction save() {\nsocket.send(JSON.stringify(editor.get()));\n}\n\nfunction generateSslCertificate() {\nconst sslModal = new bootstrap.Modal(document.getElementById('ssl-modal'), {});\nsslModal.show()\nsetTimeout(function() {\nconst keypair = forge.pki.rsa.generateKeyPair(2048);\nconst certificate = forge.pki.createCertificate();\nconst now = new Date();\nconst fiveYears = new Date(new Date(now).setFullYear(now.getFullYear() + 5));\nObject.assign(certificate, {\npublicKey: keypair.publicKey,\nserialNumber: "01",\nvalidity: {\nnotBefore: now,\nnotAfter: fiveYears,\n},\n});\ncertificate.sign(keypair.privateKey, forge.md.sha256.create());\nconst key = forge.pki.privateKeyToPem(keypair.privateKey);\nconst cert = forge.pki.certificateToPem(certificate);\nconst existingConfig = editor.get();\neditor.set({ ...existingConfig, ssl: { key, cert },\nport: parseInt(("" + existingConfig.port).replace(/(80|[0-9])80$/, '443'))\n});\nsslModal.hide();\n}, 100);\n}\n\nconst editor = new JSONEditor(container, options);\nlet socket;\nconst initialJson = ${JSON.stringify(t.config)}\neditor.set(initialJson)\neditor.validate();\neditor.aceEditor.commands.addCommand({\nname: 'save',\nbindKey: {win: 'Ctrl-S', mac: 'Command-S'},\nexec: save,\n});\n\nwindow.addEventListener("DOMContentLoaded", function() {\ndocument.getElementById('jsoneditor').style.height =\n(document.documentElement.clientHeight - 150) + 'px';\ndocument.getElementById('jsoneditor').style.width =\nparseInt(window.getComputedStyle(\ndocument.querySelector('.container')).maxWidth) + 'px';\nconst sslButton = document.createElement('button');\nsslButton.addEventListener("click", generateSslCertificate);\nsslButton.type="button";\nsslButton.classList.add("btn");\nsslButton.classList.add("btn-primary");\nsslButton.innerHTML="&#x1F512;";\ndocument.querySelector('.jsoneditor-menu')\n.appendChild(sslButton);\nconst saveButton = document.createElement('button');\nsaveButton.addEventListener("click", save);\nsaveButton.type="button";\nsaveButton.classList.add("btn");\nsaveButton.classList.add("btn-primary");\nsaveButton.innerHTML="&#x1F4BE;";\ndocument.querySelector('.jsoneditor-menu')\n.appendChild(saveButton);\nsocket = new WebSocket("ws${t.config.ssl?"s":""}://${e}/local-traffic-config");\nsocket.onmessage = function(event) {\neditor.set(JSON.parse(event.data))\neditor.validate()\n}\n});\n<\/script>\n</body></html>`),recorder:(e,t,n)=>{var o,s,r,i,a,l,d;return(null===(o=n.url)||void 0===o?void 0:o.endsWith("?forceLogInRecorderPage=true"))?D('{"ping":"pong"}',{contentType:"application/json; charset=utf-8"}):["PUT","POST","DELETE"].includes(n.method)?D('{"status": "acknowledged"}',{contentType:"application/json; charset=utf-8",onOutboundWrite:e=>{let o={};try{o=JSON.parse(e.toString("ascii"))}catch(e){}if("object"!=typeof o||Object.keys(o).filter((e=>!["strictMock","mode","mocks"].includes(e))).length||!Array.isArray(o.mocks)&&void 0!==o.mocks)return void t.log("invalid mocks update received",m.WARNING,g.MOCKS);const{mocks:s,mode:r,strictMock:i}=o,a=s?new Map(s.map((({response:e,uniqueHash:t})=>[_(t),e]))):null,l=r!==t.mode&&r===f.PROXY,d=r!==t.mode&&r===f.MOCK||null!==a&&t.mocks.size!==a.size,c=!!i!=!!t.strictMock,u="DELETE"===n.method;l&&t.log(`${Object.keys(t.config.mapping).length.toString().padStart(5)} loaded mapping rules`,m.INFO,g.RULES),d&&t.log(`${(null!=a?a:t.mocks).size.toString().padStart(5)} loaded mocks`,m.INFO,g.MOCKS),c&&t.log(`mocks strict mode : ${null!=i?i:t.strictMock}`,m.INFO,g.MOCKS),V(t,u?{strictMock:i,mode:r,mocks:new Map}:{strictMock:i,mode:r,mocks:null!=a?a:t.mocks}),(l||d||c||u)&&t.quickStatus()}}):D(`${U(9210,"recorder","")}\n<link href="${A}jsoneditor/dist/jsoneditor.min.css" rel="stylesheet" type="text/css">\n<script src="${A}jsoneditor/dist/jsoneditor.min.js"><\/script>\n<script src="${A}pako/dist/pako.min.js"><\/script>\n<span>Mode : </span>\n<div class="btn-group" role="group" aria-label="Server Mode">\n<input type="radio" class="btn-check" name="server-mode" id="record-mode" autocomplete="off"${t.mode===f.PROXY?" checked":""}>\n<label class="btn btn-outline-primary" for="record-mode">&#9210; Record</label>\n<input type="radio" class="btn-check" name="server-mode" id="mock-mode" autocomplete="off"${t.mode===f.MOCK?" checked":""}>\n<label class="btn btn-outline-primary" for="mock-mode">&#x1F310; Mock</label>\n</div>\n<span>Actions : </span>\n<button type="button" class="btn btn-light" id="add-mock">&#x2795; Mock from dummy request</button>\n<button type="button" class="btn btn-light" id="upload-mocks">&#x1F4E5; Upload mocks</button>\n<button type="button" class="btn btn-light" id="download-mocks">&#x1F4E6; Download mocks</button>\n<button type="button" class="btn btn-light" id="delete-mocks">&#x1F5D1; Delete mocks</button>\n<div class="form-check form-switch">\n<input class="form-check-input" type="checkbox" id="strict-mock-mode"${t.strictMock?" checked":""}>\n<label class="form-check-label" for="strict-mock-mode">Strict mock mode</label>\n</div>\n<input type="hidden" id="limit" value="0"/>\n<div class="modal fade" id="edit-request" tabindex="-1" \naria-labelledby="edit-request-label" aria-hidden="true">\n<div class="modal-dialog" style="max-width: 900px">\n<div class="modal-content">\n<div class="modal-header">\n<h1 class="modal-title fs-5" id="edit-request-label">Edit request to /</h1>\n<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>\n</div>\n<div class="modal-body">\n<div class="container">\n<div class="row">\n<div class="col-lg">\n<h2>Request :</h2>\n<div id="uniqueHash-editor" style="width: 400px; height: 400px;"></div>\n</div>\n<div class="col-lg">\n<h2>Response : </h2>\n<div id="response-editor" style="width: 400px; height: 400px;"></div>\n</div>\n</div>\n</div>\n</div>\n<div class="modal-footer">\n<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>\n<button type="button" class="btn btn-primary" onclick="javascript:saveRequest()">Save changes</button>\n</div>\n</div>\n</div>\n</div>\n<script>\nconst xmlOrJsonPrologsInBase64 = [\n"eyJ","PD94bWw=","PCFET0NUWVBF","PCFkb2N0eXBl","PGh0bWw","PEhUTUw","H4sIAAAAAAAA", "W3tc"\n];\nfunction getMocksData () {\nreturn JSON.stringify(\n[...document.querySelectorAll('button[data-uniqueHash]')].map(button => ({\nresponse: button.attributes['data-response']?.value,\nuniqueHash: button.attributes['data-uniqueHash']?.value}))\n)\n}\nfunction updateState () {\nfetch("http${t.config.ssl?"s":""}://${e}${null!==(i=null===(r=Object.entries(null!==(s=t.config.mapping)&&void 0!==s?s:{}).find((([e,t])=>{var n;return null===(n=null==t?void 0:t.toString())||void 0===n?void 0:n.startsWith("recorder:")})))||void 0===r?void 0:r[0])&&void 0!==i?i:"/recorder/"}", {\nmethod: 'PUT',\nheaders: { 'Content-Type': 'application/json' },\nbody: '{"strictMock":' + document.getElementById('strict-mock-mode').checked +\n',"mode":"' + \n(document.getElementById('mock-mode').checked ? "mock" : "proxy") + '"' +\n',"mocks":' + getMocksData() + '}'\n})\n}\nfunction loadMocks(mocksHashes) {\nconst time = new Date().toISOString().split('T')[1].replace('Z', '');\nlet mocks = [];\ntry {\nmocks = mocksHashes.map(mock => ({...mock, \nrequest: JSON.parse(atob(mock.uniqueHash)),\nresponse: JSON.parse(atob(mock.response))\n}));\n} catch(e) { }\nmocks.forEach(mock => {\nconst randomId = window.crypto.randomUUID();\nconst actions = getActionsHtmlText(mock.uniqueHash, mock.response);\naddNewRequest(randomId, actions, time, 'info', 'HTTP/2', mock.request.method, \n'<span class="badge bg-' + \ngetColorFromStatusCode(mock.response.status) + '">' + \nmock.response.status + \n'</span>', \n'0ms', mock.request.url, \n'N/A');\n});\n}\ndocument.getElementById('add-mock').addEventListener('click', () => {\nconst iframe = document.createElement('iframe');\niframe.style.display = 'none';\niframe.onload = function() { iframe.parentNode.removeChild(iframe); };\niframe.src = "http${t.config.ssl?"s":""}://${e}${null!==(d=null===(l=Object.entries(null!==(a=t.config.mapping)&&void 0!==a?a:{}).find((([e,t])=>{var n;return null===(n=null==t?void 0:t.toString())||void 0===n?void 0:n.startsWith("recorder:")})))||void 0===l?void 0:l[0])&&void 0!==d?d:"/recorder/"}?forceLogInRecorderPage=true";\ndocument.body.appendChild(iframe);\n});\ndocument.getElementById('upload-mocks').addEventListener('click', () => {\nconst time = new Date().toISOString().split('T')[1].replace('Z', '');\nconst fileInput = document.createElement('input');\nfileInput.type = "file";\nfileInput.multiple = "multiple";\nfileInput.onchange = function() {\nconst fileReader = new FileReader();\n[...fileInput.files].reduce((promise, file) =>\npromise.then(result => new Promise(resolve => {\nfileReader.readAsText(file);\nfileReader.onload = function(){\nresolve(result.concat(fileReader.result));\n};\n})), Promise.resolve([]))\n.then(files => files.flatMap(file => JSON.parse(file)))\n.catch(e => [])\n.then(mocks => loadMocks(mocks))\n.then(() => updateState());\n}\nfileInput.click();\n});\ndocument.getElementById('download-mocks').addEventListener('click', () => {\nconst link = document.createElement('a');\nlink.href = URL.createObjectURL(new Blob([getMocksData()], {\ntype: "application/json",\n}));\nlink.download = "mocks-" + new Date().toISOString() + ".json";\nlink.click();\nURL.revokeObjectURL(link.href);\n})\ndocument.getElementById('delete-mocks').addEventListener('click', () => {\ndocument.getElementById('limit').value = -1;\ncleanup();\nupdateState();\ndocument.getElementById('limit').value = 0;\n})\ndocument.getElementById('record-mode').addEventListener('change', () => {\ndocument.getElementById('limit').value = 0;\ncleanup();\nupdateState();\n})\ndocument.getElementById('mock-mode').addEventListener('change', () => {\nupdateState();\n})\ndocument.getElementById('strict-mock-mode').addEventListener('change', (e) => { \nupdateState();\n})\nfunction saveRequest () {\n$('#edit-request').modal("hide");\n\nconst requestBeingEdited = window.requestBeingEdited;\nlet request = uniqueHashEditor.get();\nlet response = responseEditor.get();\nif (typeof request.body === "object") {\nrequest.body = JSON.stringify(request.body);\n}\nif (typeof response.body === "object") {\nresponse.body = JSON.stringify(response.body);\n}\nconst oldRequest = JSON.parse(atob(requestBeingEdited.attributes['data-uniqueHash'].value));\nconst oldResponse = JSON.parse(atob(requestBeingEdited.attributes['data-response'].value));\nconst requestProlog = requestBeingEdited.attributes['data-requestProlog']?.value;\nconst responseProlog = requestBeingEdited.attributes['data-responseProlog']?.value;\nconst requestPrologHasChanged = request.body.substring(0, 10) !== oldRequest.body.substring(0, 10);\nconst responsePrologHasChanged = response.body.substring(0, 10) !== response.body.substring(0, 10);\nif (requestProlog === "H4sIAAAAAAAA" && !requestPrologHasChanged) {\nrequest.body =\nbtoa([...pako.gzip(request.body)].map(e => String.fromCharCode(e)).join(""));\n} else if ((requestProlog === null || !request.body.startsWith(requestProlog ?? "")) && \nrequest.body.substring(0, 10) !== oldRequest.body.substring(0, 10)) {\nrequest.body = btoa(request.body);\n}\nif (responseProlog === "H4sIAAAAAAAA" && !responsePrologHasChanged) {\nresponse.body =\nbtoa([...pako.gzip(response.body)].map(e => String.fromCharCode(e)).join(""));\n} else if ((responseProlog === null || !response.body.startsWith(responseProlog ?? "")) && \nresponse.body.substring(0, 10) !== oldResponse.body.substring(0, 10)) {\nresponse.body = btoa(response.body);\n}\nrequest = btoa(JSON.stringify(request));\nresponse = btoa(JSON.stringify(response));\nrequestBeingEdited.setAttribute('data-uniqueHash', request);\nrequestBeingEdited.setAttribute('data-response', response);\nconst row = requestBeingEdited.closest('tr');\nrow.querySelector("td.method").innerHTML = uniqueHashEditor.get().method;\nrow.querySelector("td.upstream-path").innerHTML = uniqueHashEditor.get().url;\nwindow.requestBeingEdited = undefined;\nupdateState();\n}\ndocument.getElementById('edit-request').addEventListener('show.bs.modal', event => {\nconst request = JSON.parse(atob(event.relatedTarget.attributes['data-uniqueHash'].value));\nconst response = JSON.parse(atob(event.relatedTarget.attributes['data-response'].value));\nconst requestProlog = xmlOrJsonPrologsInBase64.find(prolog => request.body?.startsWith(prolog));\nconst responseProlog = xmlOrJsonPrologsInBase64.find(prolog => response.body?.startsWith(prolog));\nif (requestProlog) {\nevent.relatedTarget.setAttribute('data-requestProlog', requestProlog);\nrequest.body = request.body.startsWith("H4sIAAAAAAAA") \n? pako.ungzip(new Uint8Array(atob(request.body).split("").map(e => e.charCodeAt(0))), {to: "string"})\n: atob(request.body);\nrequest.body = request.body.startsWith("{\\"") || request.body.startsWith("[{\\"")\n? JSON.parse(request.body) : request.body;\n}\nif (responseProlog) {\nevent.relatedTarget.setAttribute('data-responseProlog', responseProlog);\nresponse.body = response.body.startsWith("H4sIAAAAAAAA") \n? pako.ungzip(new Uint8Array(atob(response.body).split("").map(e => e.charCodeAt(0))), {to: "string"})\n: atob(response.body);\nresponse.body = response.body.startsWith("{\\"") || response.body.startsWith("[{\\"")\n? JSON.parse(response.body) : response.body;\n}\nwindow.requestBeingEdited = event.relatedTarget;\nwindow.uniqueHashEditor.set(request);\nwindow.responseEditor.set(response);\ndocument.getElementById('edit-request-label').innerText = "Edit request to " + request.url;\n})\n\nsetTimeout(() => {\nloadMocks(${JSON.stringify([...t.mocks.entries()].map((([e,t])=>({uniqueHash:e,response:t}))))});\nwindow.uniqueHashEditor = new JSONEditor(document.getElementById("uniqueHash-editor"), {\nmode: "code", allowSchemaSuggestions: true, schema: {\ntype: "object",\nproperties: {\nmethod: {type: "string"},\nurl: {type: "string"},\nbody: {oneOf: [{type:"string"},{type:"object"}]},\nheaders: {type: "object"},\n},\nrequired: [],\nadditionalProperties: false\n}});\nwindow.responseEditor = new JSONEditor(document.getElementById("response-editor"), {\nmode: "code", allowSchemaSuggestions: true, schema: {\ntype: "object",\nproperties: {\nbody: {oneOf: [{type:"string"},{type:"object"}]},\nheaders: {type: "object"},\nstatus: {type: "integer"}\n},\nrequired: [],\nadditionalProperties: false\n}});\nupdateState();\n}, 10)\n<\/script>\n${N(e,t.config,{captureResponseBody:!0})}\n</body>\n</html>`)}},j=Object.keys(L),I=j.map((e=>`${e}:`)),P={mapping:Object.assign({},...j.map((e=>({[`/${e}/`]:`${e}://`})))),port:8080,replaceRequestBodyUrls:!1,replaceResponseBodyUrls:!1,dontUseHttp2Downstream:!1,dontTranslateLocationHeader:!1,simpleLogs:!1,websocket:!0,disableWebSecurity:!1,connectTimeout:3e3,socketTimeout:3e3},C=(e=!0)=>t(void 0,void 0,void 0,(function*(){return new Promise((t=>(0,a.readFile)(y,((n,o)=>{n&&!e&&w(null,"config error. Using default value",m.ERROR,g.ERROR_1);let s=null;try{s=Object.assign({},P,JSON.parse((o||"{}").toString()))}catch(e){return w({config:s},"config syntax incorrect, aborting",m.ERROR,g.ERROR_2),s=null!=s?s:Object.assign({},P),void t(s)}s.mapping[""]||w({config:s},'default mapping "" not provided.',m.WARNING,g.ERROR_3),n&&"ENOENT"===n.code&&e&&y===b?(0,a.writeFile)(y,JSON.stringify(P,null,2),(e=>{e?w(null,"config file NOT created",m.ERROR,g.ERROR_4):w(null,"config file created",m.INFO,g.COLORED),t(s)})):t(s)}))))}));exports.load=C;const T=e=>""==e?"":(0,d.normalize)(e).replace(/\\/g,"/"),A="https://cdn.jsdelivr.net/npm/",H=["host","connection","keep-alive","upgrade","transfer-encoding","upgrade-insecure-requests","proxy-connection"],U=(e,t,n)=>`<!doctype html>\n<html lang="en">\n<head>\n<title>&#x${e.toString(16)}; local-traffic ${t} | ${n}</title>\n<link href="${A}bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"/>\n<script src="${A}jquery/dist/jquery.min.js"><\/script>\n<script src="${A}bootstrap/dist/js/bootstrap.bundle.min.js"><\/script>\n</head>\n<body><div class="container"><h1>&#x${e.toString(16)}; local-traffic ${t}</h1>\n<br/>`,M=({response:e})=>({error:null,data:null,hasRun:!1,run:function(){return this.hasRun?Promise.resolve():new Promise((t=>{try{this.data=JSON.parse(Buffer.from(e,"base64").toString("utf-8"))}catch(e){this.data={}}t(void 0)}))},events:{},on:function(e,t){return this.events[e]=t,this.run().then((()=>{var t;"response"===e&&this.events.response(Object.assign(Object.assign({},this.data.headers),{"X-LocalTraffic-Mock":"1"}),this.data.status),"data"===e&&this.data&&(this.events.data(Buffer.from(null!==(t=this.data.body)&&void 0!==t?t:"","base64")),this.events.end()),"error"===e&&this.error&&this.events.error(this.error)})),this},end:function(){return this},request:function(){return this},write:function(){return this}}),W=e=>{const t=(0,d.resolve)("/",e.hostname,...e.pathname.replace(/[?#].*$/,"").replace(/^\/+/,"").split("/"));return{error:null,data:null,hasRun:!1,run:function(){return this.hasRun?Promise.resolve():new Promise((n=>(0,a.readFile)(t,((o,s)=>{if(this.hasRun=!0,!o||"EISDIR"!==o.code)return this.error=o,this.data=s,void n(void 0);(0,a.readdir)(t,((t,o)=>{this.error=t,this.data=o,t?n(void 0):Promise.all(o.map((t=>new Promise((n=>(0,a.lstat)((0,d.resolve)(e.pathname,t),((e,o)=>n([t,o,e])))))))).then((t=>{const o=t.filter((e=>!e[2]&&e[1].isDirectory())).concat(t.filter((e=>!e[2]&&e[1].isFile())));this.data=`${U(128194,"directory",e.href)}<p>Directory content of <i>${e.href.replace(/\//g,"&#x002F;")}</i></p><ul class="list-group"><li class="list-group-item">&#x1F4C1;<a href="${e.pathname.endsWith("/")?"..":"."}">&lt;parent&gt;</a></li>${o.filter((e=>!e[2])).map((t=>`<li class="list-group-item">&#x${(t[1].isDirectory()?128193:128196).toString(16)};<a href="${e.pathname.endsWith("/")?"":`${e.pathname.split("/").slice(-1)[0]}/`}${t[0]}">${t[0]}</a></li>`)).join("\n")}</li></ul></body></html>`,n(void 0)}))}))}))))},events:{},on:function(e,n){return this.events[e]=n,this.run().then((()=>{"response"===e&&this.events.response(t.endsWith(".svg")?{Server:"local","Content-Type":"image/svg+xml"}:{Server:"local"},0),"data"===e&&this.data&&(this.events.data(this.data),this.events.end()),"error"===e&&this.error&&this.events.error(this.error)})),this},end:function(){return this},request:function(){return this},write:function(){return this}}},D=(e,t)=>({error:null,data:null,outboundData:null,run:function(){return new Promise((t=>{this.data=e,t(void 0)}))},events:{},on:function(e,n){return this.events[e]=n,this.run().then((()=>{var n;"response"===e&&this.events.response({Server:"local","Content-Type":null!==(n=null==t?void 0:t.contentType)&&void 0!==n?n:"text/html"},0),"data"===e&&this.data&&(this.events.data(this.data),this.events.end()),"error"===e&&this.error&&this.events.error(this.error)})),this},write:function(e){return this.outboundData=e,e instanceof Buffer&&(null==t||t.onOutboundWrite(e)),this},end:function(){return this},request:function(){return this}}),F=(e,n,o)=>t(void 0,void 0,void 0,(function*(){var s,r;return(null!==(r=null===(s=n["content-encoding"])||void 0===s?void 0:s.toString())&&void 0!==r?r:"").split(",").reduce(((e,n)=>t(void 0,void 0,void 0,(function*(){const t=n.trim().toLowerCase(),o="gzip"===t||"x-gzip"===t?l.gunzip:"deflate"===t?l.inflate:"br"===t?l.brotliDecompress:"identity"===t||""===t?(e,t)=>{t(null,e)}:null;if(null===o)throw new Error(`${t} compression not supported by the proxy`);const s=yield e;return yield new Promise(((e,t)=>o(s,((n,o)=>{n&&t(n),e(o)}))))}))),Promise.resolve(e)).then((e=>{const t=e.length>1e7,s=["text/html","application/javascript","application/json"].some((e=>{var t;return(null!==(t=n["content-type"])&&void 0!==t?t:"").toString().includes(e)}));return!t&&(s||!/[^\x00-\xFF]/.test(e.toString()))?J(e.toString(),{direction:o.direction,proxyHostnameAndPort:o.proxyHostnameAndPort,ssl:o.ssl,mapping:o.mapping}).replace(/\?protocol=wss?%3A&hostname=[^&]+&port=[0-9]+&pathname=/g,`?protocol=ws${o.ssl?"s":""}%3A&hostname=${o.proxyHostname}&port=${o.port}&pathname=${encodeURIComponent(o.key.replace(/\/+$/,""))}`):e})).then((e=>{var t,o;return(null!==(o=null===(t=n["content-encoding"])||void 0===t?void 0:t.toString())&&void 0!==o?o:"").split(",").reverse().reduce(((e,t)=>{const n=t.trim().toLowerCase(),o="gzip"===n||"x-gzip"===n?l.gzip:"deflate"===n?l.deflate:"br"===n?l.brotliCompress:"identity"===n||""===n?(e,t)=>{t(null,e)}:null;if(null===o)throw new Error(`${n} compression not supported by the proxy`);return e.then((e=>new Promise((t=>o(e,((e,n)=>{if(e)throw e;t(n)}))))))}),Promise.resolve(Buffer.from(e)))}))}));exports.replaceBody=F;const J=(e,{direction:t,proxyHostnameAndPort:n,ssl:o,mapping:s})=>Object.entries(s).map((([e,t])=>[e,"string"==typeof t?t:t.replaceBody])).reduce(((e,[s,r])=>I.some((e=>r.startsWith(e)))||""!==s&&!s.match(/^[-a-zA-Z0-9()@:%_\+.~#?&//=]*$/)?e:t===h.INBOUND?e.replace(new RegExp(r.replace(new RegExp(`^(file|${j.join("|")})://`),"").replace(/[*+?^${}()|[\]\\]/g,"").replace(/^https/,"https?")+"/*","ig"),`http${o?"s":""}://${n}${s.replace(/\/+$/,"")}/`):e.split(`http${o?"s":""}://${n}${s.replace(/\/+$/,"")}`).join(r)),e).split(`${n}/:`).join(`${n}:`);exports.replaceTextUsingMapping=J;const _=e=>{try{const t="object"==typeof e?e:JSON.parse(Buffer.from(e,"base64").toString("utf-8"));return["authorization","cache-control","date","proxy-authenticate","proxy-authorization","expires","last-modified","if-modified-since","if-unmodified-since","keep-alive","cookie","access-control-max-age","retry-after","signed-headers","server-timing","sec-ch-ua","sec-ch-ua-mobile","sec-ch-ua-platform","user-agent","sec-fetch-dest","sec-fetch-mode","sec-fetch-site","sec-fetch-user","referer","upgrade-insecure-requests"].forEach((e=>{var n;null===(n=null==t?void 0:t.headers)||void 0===n||delete n[e]})),t.headers=Object.keys(t.headers).sort().reduce(((e,n)=>(e[n]=t.headers[n],e)),{}),Buffer.from(JSON.stringify(t),"utf-8").toString("base64")}catch(t){return e}};exports.cleanEntropy=_;const K=(e,t,n)=>{t.writeHead(e,void 0,{"content-type":"text/html","content-length":n.length}),t.end(n)};exports.send=K;const z=(e,t)=>{var n,o,s,r,a;const l=(null!==(s=null!==(o=null===(n=e.headers[":authority"])||void 0===n?void 0:n.toString())&&void 0!==o?o:e.headers.host)&&void 0!==s?s:"localhost").replace(/:.*/,""),d=e.headers[":authority"]||`${e.headers.host}${e.headers.host.match(/:[0-9]+$/)?"":80!==t.port||t.ssl?443===t.port&&t.ssl?"":`:${null!==(r=t.port)&&void 0!==r?r:8080}`:""}`,c=new i.URL(`http${t.ssl?"s":""}://${d}${e.url}`),u=c.href.substring(c.origin.length),p=Object.assign({},Object.assign({},...Object.entries(t.mapping).map((([e,t])=>({[e]:new i.URL(T("string"==typeof t?t:t.downstreamUrl))}))))),[m,g]=null!==(a=Object.entries(p).find((([e])=>u.match(RegExp(e.replace(/^\//,"^/"))))))&&void 0!==a?a:[];return{proxyHostname:l,proxyHostnameAndPort:d,url:c,path:u,key:m,target:g}};exports.determineMapping=z;const G=function(e,t,n){var o,a,l,d;if(n.on("error",(()=>{e.log("websocket connection reset",m.WARNING,g.WEBSOCKET)})),!e.config.websocket)return n.end("HTTP/1.1 503 Service Unavailable\r\n\r\n"),{};const{key:c,target:u,path:p,url:h}=z(t,e.config);if(p.startsWith("/local-traffic-logs"))return E(n,t.headers["sec-websocket-key"]),{logsListeners:e.logsListeners.concat({stream:n,wantsMask:!(null!==(a=null===(o=t.headers["user-agent"])||void 0===o?void 0:o.toString())&&void 0!==a?a:"").includes("Chrome"),wantsResponseMessage:[...h.searchParams.entries()].some((([e,t])=>"wantsResponseMessage"===e&&"true"===t))})};if("/local-traffic-config"===p){E(n,t.headers["sec-websocket-key"]);let o=null;return n.on("data",(t=>{const n=k(t,o);if(null===o&&n.body.length<n.payloadLength)o=n;else{if(n.body.length>=n.payloadLength&&0===n.body.length)return;if(n.body.length>=n.payloadLength){let t;o=null;try{t=JSON.parse(n.body)}catch(t){return void e.log("config file NOT read, try again later",m.WARNING,g.ERROR_4)}V(e,{pendingConfigSave:t})}}})),{configListeners:e.configListeners.concat({stream:n,wantsMask:!(null!==(d=null===(l=t.headers["user-agent"])||void 0===l?void 0:l.toString())&&void 0!==d?d:"").includes("Chrome")})}}const f=new i.URL(`${u.protocol}//${u.host}${t.url.endsWith("/_next/webpack-hmr")?t.url:t.url.replace(new RegExp(`^${c}`,"g"),"").replace(/^\/*/,"/")}`),b={hostname:f.hostname,path:f.pathname,port:f.port,protocol:f.protocol,rejectUnauthorized:!1,method:t.method,headers:t.headers,host:f.hostname},y="https:"===f.protocol?(0,r.request)(b):(0,s.request)(b);y.end(),y.on("error",(t=>{e.log("websocket request has errored "+(t.errno?`(${t.errno})`:""),m.WARNING,g.WEBSOCKET)})),y.on("upgrade",((t,o)=>{const s=`HTTP/${t.httpVersion} ${t.statusCode} ${t.statusMessage}\r\n${Object.entries(t.headers).flatMap((([e,t])=>(Array.isArray(t)?t:[t]).map((t=>[e,t])))).map((([e,t])=>`${e}: ${t}\r\n`)).join("")}\r\n`;n.write(s),n.allowHalfOpen=!0,o.allowHalfOpen=!0,o.on("data",(e=>n.write(e))),n.on("data",(e=>o.write(e))),o.on("error",(t=>{e.log("downstream socket has errored "+(t.errno?`(${t.errno})`:""),m.WARNING,g.WEBSOCKET)})),n.on("error",(t=>{e.log("upstream socket has errored "+(t.errno?`(${t.errno})`:""),m.WARNING,g.WEBSOCKET)}))}))};exports.websocketServe=G;const Y=function(e,n,a){var l,d,u,p,b;return t(this,void 0,void 0,(function*(){if(!n.headers.host&&!n.headers[":authority"])return void K(400,a,Buffer.from(B(new Error("client must supply a 'host' header"),e.mode,"proxy",new i.URL(`http${e.config.ssl?"s":""}://unknowndomain${n.url}`))));const{proxyHostname:t,proxyHostnameAndPort:O,url:w,path:R,key:k,target:E}=z(n,e.config);if(!E)return void K(502,a,Buffer.from(B(new Error(`No mapping found in config file ${y}`),e.mode,"proxy",w)));const S=E.host.replace(RegExp(/\/+$/),""),$=`${E.href.substring(8+E.host.length)}${T(R.replace(RegExp(T(k)),""))}`.replace(/^\/*/,"/"),q=new i.URL(`${E.protocol}//${S}${$}`),x=I.some((e=>E.protocol===e));let N=null,j=!e.config.dontUseHttp2Downstream;const P=j&&!x&&"file:"!==E.protocol&&(yield Promise.race([new Promise((t=>{const n=(0,o.connect)(q,{timeout:e.config.connectTimeout,sessionTimeout:e.config.socketTimeout,rejectUnauthorized:!1,protocol:E.protocol},((e,o)=>{j=j&&!!o.alpnProtocol,t(j?n:null)}));n.on("error",(t=>{N=j&&Buffer.from(B(t,e.mode,"connection",w,q))}))})),new Promise((t=>setTimeout((()=>{j=!1,t(null)}),e.config.connectTimeout)))])),C=(0,c.randomBytes)(20).toString("hex");let A=null;const U=e.config.replaceRequestBodyUrls||e.logsListeners.length,D=null==n?void 0:n.readableLength,G=null===(l=null==n?void 0:n.stream)||void 0===l?void 0:l.readableLength,Y=!((e.config.ssl&&0===G||!e.config.ssl&&0===D)&&("0"===n.headers["content-length"]||void 0===n.headers["content-length"]));if(U){const o=null!==(d=null==n?void 0:n.stream)&&void 0!==d?d:n;let s=Buffer.from([]);yield Promise.race([new Promise((t=>setTimeout(t,e.config.connectTimeout))),new Promise((e=>{Y?(o.on("data",(e=>{s=Buffer.concat([s,e])})),o.on("end",e),o.on("error",e)):e(void 0)}))]),Y&&!s.length&&e.log(`body replacement error ${R.slice(-17)}`,m.WARNING,g.ERROR_4),A=e.config.replaceRequestBodyUrls?yield F(s,n.headers,{proxyHostnameAndPort:O,proxyHostname:t,key:k,mapping:e.config.mapping,port:e.config.port,ssl:!!e.config.ssl,direction:h.OUTBOUND}):s}const X=_({method:n.method,url:n.url,headers:Object.assign({},...Object.entries(n.headers).filter((([e])=>!e.startsWith(":"))).map((([e,t])=>({[e]:t})))),body:null==A?void 0:A.toString("base64")}),Z="file:"===E.protocol;e.notifyLogsListeners({level:"info",protocol:j?"HTTP/2":"HTTP1.1",method:n.method,upstreamPath:R,downstreamPath:q.href,randomId:C,uniqueHash:X});const V=e.mode===f.MOCK?_(X):"",Q=e.mode===f.MOCK&&(!x||Z),ee=e.mocks.get(V);if(Q&&!ee&&e.strictMock)return void K(502,a,Buffer.from(B(new Error("No corresponding mock found in the server. \nTry switching back to the proxy mode"),e.mode,"mock",w)));const te=v(),ne=Q&&ee?M({response:ee}):Z?W(q):x?L[E.protocol.replace(/:$/,"")](O,e,n):j?P:null;N instanceof Buffer||(N=null);const oe=Object.assign(Object.assign({},[...Object.entries(n.headers)].filter((([e])=>!H.includes(e.toLowerCase()))).reduce(((e,[t,n])=>(e[t]=(e[t]||"")+(Array.isArray(n)?n:[n]).map((e=>e.replace(w.hostname,S))).join(", "),e)),{})),{origin:E.href,referer:q.toString(),"content-length":null!==(p=null!==(u=null==A?void 0:A.length)&&void 0!==u?u:n.headers["content-length"])&&void 0!==p?p:0,":authority":S,":method":n.method,":path":$,":scheme":E.protocol.replace(":","")}),se=ne&&!N&&ne.request(oe,{endStream:e.config.ssl?!(null==G||G):!D});"object"==typeof se&&(null==se||se.on("error",(t=>{const n=-505===t.errno;N=Buffer.from(B(t,e.mode,"stream"+(n?" (error -505 usually means that the downstream service does not support this http version)":""),w,q))})));const re={hostname:E.hostname,path:$,port:E.port,protocol:E.protocol,rejectUnauthorized:!1,method:n.method,headers:Object.assign(Object.assign({},Object.assign({},...Object.entries(oe).filter((([e])=>!e.startsWith(":")&&"transfer-encoding"!==e.toLowerCase())).map((([e,t])=>({[e]:t}))))),{host:E.hostname})},ie=!N&&!j&&!["file:",...I].includes(E.protocol)&&(yield new Promise((t=>{const o="https:"===E.protocol?(0,r.request)(re,t):(0,s.request)(re,t);o.on("error",(n=>{N=Buffer.from(B(n,e.mode,"request",w,q)),t(null)})),U&&(o.write(A),o.end()),U||(n.on("data",(e=>o.write(e))),n.on("end",(()=>o.end())))})));if(N)return void K(502,a,N);N=null,G&&se&&!U?(n.stream.on("data",(e=>{se.write(e)})),n.stream.on("end",(()=>se.end()))):D&&se&&!U?(n.on("data",(e=>{se.write(e)})),n.on("end",(()=>se.end()))):se&&U&&Y&&(se.write(A),se.end());const{outboundResponseHeaders:ae}=yield new Promise((e=>se?se.on("response",(t=>{e({outboundResponseHeaders:t})})):e(!se&&ie?{outboundResponseHeaders:ie.headers}:{outboundResponseHeaders:{}})));let le=null;try{ae.location&&(le=new i.URL(ae.location.startsWith("/")?`${E.origin}${ae.location.replace(/^\/+/,"/")}`:ae.location.replace(/^file:\/+/,"file:///").replace(/^(http)(s?):\/+/,"$1$2://")))}catch(t){e.log(`location replacement error ${(null!==(b=ae.location)&&void 0!==b?b:"").slice(-13)}`,m.WARNING,g.ERROR_4)}const de=e.config.replaceResponseBodyUrls&&le?new i.URL(J(le.href,{direction:h.INBOUND,proxyHostnameAndPort:O,ssl:!!e.config.ssl,mapping:e.config.mapping}).replace(new RegExp(`^(${I.join("|")}|file:)/+`),"")):le,ce=le?de.origin!==le.origin||e.config.dontTranslateLocationHeader?de:`${w.origin}${de.href.substring(de.origin.length)}`:le,ue=se||ie,pe=null!=N?N:yield new Promise((e=>{let t=Buffer.alloc(0);ue?(ue.on("data",(e=>t=Buffer.concat([t,"string"==typeof e?Buffer.from(e):e]))),ue.on("end",(()=>{e(t)}))):e(t)})).then((n=>e.config.replaceResponseBodyUrls&&n.length?I.some((e=>E.protocol===e))?n:F(n,ae,{proxyHostnameAndPort:O,proxyHostname:t,key:k,direction:h.INBOUND,mapping:e.config.mapping,port:e.config.port,ssl:!!e.config.ssl}).catch((t=>(K(502,a,Buffer.from(B(t,e.mode,"stream",w,q))),Buffer.from("")))):n)),me=Object.assign(Object.assign({},Object.entries(Object.assign(Object.assign(Object.assign({},ae),e.config.replaceResponseBodyUrls?{"content-length":`${pe.byteLength}`}:{}),e.config.disableWebSecurity?{"content-security-policy":"report only","access-control-allow-headers":"*","access-control-allow-method":"*","access-control-allow-origin":"*"}:{})).filter((([e])=>!e.startsWith(":")&&!H.includes(e.toLowerCase()))).reduce(((e,[t,n])=>{const o=S.split("").map(((e,t)=>S.substring(t).startsWith(".")&&S.substring(t))).filter((e=>e)),s=[S].concat(o).reduce(((e,t)=>(Array.isArray(e)?e:[e]).map((e=>"string"==typeof e?e.replace(`Domain=${t}`,`Domain=${w.hostname}`):e))),n);return e[t]=(e[t]||[]).concat(s),e}),{})),ce?{location:[ce]}:{});try{Object.entries(me).forEach((([e,t])=>t&&a.setHeader(e,t)))}catch(e){}const ge=ae[":status"]||ie.statusCode||200;try{a.writeHead(ge,e.config.ssl?void 0:ie.statusMessage||"Status read from http/2",me)}catch(e){}pe?a.end(pe):a.end();const he=v();e.notifyLogsListeners({randomId:C,statusCode:ge,protocol:j?"HTTP/2":"HTTP1.1",duration:Math.floor(Number(he-te)/1e6),uniqueHash:X,response:e.logsListeners.some((e=>e.wantsResponseMessage))?{body:pe.toString("base64"),headers:ae,status:ge}:{}})}))};exports.serve=Y;const X=(e,t)=>{"EACCES"===t.code&&e.log("permission denied for this port",m.ERROR,g.NO),"EADDRINUSE"===t.code&&e.log("port is already used. NOT started",m.ERROR,g.ERROR_6)};exports.errorListener=X;const Z=e=>V({config:Object.assign(Object.assign({},P),e)},{});exports.start=Z;const V=(e,n)=>t(void 0,void 0,void 0,(function*(){var r,i,l,d,c,u,p,h,b,v,O,R,k,E,q;if(0===Object.keys(null!=n?n:{}).length&&e.server)return;if(n.pendingConfigSave)return void(0,a.writeFile)(y,JSON.stringify(n.pendingConfigSave,null,2),(t=>{var n,o;t?null===(n=e.log)||void 0===n||n.call(e,"config file NOT saved",m.ERROR,g.ERROR_4):null===(o=e.log)||void 0===o||o.call(e,"config file saved... will reload",m.INFO,g.COLORED)}));if(null===n.configListeners&&(yield Promise.all(e.configListeners.map((e=>new Promise((t=>e.stream.end(t))))))),null===n.logsListeners&&(yield Promise.all(e.logsListeners.map((e=>new Promise((t=>e.stream.end(t))))))),null===n.server){(yield Promise.race([new Promise((t=>e.server.close(t))).then((()=>!0)),new Promise((e=>setTimeout(e,5e3))).then((()=>!1))]))||e.log("error during restart (websockets ?)",m.WARNING,g.RESTART)}(null!==(r=e.configListeners)&&void 0!==r?r:[]).concat(null!==(i=e.logsListeners)&&void 0!==i?i:[]).filter((e=>e.stream.errored||e.stream.closed)).forEach((e=>e.stream.destroy()));const B=null!==(l=n.config)&&void 0!==l?l:e.config,N=null!==(c=null!==(d=n.mode)&&void 0!==d?d:e.mode)&&void 0!==c?c:f.PROXY,L=null!==(p=null!==(u=n.strictMock)&&void 0!==u?u:e.strictMock)&&void 0!==p&&p,j=null!==(b=null!==(h=n.mocks)&&void 0!==h?h:e.mocks)&&void 0!==b?b:new Map,I=(null===n.configListeners?[]:null!==(O=null!==(v=n.configListeners)&&void 0!==v?v:e.configListeners)&&void 0!==O?O:[]).filter((e=>!e.stream.errored&&!e.stream.closed)),P=(null===n.logsListeners?[]:null!==(k=null!==(R=n.logsListeners)&&void 0!==R?R:e.logsListeners)&&void 0!==k?k:[]).filter((e=>!e.stream.errored&&!e.stream.closed)),T=e;return Object.assign(T,{config:B,logsListeners:P,configListeners:I,mode:N,mocks:j,strictMock:L,configFileWatcher:void 0===T.configFileWatcher?(0,a.watchFile)(y,(()=>t(void 0,void 0,void 0,(function*(){return V(T,yield function(e){return t(this,void 0,void 0,(function*(){const t=e.config,n=yield C(!1);return isNaN(n.port)||n.port>65535||n.port<0?(e.log("port number invalid. Not refreshing",m.ERROR,g.PORT),{}):"object"!=typeof n.mapping?(e.log("mapping should be an object. Aborting",m.ERROR,g.ERROR_5),{}):(n.replaceRequestBodyUrls!==t.replaceRequestBodyUrls&&e.log(`request body url ${n.replaceRequestBodyUrls?"":"NO "}rewriting`,m.INFO,g.REWRITE),n.replaceResponseBodyUrls!==t.replaceResponseBodyUrls&&e.log(`response body url ${n.replaceResponseBodyUrls?"":"NO "}rewriting`,m.INFO,g.REWRITE),n.dontTranslateLocationHeader!==t.dontTranslateLocationHeader&&e.log(`response location header ${n.dontTranslateLocationHeader?"NO ":""}translation`,m.INFO,g.REWRITE),n.dontUseHttp2Downstream!==t.dontUseHttp2Downstream&&e.log(`http/2 ${n.dontUseHttp2Downstream?"de":""}activated downstream`,m.INFO,g.OUTBOUND),n.disableWebSecurity!==t.disableWebSecurity&&e.log(`web security ${n.disableWebSecurity?"de":""}activated`,m.INFO,g.SHIELD),n.websocket!==t.websocket&&e.log(`websocket ${n.websocket?"":"de"}activated`,m.INFO,g.WEBSOCKET),n.simpleLogs!==t.simpleLogs&&e.log("simple logs "+(n.simpleLogs?"on":"off"),m.INFO,g.COLORED),Object.keys(n.mapping).join("\n")!==Object.keys(t.mapping).join("\n")&&e.log(`${Object.keys(n.mapping).length.toString().padStart(5)} loaded mapping rules`,m.INFO,g.RULES),n.port!==t.port&&e.log(`port changed from ${t.port} to ${n.port}`,m.INFO,g.PORT),n.ssl&&!t.ssl&&e.log("ssl configuration added",m.INFO,g.INBOUND),!n.ssl&&t.ssl&&e.log("ssl configuration removed",m.INFO,g.INBOUND),n.port!==t.port||JSON.stringify(n.ssl)!==JSON.stringify(t.ssl)?(e.log("restarting server",m.INFO,g.RESTART),x.apply(Object.assign(Object.assign({},e),{config:n})),{config:n,server:null}):(x.apply(Object.assign(Object.assign({},e),{config:n})),{config:n}))}))}(T))})))):T.configFileWatcher,log:w.bind(T,T),notifyConfigListeners:S.bind(T),notifyLogsListeners:$.bind(T),quickStatus:x.bind(T),server:null!==n.server&&T.server||(null!==(q=null===(E=n.config)||void 0===E?void 0:E.port)&&void 0!==q?q:0)<0?null===n.server?null:T.server:(B.ssl?o.createSecureServer.bind(null,Object.assign(Object.assign({},B.ssl),{allowHTTP1:!0})):s.createServer)(((e,t)=>Y(T,e,t))).addListener("error",(e=>X(T,e))).addListener("listening",(()=>T.quickStatus())).on("upgrade",((e,t)=>V(T,G(T,e,t)))).listen(B.port)}),T}));exports.update=V;const Q=null!==(e=u.argv.map((e=>e.trim())).filter((e=>e&&!["ts-node","node","npx","npm","exec"].some((t=>e.includes(t)&&!e.match(/npm-cache/)&&!e.match(/_npx/)))))[0])&&void 0!==e?e:"",ee=Q.toLowerCase().replace(/[-_]/g,"").includes("localtraffic")&&!Q.match(/(.|-)?(test|spec)\.m?[jt]sx?$/),te=u.argv.some((e=>"--crash-test"===e));if(te){const e=Math.floor(40151+9e3*Math.random()),t=(t,n)=>(0,s.request)({hostname:"localhost",port:e,path:"/config/",method:"GET",headers:{Accept:"text/html"},timeout:500},(e=>n({response:e,state:t}))).on("error",(e=>n({error:e,state:t}))).end();V({config:Object.assign(Object.assign({},P),{port:e}),configFileWatcher:null},{}).then((e=>new Promise((n=>setTimeout(t.bind(null,e,n),1e3))))).then((({state:e,response:t})=>200!==t.statusCode?Promise.reject("Crash test has failed"):V(e,{config:{port:-1},server:null}))).then((e=>new Promise((n=>setTimeout(t.bind(null,e,n),1e3))))).then((({state:e,error:t})=>"ECONNREFUSED"!==t.code?Promise.reject("Server should have stopped"):w(e,"Crash test successful",m.INFO,g.COLORED))).then((()=>(0,u.exit)(0))).catch((()=>(0,u.exit)(1)))}!te&&ee&&C().then(Z);
2
+ "use strict";var e,t=this&&this.__awaiter||function(e,t,n,o){return new(n||(n=Promise))((function(r,s){function i(e){try{l(o.next(e))}catch(e){s(e)}}function a(e){try{l(o.throw(e))}catch(e){s(e)}}function l(e){var t;e.done?r(e.value):(t=e.value,t instanceof n?t:new n((function(e){e(t)}))).then(i,a)}l((o=o.apply(e,t||[])).next())}))},n=this&&this.__rest||function(e,t){var n={};for(var o in e)Object.prototype.hasOwnProperty.call(e,o)&&t.indexOf(o)<0&&(n[o]=e[o]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols){var r=0;for(o=Object.getOwnPropertySymbols(e);r<o.length;r++)t.indexOf(o[r])<0&&Object.prototype.propertyIsEnumerable.call(e,o[r])&&(n[o[r]]=e[o[r]])}return n};Object.defineProperty(exports,"__esModule",{value:!0}),exports.update=exports.serve=exports.determineMapping=exports.send=exports.cleanEntropy=exports.replaceTextUsingMapping=exports.replaceBody=exports.acknowledgeWebsocket=exports.readWebsocketBuffer=exports.createWebsocketBufferFrom=exports.websocketServe=exports.recorderHandler=exports.quickStatus=exports.errorListener=exports.load=exports.start=void 0;const o=require("http2"),r=require("http"),s=require("https"),i=require("url"),a=require("fs"),l=require("zlib"),c=require("path"),d=require("crypto"),u=require("process"),p=require("os");var m,g,h,f;!function(e){e[e.ERROR=124]="ERROR",e[e.INFO=93]="INFO",e[e.WARNING=172]="WARNING"}(m||(m={})),function(e){e.INBOUND="↘️ ",e.PORT="☎️ ",e.OUTBOUND="↗️ ",e.RULES="🔗",e.MOCKS="🌐",e.STRICT_MOCKS="🕸️\b ",e.AUTO_RECORD="📼",e.REWRITE="✒️ ",e.LOGS="📝",e.RESTART="🔄",e.WEBSOCKET="☄️ ",e.COLORED="✨",e.SHIELD="🛡️ ",e.NO="⛔",e.ERROR_1="❌",e.ERROR_2="⛈️ ",e.ERROR_3="☢️ ",e.ERROR_4="⁉️ ",e.ERROR_5="⚡",e.ERROR_6="☠️ "}(g||(g={})),function(e){e.INBOUND="INBOUND",e.OUTBOUND="OUTBOUND"}(h||(h={})),function(e){e.PROXY="proxy",e.MOCK="mock"}(f||(f={}));const b=(0,c.resolve)((0,p.homedir)(),".local-traffic.json"),y=(0,c.resolve)((0,u.cwd)(),u.argv.slice(-1)[0].endsWith(".json")?u.argv.slice(-1)[0]:b),v=()=>{var e,t;return null!==(t=null===(e=u.hrtime.bigint)||void 0===e?void 0:e.call(u.hrtime))&&void 0!==t?t:(()=>{const e=(0,u.hrtime)();return 1e3*e[0]+e[1]/1e6})()},O=e=>e===m.ERROR?"error":e===m.WARNING?"warning":"info",k=function(e,t,n,o){var r,s,i,a,l;const c=(null===(r=null==e?void 0:e.config)||void 0===r?void 0:r.simpleLogs)||(null===(s=null==e?void 0:e.logsListeners)||void 0===s?void 0:s.length)?t.replace(/⎸/g,"|").replace(/⎹/g,"|").replace(/\u001b\[[^m]*m/g,"").replace(new RegExp(g.INBOUND,"g"),"inbound:").replace(new RegExp(g.PORT,"g"),"port:").replace(new RegExp(g.OUTBOUND,"g"),"outbound:").replace(new RegExp(g.RULES,"g"),"rules:").replace(new RegExp(g.NO,"g"),"").replace(new RegExp(g.REWRITE,"g"),"+rewrite").replace(new RegExp(g.WEBSOCKET,"g"),"websocket").replace(new RegExp(g.SHIELD,"g"),"web-security").replace(new RegExp(g.MOCKS,"g"),"mocks").replace(new RegExp(g.STRICT_MOCKS,"g"),"mocks (strict)").replace(new RegExp(g.AUTO_RECORD,"g"),"auto record").replace(new RegExp(g.LOGS,"g"),"logs").replace(new RegExp(g.RESTART,"g"),"restart").replace(new RegExp(g.COLORED,"g"),"colored").replace(/\|+/g,"|"):t;console.log(`${(e=>{const t=new Date;return`${e?"":""}${`${t.getHours()}`.padStart(2,"0")}${e?":":":"}${`${t.getMinutes()}`.padStart(2,"0")}${e?":":":"}${`${t.getSeconds()}`.padStart(2,"0")}${e?"":""}`})(null===(i=null==e?void 0:e.config)||void 0===i?void 0:i.simpleLogs)} ${(null===(a=null==e?void 0:e.config)||void 0===a?void 0:a.simpleLogs)?c:n?`[48;5;${n}m⎸ ${u.stdout.isTTY&&o||""} ${t.padEnd(40)} ⎹`:t}${null===n&&e.mode===f.PROXY&&e.mockConfig.autoRecord&&!e.config.logAccessInTerminal?"\n":""}`),null===(l=null==e?void 0:e.notifyLogsListeners)||void 0===l||l.call(e,{event:c,level:O(n)})},R=(e,t)=>{const n=Array(4).fill(0).map((()=>t?Math.floor(256*Math.random()):0)),o=e.split("").map(((e,t)=>e.charCodeAt(0)^n[3&t])),r=e.length,s=t?128:0,i=e.length<126?Buffer.from(Uint8Array.from([129,s+r]).buffer):e.length<65535?Buffer.concat([Buffer.from(Uint8Array.from([129,126|s]).buffer),Buffer.from(Uint8Array.from([r>>8]).buffer),Buffer.from(Uint8Array.from([255&r]).buffer)]):Buffer.concat([Buffer.from(Uint8Array.from([129,127|s]).buffer),Buffer.concat(Number(r).toString(16).padStart(16,"0").match(/.{2}/g).map((e=>parseInt(e,16))).map((e=>Buffer.from(Uint8Array.from([e]).buffer))))]),a=Buffer.from(Int8Array.from(n).buffer),l=Buffer.from(Int8Array.from(o).buffer);return Buffer.concat(t?[i,a,l]:[i,l])};exports.createWebsocketBufferFrom=R;const w=(e,t)=>{var n;if(!t&&0==(1&e.readUInt8(0)))return{payloadLength:0,mask:[0,0,0,0],body:""};const o=t?0:e.readUInt8(1),r=o>>7,s=127&o,i=t?t.payloadLength:127!==s?s:e.readUInt8(2)<<8+e.readUInt8(3),a=t?t.mask:r?Array(4).fill(0).map(((t,n)=>e.readUInt8(n+4))):[0,0,0,0],l=t?0:r?8:4,c=Array(e.length-l).fill(0).map(((t,n)=>String.fromCharCode(e.readUInt8(n+l)^a[3&n]))).join("");return{payloadLength:i,mask:a,body:(null!==(n=null==t?void 0:t.body)&&void 0!==n?n:"").concat(c)}};exports.readWebsocketBuffer=w;const E=(e,t)=>{const n=(0,d.createHash)("sha1");n.update(t+"258EAFA5-E914-47DA-95CA-C5AB0DC85B11");const o=n.digest("base64");e.allowHalfOpen=!0,e.write(`HTTP/1.1 101 Switching Protocols\r\ndate: ${(new Date).toUTCString()}\r\nconnection: upgrade\r\nupgrade: websocket\r\nserver: local\r\nsec-websocket-accept: ${o}\r\n\r\n`)};exports.acknowledgeWebsocket=E;const S=function(e){return C(e,this.configListeners)},$=function(e){const{response:t}=e,o=n(e,["response"]);return Promise.all([C(e,this.logsListeners.filter((e=>e.wantsResponseMessage))),C(o,this.logsListeners.filter((e=>!e.wantsResponseMessage)))])},C=(e,t)=>{if(!t.length)return;const n=JSON.stringify(e),o=new Set(t.map((e=>e.wantsMask))),r=o.has(!1)&&R(n,!1),s=o.has(!0)&&R(n,!0),i=e=>{e.stream.errored&&e.stream.destroy()};t.forEach((e=>{e.stream.closed||e.stream.errored||(e.wantsMask?e.stream.write(s,"ascii",(()=>i(e))):e.stream.write(r,"ascii",(()=>i(e))))}))},x=function(){this.log(`⎸${g.PORT} ${this.config.port.toString().padStart(5)} ⎸${g.OUTBOUND} ${this.config.dontUseHttp2Downstream?"H1.1":"H/2 "}${this.config.replaceRequestBodyUrls?g.REWRITE:" "}⎹⎸${g.INBOUND} ${this.config.ssl?"H/2 ":"H1.1"}${this.config.replaceResponseBodyUrls?g.REWRITE:" "}⎹⎸${this.mode===f.PROXY&&this.mockConfig.autoRecord?`${g.AUTO_RECORD}${this.mockConfig.mocks.size.toString().padStart(3)}`:this.mode===f.PROXY?`${g.RULES}${Object.keys(this.config.mapping).length.toString().padStart(3)}`:`${this.mockConfig.strict?g.STRICT_MOCKS:g.MOCKS}${this.mockConfig.mocks.size.toString().padStart(3)}`}⎹⎸${this.config.websocket?g.WEBSOCKET:g.NO}⎹⎸${this.config.simpleLogs?g.NO:g.COLORED}⎹⎸${this.config.disableWebSecurity?g.NO:g.SHIELD}⎹`),this.notifyConfigListeners(this.config)};exports.quickStatus=x;const q=(e,t,n,o,r)=>`${D(128163,"error",e.message)}\n<p>An error happened while trying to proxy a remote exchange</p>\n<div class="alert alert-warning" role="alert">\n&#x24D8;&nbsp;This is not an error from the downstream service.\n</div>\n<div class="alert alert-danger" role="alert">\n<pre><code>${e.stack||`<i>${e.name} : ${e.message}</i>`}${e.errno?`<br/>(code : ${e.errno})`:""}</code></pre>\n</div>\nMore information about the request :\n<table class="table">\n<tbody>\n<tr>\n<td>server mode</td>\n<td>${t}</td>\n</tr>\n<tr>\n<td>phase</td>\n<td>${n}</td>\n</tr>\n<tr>\n<td>requested URL</td>\n<td>${o}</td>\n</tr>\n<tr>\n<td>downstream URL</td>\n<td>${r||"&lt;no-target-url&gt;"}</td>\n</tr>\n</tbody>\n</table>\n</div></body></html>`,B=(e,t,n)=>`<table id="table-access" class="table table-striped" style="display: block; width: 100%; overflow-y: auto">\n<thead>\n<tr>\n<th scope="col"${!0===n.captureResponseBody?' style="min-width: 120px"':""}>...</th>\n<th scope="col">Date</th>\n<th scope="col">Level</th>\n<th scope="col">Protocol</th>\n<th scope="col">Method</th>\n<th scope="col">Status</th>\n<th scope="col">Duration</th>\n<th scope="col">Upstream Path</th>\n<th scope="col">Downstream Path</th>\n</tr>\n</thead>\n<tbody id="access">\n</tbody>\n</table>\n<table id="table-proxy" class="table table-striped" style="display: none; width: 100%; overflow-y: auto">\n<thead>\n<tr>\n<th scope="col">Date</th>\n<th scope="col">Level</th>\n<th scope="col">Message</th>\n</tr>\n</thead>\n<tbody id="proxy">\n</tbody>\n</table>\n<script type="text/javascript">\nfunction start() {\ndocument.getElementById('table-access').style.height =\n(document.documentElement.clientHeight - 150) + 'px';\nconst socket = new WebSocket("ws${t.ssl?"s":""}://${e}/local-traffic-logs${n.captureResponseBody?"?wantsResponseMessage=true":""}");\nsocket.onmessage = function(event) {\nlet data = event.data\nlet uniqueHash;\ntry {\nconst { uniqueHash: uniqueHash1, ...data1 } = JSON.parse(event.data);\ndata = data1;\nuniqueHash = uniqueHash1;\n} catch(e) { }\nif (document.getElementById('mock-mode')?.checked) return;\nif (${!0===n.captureResponseBody} && \ndata?.downstreamPath?.startsWith('recorder://') &&\n!data?.upstreamPath?.endsWith('?forceLogInRecorderPage=true'))\nreturn;\nconst time = new Date().toISOString().split('T')[1].replace('Z', '');\nconst actions = getActionsHtmlText(uniqueHash, data.response);\nif(data.statusCode && uniqueHash) {\nconst color = getColorFromStatusCode(data.statusCode);\nconst statusCodeColumn = document.querySelector("#event-" + data.randomId + " .statusCode");\nif (statusCodeColumn)\nstatusCodeColumn.innerHTML = '<span class="badge bg-' + color + '">' + data.statusCode + '</span>';\n\nconst durationColumn = document.querySelector("#event-" + data.randomId + " .duration");\nif (durationColumn) {\nconst duration = data.duration > 10000 ? Math.floor(data.duration / 1000) + 's' :\ndata.duration + 'ms';\ndurationColumn.innerHTML = duration;\n}\n\nconst protocolColumn = document.querySelector("#event-" + data.randomId + " .protocol");\nif (protocolColumn) {\nprotocolColumn.innerHTML = data.protocol;\n}\n\nconst replayColumn = document.querySelector("#event-" + data.randomId + " .replay");\nif (replayColumn) {\nreplayColumn.innerHTML = actions;\n}\n} else if (uniqueHash) {\naddNewRequest(data.randomId, actions, time, data.level, data.protocol, data.method, \n'<span class="badge bg-secondary">...</span>', '&#x23F1;',\ndata.upstreamPath, data.downstreamPath);\n} else if(data.event) {\ndocument.getElementById("proxy")\n.insertAdjacentHTML('afterbegin', '<tr><td scope="col">' + time + '</td>' +\n'<td scope="col">' + (data.level || 'info')+ '</td>' + \n'<td scope="col">' + data.event + '</td></tr>');\n}\ncleanup();\n};\nsocket.onerror = function(error) {\nconsole.log(\`[error] \${JSON.stringify(error)}\`);\nsetTimeout(start, 5000);\n};\n};\nfunction show(id) {\n[...document.querySelectorAll('table')].forEach((table, index) => {\ntable.style.display = index === id ? 'block': 'none'\n});\n[...document.querySelectorAll('.navbar-nav .nav-item .nav-link')].forEach((link, index) => {\nif (index === id) { link.classList.add('active') } else link.classList.remove('active');\n});\n}\nfunction remove(event) {\nevent.target.closest('tr').remove();\nif (window.updateState) window.updateState();\n}\nfunction cleanup() {\nconst currentLimit = parseInt(document.getElementById('limit').value)\nfor (let table of ['access', 'proxy']) {\nwhile (currentLimit && document.getElementById(table).childNodes.length && \ndocument.getElementById(table).childNodes.length > currentLimit) {\n[...document.getElementById(table).childNodes].slice(-1)[0].remove();\n}\n}\n}\nfunction replay(event) {\nconst uniqueHash = event.target.dataset.uniquehash;\nconst { method, url, headers, body } = JSON.parse(atob(uniqueHash));\nfetch(url, {\nmethod,\nheaders,\nbody: !body || !body.length ? undefined : atob(body)\n});\n}\nfunction getActionsHtmlText(uniqueHash, response) {\nconst edit = ${!0===n.captureResponseBody} && uniqueHash\n? '<button data-response="' + (response ?? "") +\n'" data-uniquehash="' + uniqueHash + \n'" data-bs-toggle="modal" data-bs-target="#edit-request" type="button" ' +\n'class="btn btn-primary">&#x1F4DD;</button>'\n: ''\nconst remove = ${!0===n.captureResponseBody} && uniqueHash\n? '<button onclick="javascript:remove(event)" type="button" ' +\n'class="btn btn-primary">&#x274C;</button>'\n: ''\nconst replay = ${!1===n.captureResponseBody} && uniqueHash ? '<button data-response="' + \nbtoa(JSON.stringify(response ?? {})) +\n'" data-uniquehash="' + uniqueHash + '" onclick="javascript:replay(event)" ' +\n'type="button" class="btn btn-primary">&#x1F501;</button>' : '';\nreturn edit + replay + remove\n}\nfunction addNewRequest(\nrandomId, actions, time, level, protocol, method, \nstatusCode, duration, upstreamPath, downstreamPath\n) {\ndocument.getElementById("access")\n.insertAdjacentHTML('afterbegin', '<tr id="event-' + randomId + '">' +\n'<td scope="col" class="replay">' + actions + '</td>' +\n'<td scope="col">' + time + '</td>' +\n'<td scope="col">' + (level || 'info')+ '</td>' + \n'<td scope="col" class="protocol">' + protocol + '</td>' + \n'<td scope="col" class="method">' + method + '</td>' + \n'<td scope="col" class="statusCode">' + statusCode + '</td>' +\n'<td scope="col" class="duration text-end">' + duration + '</td>' +\n'<td scope="col" class="upstream-path">' + upstreamPath + '</td>' + \n'<td scope="col">' + downstreamPath + '</td>' + \n'</tr>');\n}\nfunction getColorFromStatusCode(statusCode) {\nreturn Math.floor(statusCode / 100) === 1 ? "info" :\nMath.floor(statusCode / 100) === 2 ? "success" :\nMath.floor(statusCode / 100) === 3 ? "dark" :\nMath.floor(statusCode / 100) === 4 ? "warning" :\nMath.floor(statusCode / 100) === 5 ? "danger" :\n"secondary";\n}\nwindow.addEventListener("DOMContentLoaded", start);\n<\/script>`,I=(e,t,n)=>{let o={};try{o=JSON.parse(t.toString("ascii"))}catch(e){}if("object"!=typeof o||Object.keys(o).filter((e=>!["strict","mode","mocks","autoRecord"].includes(e))).length||!Array.isArray(o.mocks)&&void 0!==o.mocks)return void e.log("invalid mocks update received",m.WARNING,g.MOCKS);const{mocks:r,mode:s,strict:i,autoRecord:a}=o,l=r?new Map(r.map((({response:e,uniqueHash:t})=>[K(t),e]))):null,c=s!==e.mode&&s===f.PROXY,d=(!c||!0===a)&&(null!=a?a:e.mockConfig.autoRecord),u=void 0!==d&&d!=e.mockConfig.autoRecord,p=s!==e.mode&&s===f.MOCK||null!==l&&e.mockConfig.mocks.size!==l.size,h=null!=i?i:e.mockConfig.strict,b=null!=s?s:e.mode,y=!!h!=!!e.mockConfig.strict,v=n;c&&e.log(`${Object.keys(e.config.mapping).length.toString().padStart(5)} loaded mapping rules`,m.INFO,g.RULES),p&&e.log(`${(null!=l?l:e.mockConfig.mocks).size.toString().padStart(5)} loaded mocks`,m.INFO,h?g.STRICT_MOCKS:g.MOCKS),y&&e.log(`mocks strict mode : ${null!=h?h:e.mockConfig.strict}`,m.INFO,h?g.STRICT_MOCKS:g.MOCKS),u&&e.log(`mocks auto-record : ${d}`,m.INFO,b===f.PROXY?g.AUTO_RECORD:h?g.STRICT_MOCKS:g.MOCKS),Q(e,v?{mode:b,mockConfig:{autoRecord:!1,strict:h,mocks:new Map}}:{mode:b,mockConfig:{strict:h,autoRecord:d,mocks:null!=l?l:e.mockConfig.mocks}}),(c||p||y||v)&&e.quickStatus()};exports.recorderHandler=I;const T={logs:(e,t)=>F(`${D(128250,"logs","")}\n<nav class="navbar navbar-expand-lg navbar-dark bg-primary nav-fill">\n<div class="container-fluid">\n<ul class="navbar-nav">\n<li class="nav-item">\n<a class="nav-link active" aria-current="page" href="javascript:show(0)">Access</a>\n</li>\n<li class="nav-item">\n<a class="nav-link" href="javascript:show(1)">Proxy</a>\n</li>\n</ul>\n<span class="navbar-text">\nLimit : <select id="limit" onchange="javascript:cleanup()"><option value="-1">0 (clear)</option><option value="10">10</option>\n<option value="50">50</option><option value="100">100</option><option value="200">200</option>\n<option selected="selected" value="500">500</option><option value="0">Infinity (discouraged)</option>\n</select> rows\n</span>\n</div>\n</nav>\n${B(e,t.config,{captureResponseBody:!1})}\n</body></html>`),config:(e,t)=>F(`${D(127899,"config","")}\n<link href="${H}jsoneditor/dist/jsoneditor.min.css" rel="stylesheet" type="text/css">\n<script src="${H}jsoneditor/dist/jsoneditor.min.js"><\/script>\n<script src="${H}node-forge/dist/forge.min.js"><\/script>\n<div id="ssl-modal" class="modal" tabindex="-1" role="dialog">\n<div class="modal-dialog" role="document">\n<div class="modal-content">\n<div class="modal-header">\n<h5 class="modal-title">SSL keypair generation in progress</h5>\n</div>\n<div class="modal-body">\n<p>Wait a few seconds or move your mouse to increase the entropy.</p>\n</div>\n</div>\n</div>\n</div>\n<div id="jsoneditor" style="width: 400px; height: 400px;"></div>\n<script>\n// create the editor\nconst container = document.getElementById("jsoneditor")\nconst options = {mode: "code", allowSchemaSuggestions: true, schema: {\ntype: "object",\nproperties: {\n${Object.entries(Object.assign(Object.assign({},j),{ssl:{cert:"",key:""}})).map((([e,t])=>`${e}: {type: "${"number"==typeof t?"integer":"string"==typeof t?"string":"boolean"==typeof t?"boolean":"object"}"}`)).join(",\n")}\n},\nrequired: [],\nadditionalProperties: false\n}}\n\nfunction save() {\nsocket.send(JSON.stringify(editor.get()));\n}\n\nfunction generateSslCertificate() {\nconst sslModal = new bootstrap.Modal(document.getElementById('ssl-modal'), {});\nsslModal.show()\nsetTimeout(function() {\nconst keypair = forge.pki.rsa.generateKeyPair(2048);\nconst certificate = forge.pki.createCertificate();\nconst now = new Date();\nconst fiveYears = new Date(new Date(now).setFullYear(now.getFullYear() + 5));\nObject.assign(certificate, {\npublicKey: keypair.publicKey,\nserialNumber: "01",\nvalidity: {\nnotBefore: now,\nnotAfter: fiveYears,\n},\n});\ncertificate.sign(keypair.privateKey, forge.md.sha256.create());\nconst key = forge.pki.privateKeyToPem(keypair.privateKey);\nconst cert = forge.pki.certificateToPem(certificate);\nconst existingConfig = editor.get();\neditor.set({ ...existingConfig, ssl: { key, cert },\nport: parseInt(("" + existingConfig.port).replace(/(80|[0-9])80$/, '443'))\n});\nsslModal.hide();\n}, 100);\n}\n\nconst editor = new JSONEditor(container, options);\nlet socket;\nconst initialJson = ${JSON.stringify(t.config)}\neditor.set(initialJson)\neditor.validate();\neditor.aceEditor.commands.addCommand({\nname: 'save',\nbindKey: {win: 'Ctrl-S', mac: 'Command-S'},\nexec: save,\n});\n\nwindow.addEventListener("DOMContentLoaded", function() {\ndocument.getElementById('jsoneditor').style.height =\n(document.documentElement.clientHeight - 150) + 'px';\ndocument.getElementById('jsoneditor').style.width =\nparseInt(window.getComputedStyle(\ndocument.querySelector('.container')).maxWidth) + 'px';\nconst sslButton = document.createElement('button');\nsslButton.addEventListener("click", generateSslCertificate);\nsslButton.type="button";\nsslButton.classList.add("btn");\nsslButton.classList.add("btn-primary");\nsslButton.innerHTML="&#x1F512;";\ndocument.querySelector('.jsoneditor-menu')\n.appendChild(sslButton);\nconst saveButton = document.createElement('button');\nsaveButton.addEventListener("click", save);\nsaveButton.type="button";\nsaveButton.classList.add("btn");\nsaveButton.classList.add("btn-primary");\nsaveButton.innerHTML="&#x1F4BE;";\ndocument.querySelector('.jsoneditor-menu')\n.appendChild(saveButton);\nsocket = new WebSocket("ws${t.config.ssl?"s":""}://${e}/local-traffic-config");\nsocket.onmessage = function(event) {\neditor.set(JSON.parse(event.data))\neditor.validate()\n}\n});\n<\/script>\n</body></html>`),recorder:(e,t,n)=>{var o,r,s,i,a,l,c,d,u;return(null===(o=n.url)||void 0===o?void 0:o.endsWith("?forceLogInRecorderPage=true"))?F('{"ping":"pong"}',{contentType:"application/json; charset=utf-8"}):"GET"===n.method&&(null===(s=null===(r=n.headers)||void 0===r?void 0:r["content-type"])||void 0===s?void 0:s.includes("application/json"))?F(JSON.stringify(Object.assign(Object.assign({},t.mockConfig),{mocks:[...t.mockConfig.mocks.entries()].map((([e,t])=>({uniqueHash:e,response:t})))})),{contentType:"application/json; charset=utf-8"}):["PUT","POST","DELETE"].includes(n.method)?F('{"status": "acknowledged"}',{contentType:"application/json; charset=utf-8",onOutboundWrite:e=>I(t,e,"DELETE"===n.method)}):F(`${D(9210,"recorder","")}\n<link href="${H}jsoneditor/dist/jsoneditor.min.css" rel="stylesheet" type="text/css">\n<script src="${H}jsoneditor/dist/jsoneditor.min.js"><\/script>\n<script src="${H}pako/dist/pako.min.js"><\/script>\n<form>\n<div id="commands"${t.mockConfig.autoRecord?' style="filter:blur(8px)"':""}>\n<span>Mode : </span>\n<div class="btn-group" role="group" aria-label="Server Mode">\n<input type="radio" class="btn-check" name="server-mode" id="record-mode" autocomplete="off"${t.mode===f.PROXY?" checked":""}>\n<label class="btn btn-outline-primary" for="record-mode">&#9210; Record</label>\n<input type="radio" class="btn-check" name="server-mode" id="mock-mode" autocomplete="off"${t.mode===f.MOCK?" checked":""}>\n<label class="btn btn-outline-primary" for="mock-mode">&#x1F310; Mock</label>\n</div>\n<span>Actions : </span>\n<button type="button" class="btn btn-light" id="add-mock">&#x2795; Mock from dummy request</button>\n<button type="button" class="btn btn-light" id="upload-mocks">&#x1F4E5; Upload mocks</button>\n<button type="button" class="btn btn-light" id="download-mocks">&#x1F4E6; Download mocks</button>\n<button type="button" class="btn btn-light" id="delete-mocks">&#x1F5D1; Delete mocks</button>\n</div>\n<div class="row">\n<div class="col-lg" style="max-width: 200px">\n<div class="form-check form-switch" id="strict-mock-mode-form-control">\n<input class="form-check-input" type="checkbox" id="strict-mock-mode"${t.mockConfig.strict?' checked="checked"':""}>\n<label class="form-check-label" for="strict-mock-mode">Strict mock mode</label>\n</div>\n</div>\n<div class="col-lg" style="max-width: 200px">\n<div class="form-check form-switch">\n<input class="form-check-input" type="checkbox" id="auto-record-mode"${t.mockConfig.autoRecord?' checked="checked"':""}>\n<label class="form-check-label" for="auto-record-mode">Auto record mode</label>\n</div>\n</div>\n<div class="col-lg">&nbsp;</div>\n</div>\n<input type="hidden" id="limit" value="0"/>\n<div class="modal fade" id="edit-request" tabindex="-1" \naria-labelledby="edit-request-label" aria-hidden="true">\n<div class="modal-dialog" style="max-width: 900px">\n<div class="modal-content">\n<div class="modal-header">\n<h1 class="modal-title fs-5" id="edit-request-label">Edit request to /</h1>\n<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>\n</div>\n<div class="modal-body">\n<div class="container">\n<div class="row">\n<div class="col-lg">\n<h2>Request :</h2>\n<div id="uniqueHash-editor" style="width: 400px; height: 400px;"></div>\n</div>\n<div class="col-lg">\n<h2>Response : </h2>\n<div id="response-editor" style="width: 400px; height: 400px;"></div>\n</div>\n</div>\n</div>\n</div>\n<div class="modal-footer">\n<button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>\n<button type="button" class="btn btn-primary" onclick="javascript:saveRequest()">Save changes</button>\n</div>\n</div>\n</div>\n</div>\n<script>\nconst xmlOrJsonPrologsInBase64 = [\n"eyJ","PD94bWw=","PCFET0NUWVBF","PCFkb2N0eXBl","PGh0bWw","PEhUTUw","H4sIAAAAAAAA", "W3tc"\n];\nfunction getMocksData () {\nreturn JSON.stringify(\n[...document.querySelectorAll('button[data-uniqueHash]')].map(button => ({\nresponse: button.attributes['data-response']?.value,\nuniqueHash: button.attributes['data-uniqueHash']?.value}))\n)\n}\nfunction updateState () {\nfetch("http${t.config.ssl?"s":""}://${e}${null!==(l=null===(a=Object.entries(null!==(i=t.config.mapping)&&void 0!==i?i:{}).find((([e,t])=>{var n;return null===(n=null==t?void 0:t.toString())||void 0===n?void 0:n.startsWith("recorder:")})))||void 0===a?void 0:a[0])&&void 0!==l?l:"/recorder/"}", {\nmethod: 'PUT',\nheaders: { 'Content-Type': 'application/json' },\nbody: '{"strict":' + document.getElementById('strict-mock-mode').checked +\n',"autoRecord":' + document.getElementById('auto-record-mode').checked +\n',"mode":"' + \n(document.getElementById('mock-mode').checked ? "mock" : "proxy") + '"' +\n',"mocks":' + getMocksData() + '}'\n})\n}\nfunction loadMocks(mocksHashes) {\nconst time = new Date().toISOString().split('T')[1].replace('Z', '');\nlet mocks = [];\ntry {\nmocks = mocksHashes.map(mock => ({...mock, \nrequest: JSON.parse(atob(mock.uniqueHash)),\nresponse: JSON.parse(atob(mock.response))\n}));\n} catch(e) { }\nmocks.forEach(mock => {\nconst randomId = window.crypto.randomUUID();\nconst actions = getActionsHtmlText(mock.uniqueHash, mock.response);\naddNewRequest(randomId, actions, time, 'info', 'HTTP/2', mock.request.method, \n'<span class="badge bg-' + \ngetColorFromStatusCode(mock.response.status) + '">' + \nmock.response.status + \n'</span>', \n'0ms', mock.request.url, \n'N/A');\n});\n}\ndocument.getElementById('add-mock').addEventListener('click', () => {\nconst iframe = document.createElement('iframe');\niframe.style.display = 'none';\niframe.onload = function() { iframe.parentNode.removeChild(iframe); };\niframe.src = "http${t.config.ssl?"s":""}://${e}${null!==(u=null===(d=Object.entries(null!==(c=t.config.mapping)&&void 0!==c?c:{}).find((([e,t])=>{var n;return null===(n=null==t?void 0:t.toString())||void 0===n?void 0:n.startsWith("recorder:")})))||void 0===d?void 0:d[0])&&void 0!==u?u:"/recorder/"}?forceLogInRecorderPage=true";\ndocument.body.appendChild(iframe);\n});\ndocument.getElementById('upload-mocks').addEventListener('click', () => {\nconst time = new Date().toISOString().split('T')[1].replace('Z', '');\nconst fileInput = document.createElement('input');\nfileInput.type = "file";\nfileInput.multiple = "multiple";\nfileInput.onchange = function() {\nconst fileReader = new FileReader();\n[...fileInput.files].reduce((promise, file) =>\npromise.then(result => new Promise(resolve => {\nfileReader.readAsText(file);\nfileReader.onload = function(){\nresolve(result.concat(fileReader.result));\n};\n})), Promise.resolve([]))\n.then(files => files.flatMap(file => JSON.parse(file)))\n.catch(e => [])\n.then(mocks => loadMocks(mocks))\n.then(() => updateState());\n}\nfileInput.click();\n});\ndocument.getElementById('download-mocks').addEventListener('click', () => {\nconst link = document.createElement('a');\nlink.href = URL.createObjectURL(new Blob([getMocksData()], {\ntype: "application/json",\n}));\nlink.download = "mocks-" + new Date().toISOString() + ".json";\nlink.click();\nURL.revokeObjectURL(link.href);\n})\ndocument.getElementById('delete-mocks').addEventListener('click', () => {\ndocument.getElementById('limit').value = -1;\ncleanup();\nupdateState();\ndocument.getElementById('limit').value = 0;\n})\ndocument.getElementById('record-mode').addEventListener('change', () => {\ndocument.getElementById('limit').value = 0;\ncleanup();\nupdateState();\n})\ndocument.getElementById('mock-mode').addEventListener('change', () => {\nupdateState();\n})\ndocument.getElementById('auto-record-mode').addEventListener('change', (e) => { \nupdateState();\ndocument.getElementById('table-access').style.filter = \ndocument.getElementById('auto-record-mode').checked ? 'blur(8px)' : 'blur(0px)';\ndocument.getElementById('commands').style.filter = \ndocument.getElementById('auto-record-mode').checked ? 'blur(8px)' : 'blur(0px)';\ndocument.getElementById('alert-about-auto-record-mode').style.display = \ndocument.getElementById('auto-record-mode').checked ? 'block' : 'none';\ndocument.getElementById('strict-mock-mode-form-control').style.filter = \ndocument.getElementById('auto-record-mode').checked ? 'blur(8px)' : 'blur(0px)';\n\n})\ndocument.getElementById('strict-mock-mode').addEventListener('change', (e) => { \nupdateState();\n})\nfunction saveRequest () {\n$('#edit-request').modal("hide");\n\nconst requestBeingEdited = window.requestBeingEdited;\nlet request = uniqueHashEditor.get();\nlet response = responseEditor.get();\nif (typeof request.body === "object") {\nrequest.body = JSON.stringify(request.body);\n}\nif (typeof response.body === "object") {\nresponse.body = JSON.stringify(response.body);\n}\nconst oldRequest = JSON.parse(atob(requestBeingEdited.attributes['data-uniqueHash'].value));\nconst oldResponse = JSON.parse(atob(requestBeingEdited.attributes['data-response'].value));\nconst requestProlog = requestBeingEdited.attributes['data-requestProlog']?.value;\nconst responseProlog = requestBeingEdited.attributes['data-responseProlog']?.value;\nconst requestPrologHasChanged = request.body.substring(0, 10) !== oldRequest.body.substring(0, 10);\nconst responsePrologHasChanged = response.body.substring(0, 10) !== response.body.substring(0, 10);\nif (requestProlog === "H4sIAAAAAAAA" && !requestPrologHasChanged) {\nrequest.body =\nbtoa([...pako.gzip(request.body)].map(e => String.fromCharCode(e)).join(""));\n} else if ((requestProlog === null || !request.body.startsWith(requestProlog ?? "")) && \nrequest.body.substring(0, 10) !== oldRequest.body.substring(0, 10)) {\nrequest.body = btoa(request.body);\n}\nif (responseProlog === "H4sIAAAAAAAA" && !responsePrologHasChanged) {\nresponse.body =\nbtoa([...pako.gzip(response.body)].map(e => String.fromCharCode(e)).join(""));\n} else if ((responseProlog === null || !response.body.startsWith(responseProlog ?? "")) && \nresponse.body.substring(0, 10) !== oldResponse.body.substring(0, 10)) {\nresponse.body = btoa(response.body);\n}\nrequest = btoa(JSON.stringify(request));\nresponse = btoa(JSON.stringify(response));\nrequestBeingEdited.setAttribute('data-uniqueHash', request);\nrequestBeingEdited.setAttribute('data-response', response);\nconst row = requestBeingEdited.closest('tr');\nrow.querySelector("td.method").innerHTML = uniqueHashEditor.get().method;\nrow.querySelector("td.upstream-path").innerHTML = uniqueHashEditor.get().url;\nwindow.requestBeingEdited = undefined;\nupdateState();\n}\ndocument.getElementById('edit-request').addEventListener('show.bs.modal', event => {\nconst request = JSON.parse(atob(event.relatedTarget.attributes['data-uniqueHash'].value));\nconst response = JSON.parse(atob(event.relatedTarget.attributes['data-response'].value));\nconst requestProlog = xmlOrJsonPrologsInBase64.find(prolog => request.body?.startsWith(prolog));\nconst responseProlog = xmlOrJsonPrologsInBase64.find(prolog => response.body?.startsWith(prolog));\nif (requestProlog) {\nevent.relatedTarget.setAttribute('data-requestProlog', requestProlog);\nrequest.body = request.body.startsWith("H4sIAAAAAAAA") \n? pako.ungzip(new Uint8Array(atob(request.body).split("").map(e => e.charCodeAt(0))), {to: "string"})\n: atob(request.body);\nrequest.body = request.body.startsWith("{\\"") || request.body.startsWith("[{\\"")\n? JSON.parse(request.body) : request.body;\n}\nif (responseProlog) {\nevent.relatedTarget.setAttribute('data-responseProlog', responseProlog);\nresponse.body = response.body.startsWith("H4sIAAAAAAAA") \n? pako.ungzip(new Uint8Array(atob(response.body).split("").map(e => e.charCodeAt(0))), {to: "string"})\n: atob(response.body);\nresponse.body = response.body.startsWith("{\\"") || response.body.startsWith("[{\\"")\n? JSON.parse(response.body) : response.body;\n}\nwindow.requestBeingEdited = event.relatedTarget;\nwindow.uniqueHashEditor.set(request);\nwindow.responseEditor.set(response);\ndocument.getElementById('edit-request-label').innerText = "Edit request to " + request.url;\n})\n\nsetTimeout(() => {\nloadMocks(${JSON.stringify([...t.mockConfig.mocks.entries()].map((([e,t])=>({uniqueHash:e,response:t}))))});\nwindow.uniqueHashEditor = new JSONEditor(document.getElementById("uniqueHash-editor"), {\nmode: "code", allowSchemaSuggestions: true, schema: {\ntype: "object",\nproperties: {\nmethod: {type: "string"},\nurl: {type: "string"},\nbody: {oneOf: [{type:"string"},{type:"object"}]},\nheaders: {type: "object"},\n},\nrequired: [],\nadditionalProperties: false\n}});\nwindow.responseEditor = new JSONEditor(document.getElementById("response-editor"), {\nmode: "code", allowSchemaSuggestions: true, schema: {\ntype: "object",\nproperties: {\nbody: {oneOf: [{type:"string"},{type:"object"}]},\nheaders: {type: "object"},\nstatus: {type: "integer"}\n},\nrequired: [],\nadditionalProperties: false\n}});\n${t.mockConfig.autoRecord?";document.getElementById('strict-mock-mode-form-control').style.filter='blur(8px)';;document.getElementById('table-access').style.filter='blur(8px)';":""}\ndocument.forms[0].reset();\n}, 10)\n<\/script>\n</form>\n<div class="alert alert-warning" role="alert"\nstyle="display:${t.mockConfig.autoRecord?"block":"none"};left:20%;right:20%;position:absolute;z-index:1;" id="alert-about-auto-record-mode">\n&#x24D8;&nbsp;Auto-record mode and recorder webapp are known to be mutually exclusive.\n<br/><br/>Changing the mock on both sides is somehow hard to sort out.\n<br/>This is triggering concurrent modifications in the mock config.\n<hr/>\nHere is what you can do :\n<ul>\n<li>If you want to record mocks using a frontend app, turn off the auto-record mode.</li>\n<li>If you want to record mocks with the recorder API only, close this app.</li>\n</ul>\n</div>\n${B(e,t.config,{captureResponseBody:!0})}\n</body>\n</html>`)}},N=Object.keys(T),L=N.map((e=>`${e}:`)),j={mapping:Object.assign({},...N.map((e=>({[`/${e}/`]:`${e}://`})))),port:8080,replaceRequestBodyUrls:!1,replaceResponseBodyUrls:!1,dontUseHttp2Downstream:!1,dontTranslateLocationHeader:!1,logAccessInTerminal:!1,simpleLogs:!1,websocket:!0,disableWebSecurity:!1,connectTimeout:3e3,socketTimeout:3e3},A=(e=!0)=>t(void 0,void 0,void 0,(function*(){return new Promise((t=>(0,a.readFile)(y,((n,o)=>{n&&!e&&k(null,"config error. Using default value",m.ERROR,g.ERROR_1);let r=null;try{r=Object.assign({},j,JSON.parse((o||"{}").toString()))}catch(e){return k({config:r},"config syntax incorrect, aborting",m.ERROR,g.ERROR_2),r=null!=r?r:Object.assign({},j),void t(r)}r.mapping[""]||k({config:r},'default mapping "" not provided.',m.WARNING,g.ERROR_3),n&&"ENOENT"===n.code&&e&&y===b?(0,a.writeFile)(y,JSON.stringify(j,null,2),(e=>{e?k(null,"config file NOT created",m.ERROR,g.ERROR_4):k(null,"config file created",m.INFO,g.COLORED),t(r)})):t(r)}))))}));exports.load=A;const P=e=>""==e?"":(0,c.normalize)(e).replace(/\\/g,"/"),H="https://cdn.jsdelivr.net/npm/",U=["host","connection","keep-alive","upgrade","transfer-encoding","upgrade-insecure-requests","proxy-connection"],D=(e,t,n)=>`<!doctype html>\n<html lang="en">\n<head>\n<title>&#x${e.toString(16)}; local-traffic ${t} | ${n}</title>\n<link href="${H}bootstrap/dist/css/bootstrap.min.css" rel="stylesheet"/>\n<script src="${H}jquery/dist/jquery.min.js"><\/script>\n<script src="${H}bootstrap/dist/js/bootstrap.bundle.min.js"><\/script>\n</head>\n<body><div class="container"><h1>&#x${e.toString(16)}; local-traffic ${t}</h1>\n<br/>`,M=({response:e})=>({error:null,data:null,hasRun:!1,run:function(){return this.hasRun?Promise.resolve():new Promise((t=>{try{this.data=JSON.parse(Buffer.from(e,"base64").toString("utf-8"))}catch(e){this.data={}}t(void 0)}))},events:{},on:function(e,t){return this.events[e]=t,this.run().then((()=>{var t;"response"===e&&this.events.response(Object.assign(Object.assign({},this.data.headers),{"X-LocalTraffic-Mock":"1"}),this.data.status),"data"===e&&this.data&&(this.events.data(Buffer.from(null!==(t=this.data.body)&&void 0!==t?t:"","base64")),this.events.end()),"error"===e&&this.error&&this.events.error(this.error)})),this},end:function(){return this},request:function(){return this},write:function(){return this}}),W=e=>{const t=(0,c.resolve)("/",e.hostname,...e.pathname.replace(/[?#].*$/,"").replace(/^\/+/,"").split("/"));return{error:null,data:null,hasRun:!1,run:function(){return this.hasRun?Promise.resolve():new Promise((n=>(0,a.readFile)(t,((o,r)=>{if(this.hasRun=!0,!o||"EISDIR"!==o.code)return this.error=o,this.data=r,void n(void 0);(0,a.readdir)(t,((t,o)=>{this.error=t,this.data=o,t?n(void 0):Promise.all(o.map((t=>new Promise((n=>(0,a.lstat)((0,c.resolve)(e.pathname,t),((e,o)=>n([t,o,e])))))))).then((t=>{const o=t.filter((e=>!e[2]&&e[1].isDirectory())).concat(t.filter((e=>!e[2]&&e[1].isFile())));this.data=`${D(128194,"directory",e.href)}<p>Directory content of <i>${e.href.replace(/\//g,"&#x002F;")}</i></p><ul class="list-group"><li class="list-group-item">&#x1F4C1;<a href="${e.pathname.endsWith("/")?"..":"."}">&lt;parent&gt;</a></li>${o.filter((e=>!e[2])).map((t=>`<li class="list-group-item">&#x${(t[1].isDirectory()?128193:128196).toString(16)};<a href="${e.pathname.endsWith("/")?"":`${e.pathname.split("/").slice(-1)[0]}/`}${t[0]}">${t[0]}</a></li>`)).join("\n")}</li></ul></body></html>`,n(void 0)}))}))}))))},events:{},on:function(e,n){return this.events[e]=n,this.run().then((()=>{"response"===e&&this.events.response(t.endsWith(".svg")?{Server:"local","Content-Type":"image/svg+xml"}:{Server:"local"},0),"data"===e&&this.data&&(this.events.data(this.data),this.events.end()),"error"===e&&this.error&&this.events.error(this.error)})),this},end:function(){return this},request:function(){return this},write:function(){return this}}},F=(e,t)=>({error:null,data:null,outboundData:null,run:function(){return new Promise((t=>{this.data=e,t(void 0)}))},events:{},on:function(e,n){return this.events[e]=n,this.run().then((()=>{var n;"response"===e&&this.events.response({Server:"local","Content-Type":null!==(n=null==t?void 0:t.contentType)&&void 0!==n?n:"text/html"},0),"data"===e&&this.data&&(this.events.data(this.data),this.events.end()),"error"===e&&this.error&&this.events.error(this.error)})),this},write:function(e){return this.outboundData=e,e instanceof Buffer&&(null==t||t.onOutboundWrite(e)),this},end:function(){return this},request:function(){return this}}),J=(e,n,o)=>t(void 0,void 0,void 0,(function*(){var r,s;return(null!==(s=null===(r=n["content-encoding"])||void 0===r?void 0:r.toString())&&void 0!==s?s:"").split(",").reduce(((e,n)=>t(void 0,void 0,void 0,(function*(){const t=n.trim().toLowerCase(),o="gzip"===t||"x-gzip"===t?l.gunzip:"deflate"===t?l.inflate:"br"===t?l.brotliDecompress:"identity"===t||""===t?(e,t)=>{t(null,e)}:null;if(null===o)throw new Error(`${t} compression not supported by the proxy`);const r=yield e;return yield new Promise(((e,t)=>o(r,((n,o)=>{n&&t(n),e(o)}))))}))),Promise.resolve(e)).then((e=>{const t=e.length>1e7,r=["text/html","application/javascript","application/json"].some((e=>{var t;return(null!==(t=n["content-type"])&&void 0!==t?t:"").toString().includes(e)}));return!t&&(r||!/[^\x00-\xFF]/.test(e.toString()))?_(e.toString(),{direction:o.direction,proxyHostnameAndPort:o.proxyHostnameAndPort,ssl:o.ssl,mapping:o.mapping}).replace(/\?protocol=wss?%3A&hostname=[^&]+&port=[0-9]+&pathname=/g,`?protocol=ws${o.ssl?"s":""}%3A&hostname=${o.proxyHostname}&port=${o.port}&pathname=${encodeURIComponent(o.key.replace(/\/+$/,""))}`):e})).then((e=>{var t,o;return(null!==(o=null===(t=n["content-encoding"])||void 0===t?void 0:t.toString())&&void 0!==o?o:"").split(",").reverse().reduce(((e,t)=>{const n=t.trim().toLowerCase(),o="gzip"===n||"x-gzip"===n?l.gzip:"deflate"===n?l.deflate:"br"===n?l.brotliCompress:"identity"===n||""===n?(e,t)=>{t(null,e)}:null;if(null===o)throw new Error(`${n} compression not supported by the proxy`);return e.then((e=>new Promise((t=>o(e,((e,n)=>{if(e)throw e;t(n)}))))))}),Promise.resolve(Buffer.from(e)))}))}));exports.replaceBody=J;const _=(e,{direction:t,proxyHostnameAndPort:n,ssl:o,mapping:r})=>Object.entries(r).map((([e,t])=>[e,"string"==typeof t?t:t.replaceBody])).reduce(((e,[r,s])=>L.some((e=>s.startsWith(e)))||""!==r&&!r.match(/^[-a-zA-Z0-9()@:%_\+.~#?&//=]*$/)?e:t===h.INBOUND?e.replace(new RegExp(s.replace(new RegExp(`^(file|${N.join("|")})://`),"").replace(/[*+?^${}()|[\]\\]/g,"").replace(/^https/,"https?")+"/*","ig"),`http${o?"s":""}://${n}${r.replace(/\/+$/,"")}/`):e.split(`http${o?"s":""}://${n}${r.replace(/\/+$/,"")}`).join(s)),e).split(`${n}/:`).join(`${n}:`);exports.replaceTextUsingMapping=_;const K=e=>{try{const t="object"==typeof e?e:JSON.parse(Buffer.from(e,"base64").toString("utf-8"));return["access-control-max-age","authorization","cache-control","cookie","date","dnt","expires","if-modified-since","if-unmodified-since","keep-alive","last-modified","pragma","proxy-authenticate","proxy-authorization","referer","retry-after","signed-headers","server-timing","sec-ch-ua","sec-ch-ua-mobile","sec-ch-ua-platform","sec-fetch-dest","sec-fetch-mode","sec-fetch-site","sec-fetch-user","upgrade-insecure-requests","user-agent"].forEach((e=>{var n;null===(n=null==t?void 0:t.headers)||void 0===n||delete n[e]})),t.headers=Object.keys(t.headers).sort().reduce(((e,n)=>(e[n]=t.headers[n],e)),{}),Buffer.from(JSON.stringify(t),"utf-8").toString("base64")}catch(t){return e}};exports.cleanEntropy=K;const z=(e,t,n)=>{t.writeHead(e,void 0,{"content-type":"text/html","content-length":n.length}),t.end(n)};exports.send=z;const G=(e,t)=>{var n,o,r,s,a;const l=(null!==(r=null!==(o=null===(n=e.headers[":authority"])||void 0===n?void 0:n.toString())&&void 0!==o?o:e.headers.host)&&void 0!==r?r:"localhost").replace(/:.*/,""),c=e.headers[":authority"]||`${e.headers.host}${e.headers.host.match(/:[0-9]+$/)?"":80!==t.port||t.ssl?443===t.port&&t.ssl?"":`:${null!==(s=t.port)&&void 0!==s?s:8080}`:""}`,d=new i.URL(`http${t.ssl?"s":""}://${c}${e.url}`),u=d.href.substring(d.origin.length),p=Object.assign({},Object.assign({},...Object.entries(t.mapping).map((([e,t])=>({[e]:new i.URL(P("string"==typeof t?t:t.downstreamUrl))}))))),[m,g]=null!==(a=Object.entries(p).find((([e])=>u.match(RegExp(e.replace(/^\//,"^/"))))))&&void 0!==a?a:[];return{proxyHostname:l,proxyHostnameAndPort:c,url:d,path:u,key:m,target:g}};exports.determineMapping=G;const Y=function(e,t,n){var o,a,l,c;if(n.on("error",(()=>{e.log("websocket connection reset",m.WARNING,g.WEBSOCKET)})),!e.config.websocket)return n.end("HTTP/1.1 503 Service Unavailable\r\n\r\n"),{};const{key:d,target:u,path:p,url:h}=G(t,e.config);if(p.startsWith("/local-traffic-logs"))return E(n,t.headers["sec-websocket-key"]),{logsListeners:e.logsListeners.concat({stream:n,wantsMask:!(null!==(a=null===(o=t.headers["user-agent"])||void 0===o?void 0:o.toString())&&void 0!==a?a:"").includes("Chrome"),wantsResponseMessage:[...h.searchParams.entries()].some((([e,t])=>"wantsResponseMessage"===e&&"true"===t))})};if("/local-traffic-config"===p){E(n,t.headers["sec-websocket-key"]);let o=null;return n.on("data",(t=>{const n=w(t,o);if(null===o&&n.body.length<n.payloadLength)o=n;else{if(n.body.length>=n.payloadLength&&0===n.body.length)return;if(n.body.length>=n.payloadLength){let t;o=null;try{t=JSON.parse(n.body)}catch(t){return void e.log("config file NOT read, try again later",m.WARNING,g.ERROR_4)}Q(e,{pendingConfigSave:t})}}})),{configListeners:e.configListeners.concat({stream:n,wantsMask:!(null!==(c=null===(l=t.headers["user-agent"])||void 0===l?void 0:l.toString())&&void 0!==c?c:"").includes("Chrome")})}}const f=new i.URL(`${u.protocol}//${u.host}${t.url.endsWith("/_next/webpack-hmr")?t.url:t.url.replace(new RegExp(`^${d}`,"g"),"").replace(/^\/*/,"/")}`),b={hostname:f.hostname,path:f.pathname,port:f.port,protocol:f.protocol,rejectUnauthorized:!1,method:t.method,headers:t.headers,host:f.hostname},y="https:"===f.protocol?(0,s.request)(b):(0,r.request)(b);y.end(),y.on("error",(t=>{e.log("websocket request has errored "+(t.errno?`(${t.errno})`:""),m.WARNING,g.WEBSOCKET)})),y.on("upgrade",((t,o)=>{const r=`HTTP/${t.httpVersion} ${t.statusCode} ${t.statusMessage}\r\n${Object.entries(t.headers).flatMap((([e,t])=>(Array.isArray(t)?t:[t]).map((t=>[e,t])))).map((([e,t])=>`${e}: ${t}\r\n`)).join("")}\r\n`;n.write(r),n.allowHalfOpen=!0,o.allowHalfOpen=!0,o.on("data",(e=>n.write(e))),n.on("data",(e=>o.write(e))),o.on("error",(t=>{e.log("downstream socket has errored "+(t.errno?`(${t.errno})`:""),m.WARNING,g.WEBSOCKET)})),n.on("error",(t=>{e.log("upstream socket has errored "+(t.errno?`(${t.errno})`:""),m.WARNING,g.WEBSOCKET)}))}))};exports.websocketServe=Y;const X=function(e,n,a){var l,c,p,b,O;return t(this,void 0,void 0,(function*(){if(!n.headers.host&&!n.headers[":authority"])return void z(400,a,Buffer.from(q(new Error("client must supply a 'host' header"),e.mode,"proxy",new i.URL(`http${e.config.ssl?"s":""}://unknowndomain${n.url}`))));const{proxyHostname:t,proxyHostnameAndPort:k,url:R,path:w,key:E,target:S}=G(n,e.config);if(!S)return void z(502,a,Buffer.from(q(new Error(`No mapping found in config file ${y}`),e.mode,"proxy",R)));const $=S.host.replace(RegExp(/\/+$/),""),C=`${S.href.substring(8+S.host.length)}${P(w.replace(RegExp(P(E)),""))}`.replace(/^\/*/,"/"),x=new i.URL(`${S.protocol}//${$}${C}`),B=L.some((e=>S.protocol===e));let I=null,N=!e.config.dontUseHttp2Downstream;const j=N&&!B&&"file:"!==S.protocol&&(yield Promise.race([new Promise((t=>{const n=(0,o.connect)(x,{timeout:e.config.connectTimeout,sessionTimeout:e.config.socketTimeout,rejectUnauthorized:!1,protocol:S.protocol},((e,o)=>{N=N&&!!o.alpnProtocol,t(N?n:null)}));n.on("error",(t=>{I=N&&Buffer.from(q(t,e.mode,"connection",R,x))}))})),new Promise((t=>setTimeout((()=>{N=!1,t(null)}),e.config.connectTimeout)))])),A=(0,d.randomBytes)(20).toString("hex");let H=null;const D=e.config.replaceRequestBodyUrls||e.logsListeners.length,F=null==n?void 0:n.readableLength,Y=null===(l=null==n?void 0:n.stream)||void 0===l?void 0:l.readableLength,X=!((e.config.ssl&&0===Y||!e.config.ssl&&0===F)&&("0"===n.headers["content-length"]||void 0===n.headers["content-length"]));if(D){const o=null!==(c=null==n?void 0:n.stream)&&void 0!==c?c:n;let r=Buffer.from([]);yield Promise.race([new Promise((t=>setTimeout(t,e.config.connectTimeout))),new Promise((e=>{X?(o.on("data",(e=>{r=Buffer.concat([r,e])})),o.on("end",e),o.on("error",e)):e(void 0)}))]),X&&!r.length&&e.log(`body replacement error ${w.slice(-17)}`,m.WARNING,g.ERROR_4),H=e.config.replaceRequestBodyUrls?yield J(r,n.headers,{proxyHostnameAndPort:k,proxyHostname:t,key:E,mapping:e.config.mapping,port:e.config.port,ssl:!!e.config.ssl,direction:h.OUTBOUND}):r}const Z=e.logsListeners.some((e=>e.wantsResponseMessage)),V=e.mockConfig.autoRecord&&e.mode===f.PROXY,Q=e.mode===f.MOCK||Z||V?K({method:n.method,url:n.url,headers:Object.assign({},...Object.entries(n.headers).filter((([e])=>!e.startsWith(":"))).map((([e,t])=>({[e]:t})))),body:null==H?void 0:H.toString("base64")}):"",ee="file:"===S.protocol;e.notifyLogsListeners({level:"info",protocol:N?"HTTP/2":"HTTP1.1",method:n.method,upstreamPath:w,downstreamPath:x.href,randomId:A,uniqueHash:Q}),e.config.logAccessInTerminal&&!x.pathname.startsWith("/:/")&&e.log(e.config.simpleLogs?`${n.method} ${x.pathname}`:`[48;5;${"GET"===n.method?"22":"POST"===n.method?"52":"PUT"===n.method?"94":"DELETE"===n.method?"244":"OPTIONS"===n.method?"19":"PATCH"===n.method?"162":"HEAD"===n.method?"53":"TRACE"===n.method?"6":"CONNECT"===n.method?"2":"0"}m⎸${n.method.toString().padStart(7)} ⎸${x.pathname.toString().padStart(40).substring(0,40)}⎹`);const te=e.mode===f.MOCK&&(!B||ee),ne=e.mockConfig.mocks.get(Q);if(te&&!ne&&e.mockConfig.strict)return void z(502,a,Buffer.from(q(new Error("No corresponding mock found in the server. \nTry switching back to the proxy mode"),e.mode,"mock",R)));const oe=v(),re=te&&ne?M({response:ne}):ee?W(x):B?T[S.protocol.replace(/:$/,"")](k,e,n):N?j:null;I instanceof Buffer||(I=null);const se=Object.assign(Object.assign({},[...Object.entries(n.headers)].filter((([e])=>!U.includes(e.toLowerCase()))).reduce(((e,[t,n])=>(e[t]=(e[t]||"")+(Array.isArray(n)?n:[n]).map((e=>e.replace(R.hostname,$))).join(", "),e)),{})),{origin:S.href,referer:x.toString(),"content-length":null!==(b=null!==(p=null==H?void 0:H.length)&&void 0!==p?p:n.headers["content-length"])&&void 0!==b?b:0,":authority":$,":method":n.method,":path":C,":scheme":S.protocol.replace(":","")}),ie=re&&!I&&re.request(se,{endStream:e.config.ssl?!(null==Y||Y):!F});"object"==typeof ie&&(null==ie||ie.on("error",(t=>{const n=-505===t.errno;I=Buffer.from(q(t,e.mode,"stream"+(n?" (error -505 usually means that the downstream service does not support this http version)":""),R,x))})));const ae={hostname:S.hostname,path:C,port:S.port,protocol:S.protocol,rejectUnauthorized:!1,method:n.method,headers:Object.assign(Object.assign({},Object.assign({},...Object.entries(se).filter((([e])=>!e.startsWith(":")&&"transfer-encoding"!==e.toLowerCase())).map((([e,t])=>({[e]:t}))))),{host:S.hostname})},le=!I&&!N&&!["file:",...L].includes(S.protocol)&&(yield new Promise((t=>{const o="https:"===S.protocol?(0,s.request)(ae,t):(0,r.request)(ae,t);o.on("error",(n=>{I=Buffer.from(q(n,e.mode,"request",R,x)),t(null)})),D&&(o.write(H),o.end()),D||(n.on("data",(e=>o.write(e))),n.on("end",(()=>o.end())))})));if(I)return void z(502,a,I);I=null,Y&&ie&&!D?(n.stream.on("data",(e=>{ie.write(e)})),n.stream.on("end",(()=>ie.end()))):F&&ie&&!D?(n.on("data",(e=>{ie.write(e)})),n.on("end",(()=>ie.end()))):ie&&D&&X&&(ie.write(H),ie.end());const{outboundResponseHeaders:ce}=yield new Promise((e=>ie?ie.on("response",(t=>{e({outboundResponseHeaders:t})})):e(!ie&&le?{outboundResponseHeaders:le.headers}:{outboundResponseHeaders:{}})));let de=null;try{ce.location&&(de=new i.URL(ce.location.startsWith("/")?`${S.origin}${ce.location.replace(/^\/+/,"/")}`:ce.location.replace(/^file:\/+/,"file:///").replace(/^(http)(s?):\/+/,"$1$2://")))}catch(t){e.log(`location replacement error ${(null!==(O=ce.location)&&void 0!==O?O:"").slice(-13)}`,m.WARNING,g.ERROR_4)}const ue=e.config.replaceResponseBodyUrls&&de?new i.URL(_(de.href,{direction:h.INBOUND,proxyHostnameAndPort:k,ssl:!!e.config.ssl,mapping:e.config.mapping}).replace(new RegExp(`^(${L.join("|")}|file:)/+`),"")):de,pe=de?ue.origin!==de.origin||e.config.dontTranslateLocationHeader?ue:`${R.origin}${ue.href.substring(ue.origin.length)}`:de,me=ie||le,ge=null!=I?I:yield new Promise((e=>{let t=Buffer.alloc(0);me?(me.on("data",(e=>t=Buffer.concat([t,"string"==typeof e?Buffer.from(e):e]))),me.on("end",(()=>{e(t)}))):e(t)})).then((n=>e.config.replaceResponseBodyUrls&&n.length?L.some((e=>S.protocol===e))?n:J(n,ce,{proxyHostnameAndPort:k,proxyHostname:t,key:E,direction:h.INBOUND,mapping:e.config.mapping,port:e.config.port,ssl:!!e.config.ssl}).catch((t=>(z(502,a,Buffer.from(q(t,e.mode,"stream",R,x))),Buffer.from("")))):n)),he=Object.assign(Object.assign({},Object.entries(Object.assign(Object.assign(Object.assign({},ce),e.config.replaceResponseBodyUrls?{"content-length":`${ge.byteLength}`}:{}),e.config.disableWebSecurity?{"content-security-policy":"report only","access-control-allow-headers":"*","access-control-allow-method":"*","access-control-allow-origin":"*"}:{})).filter((([e])=>!e.startsWith(":")&&!U.includes(e.toLowerCase()))).reduce(((e,[t,n])=>{const o=$.split("").map(((e,t)=>$.substring(t).startsWith(".")&&$.substring(t))).filter((e=>e)),r=[$].concat(o).reduce(((e,t)=>(Array.isArray(e)?e:[e]).map((e=>"string"==typeof e?e.replace(`Domain=${t}`,`Domain=${R.hostname}`):e))),n);return e[t]=(e[t]||[]).concat(r),e}),{})),pe?{location:[pe]}:{});try{Object.entries(he).forEach((([e,t])=>t&&a.setHeader(e,t)))}catch(e){}const fe=ce[":status"]||le.statusCode||200;try{a.writeHead(fe,e.config.ssl?void 0:le.statusMessage||"Status read from http/2",he)}catch(e){}ge?a.end(ge):a.end();const be=v(),ye=Z||V?Buffer.from(JSON.stringify({body:null==ge?void 0:ge.toString("base64"),headers:ce,status:fe})).toString("base64"):"";e.notifyLogsListeners({randomId:A,statusCode:fe,protocol:N?"HTTP/2":"HTTP1.1",duration:Math.floor(Number(be-oe)/1e6),uniqueHash:Q,response:ye}),!V||e.config.logAccessInTerminal||B||(e.mockConfig.mocks.set(Q,ye),u.stdout.moveCursor(0,-1,(()=>u.stdout.clearLine(-1,e.quickStatus))))}))};exports.serve=X;const Z=(e,t)=>{"EACCES"===t.code&&e.log("permission denied for this port",m.ERROR,g.NO),"EADDRINUSE"===t.code&&e.log("port is already used. NOT started",m.ERROR,g.ERROR_6)};exports.errorListener=Z;const V=e=>Q({config:Object.assign(Object.assign({},j),e)},{});exports.start=V;const Q=(e,n)=>t(void 0,void 0,void 0,(function*(){var s,i,l,c,d,u,p,h,b,v,O,R,w,E,C,q,B,I,T,N,L,j,P;if(0===Object.keys(null!=n?n:{}).length&&e.server)return;if(n.pendingConfigSave)return void(0,a.writeFile)(y,JSON.stringify(n.pendingConfigSave,null,2),(t=>{var n,o;t?null===(n=e.log)||void 0===n||n.call(e,"config file NOT saved",m.ERROR,g.ERROR_4):null===(o=e.log)||void 0===o||o.call(e,"config file saved... will reload",m.INFO,g.COLORED)}));if(null===n.configListeners&&(yield Promise.all(e.configListeners.map((e=>new Promise((t=>e.stream.end(t))))))),null===n.logsListeners&&(yield Promise.all(e.logsListeners.map((e=>new Promise((t=>e.stream.end(t))))))),null===n.server){(yield Promise.race([new Promise((t=>e.server.close(t))).then((()=>!0)),new Promise((e=>setTimeout(e,5e3))).then((()=>!1))]))||e.log("error during restart (websockets ?)",m.WARNING,g.RESTART)}(null!==(s=e.configListeners)&&void 0!==s?s:[]).concat(null!==(i=e.logsListeners)&&void 0!==i?i:[]).filter((e=>e.stream.errored||e.stream.closed)).forEach((e=>e.stream.destroy()));const H=null!==(l=n.config)&&void 0!==l?l:e.config,U=null!==(d=null!==(c=n.mode)&&void 0!==c?c:e.mode)&&void 0!==d?d:f.PROXY,D=null!==(b=null!==(p=null===(u=n.mockConfig)||void 0===u?void 0:u.autoRecord)&&void 0!==p?p:null===(h=e.mockConfig)||void 0===h?void 0:h.autoRecord)&&void 0!==b&&b,M=null!==(w=null!==(O=null===(v=n.mockConfig)||void 0===v?void 0:v.strict)&&void 0!==O?O:null===(R=e.mockConfig)||void 0===R?void 0:R.strict)&&void 0!==w&&w,W=null!==(B=null!==(C=null===(E=n.mockConfig)||void 0===E?void 0:E.mocks)&&void 0!==C?C:null===(q=e.mockConfig)||void 0===q?void 0:q.mocks)&&void 0!==B?B:new Map,F=(null===n.configListeners?[]:null!==(T=null!==(I=n.configListeners)&&void 0!==I?I:e.configListeners)&&void 0!==T?T:[]).filter((e=>!e.stream.errored&&!e.stream.closed)),J=(null===n.logsListeners?[]:null!==(L=null!==(N=n.logsListeners)&&void 0!==N?N:e.logsListeners)&&void 0!==L?L:[]).filter((e=>!e.stream.errored&&!e.stream.closed)),_=e;return Object.assign(_,{config:H,logsListeners:J,configListeners:F,mode:U,mockConfig:{mocks:W,strict:M,autoRecord:D},configFileWatcher:void 0===_.configFileWatcher?(0,a.watchFile)(y,(()=>t(void 0,void 0,void 0,(function*(){return Q(_,yield function(e){return t(this,void 0,void 0,(function*(){const t=e.config,n=yield A(!1);return isNaN(n.port)||n.port>65535||n.port<0?(e.log("port number invalid. Not refreshing",m.ERROR,g.PORT),{}):"object"!=typeof n.mapping?(e.log("mapping should be an object. Aborting",m.ERROR,g.ERROR_5),{}):(n.replaceRequestBodyUrls!==t.replaceRequestBodyUrls&&e.log(`request body url ${n.replaceRequestBodyUrls?"":"NO "}rewriting`,m.INFO,g.REWRITE),n.replaceResponseBodyUrls!==t.replaceResponseBodyUrls&&e.log(`response body url ${n.replaceResponseBodyUrls?"":"NO "}rewriting`,m.INFO,g.REWRITE),n.dontTranslateLocationHeader!==t.dontTranslateLocationHeader&&e.log(`response location header ${n.dontTranslateLocationHeader?"NO ":""}translation`,m.INFO,g.REWRITE),n.dontUseHttp2Downstream!==t.dontUseHttp2Downstream&&e.log(`http/2 ${n.dontUseHttp2Downstream?"de":""}activated downstream`,m.INFO,g.OUTBOUND),n.disableWebSecurity!==t.disableWebSecurity&&e.log(`web security ${n.disableWebSecurity?"de":""}activated`,m.INFO,g.SHIELD),n.websocket!==t.websocket&&e.log(`websocket ${n.websocket?"":"de"}activated`,m.INFO,g.WEBSOCKET),n.logAccessInTerminal!==t.logAccessInTerminal&&e.log("access terminal logging "+(n.logAccessInTerminal?"on":"off"),m.INFO,g.LOGS),n.simpleLogs!==t.simpleLogs&&e.log("simple logs "+(n.simpleLogs?"on":"off"),m.INFO,g.COLORED),Object.keys(n.mapping).join("\n")!==Object.keys(t.mapping).join("\n")&&e.log(`${Object.keys(n.mapping).length.toString().padStart(5)} loaded mapping rules`,m.INFO,g.RULES),n.port!==t.port&&e.log(`port changed from ${t.port} to ${n.port}`,m.INFO,g.PORT),n.ssl&&!t.ssl&&e.log("ssl configuration added",m.INFO,g.INBOUND),!n.ssl&&t.ssl&&e.log("ssl configuration removed",m.INFO,g.INBOUND),n.port!==t.port||JSON.stringify(n.ssl)!==JSON.stringify(t.ssl)?(e.log("restarting server",m.INFO,g.RESTART),x.apply(Object.assign(Object.assign({},e),{config:n})),{config:n,server:null}):(x.apply(Object.assign(Object.assign({},e),{config:n})),{config:n}))}))}(_))})))):_.configFileWatcher,log:k.bind(_,_),notifyConfigListeners:S.bind(_),notifyLogsListeners:$.bind(_),quickStatus:x.bind(_),server:null!==n.server&&_.server||(null!==(P=null===(j=n.config)||void 0===j?void 0:j.port)&&void 0!==P?P:0)<0?null===n.server?null:_.server:(H.ssl?o.createSecureServer.bind(null,Object.assign(Object.assign({},H.ssl),{allowHTTP1:!0})):r.createServer)(((e,t)=>X(_,e,t))).addListener("error",(e=>Z(_,e))).addListener("listening",(()=>_.quickStatus())).on("upgrade",((e,t)=>Q(_,Y(_,e,t)))).listen(H.port)}),_}));exports.update=Q;const ee=null!==(e=u.argv.map((e=>e.trim())).filter((e=>e&&!["ts-node","node","npx","npm","exec"].some((t=>e.includes(t)&&!e.match(/npm-cache/)&&!e.match(/_npx/)))))[0])&&void 0!==e?e:"",te=ee.toLowerCase().replace(/[-_]/g,"").includes("localtraffic")&&!ee.match(/(.|-)?(test|spec)\.m?[jt]sx?$/),ne=u.argv.some((e=>"--crash-test"===e));if(ne){const e=Math.floor(40151+9e3*Math.random()),t=(t,n)=>(0,r.request)({hostname:"localhost",port:e,path:"/config/",method:"GET",headers:{Accept:"text/html"},timeout:500},(e=>n({response:e,state:t}))).on("error",(e=>n({error:e,state:t}))).end();Q({config:Object.assign(Object.assign({},j),{port:e}),configFileWatcher:null},{}).then((e=>new Promise((n=>setTimeout(t.bind(null,e,n),1e3))))).then((({state:e,response:t})=>200!==t.statusCode?Promise.reject("Crash test has failed"):Q(e,{config:{port:-1},server:null}))).then((e=>new Promise((n=>setTimeout(t.bind(null,e,n),1e3))))).then((({state:e,error:t})=>"ECONNREFUSED"!==t.code?Promise.reject("Server should have stopped"):k(e,"Crash test successful",m.INFO,g.COLORED))).then((()=>(0,u.exit)(0))).catch((()=>(0,u.exit)(1)))}!ne&&te&&A().then(V);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "local-traffic",
3
- "version": "0.0.84",
3
+ "version": "0.0.86",
4
4
  "main": "./dist/local-traffic.js",
5
5
  "private": false,
6
6
  "keywords": [
@@ -27,8 +27,8 @@
27
27
  "test": "node ./test/tests.spec.mjs"
28
28
  },
29
29
  "devDependencies": {
30
- "@types/node": "^20.6.0",
31
- "terser": "^5.19.4",
30
+ "@types/node": "^20.6.3",
31
+ "terser": "^5.20.0",
32
32
  "typescript": "^5.2.2"
33
33
  },
34
34
  "bin": {