reserve
Version:
Lightweight http server statically configurable using regular expressions
1 lines • 25.8 kB
JavaScript
module.exports=function(e,t,n,r,o,s,i,a,c,d,u,l,h,p,f,m,g,y,w){t=y(t),n=y(n),r=y(r);const b=Object.assign,v=Object.keys,x=e=>new Promise(e),S=()=>Symbol(),[E,_,B,C,I,$,R]=",object,string,number,function,boolean,error".split(","),k=function(e={}){const t=Number.POSITIVE_INFINITY,n=n=>{const r=e[n];if(void 0===r)return t;if(!Number.isInteger(r)||r<=0)throw new Error(`Invalid ${n}`);return r},r=n("ttl"),o=n("max"),s=e.policy||"lru",i=new Map,a=()=>Date.now(),c=()=>i.keys(),d=e=>()=>{let n,r=t;for(const t of c()){const{[e]:o}=i.get(t);o<r&&(r=o,n=t)}i.delete(n)},u={lru:d("t"),lfu:d("f")}[s];if(void 0===u)throw new Error("Invalid policy");const l=()=>{const e=a();let t=!1;for(const n of c()){const{e:r}=i.get(n);r<=e&&(i.delete(n),t=!0)}return t},h=e=>{const t=i.get(e);if(t){const e=a();if(t.e>e)return t.t=e,t}};return{set(e,t){const n=a();let s=h(e);s||(i.size===o&&!l()&&u(),s={f:0},i.set(e,s)),b(s,{e:n+r,t:n,f:s.f+1,v:t})},get(e){const t=h(e);if(t)return++t.f,t.v},del(e){i.delete(e)},keys:()=>(l(),Array.from(c()))}},A=(()=>{const e={string:(e,t)=>t.replace(/\$(\d+)|\$(\w+)|\$\$/g,((t,n,r)=>n?e[n]||E:r?e.groups&&e.groups[r]||E:"$")),object:(e,n)=>{const r={};return v(n).forEach((o=>{r[o]=t(e,n[o])})),r}};function t(t,n){const r=e[typeof n];return r?r(t,n):n}return t})(),P=[S(),S(),S(),S(),S(),S(),S(),S(),S(),S(),S(),S(),S(),S(),S(),S(),S(),S(),S()],N=async e=>{if(e.endsWith(".mjs"))return(await import(`file://${e}`)).default;try{return require(e)}catch(t){if("ERR_REQUIRE_ESM"===t.code)return(await import(`file://${e}`)).default;throw t}},O=(()=>{const e=A,t='Unknown event name|Invalid callback|Configured port $port already in use|Invalid mapping match|Invalid mapping invert-match|Invalid mapping if-match|Invalid mapping exclude-from-holding-list|Unknown handler for $mapping|Invalid method specification|No method specified (or left)|Invalid "$type" handler: redirect is not a function|Invalid listeners member, must be an array of functions|Invalid http2 setting|Configuration must be an object|iconfiguration.setMappings appears to be blocked|Missing property $name|Invalid type of property $name|Invalid custom handler, expected a function|index.html not a file|Invalid custom-file-system specification ($invalids}|Invalid caching-strategy name|Internal redirection impossible because the body is already consumed|Unexpected middleware signature|Unsupported encoding: $encoding|Invalid status'.split("|");function n(n=-1,r){let o=t[n]||"An error occurred";r&&(o=e({groups:r},o));const s=new Error(o);return s.name="REserveError",s.code=n,s}return[function(e,t){throw n(e,t)},n]})(),j=(()=>{const[e]=O;return(t,n,r)=>{let o=t.method;void 0!==o?(typeof o===B&&(o=o.split(",")),Array.isArray(o)||e(8),o=o.map((e=>e.toUpperCase())),r&&(o=o.filter((e=>r.includes(e)))),o.length||e(9),t[n]=o):t[n]=r}})(),q=(()=>{const[e]=O;return[function(e){return v(e).map((t=>function(e,t){let n;const{defaultValue:r}=t;return n=typeof t===B?[t]:Array.isArray(t)?t:t.types||[t.type||B],{name:e,types:n,defaultValue:r}}(t,e[t])))},function(t,n){t.forEach((t=>function(t,n,r=t.defaultValue){const{name:o,types:s}=t;void 0===r&&e(15,{name:o});const i=typeof r;s.includes(i)||e(16,{name:o}),n[t.name]=r}(t,n,n[t.name])))},function(e){return!0!==e&&void 0!==e}]})(),H=(()=>{const{7:e,16:t}=P,n=N,[r]=O;return{[e]:"use",schema:{use:[B,I],options:{type:_,defaultValue:{}}},validate:async e=>{let o;o=typeof e.use===I?e.use:await n(e.use);const s=o(e.options);3!==s.length&&r(22),e[t]=s},redirect:({mapping:e,request:n,response:r})=>x(((o,s)=>{const i=()=>{o(),r.end()},a=new Proxy(r,{get:(e,t)=>"end"===t?i:r[t]}),c=e=>{e?s(e):o()};try{e[t](n,a,c)}catch(e){s(e)}}))}})(),U=(()=>{const e=e=>typeof e===B?e.toLowerCase():e;return(t={})=>{const n=new Proxy({},{get:(t,n)=>t[e(n)],set:(t,n,r)=>(Array.isArray(r)?t[e(n)]=r.map((e=>e.toString())):t[e(n)]=r.toString(),!0)});return Reflect.ownKeys(t).forEach((e=>{n[e]=t[e]})),n}})(),V=(()=>{const e=U,t="http://localhost";return class extends g{_read(){this.push(this._body),this.push(null)}_fromObject({method:n,url:r,headers:o={},body:s=E,properties:i}){this._method=n,this._url=function(e){const n=new URL(e,t).toString();return n.startsWith(t)?n.substring(16):n}(r),this._headers=e(o),this._body=s,i&&b(this,i)}_fromParams(e,t,n,r,o){return typeof r===_&&(o=r,r=E),typeof n===B&&(r=n,n={}),this._fromObject({method:e,url:t,headers:n,body:r,properties:o})}constructor(e){super(),typeof e===_?this._fromObject(e):this._fromParams(...arguments)}get method(){return this._method}get url(){return this._url}setForgedUrl(e){this._url=e}get headers(){return this._headers}get socket(){return this._socket||(this._socket=new a),this._socket}abort(){this.aborted=!0,this.emit("aborted")}}})(),D=()=>{let e,t;return[x(((n,r)=>{e=n,t=r})),e,t]},T=(()=>{const e=U,t=D;return class extends m{_read(){this.push(this.toString()),this.push(null)}_write(e,t,n){this._headersSent=!0,this._buffer.push(e.toString()),this._asynchronous?setTimeout(n,0):n()}getHeader(e){return this._headers[e]||E}setHeader(e,t){this._headers[e]=t}writeHead(e,t={}){this._statusCode=e,v(t).forEach((e=>{this._headers[e]=t[e]}))}flushHeaders(){this._headersSent=!0}end(){return this._headersSent=!0,this._ended=!0,super.end.apply(this,arguments)}constructor(n){super(n),this._buffer=[],this._headers=e(),this._headersSent=!1;const[r,o]=t();this._waitForFinish=r,this.on("finish",(()=>o(this))),this._statusCode=200,this._ended=!1}get headers(){return this._headers}get statusCode(){return this._statusCode}set statusCode(e){this._statusCode=e}get headersSent(){return this._headersSent}get writableEnded(){return this._ended}toString(){return this._buffer.join(E)}waitForFinish(){return this._waitForFinish}isInitial(){return 0===this._buffer.length&&!this._headersSent&&0===v(this._headers).length}setAsynchronous(){this._asynchronous=!0}}})(),z=(()=>{const e=D,[t,n]=O,r={gzip:w.createGunzip,deflate:w.createInflate,br:w.createBrotliDecompress,default:e=>{t(23,{encoding:e})}};function o(e,t){let[n,r,o=()=>{}]=t;return e&&typeof n===I?(o=n,n=void 0,r=void 0):typeof r===I&&(o=r,r=void 0),{data:n,encoding:r,callback:o}}const s=o.bind(null,!1),i=o.bind(null,!0);function a(t,n,o){const[a,c,d]=e(),{emit:u,end:l,write:h}=t;function p(e){d(e),t.write=h,t.end=l}try{const e=function(e){const t=e["content-encoding"];if(t&&"identity"!==t)return(r[t]||r.default)(t)}(n)||o;e.on(R,p),e!==o&&(o.on(R,p),f(e,o,(()=>{o.end()}))),t.on(R,p),o.on("finish",(()=>c()));let a=!0;t.write=function(){const{data:n,encoding:r,callback:o}=s(arguments);let i=0;function c(){0===--i&&(t.emit=u,t.emit("drain"))}return a&&(e.write(n,r)||(++i,e.once("drain",c))),h.call(t,n,r,o)||++i,!i||(t.emit=function(e){if("drain"!==e)return u.apply(t,arguments);c()},!1)},t.end=function(){const{data:n,encoding:r,callback:s}=i(arguments);return e!==o?e.end(n,r):o.end(n,r),a=!1,l.call(t,n,r,(function(){s.apply(this,arguments)})),this}}catch(e){d(e)}return a}return(t,r)=>{const[o,s,i]=e(),{writeHead:c}=t;return t.writeHead=function(e,o={}){200===e?s(a(t,o,r)):i(n(24)),c.apply(t,arguments)},o}})(),F=(()=>{const e=U,t=D,{7:n,18:r}=P,s=N,[,a]=O,c=["transfer-encoding","connection","keep-alive"];function d(){}async function u(e,t){typeof e[t]===B&&(e[t]=await s(e[t]))}return{[n]:"url",schema:{"unsecure-cookies":{type:$,defaultValue:!1},"forward-request":{types:[I,B],defaultValue:d},"forward-response":{types:[I,B],defaultValue:d},"ignore-unverifiable-certificate":{type:$,defaultValue:!1},"absolute-location":{type:$,defaultValue:!1}},validate:async e=>{await u(e,"forward-request"),await u(e,"forward-response")},redirect:async({configuration:n,mapping:s,match:d,redirect:u,request:l,response:h})=>{const{socket:p}=l;void 0===p[r]&&(p[r]=!1,p.on("close",(()=>{p[r]=!0})));const[f,m,g]=t(),{method:y,headers:w}=l,b={method:y,url:u,headers:e(w)};delete b.headers.host,s["ignore-unverifiable-certificate"]&&(b.rejectUnauthorized=!1);const x={configuration:n,context:{},mapping:s,match:d,request:b,incoming:l};await s["forward-request"](x),v(b.headers).filter((e=>e.startsWith(":"))).forEach((e=>delete b.headers[e]));const S=function(e){return e.startsWith("https")?i:o}(b.url).request(b.url,b,(async e=>{s["unsecure-cookies"]&&function(e){const t=e["set-cookie"];t&&(e["set-cookie"]=t.map((e=>{const t=e.replace(/\s*secure;?/i,E);return t!==e?t.replace(/\s*samesite=none;?/i," SameSite=Lax;"):e})))}(e.headers);const{headers:t}=e,{location:o}=t;o&&s["absolute-location"]&&!o.match(/^https?:\/\//)&&(t.location=b.url.match(/^http?s:\/\/[^/]+/)[0]+o);const i=await s["forward-response"]({...x,statusCode:e.statusCode,headers:t});return void 0!==i?["GET","HEAD"].includes(l.method)?m(i):g(a(21)):(n.http2&&c.forEach((e=>delete t[e])),h.writeHead(e.statusCode,t),l.aborted||p[r]?(e.destroy(),h.end(),m()):(h.on("finish",(()=>m(i))),void e.on(R,g).pipe(h)))}));return S.on(R,g),l.on(R,g).pipe(S),f}}})(),L=(()=>{const e={},t="openxmlformats,application/,octet-stream,presentation,document,office,image/,audio/,video/,text/,font/,oasis,woff,vnd.,xml,zip,x-".split(",");let n,r="aac=Haac,abw=BQabiword,arc=BC,avi=IQmsvideo,azw=BNamazon.ebook,bin=BC,bmp=Gbmp,bz=BQbP,bz2=BQbP2,csh=BQcsh,css=Jcss,csv=Jcsv,doc=Bmsword,docx=BNA-FE.wordprocessingml.E,eot=BNms-fontobject,epub=Bepub+P,gif=Ggif,htm=Jhtml,html,ico=GQicon,ics=Jcalendar,jar=Bjava-archive,jpeg=Gjpeg,jpg,js=Bjavascript,json=Bjson,mid=Hmidi,midi,mpeg=Impeg,mpkg=BNapple.installer+O,odp=BNL.openE.D,ods=BNL.openE.spreadsheet,odt=BNL.openE.text,oga=Hogg,ogv=Iogg,ogx=Bogg,otf=Kotf,png=Gpng,pdf=Bpdf,ppt=BNms-powerpoint,pptx=BNA-FE.Dml.D,rar=BQrar-compressed,rtf=Brtf,sh=BQsh,svg=Gsvg+O,swf=BQshockwave-flash,tar=BQtar,text=Jplain,tif=Gtiff,tiff,ts=Btypescript,ttf=Kttf,txt=Jplain,vsd=BNvisio,wasm=Bwasm,wav=HQwav,weba=Hwebm,webm=Iwebm,webp=Gwebp,woff=KM,woff2=KM2,xhtml=Bxhtml+O,xls=BNms-excel,xlsx=BNA-FE.spreadsheetml.sheet,xml=BO,xul=BNmozilla.xul+O,zip=BP,7z=BQ7z-compressed";return t.forEach(((e,t)=>{r=r.replace(new RegExp(String.fromCharCode(65+t),"g"),e)})),r.split(",").forEach((t=>{const[r,o]=t.split("=");o&&(n=o),e[r]=n})),e})(),M=(()=>{const{text:e,json:t}=L,n=D;return function(r,o={}){let s;const[i,a,c]=n();r.on(R,c);const{ignoreContentLength:d=!1}=o,u=!d&&r.headers&&r.headers["content-length"],l=r.headers&&r.headers["content-type"];if(l&&(l.startsWith(e)?s=e:l.startsWith(t)&&(s=t)),u){const e=parseInt(u,10),t=Buffer.alloc(e);let n=0;r.on("data",(e=>{e.copy(t,n),n+=e.length})).on("end",(()=>a(t)))}else{const e=[];r.on("data",(t=>e.push(t))).on("end",(()=>a(Buffer.concat(e))))}const h=e=>e.toString(),p=e=>JSON.parse(e.toString());let f;return f=s===e?i.then(h):s===t?i.then(p):i,f.buffer=()=>i,f.text=()=>i.then(h),f.json=()=>i.then(p),f}})(),Q=(()=>{const{bin:e,text:t,json:n}=L,r=U,o="content-type",s="content-length";return(i,a,c={})=>{let{statusCode:d=200,noBody:u}=c;const l=r(c.headers);let h,p=!1;if(void 0===a?u=!0:typeof a===B?h=t:typeof a.on===I?(h=e,p=!0):(h=n,a=JSON.stringify(a)),!l[o]&&h&&(l[o]=h),!a||p||l[s]||(l[s]=(new TextEncoder).encode(a).length),i.writeHead(d,l),u)i.end();else{if(p)return x(((e,t)=>{i.on("finish",e),a.on(R,t),f(a,i,(n=>{n?(i.end(),t(n)):e()}))}));i.end(a)}}})(),G=(()=>{const[,,,,,e,t,n]=P,r=N,[o]=O,s=Q;function i(e,t,n,[,...r]){return e.call(this,t,n,...r)}return{[n]:"custom",schema:{custom:[I,B,_]},validate:async(n,s)=>{const a=n.custom;if(Array.isArray(a)&&a.length>0)n[e]=()=>a,n[t]=n[e];else{n[e]=typeof a===B?await r(h(n.cwd,a)):n.custom,typeof n[e]!==I&&o(17);const{length:s}=n[e];n[t]=0===s||s>2?i.bind(n,n[e]):n[e]}n.configuration=s},redirect:({mapping:e,match:n,request:r,response:o})=>{const i=e[t](r,o,n);return i&&i.then?i.then((e=>Array.isArray(e)?s(o,e[0],e[1]):e)):Array.isArray(i)?s(o,i[0],i[1]):i}}})(),J=(()=>{const{7:n,17:o}=P,s=Q,i=L,a=N,c=k,[l]=O,p="custom-file-system",f="caching-strategy",m="mime-types",g="static",y={stat:r,readdir:t,createReadStream:e};async function w({cachingStrategy:e,mapping:t,request:n,response:r,fs:o,filePath:a},c){const{header:d,status:u}=function(e,t,{mtime:n}){if("modified"===t){const t=n.toUTCString(),r=e.headers["if-modified-since"];let o;return r&&t===r&&(o=304),{header:{"cache-control":"no-cache","last-modified":t},status:o}}return t>0?{header:{"cache-control":`public, max-age=${t}, immutable`}}:{header:{"cache-control":"no-store"}}}(n,e,c),{start:l,end:h,header:p,status:f,contentLength:g}=function(e,{mtime:t,size:n}){const r=/bytes=(\d+)-(\d+)?(,)?/.exec(e.headers.range),o=e.headers["if-range"];if((!o||o===t.toUTCString())&&r&&!r[3]){const e=parseInt(r[1],10);let t;return t=r[2]?parseInt(r[2],10):n-1,e>t||e>=n?{status:416,contentLength:0}:{start:e,end:t,header:{"content-range":`bytes ${e}-${t}/${n}`},status:206,contentLength:t-e+1}}return{status:200,contentLength:n}}(n,c);let{statusCode:y}=r;200===y&&(y=u||f);const w=(/\.([^.]*)$/.exec(a)||[])[1],b=t[m][w]||i[w]||i.bin,v="HEAD"===n.method||0===g||n.aborted||304===y;let x;if(v||(x=await o.createReadStream(a,{start:l,end:h}),!n.aborted))return s(r,x,{statusCode:y,headers:{"content-type":b,"content-length":g,"accept-ranges":"bytes",...p,...d},noBody:v});r.end()}return{[n]:"file",schema:{[p]:{types:[B,_],defaultValue:y},[f]:{types:[B,C],defaultValue:0},[m]:{type:_,defaultValue:{}},[g]:{types:[$,_],defaultValue:!1}},method:"GET,HEAD",validate:async e=>{typeof e[p]===B&&(e[p]=await a(h(e.cwd,e[p])));const t=["stat","createReadStream","readdir"].filter((t=>typeof e[p][t]!==I));t.length&&l(19,{invalids:t.join(", ")});const n=e[f];typeof n===B&&"modified"!==n&&l(20),!0===e[g]&&(e[g]={}),e[g]&&(e=>{const t=c(e[g]),{stat:n,readdir:r,createReadStream:s}=e[p];e[o]=t;const i=(e,n)=>async r=>{const o=`${e}:${r}`,s=t.get(o);if(s)return s;const i=n(r);return t.set(o,i),i};e[p]={stat:i("stat",n),readdir:i("dir",r),createReadStream:s}})(e)},redirect:({request:e,mapping:t,redirect:n,response:r})=>{let o=/([^?#]*)/.exec(n)[1];if(o=h(t.cwd,o),!o.startsWith(t.cwd))return Promise.resolve();const s=!o.match(/(\\|\/)$/),i={cachingStrategy:t[f],fs:t[p],filePath:o,mapping:t,request:e,response:r};return i.fs.stat(o).then((async e=>{await async function(e,t,n){let r=n;for(;r!==t;){const t=u(r),n=d(r);(await e.readdir(t)).includes(n)||l(),r=t}}(i.fs,t.cwd,o);const n=e.isDirectory();if(n||s)return n?async function(e){const t=h(e.filePath,"index.html"),n=await e.fs.stat(t);return n.isDirectory()&&l(18),w({...e,filePath:t},n)}(i):w(i,e)})).catch((()=>{}))}}})(),W=(()=>{const e=A,{7:t}=P,n=Q,r={403:"Forbidden",404:"Not found",405:"Method Not Allowed",500:"Internal Server Error",501:"Not Implemented",503:"Service Unavailable",508:"Loop Detected"};return{[t]:"status",schema:{status:C,headers:{type:_,defaultValue:{}}},redirect:function({mapping:t,match:o,response:s,redirect:i}){return n(s,r[i]||E,{statusCode:i,headers:{...e(o,t?t.headers:void 0)}})}}})(),K=(()=>{const{log:e,error:t}=console;return[e,t]})(),Y=(()=>{const[e,t]=K;return function(n,r,...o){let s;const i=[];if("ERROR"===n?(s=t,i.push(n)):(s=e,i.push(n)),r){const e=this.id.toString(16).toUpperCase();i.push(e.padStart(Math.max(4,e.length),"0")),this.internal&&i.push("(i)")}else i.push(this.method,this.url);i.push(o.join(" ")),s(...i)}})(),X=(()=>{const e=Y;return(t,n=!1)=>{const r=t.reason;if(t.method&&t.url){const o=[];n?o.push(r.toString()):o.push("\n\\____",r.toString()),e.call(t,"ERROR",n,...o)}else e.call({...t,method:E,url:E},"ERROR",!1,r.toString())}})(),Z=(()=>{const[e]=K,t=Y,n=X,r=(e,n)=>{const r=n.statusCode;let o;o=r?r.toString():"N/A",t.call(n,"SERVE",e,o,`${n.timeSpent} ms`)},o=e=>t.call(e,"INCMG",!0,e.method,e.url),s=(e,n)=>t.call(n,e,!0),i=e=>{const n=e.redirect;let r;r=typeof n===I?n.name||"anonymous":n.toString(),t.call(e,"RDRCT",!0,e.type,r)};return(t,a)=>(t.on("ready",(({url:t})=>{e(`Server running at ${t}`)})).on("redirected",r.bind(null,a)),a?t.on(R,(e=>{n(e,!0)})).on("incoming",o).on("aborted",s.bind(null,"ABORT")).on("closed",s.bind(null,"CLOSE")).on("redirecting",i):t.on(R,n),t)})(),ee=(()=>{const[e]=O,t="created,ready,incoming,error,redirecting,redirected,aborted,closed".split(",");return[function(){const n=[],r=(r,o)=>{const s=t.indexOf(r);-1===s&&e(0),typeof o!==I&&e(1),void 0===n[s]&&(n[s]=[]),n[s].push(o)};return{on:function(e,n){return"*"===e?t.forEach((e=>r(e,n))):r(e,n),this},emit:(e,...r)=>{const o=n[e];if(void 0!==o){const n=b({eventName:t[e]},...r);try{for(const e of o)e(n)}catch(t){if(0===e)throw t}return o.length}return 0}}}]})(),te=()=>{let e="127.0.0.1";const t=c();for(const n of v(t))for(const r of t[n])if(!r.internal&&("IPv4"===r.family||4===r.family)){e=r.address;break}return e},ne=(()=>{const[,e,,t]=P,n=D;return async(r,o)=>{r[e]=!0;const{timeout:s=0,force:i=!1}=o||{};if(s>0){const e=Array.from(r[t].contexts.values()).map((({holding:e})=>e)),[o,i]=n(),a=setTimeout((()=>i()),s);await Promise.race([Promise.all(e),o]),clearTimeout(a)}if(i)for(const{request:e}of r[t].contexts.values())e.destroy()}})(),re=(e,{timeout:t=400,host:n="127.0.0.1"}={})=>x((r=>{const o=new a;let s=!1;o.setTimeout(t),o.on("connect",(()=>{s=!0,o.destroy()})).on("timeout",(()=>{o.destroy()})).on(R,(()=>{})).on("close",(()=>{r(s)})),o.connect(e,n)})),oe=e=>{if(-1!==e.indexOf("./")||-1!==e.indexOf("%")||-1===e.indexOf("/"))try{const{pathname:t,search:n,hash:r}=new URL(e,"p:/");e=decodeURIComponent(t.replace(/%(0|1)(\d|[a-f])/gi,E))+n+r}catch(t){e=400}return e},se=(()=>{const e=X,t=A,n=oe,[,r,o,s,i,,,,,,,a,,c,d,u]=P,l=D,h=W;function f(e){const{emit:t,emitParameters:n,response:{statusCode:r},redirected:o}=e,s=p.now();n.end=new Date,n.perfEnd=s,n.timeSpent=Math.ceil(s-n.perfStart),n.statusCode=r,t(5,n),o()}function m(t,n){let r;r=typeof n===C?n:500,function({emit:t,emitParameters:n},r){t(3,n,{reason:r})||e({...n,reason:r})}(t,n),t.request.aborted?f(t):t.failed?(t.response.end(),f(t)):(t.failed=!0,w(t,r))}function g(e,{url:t,index:n},r){void 0!==r?function(e,t){++e.redirectCount>e.configuration["max-redirect"]?m(e,508):w(e,t)}(e,r):e.response.writableEnded?f(e):w(e,t,n+1)}function y(e,{mapping:t={},match:n,handler:r,type:s,redirect:i,url:a,index:c=0}){try{const{configuration:d,request:u,response:l,emit:h,emitParameters:p}=e;h(4,p,{type:s,redirect:i}),t["exclude-from-holding-list"]&&(e.nonHolding=!0,e.holding=Promise.resolve());const f=r.redirect({configuration:d[o],mapping:t,match:n,redirect:i,request:u,response:l});f&&f.then?f.then(g.bind(null,e,{url:a,index:c}),(t=>m(e,t))):g(e,{url:a,index:c},f)}catch(t){m(e,t)}}function w(e,t,n=0){const{configuration:r}=e;return typeof t===C?y(e,{type:"status",handler:r.handlers.status,redirect:t}):b(e,t,n)}function b(e,n,r){try{const{mappings:o}=e.configuration,{length:s}=o;for(;r<s;){const s=o[r],i=s[a](n,e.request);if(i){if(i.then)return void i.then((o=>{if(o){const{handler:i,redirect:a,type:d}=s[c];y(e,{mapping:s,match:o,handler:i,type:d,redirect:t(o,a),url:n,index:r})}else b(e,n,r+1)})).catch((t=>m(e,t)));const{handler:o,redirect:a,type:d}=s[c];return y(e,{mapping:s,match:i,handler:o,type:d,redirect:t(i,a),url:n,index:r})}++r}m(e,501)}catch(t){m(e,t)}}function v(){const{emit:e,emitParameters:t}=this[u];e(6,t)}function x(){const{emit:e,emitParameters:t,configuration:{[s]:{contexts:n}},id:r}=this[u];e(7,t),n.delete(r)}return function(e,t,o){if(e[r])return Promise.resolve(h.redirect({response:o,redirect:503}));const a=n(t.url),{[s]:c,[i]:f}=e,{contexts:m}=c,g=++c.lastId,y={id:g,internal:!!t[d],method:t.method.toUpperCase(),incomingUrl:t.url,url:a,headers:{...t.headers},start:new Date,perfStart:p.now()},[b,S]=l(),E={id:g,configuration:e,emit:f,emitParameters:y,holding:b,redirectCount:0,redirected:S,request:t,response:o};return t[u]=E,t.on("aborted",v),t.on("close",x),f(2,y),m.set(g,E),c.holding?c.holding.then((()=>w(E,a))):w(E,a),b}})(),ie=(()=>{const[e]=O,t="()^$[]|\\?+*{}".split(E);return n=>{if(n instanceof RegExp)return n;if(n&&n.re)return new RegExp(n.re,n.flags);if(typeof n!==B&&e(3),t.some((e=>n.includes(e))))return new RegExp(n);const r=n.endsWith("/");return new RegExp(`^${n.replace(/\./g,"\\.").replace(/:(\w+)/g,((e,t)=>`(?<${t}>[^/]*)`))}${r?E:"\\b"}(.*)`)}})(),ae=(()=>{const e=ie,[,,t]=q,[n]=O,{11:r,12:o}=P,s=[e=>t=>e.exec(t),(e,t)=>(n,{method:r})=>t.includes(r)&&e.exec(n),e=>t=>!e.exec(t)&&[],(e,t)=>(n,{method:r})=>(!t.includes(r)||!e.exec(n))&&[]];return i=>{let{match:a}=i;a=void 0===a?/(.*)/:e(a);const c=i["invert-match"];t(c)&&n(4);const d=i["if-match"];["undefined",I].includes(typeof d)||n(5);let u=0;const l=i[o];l&&(u+=1),c&&(u+=2);const h=s[u](a,l);i[r]=d?function(e,t){const n=h(e,t),r=e=>e?n:null;return n?(a=d(t,n),a&&a.then?a.then(r):r(a)):null}:h}})(),ce=(()=>{const[,e,t]=q,n=j,r=ae,[,,o,,,,,,s,i,a,,c,d]=P,[u]=O;return async(l,h)=>{!function(e,t){t.cwd||(t.cwd=e.cwd)}(l,h),function(e){t(e["exclude-from-holding-list"])&&u(6)}(h),h[d]=function(e,t){const{handlers:n}=e,r=v(n);for(const e of r){const r=t[e];if(void 0!==r)return{handler:n[e],redirect:r,type:e}}u(7,{mapping:JSON.stringify(t)})}(l,h);const{handler:p}=h[d];n(h,c,p[s]),p[i]&&e(p[i],h),p.validate&&await p.validate(h,l[o]),r(h),h[a]=!0}})(),de=(()=>{const e=ce,t=se,[n,,,r,,,,,,,o,,,,s]=P,i=D,[,a]=O;return class{constructor(e){this[n]=e}get handlers(){const{handlers:e}=this[n];return v(e).reduce(((t,n)=>(t[n]=b({},e[n]),t)),{})}get mappings(){return[].concat(this[n].mappings)}get http2(){return this[n].http2}get protocol(){return this[n].protocol}async setMappings(t,s,c=5e3){const d=this[n];await async function(t,n){for(const r of n)r[o]||await e(t,r)}(d,t);const u=d[r],l=Array.from(u.contexts.values()),h=l.filter((({request:e})=>e===s))[0],p=l.filter((e=>e!==h)).map((({holding:e})=>e)),[f,,m]=i(),g=setTimeout((()=>m(a(14))),c),y=Promise.race([Promise.all(p),f]).then((()=>{clearTimeout(g),d.mappings=t}));return u.holding=y.then(void 0,(()=>{})),y.then(void 0,(()=>{console.log("REserve blocked during configuration.setMappings"),console.table(l.map((e=>{const{emitParameters:t,request:n,nonHolding:r,id:o}=e;let s;return s=t.statusCode?{statusCode:t.statusCode}:r?"exclude-from-holding-list":e===h?"configure.setMappings":{ms:new Date-t.start},{id:o,method:n.method,url:n.url,info:s}})))})),y}dispatch(e,r){const o=this[n];return e[s]=!0,t(o,e,r)}}})(),ue=(()=>{const e=de,t=ce,o=j,[s]=q,[,,i,a,,,,c,d,p]=P,f=N,[m]=O,g=[G,J,W,F,H].reduce(((e,t)=>(w(t),e[t[c]]=t,e)),{}),y={cwd:process.cwd(),hostname:void 0,port:5e3,"max-redirect":10,listeners:[],mappings:[{match:"(.*)",file:"./$1"},{status:404}]};function w(e,t){e.schema&&!e[p]&&(e[p]=s(e.schema)),e.method&&!e[d]&&o(e,d),typeof e.redirect!==I&&m(10,{type:t})}async function x({cwd:e,handlers:t},n){let r=t[n];typeof r===B&&(l(r)||(r=h(e,r)),r=await f(r),t[n]=r),w(r,n)}function S(){m(11)}async function E(e,t){return l(t)?(await n(t)).toString():(await n(h(e.ssl.cwd,t))).toString()}function C(e,t){const r=u(e);if(function(e,t){t.handlers&&v(t.handlers).forEach((n=>{const r=t.handlers[n];typeof r===B&&r.match(/^\.\.?\//)&&(t.handlers[n]=h(e,r))})),t.mappings&&t.mappings.forEach((t=>{t.cwd||(t.cwd=e)})),t.ssl&&!t.ssl.cwd&&(t.ssl.cwd=e),t.cwd=e}(r,t),t.extend){const e=h(r,t.extend);return delete t.extend,n(e).then((e=>JSON.parse(e.toString()))).then((n=>{const r=n.mappings,o=b(n,t);return r&&r!==o.mappings&&(o.mappings=[...t.mappings,...r]),C(e,o)}))}return t}return[w,async function(n,r){typeof n===_&&null!==n||m(13);const o=b({},n);return function(e){v(y).forEach((t=>{Object.prototype.hasOwnProperty.call(e,t)||(e[t]=y[t])}))}(o),await async function(e,t={}){const n=v(g).reduce(((e,t)=>(e[t]=b({},g[t]),e)),{});e.handlers=b({},e.handlers||{},n),v(t).forEach((n=>b(e.handlers[n],t[n])));for(const t of v(e.handlers))await x(e,t)}(o,r),await async function({cwd:e,listeners:t}){Array.isArray(t)||S();let n=0;for(let r of t){let o=typeof r;o===B&&(r=await f(h(e,r)),t[n]=r,o=typeof r),o!==I&&S(),++n}}(o),await async function(e){e.ssl?(e.ssl.cert=await E(e,e.ssl.cert),e.ssl.key=await E(e,e.ssl.key),e.protocol="https"):e.protocol="http",[!0,!1,void 0].includes(e.http2)||m(12),e.http2||(e.http2=!1)}(o),await async function(n){const r=new e(n);n[i]=r;for(const e of n.mappings)await t(n,e)}(o),o[a]={lastId:0,holding:null,contexts:new Map},o},async function(e){let t;return t=l(e)?e:h(process.cwd(),e),r(t).then((()=>n(t).then((e=>JSON.parse(e.toString()))))).then((e=>C(t,e)))}]})(),le=(()=>{const[,e]=ue,t=se,[n]=ee,r=V,o=T,[,,s,,i]=P,a=te,c=ne;return(d,u)=>{const{on:l,emit:h}=n();let p;const f={on:l,async close(e){await c(p,e)}};return e(d,u).then((e=>{p=e,p[i]=h,p.listeners.forEach((e=>e(f))),h(0,{configuration:p[s],server:null});const n=t.bind(null,p);f.request=function(){const e=new r(...arguments),t=new o,s=t.waitForFinish();return n(e,t).then((()=>s))};const c=p.hostname||a(),{port:d,http2:u}=p;h(1,{url:`${p.protocol}://${c}:${d}/`,port:d,http2:u})})).catch((e=>{h(3,{error:e})})),f}})(),he=(()=>{const[e]=ee,[,t]=ue,n=se,[,,r,,a]=P,c=te,d=re,[u]=O,l=ne;function h(e,t,n){return x(((a,c)=>{const d=function(e,t){const{httpOptions:n}=e;return e.ssl?e.http2?s.createSecureServer({key:e.ssl.key,cert:e.ssl.cert,...n},t):i.createServer({key:e.ssl.key,cert:e.ssl.cert,...n},t):e.http2?s.createServer(n,t):o.createServer(n,t)}(t,n.bind(null,t));e(0,{configuration:t[r],server:d});let{port:u}=t;"auto"===u&&(u=0),d.listen(u,t.hostname,(e=>e?c(e):a(d)))}))}return r=>{const{on:o,emit:s}=e();let i,p;const f={on:o,async close(e){i&&(await l(p,e),await x((e=>i.close((()=>e())))),i.closeIdleConnections&&i.closeIdleConnections(),i.closeAllConnections&&i.closeAllConnections())}};return t(r).then((async e=>{p=e;let{port:t,http2:r}=p;0!==t&&await d(t)&&u(2,{port:t}),p[a]=s,p.listeners.forEach((e=>e(f))),i=await h(s,p,n);const o=p.hostname||c();t=i.address().port,s(1,{url:`${p.protocol}://${o}:${t}/`,port:t,http2:r})})).catch((e=>{s(3,{reason:e})})),f}})();return(()=>{const[,e,t]=ue;return{Request:V,Response:T,body:M,capture:z,check:e,interpolate:A,log:Z,mock:le,punycache:k,read:t,send:Q,serve:he}})()};