@aventurevc/mcp-server 0.8.219 → 0.8.220

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.
@@ -142,7 +142,7 @@ Profile on interface`)}catch(e){return e.status===1&&e.stdout.includes(`AutoConf
142
142
  `).map(e=>e.trim());i=c.getValue(e,`gateway`)}i?(e&&e(i),t(i)):(n=`netstat -rn | awk '/default/ {print $2}'`,r(n,{maxBuffer:104857600},(n,r)=>{i=r.toString().split(`
143
143
  `).map(e=>e.trim()).find(e=>/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(e)),e&&e(i),t(i)}))})}catch{e&&e(i),t(i)}}if(f)try{r(`netstat -r`,c.execOptsWin,(r,a)=>{a.toString().split(n.EOL).forEach(e=>{if(e=e.replace(/\s+/g,` `).trim(),e.indexOf(`0.0.0.0 0.0.0.0`)>-1&&!/[a-zA-Z]/.test(e)){let t=e.split(` `);t.length>=5&&t[t.length-3].indexOf(`.`)>-1&&(i=t[t.length-3])}}),i?(e&&e(i),t(i)):c.powerShell(`Get-CimInstance -ClassName Win32_IP4RouteTable | Where-Object { $_.Destination -eq '0.0.0.0' -and $_.Mask -eq '0.0.0.0' }`).then(n=>{let r=n.toString().split(`\r
144
144
  `);r.length>1&&!i&&(i=c.getValue(r,`NextHop`),e&&e(i),t(i))})})}catch{e&&e(i),t(i)}})})}t.networkGatewayDefault=ye})),wb=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getNetworkData=void 0;var t=Cb();function n(){return new Promise(e=>{(0,t.networkStats)().then(e).catch(()=>{e([])})})}e.getNetworkData=n})),Tb=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.HostMetrics=void 0;var t=yb(),n=bb(),r=xb(),i=wb();e.HostMetrics=class extends t.BaseMetrics{_batchUpdateCpuUsages(e,t){for(let r=0,i=t.length;r<i;r++){let i=t[r];e.observe(this._cpuTime,i.user,{[n.ATTR_SYSTEM_CPU_STATE]:n.SYSTEM_CPU_STATE_VALUE_USER,[n.ATTR_SYSTEM_CPU_LOGICAL_NUMBER]:i.cpuNumber}),e.observe(this._cpuTime,i.system,{[n.ATTR_SYSTEM_CPU_STATE]:n.SYSTEM_CPU_STATE_VALUE_SYSTEM,[n.ATTR_SYSTEM_CPU_LOGICAL_NUMBER]:i.cpuNumber}),e.observe(this._cpuTime,i.idle,{[n.ATTR_SYSTEM_CPU_STATE]:n.SYSTEM_CPU_STATE_VALUE_IDLE,[n.ATTR_SYSTEM_CPU_LOGICAL_NUMBER]:i.cpuNumber}),e.observe(this._cpuTime,i.interrupt,{[n.ATTR_SYSTEM_CPU_STATE]:n.SYSTEM_CPU_STATE_VALUE_INTERRUPT,[n.ATTR_SYSTEM_CPU_LOGICAL_NUMBER]:i.cpuNumber}),e.observe(this._cpuTime,i.nice,{[n.ATTR_SYSTEM_CPU_STATE]:n.SYSTEM_CPU_STATE_VALUE_NICE,[n.ATTR_SYSTEM_CPU_LOGICAL_NUMBER]:i.cpuNumber}),e.observe(this._cpuUtilization,i.userP,{[n.ATTR_SYSTEM_CPU_STATE]:n.SYSTEM_CPU_STATE_VALUE_USER,[n.ATTR_SYSTEM_CPU_LOGICAL_NUMBER]:i.cpuNumber}),e.observe(this._cpuUtilization,i.systemP,{[n.ATTR_SYSTEM_CPU_STATE]:n.SYSTEM_CPU_STATE_VALUE_SYSTEM,[n.ATTR_SYSTEM_CPU_LOGICAL_NUMBER]:i.cpuNumber}),e.observe(this._cpuUtilization,i.idleP,{[n.ATTR_SYSTEM_CPU_STATE]:n.SYSTEM_CPU_STATE_VALUE_IDLE,[n.ATTR_SYSTEM_CPU_LOGICAL_NUMBER]:i.cpuNumber}),e.observe(this._cpuUtilization,i.interruptP,{[n.ATTR_SYSTEM_CPU_STATE]:n.SYSTEM_CPU_STATE_VALUE_INTERRUPT,[n.ATTR_SYSTEM_CPU_LOGICAL_NUMBER]:i.cpuNumber}),e.observe(this._cpuUtilization,i.niceP,{[n.ATTR_SYSTEM_CPU_STATE]:n.SYSTEM_CPU_STATE_VALUE_NICE,[n.ATTR_SYSTEM_CPU_LOGICAL_NUMBER]:i.cpuNumber})}}_batchUpdateProcessCpuUsages(e,t){e.observe(this._processCpuTime,t.user,{[n.ATTR_PROCESS_CPU_STATE]:n.PROCESS_CPU_STATE_VALUE_USER}),e.observe(this._processCpuTime,t.system,{[n.ATTR_PROCESS_CPU_STATE]:n.PROCESS_CPU_STATE_VALUE_SYSTEM}),e.observe(this._processCpuUtilization,t.userP,{[n.ATTR_PROCESS_CPU_STATE]:n.PROCESS_CPU_STATE_VALUE_USER}),e.observe(this._processCpuUtilization,t.systemP,{[n.ATTR_PROCESS_CPU_STATE]:n.PROCESS_CPU_STATE_VALUE_SYSTEM})}_batchUpdateMemUsages(e,t){e.observe(this._memoryUsage,t.used,{[n.ATTR_SYSTEM_MEMORY_STATE]:n.SYSTEM_MEMORY_STATE_VALUE_USED}),e.observe(this._memoryUsage,t.free,{[n.ATTR_SYSTEM_MEMORY_STATE]:n.SYSTEM_MEMORY_STATE_VALUE_FREE}),e.observe(this._memoryUtilization,t.usedP,{[n.ATTR_SYSTEM_MEMORY_STATE]:n.SYSTEM_MEMORY_STATE_VALUE_USED}),e.observe(this._memoryUtilization,t.freeP,{[n.ATTR_SYSTEM_MEMORY_STATE]:n.SYSTEM_MEMORY_STATE_VALUE_FREE})}_batchUpdateProcessMemUsage(e,t){e.observe(this._processMemoryUsage,t)}_batchUpdateNetworkData(e,t){for(let r=0,i=t.length;r<i;r++){let i=t[r];e.observe(this._networkDropped,i.rx_dropped,{[n.ATTR_SYSTEM_DEVICE]:i.iface,[n.ATTR_NETWORK_IO_DIRECTION]:n.NETWORK_IO_DIRECTION_VALUE_RECEIVE}),e.observe(this._networkDropped,i.tx_dropped,{[n.ATTR_SYSTEM_DEVICE]:i.iface,[n.ATTR_NETWORK_IO_DIRECTION]:n.NETWORK_IO_DIRECTION_VALUE_TRANSMIT}),e.observe(this._networkErrors,i.rx_errors,{[n.ATTR_SYSTEM_DEVICE]:i.iface,[n.ATTR_NETWORK_IO_DIRECTION]:n.NETWORK_IO_DIRECTION_VALUE_RECEIVE}),e.observe(this._networkErrors,i.tx_errors,{[n.ATTR_SYSTEM_DEVICE]:i.iface,[n.ATTR_NETWORK_IO_DIRECTION]:n.NETWORK_IO_DIRECTION_VALUE_TRANSMIT}),e.observe(this._networkIo,i.rx_bytes,{[n.ATTR_SYSTEM_DEVICE]:i.iface,[n.ATTR_NETWORK_IO_DIRECTION]:n.NETWORK_IO_DIRECTION_VALUE_RECEIVE}),e.observe(this._networkIo,i.tx_bytes,{[n.ATTR_SYSTEM_DEVICE]:i.iface,[n.ATTR_NETWORK_IO_DIRECTION]:n.NETWORK_IO_DIRECTION_VALUE_TRANSMIT})}}_createMetrics(){let e=[],t=!this._metricGroups||this._metricGroups.includes(`system.cpu`),a=!this._metricGroups||this._metricGroups.includes(`system.memory`),o=!this._metricGroups||this._metricGroups.includes(`system.network`),s=!this._metricGroups||this._metricGroups.includes(`process.cpu`),c=!this._metricGroups||this._metricGroups.includes(`process.memory`);t&&(this._cpuTime=this._meter.createObservableCounter(n.METRIC_SYSTEM_CPU_TIME,{description:`Cpu time in seconds`,unit:`s`}),e.push(this._cpuTime),this._cpuUtilization=this._meter.createObservableGauge(n.METRIC_SYSTEM_CPU_UTILIZATION,{description:`Cpu usage time 0-1`}),e.push(this._cpuUtilization)),a&&(this._memoryUsage=this._meter.createObservableGauge(n.METRIC_SYSTEM_MEMORY_USAGE,{description:`Memory usage in bytes`}),e.push(this._memoryUsage),this._memoryUtilization=this._meter.createObservableGauge(n.METRIC_SYSTEM_MEMORY_UTILIZATION,{description:`Memory usage 0-1`}),e.push(this._memoryUtilization)),o&&(this._networkDropped=this._meter.createObservableCounter(`system.network.dropped`,{description:`Network dropped packets`}),e.push(this._networkDropped),this._networkErrors=this._meter.createObservableCounter(n.METRIC_SYSTEM_NETWORK_ERRORS,{description:`Network errors counter`}),e.push(this._networkErrors),this._networkIo=this._meter.createObservableCounter(n.METRIC_SYSTEM_NETWORK_IO,{description:`Network transmit and received bytes`}),e.push(this._networkIo)),s&&(this._processCpuTime=this._meter.createObservableCounter(n.METRIC_PROCESS_CPU_TIME,{description:`Process Cpu time in seconds`,unit:`s`}),e.push(this._processCpuTime),this._processCpuUtilization=this._meter.createObservableGauge(n.METRIC_PROCESS_CPU_UTILIZATION,{description:`Process Cpu usage time 0-1`}),e.push(this._processCpuUtilization)),c&&(this._processMemoryUsage=this._meter.createObservableGauge(n.METRIC_PROCESS_MEMORY_USAGE,{description:`Process Memory usage in bytes`}),e.push(this._processMemoryUsage)),this._meter.addBatchObservableCallback(async e=>{if(t){let t=(0,r.getCpuUsageData)();this._batchUpdateCpuUsages(e,t)}if(a){let t=(0,r.getMemoryData)();this._batchUpdateMemUsages(e,t)}if(s){let t=(0,r.getProcessCpuUsageData)();this._batchUpdateProcessCpuUsages(e,t)}if(c){let t=(0,r.getProcessMemoryData)();this._batchUpdateProcessMemUsage(e,t)}if(o){let t=await(0,i.getNetworkData)();this._batchUpdateNetworkData(e,t)}},e)}start(){this._createMetrics()}_cpuTime;_cpuUtilization;_memoryUsage;_memoryUtilization;_processCpuTime;_processCpuUtilization;_processMemoryUsage;_networkDropped;_networkErrors;_networkIo}})),Eb=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.HostMetrics=e.BaseMetrics=void 0;var t=yb();Object.defineProperty(e,"BaseMetrics",{enumerable:!0,get:function(){return t.BaseMetrics}});var n=Tb();Object.defineProperty(e,"HostMetrics",{enumerable:!0,get:function(){return n.HostMetrics}})}));u();var Db=ob(),Ob=Eb();m(),Mc();var kb=`aventure-mcp-server`,Ab=`http_server_requests_seconds`,jb=[.005,.01,.025,.05,.1,.25,.5,1,2.5,5,10],Mb,Nb,Pb,Fb,Ib;function Lb(e,t){if(Nb!==void 0)return;let n=e?new Db.PrometheusExporter({preventServerStart:!0}):void 0,r=new kc({resource:S({...ce(),"service.version":process.env.GIT_SHA??process.env.SENTRY_RELEASE??Ii().version}),readers:[...n===void 0?[]:[n],...t===void 0?[]:[new Qo({exporter:new _b({url:t}),exportIntervalMillis:1e4,exportTimeoutMillis:5e3})]]});s.setGlobalMeterProvider(r),Nb=r,Mb=n;let i=new Ob.HostMetrics({meterProvider:r,name:kb});i.start(),Ib=i}function Rb(){return Pb===void 0&&(Pb=Nb?.getMeter(kb)),Pb}function zb(e,t,n,r,{rpcMethod:i,toolName:a,client:o,outcome:s}){let c=Rb();c!==void 0&&(Fb===void 0&&(Fb=c.createHistogram(Ab,{description:`HTTP server request latency in seconds, partitioned by method/route/status/rpc_method/tool/client/outcome.`,unit:`s`,advice:{explicitBucketBoundaries:jb}})),Fb.record(r/1e3,{method:e.toUpperCase(),route:t,status:String(n),rpc_method:i,tool:a,client:o,outcome:s}))}function Bb(e,t){let n=Ii().registry===``&&!!t,r=process.env.OTEL_EXPORTER_OTLP_METRICS_ENDPOINT?.trim()||void 0;if(!n&&r===void 0)return;Lb(n,r);let i=Mb;if(!n||t===void 0||i===void 0)return;let a=aa(`sha256`).update(t).digest();e.get(`/metrics`,(e,t,n)=>{if(!Hb(e.headers.authorization,a)){t.status(401).type(`text/plain`).send(`Unauthorized`);return}n()},(e,t)=>{i.getMetricsRequestHandler(e,t)})}async function Vb(){let e=Nb;Ib!==void 0&&(Ib=void 0),Nb=void 0,Mb=void 0,Pb=void 0,Fb=void 0,e!==void 0&&await e.shutdown()}function Hb(e,t){let n=Mr(e);if(n===void 0)return!1;let r=aa(`sha256`).update(n).digest();return r.length===t.length&&sa(r,t)}var Ub=`#/components/schemas/`,Wb=/"#\/components\/schemas\/([^"]+)"/g,Gb=-32011,Kb=-32012,qb=-32013,Jb=-32015;function Yb(e){let t=_t().components.schemas[e];if(t===void 0)throw Error(`OpenAPI has no component ${e}`);return t}function Xb(e){let t=ve(e?.content?.[`application/json`]?.schema);return t===void 0?void 0:Yb(t)}function Zb(e){let t=Object.keys(e).length===1?ve(e):void 0,n=t===void 0?e:Yb(t),r={},i=e=>{for(let[,t]of JSON.stringify(e).matchAll(Wb))t===void 0||t in r||(r[t]=Yb(t),i(r[t]))};i(n);let a=Object.keys(r).length===0?n:{...n,$defs:r},o=Mi.safeParse(JSON.parse(JSON.stringify(a).replaceAll(`"${Ub}`,`"#/$defs/`)));if(!o.success)throw Error(`Event schema is not JSON: ${o.error}`);return o.data}function Qb(e,t){let n=Object.entries(_t().paths).find(([,n])=>Xb(n[e]?.requestBody)?.properties?.name?.$ref===t);if(n===void 0)throw Error(`OpenAPI has no ${e} operation for ${t}`);return n[0]}var $b=new Map(Object.entries(_t().webhooks??{}).map(([e,t])=>{let n=Xb(t.post.requestBody),r=n?.properties?.name?.$ref,i=n?.properties?.data;if(r===void 0||i===void 0)throw Error(`Webhook ${e} body must carry a name enum $ref and a data schema`);let a=Qb(`put`,r),o=Xb(_t().paths[a]?.put?.requestBody)?.properties?.arguments;if(o===void 0)throw Error(`Subscribe body for ${e} must carry an arguments schema`);return[e,{descriptor:{name:e,description:t.post.description,delivery:[`webhook`],inputSchema:Zb(o),payloadSchema:Zb(i)},subscribePath:a,unsubscribePath:Qb(`delete`,r)}]})),ex=G({name:W()}).catchall(Mi),tx=F(W(),Mi);function nx(e){let t=$b.get(e);if(t===void 0)throw new Z(Gb,`Unknown event ${e}`);return t}async function rx(e,t,n){let{_meta:r,...i}=n,a=await Bt({method:e,path:t,body:i,auth:`auto`});if(a.ok){let e=tx.safeParse(a.data!==null&&typeof a.data==`object`&&`response`in a.data?a.data.response??{}:{});if(e.success)return e.data;throw new Z(X.InternalError,`${t} answered a non-object body`)}let o=ix(a.problem?.code);throw o===void 0?a.problem?.code===`news_subscription_limit`?new Z(qb,a.summary,{limit:`subscriptions`}):new Z(ax(a.httpStatus),a.summary,a.problem):new Z(Jb,`CallbackEndpointError`,{reason:o})}function ix(e){switch(e){case`callback_connection_refused`:return`connection_refused`;case`callback_timeout`:return`timeout`;case`callback_tls_error`:return`tls_error`;case`callback_http_4xx`:return`http_4xx`;case`callback_http_5xx`:return`http_5xx`;case`callback_challenge_failed`:return`challenge_failed`;default:return}}function ax(e){switch(e){case 400:case 422:return X.InvalidParams;case 401:case 403:return Kb;case 404:return Gb;default:return X.InternalError}}function ox(e){if($b.size===0)return;let t=[...$b.values()].map(e=>e.descriptor);e.server.setRequestHandler(`events/list`,{params:G({})},()=>({events:t})),e.server.setRequestHandler(`events/subscribe`,{params:ex},e=>rx(`PUT`,nx(e.name).subscribePath,e)),e.server.setRequestHandler(`events/unsubscribe`,{params:ex},e=>rx(`DELETE`,nx(e.name).unsubscribePath,e))}async function sx(e){try{return await Bt(e)}catch(t){return N({component:`aventure-mcp-server`,event:`tool_request_failed`,fields:{requestId:we(),method:e.method},error:t}),Ai(le(t))}}function cx(e,t){let n=Oe(e.requestBody??[],t.contentType).data;return[...e.parameter.filter(e=>e.in===`query`).map(e=>({parameter:e,label:`Query parameter`,sent:[e.name,e.legacyName].flatMap(e=>e===void 0?[]:[t.query?.[e]])})),...(n?.parameter??[]).map(e=>({parameter:e,label:`Body field`,sent:ux(t.body,e.name.split(`.`))}))].flatMap(({parameter:{name:e,schemaEnum:t,itemSchemaEnum:n,enumOpen:r},label:i,sent:a})=>{let o=r===!0?[]:t??n??[],s=new Set(o.map(lx)),c=i===`Query parameter`&&n!==void 0,l=a.flatMap(e=>Array.isArray(e)?e.filter(e=>typeof e==`string`):typeof e==`string`?c?e.split(`,`).map(e=>e.trim()):[e]:[]).filter(e=>!s.has(lx(e)));return o.length===0||l.length===0?[]:[` ${i} '${e}' does not accept ${l.map(e=>JSON.stringify(e)).join(`, `)}; send one of ${o.join(`, `)}.`]}).join(``)}var lx=e=>e.toLowerCase().replaceAll(/[^\p{L}\p{N}]/gu,``);function ux(e,t){let[n,...r]=t;if(e===void 0)return[];if(n===void 0)return[e];if(typeof e!=`object`||!e||Array.isArray(e))return[];if(!n.endsWith(`[]`))return ux(e[n],r);let i=e[n.slice(0,-2)];return Array.isArray(i)?i.flatMap(e=>ux(e,r)):[]}var dx=3,fx=200,px=80;function mx(e,t){let{operationId:n}=e;if(n===void 0&&e.method!==void 0&&e.path!==void 0)return null;let r=t.find(e=>e.operationId===n);if(r!==void 0)return hx(r,e,t);let i=bx(n??``,t),a=qi(i.noun),o=Sx(e),s=[...a,...o.flatMap(({word:e})=>e)].join(` `),c=(s.length===0?[]:Wi(s,t,Bi)).map(({item:e,score:t})=>({item:e,score:t+xx(e,a,o.map(({key:e})=>e))})).toSorted((e,t)=>Number(e.item.deprecated===!0)-Number(t.item.deprecated===!0)||Number(i.intent.has(t.item.intent))-Number(i.intent.has(e.item.intent))||Number(i.method.has(t.item.method))-Number(i.method.has(e.item.method))||t.score-e.score).slice(0,dx).map(({item:e})=>zi(e,!1)),l=c.map(e=>`${e.operationId} (${e.method} ${e.path})`);return Ai(`${n===void 0?`Pass operationId or method+path; aventure_help with q set to the task lists operationIds.`:`Operation ${n} is not in the MCP catalog.`}${l.length===0?``:` Closest operations: ${l.join(`, `)}.`}`,c.map(e=>`Use operationId ${e.operationId} with aventure_${e.intent}: ${e.method} ${e.path}; required inputs: ${e.requiredInput.length===0?`none`:e.requiredInput.join(`, `)}.`))}function hx(e,t,n){let r=t.pathParams??{},i=e.parameter.filter(({in:e,required:t,name:n,legacyName:i})=>e===`path`&&t&&r[n]==null&&(i===void 0||r[i]==null));if(i.length===0)return null;let a=new Set(e.parameter.filter(({in:e})=>e===`query`).flatMap(({name:e,legacyName:t})=>t===void 0?[e]:[e,t])),o=Object.fromEntries(i.flatMap(e=>{let n=[e.name,e.legacyName].find(e=>e!==void 0&&!a.has(e)&&t.query?.[e]!=null),r=n===void 0?void 0:t.query?.[n];return gx(e,r)?[[e.name,r]]:[]})),s=i.map(({name:e})=>e).filter(e=>!(e in o)),c=Object.entries(t.query??{}).filter(([e])=>a.has(e)||!i.some(({name:t,legacyName:n})=>e===t||e===n)),l=JSON.stringify({operationId:e.operationId,pathParams:{...r,...o,...Object.fromEntries(s.map(e=>[e,`<${e}>`]))},...c.length===0?{}:{query:Object.fromEntries(c)}}),u=s.flatMap(t=>_x(e.path,t,n).map(e=>{let n=e.parameter.filter(e=>e.in===`query`&&e.schemaEnum===void 0),r=n.filter(e=>e.required),i=r.length>0?r:n.filter(e=>e.schemaType===`string`&&e.name!==`cursor`).slice(0,1),a=n.filter(e=>e.schemaType===`string`);return` Get ${t} from ${e.operationId} (${e.method} ${e.path}): aventure_${e.intent} ${JSON.stringify({operationId:e.operationId,...i.length===0?{}:{query:Object.fromEntries(i.map(e=>[e.name,`<${e.name}>`]))}})} returns the record whose id goes in pathParams.${t}${a.length===0?``:`; its query takes ${a.map(e=>e.name).join(`, `)}`}.`}));return Ai(`Missing path parameter${i.length===1?``:`s`} ${i.map(({name:e})=>`'${e}'`).join(`, `)} for ${e.operationId}. Path parameters go in pathParams: aventure_${e.intent} ${l}.${u.join(``)}`)}function gx(e,t){return e.schemaType===`integer`?typeof t==`number`&&Number.isInteger(t):e.schemaType===`number`?typeof t==`number`&&Number.isFinite(t):typeof t==`string`&&t.length>0}function _x(e,t,n){let r=`{${t}}`,i=e.slice(0,e.indexOf(r)+r.length),a=n.find(e=>e.method===`GET`&&e.path===i),o=a===void 0?void 0:yx(a);return o===void 0?[]:n.filter(e=>e.method===`GET`&&e.deprecated!==!0&&e.parameter.every(e=>e.in!==`path`)&&yx(e)===o).toSorted((e,t)=>Number(vx(t))-Number(vx(e)))}function vx(e){return e.intent===`lookup`||/lookup/iu.test(e.operationId)}function yx(e){let t=_e(_t().paths,e.operationId)?.operation.responses??{},n=new Set(Object.entries(t).filter(([e])=>e.startsWith(`2`)).map(([,e])=>e.content?.[`application/json`]?.schema?.$ref));return n.size===1?[...n][0]:void 0}function bx(e,t){let[n=``,...r]=Yi(e).split(` `),i=t.filter(e=>Yi(e.operationId).startsWith(`${n} `));return i.length>0&&r.length>0?{noun:r.join(` `),intent:new Set(i.map(e=>e.intent)),method:new Set(i.map(e=>e.method))}:{noun:e,intent:new Set,method:new Set}}function xx(e,t,n){let r=`${e.operationId} ${e.summary}`,i=new Set(qi(r)),a=Ri(Yi(r)),o=t.reduce((e,t)=>e+(i.has(t)?2:+!!a.has(t)),0),s=new Set([...e.parameter,...(e.requestBody??[]).flatMap(e=>e.parameter)].map(({name:e})=>e)),c=n.filter(e=>s.has(e)).length,l=Ri(t.join(` `)),u=qi(e.operationId).slice(1).filter(e=>!l.has(e)).length;return(o+2*c-u)*px}function Sx(e){let t=e.body,n=typeof t==`object`&&t&&!Array.isArray(t)?Object.entries(t):[];return[...Object.entries(e.pathParams??{}),...Object.entries(e.query??{}),...n].map(([e,t])=>({key:e,word:typeof t==`string`&&t.length<=fx?[e,t]:[e]}))}function Cx({contract:e,input:t,intent:n,contracts:r,catalog:i}){let{operationId:a}=e;if(!n.includes(e.intent))return Ai(`Operation ${a} has intent=${e.intent}; call aventure_${e.intent} ${JSON.stringify({operationId:a,pathParams:t.pathParams,query:t.query,body:t.body})}.`);let o=i.find(e=>e.operationId===a)??e,s=o.parameter.filter(e=>e.in===`query`),c=Object.entries(t.query??{}),l=c.filter(([e])=>!pt.includes(e)&&!s.some(t=>wx(t,e))),u=e.parameter.filter(e=>e.in===`query`),d=u.map(({name:e})=>e),f=e.requestBody??[],p=f[0]?.schemaType===`array`,m=new Set((o.requestBody??[]).flatMap(e=>e.parameter.map(({name:e})=>e))),h=p?[]:l.filter(([e])=>m.has(e)),g=new Map(l.flatMap(([e])=>{let t=u.filter(t=>Tx(t,e)),n=d.find(t=>lx(t)===lx(e))??(t.length===1?t[0]?.name:void 0);return n===void 0||h.some(([t])=>t===e)?[]:[[e,n]]})),_=l.filter(([e])=>!g.has(e)&&!h.some(([t])=>t===e)),v=t.body===void 0&&f.some(e=>e.required&&e.kind!==`multipart`),y=cx(o,t);if(l.length===0&&!v)return y===``?null:Ai(y.trim());let b=typeof t.body==`object`&&t.body!==null&&!Array.isArray(t.body)?t.body:void 0,x=f[0]?.parameter??[],S=v?x.filter(({name:e,required:t})=>t&&!h.some(([t])=>t===e)).map(({name:e})=>e):[],C=p||t.body!==void 0&&b===void 0?t.body??[]:{...Object.fromEntries(S.map(e=>[e,`<${e}>`])),...b,...Object.fromEntries(h)},w=c.flatMap(([e,t])=>{let n=l.some(([t])=>t===e)?g.get(e):e;return n===void 0?[]:[[n,t]]}),T=JSON.stringify({operationId:a,...t.pathParams===void 0?{}:{pathParams:t.pathParams},...w.length===0?{}:{query:Object.fromEntries(w)},...f.length===0?{}:{body:C}}),E=l.length===0?``:`${a} declares no query parameter ${Ox(l)}; ${d.length===0?`it takes no query`:`its query takes ${d.join(`, `)}`}.${[...g].map(([e,t])=>` Send '${e}' as '${t}'.`).join(``)}${_.length===0?``:` The call below removes ${Ox(_)}: no declared filter matches ${_.length===1?`it`:`them`}.`}`,D=h.length>0?` ${Ox(h)} ${h.length===1?`is a request body field`:`are request body fields`}: send ${h.length===1?`it`:`them`} in body.`:v?` ${a} requires a request body: send it in body${x.length===0?``:`; its fields are ${x.map(({name:e})=>e).join(`, `)}`}.`:``;return Ai(`${E}${D}${y} Call aventure_${e.intent} ${T}.${kx(e,r)}`.trim())}function wx(e,t){if(t===e.name||t===e.legacyName)return!0;let n=Number(/^\[(?<index>\d+)\]/u.exec(t.slice(e.name.length))?.groups?.index),r=Ji(e.name,0,``);return t.startsWith(e.name)&&Number.isInteger(n)&&(e.itemProperty??[]).some(i=>t===Ji(e.name,n,i.name.slice(r.length)))}function Tx(e,t){let[n=``]=e.description.split(/(?<=\.)\s/u),r=new Set(qi(`${e.name} ${n}`)),i=qi(t);return i.length>=Ex&&i.at(-1)===qi(e.name).at(-1)&&i.every(e=>r.has(e))}var Ex=3,Dx=/\b(?<method>GET|POST|PUT|PATCH|DELETE) (?<path>\/[^\s?),]*[^\s?),.])/u;function Ox(e){return e.map(([e])=>`'${e}'`).join(`, `)}function kx(e,t){if(e.deprecated!==!0)return``;let n=/^Deprecated: (?<advice>.*?\.)(?=\s|$)/su.exec(e.description)?.groups?.advice;if(n===void 0)return` ${e.operationId} is deprecated.`;let r=Dx.exec(n)?.groups,i=t.find(e=>e.method===r?.method&&e.path===r?.path);return` ${e.operationId} is deprecated: ${n}${i===void 0?``:` Its replacement is ${i.operationId}: call aventure_${i.intent} {"operationId":"${i.operationId}"}.`}`}function Ax(e,t){return t?e:e.map(jx)}function jx(e){let t=e.parameter.flatMap(Nx),n=Mx(e.requestBody);return Fx(t,e.parameter)&&n===e.requestBody?e:{...e,parameter:t,...n===void 0?{}:{requestBody:n}}}function Mx(e){if(e===void 0)return;let t=e.map(e=>{let t=e.parameter.flatMap(Nx);return Fx(t,e.parameter)?e:{...e,parameter:t}});return t.every((t,n)=>t===e[n])?e:t}function Nx(e){if(!Px(e))return[];let t=e.itemProperty?.filter(Px);return Fx(t,e.itemProperty)?[e]:[{...e,...t===void 0||t.length===0?{}:{itemProperty:t}}]}var Px=e=>e.visibility!==`private`;function Fx(e,t){return e===t?!0:e?.length!==t?.length||e===void 0||t===void 0?!1:e.every((e,n)=>e===t[n])}new RegExp(oe.join(`|`),`i`);var Ix;function Lx(e,t){let n=Ix??=Ki([...Xi,...Zi]),r=Gi(e,n),i=Rx(Ni(e,r)),a=t===`json`?JSON.stringify(Rx(Ni(e,{...r,maxBytes:Di}))):Hi(n,i.data,i.summary)??JSON.stringify(i);return{isError:!i.ok,structuredContent:i,content:[{type:`text`,text:a}]}}function Rx(e){let{omitted:t,ids:n,counts:r,references:i,warnings:a,...o}=e;return{...o,...t.length>0?{omitted:t}:{},...n.length>0?{ids:n}:{},...Object.keys(r).length>0?{counts:r}:{},...i.length>0?{references:i}:{},...a.length>0?{warnings:a}:{}}}var zx=`aventure_help`,Bx=`aventure_read`,Vx=`aventure_lookup`,Hx=`aventure_search`,Ux=`aventure_job`,Wx=I([W(),U(),H()]),Gx=F(W(),I([W(),U()])).optional(),Kx=F(W(),I([Wx,B(Wx)])).optional(),qx=F(W(),W()).optional(),Jx=V([`GET`,`POST`,`PUT`,`PATCH`,`DELETE`]),Yx=I([Wx,Ve(),B(Me()),F(W(),Me())]).optional().describe(`JSON request body. For multipart/form-data operations, pass an object keyed by form part name; binary part values are http(s) URLs.`),Xx=G({operationId:W().optional().describe(`Exact OpenAPI operationId, as listed by aventure_help. Takes precedence over method and path.`),method:Jx.optional().describe(`HTTP method when resolving by method+path.`),path:W().optional().describe(`OpenAPI route template or concrete API path.`),pathParams:Gx.describe(`Values for route template parameters.`),query:Kx.describe(`Query parameters.`),headers:qx.describe(`Headers declared by the selected OpenAPI operation.`),contentType:W().optional().describe(`Declared request media type; omit for the first supported descriptor.`),responseFormat:V([`auto`,`json`]).optional().describe(`Omit for the default: readable text, from the operation's own text/plain rendering when aventure_help lists text/plain in responseContentType, otherwise from its JSON. json returns the JSON result envelope.`)}),Zx=G({q:W().optional().describe(`Plain-English task text, ranked against operationId, path, CLI command, summary, description, and query-parameter enum values. This tool reads no argument named query. Omitting q returns the catalog head unranked.`),root:He(e=>typeof e==`string`?e.trim().toLowerCase()||void 0:e,V([...new Set(Xi.flatMap(e=>[e.resource,...e.projection.cliPath.slice(0,1)]))].sort()).optional()).describe(`Filter by resource or first CLI segment.`),method:Jx.optional().describe(`Filter by HTTP method.`),limit:ze().min(1).max(100).default(20).describe(`Maximum rows to return. Set q to the chosen operationId and limit to 1 for argument types, enum choices, and defaults.`),resolve:H().default(!1).describe(`Resolve q to one operation with the server resolver (requires sign-in): operation advice with an mcpCall skeleton, a clarification between candidate operations, or an abstention. Root, method, and limit do not apply.`)}),Qx=Xx.extend({body:Yx}),$x=(e,t)=>Ax(Xi,t?.operationAccess===`ADMIN`||t===void 0&&e===`write`).filter(n=>(t===void 0?e===`write`||n.projection.scope===`read`&&(n.projection.auth===`read`||n.projection.auth===`none`):t.operationAccess!==`READ`||n.projection.scope===`read`||n.projection.visibility!==`private`)&&(t===void 0||t.operation.some(e=>e.operationId===n.operationId&&e.method===n.method&&e.path===n.path)));async function eS(e,t,n,r,i,a){let o=mx(e,r)??vr(e);if(!o.ok)return Ai(o.summary,o.warnings);if(o.data===null)return Ai(`OpenAPI operation resolution returned no data.`);let{method:s,operation:c,path:l,template:u}=o.data,d=c.operationId,f=r.find(e=>e.operationId===d&&e.method.toLowerCase()===s&&e.path===u);if(f===void 0)return Ai(`Operation `+d+` is not in the MCP catalog.`);let p=Cx({contract:f,input:e,intent:t,contracts:r,catalog:Xi});if(p!==null)return p;let m=Oe(f.requestBody??[],e.contentType);if(!m.ok||m.data===null)return Ai(m.summary,m.warnings);let h=m.data;return f.intent===`delete`&&h===void 0&&e.body!==void 0?Ai(d+` does not accept a request body.`):await sx({method:f.method,path:l,searchParams:e.query,headers:e.headers,body:e.body,contentType:e.contentType,auth:f.projection.auth,requesterScope:n,responseFormat:e.responseFormat,clientInfo:i,signal:a})}function tS(e,t){let n=new Set($x(e,t).map(e=>e.intent));return new Set([zx,Bx,Vx,Hx,...n.has(`job`)?[Ux]:[]])}function nS(e,t,n){let r=$x(t,n),i=tS(t,n),a=()=>e.server.getClientVersion();e.registerTool(zx,{title:`aVenture help`,annotations:{readOnlyHint:!0},description:`Lists the aVenture operations, each with the tool that runs it and the inputs it accepts. Pass q with a plain-English task to rank them. After choosing one, set q to its operationId and limit to 1 to see its full inputs, allowed values, and defaults. Set resolve to have the server pick one operation for q and return the call to make.`,inputSchema:Zx},async(e,n)=>{if(e.resolve)return Lx(await Vi(e,r,Xi,(e,r)=>sx({method:e.method,path:Je(e.operationId,{}),body:r.body,auth:e.projection.auth,requesterScope:t,responseFormat:`json`,clientInfo:a(),signal:n?.mcpReq.signal})));let{summary:i,data:o,counts:s}=Ui(e,r);return Lx(ji(i,o,{counts:s}))}),e.registerTool(Bx,{title:`aVenture read`,annotations:{readOnlyHint:!0},description:`Runs one catalog operation whose intent is read: fetch a record by id or slug, list the records attached to it, or list a collection. Put route values in pathParams and URL query values in query. Example for an aventure.vc profile URL, slug, website, or domain: {"operationId":"getEntityLookup","query":{"url":"https://aventure.vc/investors/firms/<slug>"}}. When a read's newsArticle (or listNews or a web source) reports a newer funding round, investor, role, or detail not yet reflected in the structured fields, report both and ask the user whether to request a record update with aventure_job (enrichEntity or enrichPerson). Select the operation by operationId from aventure_help, or by method plus path; operationId wins when both are given. An operation with a different intent is refused with the name of the tool that runs it.`,inputSchema:Qx},async(e,n)=>Lx(await eS(e,[`read`],t,r,a(),n?.mcpReq.signal),e.responseFormat)),e.registerTool(Vx,{title:`aVenture lookup`,annotations:{readOnlyHint:!0,openWorldHint:!0},description:`Runs one catalog operation whose intent is lookup: identify a record from a name plus clues (such as lookupRecord), resolve a ticker or other identifier, or run a batch, preview, or duplicate check. Most lookups are POST operations that take a JSON body. An exact aventure.vc profile URL, slug, website, or domain is a read, not a lookup: call aventure_read with operationId getEntityLookup (or getPersonLookup) and query {url} or {slug}. Select the operation by operationId from aventure_help, or by method plus path; operationId wins when both are given. An operation with a different intent is refused with the name of the tool that runs it.`,inputSchema:Qx},async(e,n)=>Lx(await eS(e,[`lookup`],t,r,a(),n?.mcpReq.signal),e.responseFormat)),e.registerTool(Hx,{title:`aVenture search`,annotations:{readOnlyHint:!0,openWorldHint:!0},description:`Runs one catalog operation whose intent is search: search or filter companies, people, news, publications, content, links, or the web, or answer a question. It has no free-text argument of its own: pass search text and filters where the chosen operation declares them, in query or body. Select the operation by operationId from aventure_help, or by method plus path; operationId wins when both are given. An operation with a different intent is refused with the name of the tool that runs it.`,inputSchema:Qx},async(e,n)=>Lx(await eS(e,[`search`],t,r,a(),n?.mcpReq.signal),e.responseFormat)),i.has(`aventure_job`)&&e.registerTool(Ux,{title:`aVenture job`,annotations:{readOnlyHint:!0,idempotentHint:!0,openWorldHint:!0},description:`Runs one catalog operation whose intent is job: request a research job that deepens or updates aVenture's data on a company or person (enrichEntity, enrichPerson, createResearchRun, enrichRecords), or a lookup job that identifies the companies and people an article names. When an indexed aVenture news article (newsArticle or listNews) or web source reports a newer or missing detail—such as a funding round, investor, role, or URL—not yet reflected in the structured profile, ask the user if they would like to request an update to the aVenture record; on confirmation, call enrichEntity, enrichPerson, or createResearchRun with body.finding (statement, sourceUrl, verbatim quote from an external page you read for an entity) or body.userPrompt (the observed detail and sourceUrl or newsUrlOriginal). Returns the run or job to poll with aventure_read. A research run costs one research unit only when it saves research, and a record already being researched returns that run instead of starting another. Select the operation by operationId from aventure_help, or by method plus path; operationId wins when both are given. An operation with a different intent is refused with the name of the tool that runs it.`,inputSchema:Qx},async(e,n)=>Lx(await eS(e,[`job`],t,r,a(),n?.mcpReq.signal),e.responseFormat))}var rS=Ii().version,iS={tools:{},events:{}};function aS(e,t){let n=_t().info?.description,r=new iy({name:`aventure-mcp-server`,title:`aVenture MCP Server`,version:rS,websiteUrl:M,icons:[{src:`${M}/apple-touch-icon.png`,mimeType:`image/png`,sizes:[`180x180`]}]},{capabilities:iS,...n===void 0?{}:{instructions:n}});return nS(r,e,t),ox(r),r}var oS=new Set([...zn.options,...xi.options].map(e=>e.shape.method.value)),sS=`mcpRegisteredToolName`;function cS(e,t,n){e.locals[sS]=tS(t,n)}function lS(e){let t=e.locals[sS];return t instanceof Set?t:new Set}function uS(e,t){let n=typeof e==`object`&&e?Reflect.get(e,`method`):void 0,r=typeof e==`object`&&e?Reflect.get(e,`params`):void 0,i=typeof r==`object`&&r?Reflect.get(r,`name`):void 0;return{rpcMethod:typeof n==`string`&&oS.has(n)?n:`other`,toolName:typeof i==`string`?t.has(i)?i:`unregistered`:`none`}}var dS=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.AddressError=void 0,e.AddressError=class extends Error{constructor(e,t){super(e),this.name=`AddressError`,this.parseMessage=t}}})),fS=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.isInSubnet=n,e.isHostInSubnet=r,e.isGloballyReachable=i,e.offsetBigInt=a,e.isCorrect=o,e.prefixLengthFromMask=s,e.assertByteArray=c,e.numberToPaddedHex=l,e.stringToPaddedHex=u,e.testBit=d;var t=dS();function n(e){return this.subnetMask<e.subnetMask?!1:r.call(this,e)}function r(e){return this.binaryZeroPad().length===e.binaryZeroPad().length&&this.mask(e.subnetMask)===e.mask()}function i(e){let t=null;for(let n=0;n<e.length;n++){let i=e[n];i.reachable!==null&&r.call(this,i.subnet)&&(t===null||i.subnet.subnetMask>t.subnet.subnetMask)&&(t=i)}return t===null||t.reachable}function a(e,n,r,i){if(typeof n==`number`&&!Number.isSafeInteger(n)||typeof n!=`number`&&typeof n!=`bigint`)throw new t.AddressError(`${i} offset must be an integer`);let a=e+BigInt(n);if(a<BigInt(0)||a>(BigInt(1)<<BigInt(r))-BigInt(1))throw new t.AddressError(`${i} offset leaves the address space`);return a}function o(e){return function(){return this.addressMinusSuffix===this.correctForm()?this.subnetMask===e&&!this.parsedSubnet||this.parsedSubnet===String(this.subnetMask):!1}}function s(e,n){let r=e.toString(2).padStart(n,`0`);if(r.length>n)throw new t.AddressError(`Invalid subnet mask.`);let i=r.indexOf(`0`);if(i===-1)return n;if(r.slice(i).includes(`1`))throw new t.AddressError(`Invalid subnet mask.`);return i}function c(e,n,r,i){if(e.length!==n)throw new t.AddressError(`${r} addresses require exactly ${n} bytes`);for(let n=0;n<e.length;n++)if(!Number.isInteger(e[n])||e[n]<i||e[n]>255)throw new t.AddressError(`All bytes must be integers between ${i} and 255`)}function l(e){return e.toString(16).padStart(2,`0`)}function u(e){return l(parseInt(e,10))}function d(e,t){let{length:n}=e;if(t>n)return!1;let r=n-t;return e.substring(r,r+1)===`1`}})),pS=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.SPECIAL_PURPOSE=e.RE_SUBNET_STRING=e.RE_ADDRESS=e.GROUPS=e.BITS=void 0,e.BITS=32,e.GROUPS=4,e.RE_ADDRESS=/^(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])$/g,e.RE_SUBNET_STRING=/\/\d{1,2}$/,e.SPECIAL_PURPOSE=[[`0.0.0.0/8`,`This network`,!1],[`0.0.0.0/32`,`This host on this network`,!1],[`10.0.0.0/8`,`Private-Use`,!1],[`100.64.0.0/10`,`Shared Address Space`,!1],[`127.0.0.0/8`,`Loopback`,!1],[`169.254.0.0/16`,`Link Local`,!1],[`172.16.0.0/12`,`Private-Use`,!1],[`192.0.0.0/24`,`IETF Protocol Assignments`,!1],[`192.0.0.0/29`,`IPv4 Service Continuity Prefix`,!1],[`192.0.0.8/32`,`IPv4 dummy address`,!1],[`192.0.0.9/32`,`Port Control Protocol Anycast`,!0],[`192.0.0.10/32`,`Traversal Using Relays around NAT Anycast`,!0],[`192.0.0.170/32`,`NAT64/DNS64 Discovery`,!1],[`192.0.0.171/32`,`NAT64/DNS64 Discovery`,!1],[`192.0.2.0/24`,`Documentation (TEST-NET-1)`,!1],[`192.31.196.0/24`,`AS112-v4`,!0],[`192.52.193.0/24`,`AMT`,!0],[`192.88.99.0/24`,`Deprecated (6to4 Relay Anycast)`,null],[`192.88.99.2/32`,`6a44-relay anycast address`,!1],[`192.168.0.0/16`,`Private-Use`,!1],[`192.175.48.0/24`,`Direct Delegation AS112 Service`,!0],[`198.18.0.0/15`,`Benchmarking`,!1],[`198.51.100.0/24`,`Documentation (TEST-NET-2)`,!1],[`203.0.113.0/24`,`Documentation (TEST-NET-3)`,!1],[`240.0.0.0/4`,`Reserved`,!1],[`255.255.255.255/32`,`Limited Broadcast`,!1]]})),mS=r((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||(`get`in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),r=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var i in e)i!=="default"&&Object.prototype.hasOwnProperty.call(e,i)&&t(r,e,i);return n(r,e),r};Object.defineProperty(e,"__esModule",{value:!0}),e.Address4=void 0;var i=r(fS()),a=r(pS()),o=dS(),s=i.isCorrect(a.BITS),c=class e{constructor(e){this.addressMinusSuffix=``,this.groups=a.GROUPS,this.parsedAddress=[],this.parsedSubnet=``,this.subnet=`/32`,this.subnetMask=32,this.v4=!0,this.isCorrect=s,this.isInSubnet=i.isInSubnet,this.isHostInSubnet=i.isHostInSubnet,this.address=e;let t=a.RE_SUBNET_STRING.exec(e);if(t){if(this.parsedSubnet=t[0].replace(`/`,``),this.subnetMask=parseInt(this.parsedSubnet,10),this.subnet=`/${this.subnetMask}`,this.subnetMask<0||this.subnetMask>a.BITS)throw new o.AddressError(`Invalid subnet mask.`);e=e.replace(a.RE_SUBNET_STRING,``)}let n=a.GROUPS*4-1;if(e.length>n)throw new o.AddressError(`IPv4 addresses are at most ${n} characters.`);this.addressMinusSuffix=e,this.parsedAddress=this.parse(e)}static isValid(t){try{return new e(t),!0}catch{return!1}}parse(e){let t=e.split(`.`);if(t.some(e=>/^0\d/.test(e)))throw new o.AddressError(`IPv4 addresses can't have leading zeroes.`);if(!e.match(a.RE_ADDRESS))throw new o.AddressError(`Invalid IPv4 address.`);return t}correctForm(){return this.parsedAddress.map(e=>parseInt(e,10)).join(`.`)}static fromAddressAndMask(t,n){let r=i.prefixLengthFromMask(new e(n).bigInt(),a.BITS);return new e(`${t}/${r}`)}static fromAddressAndWildcardMask(t,n){let r=new e(n).bigInt()^(BigInt(1)<<BigInt(a.BITS))-BigInt(1),o=i.prefixLengthFromMask(r,a.BITS);return new e(`${t}/${o}`)}static fromWildcard(t){let n=t.split(`.`);if(n.length!==a.GROUPS)throw new o.AddressError(`Wildcard pattern must have 4 octets`);let r=-1;for(let e=0;e<n.length;e++)if(n[e]===`*`)r===-1&&(r=e);else if(r!==-1)throw new o.AddressError("Wildcard `*` must only appear in trailing octets (e.g. `192.168.0.*`)");let i=r===-1?0:n.length-r,s=n.map(e=>e===`*`?`0`:e),c=a.BITS-i*8;return new e(`${s.join(`.`)}/${c}`)}static fromHex(t){let n=t.replace(/:/g,``);if(!/^[0-9a-fA-F]{8}$/.test(n))throw new o.AddressError(`IPv4 hex must be exactly 8 hex digits`);let r=[];for(let e=0;e<8;e+=2)r.push(parseInt(n.slice(e,e+2),16));return new e(r.join(`.`))}static fromInteger(t){if(!Number.isInteger(t)||t<0||t>4294967295)throw new o.AddressError(`IPv4 integer must be in the range 0 to 2**32 - 1`);return e.fromHex(t.toString(16).padStart(8,`0`))}static fromArpa(t){let n=t.replace(/(\.in-addr\.arpa)?\.?$/i,``).split(`.`).reverse().join(`.`);return new e(n)}toHex(){return this.parsedAddress.map(e=>i.stringToPaddedHex(e)).join(`:`)}toArray(){return this.parsedAddress.map(e=>parseInt(e,10))}toGroup6(){let e=[],t=0;for(;t<a.GROUPS;t+=2)e.push(`${i.stringToPaddedHex(this.parsedAddress[t])}${i.stringToPaddedHex(this.parsedAddress[t+1])}`);return e.join(`:`)}bigInt(){return BigInt(`0x${this.parsedAddress.map(e=>i.stringToPaddedHex(e)).join(``)}`)}_startAddress(){return BigInt(`0b${this.mask()+`0`.repeat(a.BITS-this.subnetMask)}`)}startAddress(){return e.fromBigInt(this._startAddress())}startAddressExclusive(){let t=BigInt(`1`);return e.fromBigInt(this._startAddress()+t)}offset(t){return e.fromBigInt(i.offsetBigInt(this.bigInt(),t,a.BITS,`IPv4`)).withSubnetMask(this.subnetMask)}nextNetwork(){return e.fromBigInt(i.offsetBigInt(this._endAddress(),1,a.BITS,`IPv4`)).withSubnetMask(this.subnetMask)}withSubnetMask(t){return new e(`${this.correctForm()}/${t}`)}_endAddress(){return BigInt(`0b${this.mask()+`1`.repeat(a.BITS-this.subnetMask)}`)}endAddress(){return e.fromBigInt(this._endAddress())}endAddressExclusive(){let t=BigInt(`1`);return e.fromBigInt(this._endAddress()-t)}subnetMaskAddress(){return e.fromBigInt(BigInt(`0b${`1`.repeat(this.subnetMask)}${`0`.repeat(a.BITS-this.subnetMask)}`))}wildcardMask(){return e.fromBigInt(BigInt(`0b${`0`.repeat(this.subnetMask)}${`1`.repeat(a.BITS-this.subnetMask)}`))}networkForm(){return`${this.startAddress().correctForm()}/${this.subnetMask}`}static fromBigInt(t){if(t<BigInt(0)||t>BigInt(4294967295))throw new o.AddressError(`IPv4 BigInt must be in the range 0 to 2**32 - 1`);return e.fromHex(t.toString(16).padStart(8,`0`))}static fromByteArray(e){return i.assertByteArray(e,4,`IPv4`,0),this.fromUnsignedByteArray(e)}static fromUnsignedByteArray(t){if(t.length!==4)throw new o.AddressError(`IPv4 addresses require exactly 4 bytes`);let n=t.join(`.`);return new e(n)}mask(e){return e===void 0&&(e=this.subnetMask),this.getBitsBase2(0,e)}getBitsBase2(e,t){return this.binaryZeroPad().slice(e,t)}reverseForm(e){e||={};let t=this.correctForm().split(`.`).reverse().join(`.`);return e.omitSuffix?t:`${t}.in-addr.arpa.`}isMulticast(){return this.isHostInSubnet(l)}isPrivate(){return u.some(e=>this.isHostInSubnet(e))}isLoopback(){return this.isHostInSubnet(d)}isLinkLocal(){return this.isHostInSubnet(f)}isUnspecified(){return this.isHostInSubnet(p)}isBroadcast(){return this.isHostInSubnet(m)}isCGNAT(){return this.isHostInSubnet(h)}isDocumentation(){return g.some(e=>this.isHostInSubnet(e))}isBenchmarking(){return this.isHostInSubnet(_)}isReserved(){return this.isHostInSubnet(v)}isGlobal(){return!this.isMulticast()&&i.isGloballyReachable.call(this,y)}binaryZeroPad(){return this._binaryZeroPad===void 0&&(this._binaryZeroPad=this.bigInt().toString(2).padStart(a.BITS,`0`)),this._binaryZeroPad}groupForV6(){let e=this.parsedAddress;return this.correctForm().replace(a.RE_ADDRESS,`<span class="hover-group group-v4 group-6">${e.slice(0,2).join(`.`)}</span>.<span class="hover-group group-v4 group-7">${e.slice(2,4).join(`.`)}</span>`)}};e.Address4=c;var l=new c(`224.0.0.0/4`),u=[new c(`10.0.0.0/8`),new c(`172.16.0.0/12`),new c(`192.168.0.0/16`)],d=new c(`127.0.0.0/8`),f=new c(`169.254.0.0/16`),p=new c(`0.0.0.0/32`),m=new c(`255.255.255.255/32`),h=new c(`100.64.0.0/10`),g=[new c(`192.0.2.0/24`),new c(`198.51.100.0/24`),new c(`203.0.113.0/24`)],_=new c(`198.18.0.0/15`),v=new c(`240.0.0.0/4`),y=a.SPECIAL_PURPOSE.map(([e,,t])=>({subnet:new c(e),reachable:t}))})),hS=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.SPECIAL_PURPOSE=e.RE_URL_WITH_PORT=e.RE_URL=e.RE_ZONE_STRING=e.RE_SUBNET_STRING=e.RE_BAD_ADDRESS=e.RE_BAD_CHARACTERS=e.TYPES=e.SCOPES=e.GROUPS=e.BITS=void 0,e.BITS=128,e.GROUPS=8,e.SCOPES={0:`Reserved`,1:`Interface local`,2:`Link local`,4:`Admin local`,5:`Site local`,8:`Organization local`,14:`Global`,15:`Reserved`},e.TYPES={"ff01::1/128":`Multicast (All nodes on this interface)`,"ff01::2/128":`Multicast (All routers on this interface)`,"ff02::1/128":`Multicast (All nodes on this link)`,"ff02::2/128":`Multicast (All routers on this link)`,"ff05::2/128":`Multicast (All routers in this site)`,"ff02::5/128":`Multicast (OSPFv3 AllSPF routers)`,"ff02::6/128":`Multicast (OSPFv3 AllDR routers)`,"ff02::9/128":`Multicast (RIP routers)`,"ff02::a/128":`Multicast (EIGRP routers)`,"ff02::d/128":`Multicast (PIM routers)`,"ff02::16/128":`Multicast (MLDv2 reports)`,"ff01::fb/128":`Multicast (mDNSv6)`,"ff02::fb/128":`Multicast (mDNSv6)`,"ff05::fb/128":`Multicast (mDNSv6)`,"ff02::1:2/128":`Multicast (All DHCP servers and relay agents on this link)`,"ff05::1:2/128":`Multicast (All DHCP servers and relay agents in this site)`,"ff02::1:3/128":`Multicast (All DHCP servers on this link)`,"ff05::1:3/128":`Multicast (All DHCP servers in this site)`,"::/128":`Unspecified`,"::1/128":`Loopback`,"::ffff:0:0/96":`IPv4-mapped`,"ff00::/8":`Multicast`,"fe80::/10":`Link-local unicast`,"fc00::/7":`Unique local`,"2001::/32":`Teredo`,"2001:2::/48":`Benchmarking`,"2002::/16":`6to4`,"2001:db8::/32":`Documentation`,"3fff::/20":`Documentation`,"100::/64":`Discard-only`,"fec0::/10":`Site-local unicast (deprecated)`,"::/96":`IPv4-compatible (deprecated)`,"64:ff9b::/96":`NAT64 (well-known)`,"64:ff9b:1::/48":`NAT64 (local-use)`},e.RE_BAD_CHARACTERS=/([^0-9a-f:/%])/gi,e.RE_BAD_ADDRESS=/([0-9a-f]{5,}|:{3,}|[^:]:$|^:[^:]|\/$)/gi,e.RE_SUBNET_STRING=/\/\d{1,3}(?=%|$)/,e.RE_ZONE_STRING=/%.*$/,e.RE_URL=/^(?:\[([0-9a-f:.]+)\]|([0-9a-f:.]+))(?:[/?#].*)?$/i,e.RE_URL_WITH_PORT=/^\[([0-9a-f:.]+)\]:([0-9]{1,5})(?:[/?#].*)?$/i,e.SPECIAL_PURPOSE=[[`::1/128`,`Loopback Address`,!1],[`::/128`,`Unspecified Address`,!1],[`::ffff:0:0/96`,`IPv4-mapped Address`,!1],[`64:ff9b::/96`,`IPv4-IPv6 Translat.`,!0],[`64:ff9b:1::/48`,`IPv4-IPv6 Translat.`,!1],[`100::/64`,`Discard-Only Address Block`,!1],[`100:0:0:1::/64`,`Dummy IPv6 Prefix`,!1],[`2001::/23`,`IETF Protocol Assignments`,!1],[`2001::/32`,`TEREDO`,!1],[`2001:1::1/128`,`Port Control Protocol Anycast`,!0],[`2001:1::2/128`,`Traversal Using Relays around NAT Anycast`,!0],[`2001:1::3/128`,`DNS-SD Service Registration Protocol Anycast`,!0],[`2001:2::/48`,`Benchmarking`,!1],[`2001:3::/32`,`AMT`,!0],[`2001:4:112::/48`,`AS112-v6`,!0],[`2001:10::/28`,`Deprecated (previously ORCHID)`,null],[`2001:20::/28`,`ORCHIDv2`,!0],[`2001:30::/28`,`Drone Remote ID Protocol Entity Tags (DETs) Prefix`,!0],[`2001:db8::/32`,`Documentation`,!1],[`2002::/16`,`6to4`,!1],[`2620:4f:8000::/48`,`Direct Delegation AS112 Service`,!0],[`3fff::/20`,`Documentation`,!1],[`5f00::/16`,`Segment Routing (SRv6) SIDs`,!1],[`fc00::/7`,`Unique-Local`,!1],[`fe80::/10`,`Link-Local Unicast`,!1]]})),gS=r((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.escapeHtml=t,e.spanAllZeroes=n,e.spanAll=r,e.spanLeadingZeroes=a,e.simpleGroup=o;function t(e){return e.replace(/&/g,`&amp;`).replace(/</g,`&lt;`).replace(/>/g,`&gt;`).replace(/"/g,`&quot;`).replace(/'/g,`&#39;`)}function n(e){return t(e).replace(/(0+)/g,`<span class="zero">$1</span>`)}function r(e,r=0){return e.split(``).map((e,i)=>`<span class="digit value-${t(e)} position-${i+r}">${n(e)}</span>`).join(``)}function i(e){return t(e).replace(/^(0+)/,`<span class="zero">$1</span>`)}function a(e){return e.split(`:`).map(e=>i(e)).join(`:`)}function o(e,t=0){return e.split(`:`).map((e,n)=>/group-v4/.test(e)?e:`<span class="hover-group group-${n+t}">${i(e)}</span>`)}})),_S=r((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||(`get`in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),r=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var i in e)i!=="default"&&Object.prototype.hasOwnProperty.call(e,i)&&t(r,e,i);return n(r,e),r};Object.defineProperty(e,"__esModule",{value:!0}),e.ADDRESS_BOUNDARY=void 0,e.groupPossibilities=a,e.padGroup=o,e.simpleRegularExpression=s,e.possibleElisions=c;var i=r(hS());function a(e){return`(${e.join(`|`)})`}function o(e){return e.length<4?`0{0,${4-e.length}}${e}`:e}e.ADDRESS_BOUNDARY=`[^A-Fa-f0-9:]`;function s(e){let t=[];e.forEach((e,n)=>{parseInt(e,16)===0&&t.push(n)});let n=t.map(t=>e.map((e,n)=>{if(n===t){let t=n===0||n===i.GROUPS-1?`:`:``;return a([o(e),t])}return o(e)}).join(`:`));return n.push(e.map(o).join(`:`)),a(n)}function c(e,t,n){let r=t?``:`:`,i=n?``:`:`,o=[];!t&&!n&&o.push(`::`),t&&n&&o.push(``),(n&&!t||!n&&t)&&o.push(`:`),o.push(`${r}(:0{1,4}){1,${e-1}}`),o.push(`(0{1,4}:){1,${e-1}}${i}`),o.push(`(0{1,4}:){${e-1}}0{1,4}`);for(let t=1;t<e-1;t++)for(let n=1;n<e-t;n++)o.push(`(0{1,4}:){${n}}:(0{1,4}:){${e-n-t-1}}0{1,4}`);return a(o)}})),vS=r((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||(`get`in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),r=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var i in e)i!=="default"&&Object.prototype.hasOwnProperty.call(e,i)&&t(r,e,i);return n(r,e),r};Object.defineProperty(e,"__esModule",{value:!0}),e.Address6=void 0;var i=r(fS()),a=r(pS()),o=r(hS()),s=r(gS()),c=mS(),l=_S(),u=dS(),d=fS(),f=i.isCorrect(o.BITS);function p(e){if(!e)throw Error(`Assertion failed.`)}function m(e){let t=/(\d+)(\d{3})/;for(;t.test(e);)e=e.replace(t,`$1,$2`);return e}function h(e){return e=e.replace(/^(0{1,})([1-9]+)$/,`<span class="parse-error">$1</span>$2`),e=e.replace(/^(0{1,})(0)$/,`<span class="parse-error">$1</span>$2`),e}function g(e,t){let n=[],r=[],i=0;for(;i<e.length;i++)i<t[0]?n.push(e[i]):i>t[1]&&r.push(e[i]);return n.concat([`compact`]).concat(r)}function _(e){return parseInt(e,16).toString(16).padStart(4,`0`)}function v(e){return e&255}var y=class e{constructor(e,t){this.addressMinusSuffix=``,this.parsedSubnet=``,this.subnet=`/128`,this.subnetMask=128,this.v4=!1,this.zone=``,this.isInSubnet=i.isInSubnet,this.isHostInSubnet=i.isHostInSubnet,this.isCorrect=f,this.groups=t===void 0?o.GROUPS:t,this.address=e;let n=o.RE_SUBNET_STRING.exec(e);if(n){if(this.parsedSubnet=n[0].replace(`/`,``),this.subnetMask=parseInt(this.parsedSubnet,10),this.subnet=`/${this.subnetMask}`,Number.isNaN(this.subnetMask)||this.subnetMask<0||this.subnetMask>o.BITS)throw new u.AddressError(`Invalid subnet mask.`);e=e.replace(o.RE_SUBNET_STRING,``)}if(/\//.test(e))throw new u.AddressError(`Invalid subnet mask.`);let r=o.RE_ZONE_STRING.exec(e);r&&(this.zone=r[0],e=e.replace(o.RE_ZONE_STRING,``));let a=this.groups*5+5;if(e.length>a)throw new u.AddressError(`IPv6 addresses are at most ${a} characters.`);this.addressMinusSuffix=e,this.parsedAddress=this.parse(this.addressMinusSuffix)}static isValid(t){try{return new e(t),!0}catch{return!1}}static fromBigInt(t){if(t<BigInt(0)||t>(BigInt(1)<<BigInt(o.BITS))-BigInt(1))throw new u.AddressError(`IPv6 BigInt must be in the range 0 to 2**128 - 1`);let n=t.toString(16).padStart(32,`0`),r=[];for(let e=0;e<o.GROUPS;e++)r.push(n.slice(e*4,(e+1)*4));return new e(r.join(`:`))}static fromURL(t){let n,r=null,i,a,s=t.replace(/^[a-z][a-z0-9+.-]*:\/\//i,``);if(s.indexOf(`[`)!==-1&&s.indexOf(`]:`)!==-1){if(a=`failed to parse address with port`,i=o.RE_URL_WITH_PORT.exec(s),i===null)return{error:a,address:null,port:null};n=i[1],r=i[2]}else{if(a=`failed to parse address from URL`,i=o.RE_URL.exec(s),i===null)return{error:a,address:null,port:null};n=i[1]??i[2]}r?(r=parseInt(r,10),(r<0||r>65535)&&(r=null)):r=null;let c;try{c=new e(n)}catch{return{error:a,address:null,port:null}}return{address:c,port:r}}static fromAddressAndMask(t,n){let r=i.prefixLengthFromMask(new e(n).bigInt(),o.BITS);return new e(`${t}/${r}`)}static fromAddressAndWildcardMask(t,n){let r=new e(n).bigInt()^(BigInt(1)<<BigInt(o.BITS))-BigInt(1),a=i.prefixLengthFromMask(r,o.BITS);return new e(`${t}/${a}`)}static fromWildcard(t){if(t.includes(`%`)||t.includes(`/`))throw new u.AddressError(`Wildcard pattern must not include a zone or CIDR suffix`);let n=t.split(`::`);if(n.length>2)throw new u.AddressError(`Wildcard pattern cannot contain more than one '::'`);let r;if(n.length===2){let e=n[0]===``?[]:n[0].split(`:`),t=n[1]===``?[]:n[1].split(`:`),i=o.GROUPS-e.length-t.length;if(i<1)throw new u.AddressError(`Wildcard pattern with '::' has too many groups`);r=[...e,...Array(i).fill(`0`),...t]}else r=t.split(`:`);if(r.length!==o.GROUPS)throw new u.AddressError(`Wildcard pattern must have 8 groups`);let i=-1;for(let e=0;e<r.length;e++)if(r[e]===`*`)i===-1&&(i=e);else if(i!==-1)throw new u.AddressError("Wildcard `*` must only appear in trailing groups (e.g. `2001:db8:*:*:*:*:*:*`)");let a=i===-1?0:r.length-i,s=r.map(e=>e===`*`?`0`:e),c=o.BITS-a*16;return new e(`${s.join(`:`)}/${c}`)}static fromAddress4(t){let n=new c.Address4(t),r=o.BITS-(a.BITS-n.subnetMask);return new e(`::ffff:${n.correctForm()}/${r}`)}static fromArpa(t){let n=t.replace(/(\.ip6\.arpa)?\.?$/i,``);if(!/^[0-9a-f](\.[0-9a-f]){0,31}$/i.test(n))throw new u.AddressError(`Invalid 'ip6.arpa' form.`);let r=n.split(`.`).reverse(),i=r.length*4,a=r.join(``).padEnd(32,`0`),s=[];for(let e=0;e<o.GROUPS;e++)s.push(a.slice(e*4,(e+1)*4));return new e(`${s.join(`:`)}/${i}`)}microsoftTranscription(){return`${this.correctForm().replace(/:/g,`-`)}.ipv6-literal.net`}mask(e=this.subnetMask){return this.getBitsBase2(0,e)}possibleSubnets(e=128){let t=o.BITS-this.subnetMask-Math.abs(e-o.BITS);return t<0?`0`:m((BigInt(`2`)**BigInt(t)).toString(10))}_startAddress(){return BigInt(`0b${this.mask()+`0`.repeat(o.BITS-this.subnetMask)}`)}startAddress(){return e.fromBigInt(this._startAddress())}startAddressExclusive(){let t=BigInt(`1`);return e.fromBigInt(this._startAddress()+t)}_endAddress(){return BigInt(`0b${this.mask()+`1`.repeat(o.BITS-this.subnetMask)}`)}endAddress(){return e.fromBigInt(this._endAddress())}endAddressExclusive(){let t=BigInt(`1`);return e.fromBigInt(this._endAddress()-t)}offset(t){return e.fromBigInt(i.offsetBigInt(this.bigInt(),t,o.BITS,`IPv6`)).withSubnetMask(this.subnetMask)}nextNetwork(){return e.fromBigInt(i.offsetBigInt(this._endAddress(),1,o.BITS,`IPv6`)).withSubnetMask(this.subnetMask)}withSubnetMask(t){return new e(`${this.correctForm()}/${t}`)}subnetMaskAddress(){return e.fromBigInt(BigInt(`0b${`1`.repeat(this.subnetMask)}${`0`.repeat(o.BITS-this.subnetMask)}`))}wildcardMask(){return e.fromBigInt(BigInt(`0b${`0`.repeat(this.subnetMask)}${`1`.repeat(o.BITS-this.subnetMask)}`))}networkForm(){return`${this.startAddress().correctForm()}/${this.subnetMask}`}getScope(){let e=this.getType();return e===`Multicast`||e.startsWith(`Multicast `)?o.SCOPES[parseInt(this.getBits(12,16).toString(10),10)]||`Unknown`:e===`Link-local unicast`||e===`Loopback`?`Link local`:e===`Unspecified`?`Unknown`:`Global`}getType(){for(let e=0;e<b.length;e++){let t=b[e];if(this.isHostInSubnet(t[0]))return t[1]}return`Global unicast`}getBits(e,t){return BigInt(`0b${this.getBitsBase2(e,t)}`)}getBitsBase2(e,t){return this.binaryZeroPad().slice(e,t)}getBitsBase16(e,t){let n=t-e;if(n%4!=0)throw Error(`Length of bits to retrieve must be divisible by four`);return this.getBits(e,t).toString(16).padStart(n/4,`0`)}getBitsPastSubnet(){return this.getBitsBase2(this.subnetMask,o.BITS)}reverseForm(e){e||={};let t=Math.floor(this.subnetMask/4),n=this.canonicalForm().replace(/:/g,``).split(``).slice(0,t).reverse().join(`.`);return t>0?e.omitSuffix?n:`${n}.ip6.arpa.`:e.omitSuffix?``:`ip6.arpa.`}correctForm(){let e,t=[],n=0,r=[];for(e=0;e<this.parsedAddress.length;e++){let t=parseInt(this.parsedAddress[e],16);t===0&&n++,t!==0&&n>0&&(n>1&&r.push([e-n,e-1]),n=0)}n>1&&r.push([this.parsedAddress.length-n,this.parsedAddress.length-1]);let i=r.map(e=>e[1]-e[0]+1);if(r.length>0){let e=i.indexOf(Math.max(...i));t=g(this.parsedAddress,r[e])}else t=this.parsedAddress;for(e=0;e<t.length;e++)t[e]!==`compact`&&(t[e]=parseInt(t[e],16).toString(16));let a=t.join(`:`);return a=a.replace(/^compact$/,`::`),a=a.replace(/(^compact)|(compact$)/,`:`),a=a.replace(/compact/,``),a}binaryZeroPad(){return this._binaryZeroPad===void 0&&(this._binaryZeroPad=this.bigInt().toString(2).padStart(o.BITS,`0`)),this._binaryZeroPad}parse4in6(e){if(e.indexOf(`.`)===-1)return e;let t=e.split(`:`),n=t.slice(-1)[0],r=n.split(`.`);if(r.length===a.GROUPS&&r.every(e=>/^\d{1,3}$/.test(e))&&r.some(e=>/^0\d/.test(e))){let e=r.map(h).join(`.`),n=t.slice(0,-1).map(s.escapeHtml).join(`:`),i=t.length>1?`:`:``;throw new u.AddressError(`IPv4 addresses can't have leading zeroes.`,`${n}${i}${e}`)}let i=n.match(a.RE_ADDRESS);if(i){this.parsedAddress4=i[0];let n=this.subnetMask>=96?`/${this.subnetMask-96}`:``;this.address4=new c.Address4(`${this.parsedAddress4}${n}`),this.v4=!0,t[t.length-1]=this.address4.toGroup6(),e=t.join(`:`)}return e}parse(e){e=this.parse4in6(e);let t=e.match(o.RE_BAD_CHARACTERS);if(t)throw new u.AddressError(`Bad character${t.length>1?`s`:``} detected in address: ${t.join(``)}`,e.replace(o.RE_BAD_CHARACTERS,`<span class="parse-error">$1</span>`));let n=e.match(o.RE_BAD_ADDRESS);if(n)throw new u.AddressError(`Address failed regex: ${n.join(``)}`,e.replace(o.RE_BAD_ADDRESS,`<span class="parse-error">$1</span>`));let r=[],i=e.split(`::`);if(i.length===2){let e=i[0].split(`:`),t=i[1].split(`:`);e.length===1&&e[0]===``&&(e=[]),t.length===1&&t[0]===``&&(t=[]);let n=this.groups-(e.length+t.length);if(!n)throw new u.AddressError(`Error parsing groups`);this.elidedGroups=n,this.elisionBegin=e.length,this.elisionEnd=e.length+this.elidedGroups,r=r.concat(e);for(let e=0;e<n;e++)r.push(`0`);r=r.concat(t)}else if(i.length===1)r=e.split(`:`),this.elidedGroups=0;else throw new u.AddressError(`Too many :: groups found`);if(r=r.map(e=>parseInt(e,16).toString(16)),r.length!==this.groups)throw new u.AddressError(`Incorrect number of groups found`);return r}canonicalForm(){return this.parsedAddress.map(_).join(`:`)}decimal(){return this.parsedAddress.map(e=>parseInt(e,16).toString(10).padStart(5,`0`)).join(`:`)}bigInt(){return BigInt(`0x${this.parsedAddress.map(_).join(``)}`)}to4(){let e=this.binaryZeroPad().split(``),t=BigInt(`0b${e.slice(96,128).join(``)}`).toString(16).padStart(8,`0`);if(this.subnetMask>=96){let e=this.subnetMask-96,n=[];for(let e=0;e<8;e+=2)n.push(parseInt(t.slice(e,e+2),16));return new c.Address4(`${n.join(`.`)}/${e}`)}return c.Address4.fromHex(t)}to4in6(){let t=this.to4(),n=new e(this.parsedAddress.slice(0,6).join(`:`),6).correctForm(),r=``;return/:$/.test(n)||(r=`:`),n+r+t.correctForm()}inspectTeredo(){let e=this.getBitsBase16(0,32),t=(this.getBits(80,96)^BigInt(`0xffff`)).toString(),n=c.Address4.fromHex(this.getBitsBase16(32,64)),r=this.getBits(96,128),i=c.Address4.fromHex((r^BigInt(`0xffffffff`)).toString(16).padStart(8,`0`)),a=this.getBitsBase2(64,80),o=(0,d.testBit)(a,15),s=(0,d.testBit)(a,14),l=(0,d.testBit)(a,8),u=(0,d.testBit)(a,9),f=BigInt(`0b${a.slice(2,6)+a.slice(8,16)}`).toString(10);return{prefix:`${e.slice(0,4)}:${e.slice(4,8)}`,server4:n.address,client4:i.address,flags:a,coneNat:o,microsoft:{reserved:s,universalLocal:u,groupIndividual:l,nonce:f},udpPort:t}}inspect6to4(){let e=this.getBitsBase16(0,16),t=c.Address4.fromHex(this.getBitsBase16(16,48));return{prefix:e.slice(0,4),gateway:t.address}}to6to4(){if(!this.is4())return null;let t=[`2002`,this.getBitsBase16(96,112),this.getBitsBase16(112,128),``,`/16`].join(`:`);return new e(t)}static fromAddress4Nat64(t,n=`64:ff9b::/96`){let r=new c.Address4(t),i=new e(n),a=i.subnetMask;if(a!==32&&a!==40&&a!==48&&a!==56&&a!==64&&a!==96)throw new u.AddressError(`NAT64 prefix length must be 32, 40, 48, 56, 64, or 96`);let o=i.binaryZeroPad(),s=r.binaryZeroPad(),l;if(a===96)l=o.slice(0,96)+s;else{let e=64-a;l=[o.slice(0,a),s.slice(0,e),`00000000`,s.slice(e),`0`.repeat(56-(32-e))].join(``)}let d=BigInt(`0b${l}`).toString(16).padStart(32,`0`),f=[];for(let e=0;e<8;e++)f.push(d.slice(e*4,(e+1)*4));return new e(f.join(`:`))}toAddress4Nat64(t=`64:ff9b::/96`){let n=new e(t),r=n.subnetMask;if(r!==32&&r!==40&&r!==48&&r!==56&&r!==64&&r!==96)throw new u.AddressError(`NAT64 prefix length must be 32, 40, 48, 56, 64, or 96`);if(!this.isHostInSubnet(n))return null;let i=this.binaryZeroPad(),a;if(r===96)a=i.slice(96,128);else{let e=64-r;a=i.slice(r,r+e)+i.slice(72,72+(32-e))}let o=[];for(let e=0;e<4;e++)o.push(parseInt(a.slice(e*8,(e+1)*8),2).toString());return new c.Address4(o.join(`.`))}toByteArray(){let e=this.bigInt().toString(16).padStart(o.BITS/4,`0`),t=[];for(let n=0,r=e.length;n<r;n+=2)t.push(parseInt(e.substring(n,n+2),16));return t}toUnsignedByteArray(){return this.toByteArray().map(v)}static fromByteArray(e){return i.assertByteArray(e,16,`IPv6`,-128),this.fromUnsignedByteArray(e.map(v))}static fromUnsignedByteArray(t){i.assertByteArray(t,16,`IPv6`,0);let n=BigInt(`256`),r=BigInt(`0`),a=BigInt(`1`);for(let e=t.length-1;e>=0;e--)r+=a*BigInt(t[e].toString(10)),a*=n;return e.fromBigInt(r)}isCanonical(){return this.addressMinusSuffix===this.canonicalForm()}isLinkLocal(){let e=this.embeddedIPv4();return e?e.isLinkLocal():this.isHostInSubnet(w)}isMulticast(){let e=this.embeddedIPv4();if(e)return e.isMulticast();let t=this.getType();return t===`Multicast`||t.startsWith(`Multicast `)}is4(){return this.v4}isMapped4(){return this.isHostInSubnet(k)}embeddedIPv4(){return this.isMapped4()||this.isHostInSubnet(A)?this.to4():null}isTeredo(){return this.isHostInSubnet(x)}is6to4(){return this.isHostInSubnet(S)}isLoopback(){let e=this.embeddedIPv4();return e?e.isLoopback():this.getType()===`Loopback`}isULA(){return this.isHostInSubnet(C)}isPrivate(){let e=this.embeddedIPv4();return e?e.isPrivate():this.isULA()||this.isHostInSubnet(j)}isCGNAT(){let e=this.embeddedIPv4();return e?e.isCGNAT():!1}isBroadcast(){let e=this.embeddedIPv4();return e?e.isBroadcast():!1}isUnspecified(){let e=this.embeddedIPv4();return e?e.isUnspecified():this.getType()===`Unspecified`}isDocumentation(){return T.some(e=>this.isHostInSubnet(e))}isBenchmarking(){let e=this.embeddedIPv4();return e?e.isBenchmarking():this.isHostInSubnet(E)}isGlobal(){let e=this.embeddedIPv4();return e?e.isGlobal():this.isHostInSubnet(D)&&i.isGloballyReachable.call(this,O)}href(e){return e=e===void 0?``:`:${e}`,`http://[${this.correctForm()}]${e}/`}link(e){e||={},e.className===void 0&&(e.className=``),e.prefix===void 0&&(e.prefix=`/#address=`),e.v4===void 0&&(e.v4=!1);let t=this.correctForm;e.v4&&(t=this.to4in6);let n=t.call(this),r=s.escapeHtml(`${e.prefix}${n}`),i=s.escapeHtml(n);return e.className?`<a href="${r}" class="${s.escapeHtml(e.className)}">${i}</a>`:`<a href="${r}">${i}</a>`}group(){if(this.elidedGroups===0)return s.simpleGroup(this.addressMinusSuffix).join(`:`);p(typeof this.elidedGroups==`number`),p(typeof this.elisionBegin==`number`);let e=[],[t,n]=this.addressMinusSuffix.split(`::`);t.length?e.push(...s.simpleGroup(t)):e.push(``);let r=[`hover-group`];for(let e=this.elisionBegin;e<this.elisionBegin+this.elidedGroups;e++)r.push(`group-${e}`);return e.push(`<span class="${r.join(` `)}"></span>`),n.length?e.push(...s.simpleGroup(n,this.elisionEnd)):e.push(``),this.is4()&&(p(this.address4 instanceof c.Address4),e.pop(),e.push(this.address4.groupForV6())),e.join(`:`)}regularExpressionString(t=!1){let n=[],r=new e(this.correctForm());if(r.elidedGroups===0)n.push((0,l.simpleRegularExpression)(r.parsedAddress));else if(r.elidedGroups===o.GROUPS)n.push((0,l.possibleElisions)(o.GROUPS));else{let e=r.address.split(`::`);e[0].length&&n.push((0,l.simpleRegularExpression)(e[0].split(`:`))),p(typeof r.elidedGroups==`number`),n.push((0,l.possibleElisions)(r.elidedGroups,e[0].length!==0,e[1].length!==0)),e[1].length&&n.push((0,l.simpleRegularExpression)(e[1].split(`:`))),n=[n.join(`:`)]}return t||(n=[`(?=^|`,l.ADDRESS_BOUNDARY,`|[^\\w\\:])(`,...n,`)(?=[^\\w\\:]|`,l.ADDRESS_BOUNDARY,`|$)`]),n.join(``)}regularExpression(e=!1){return new RegExp(this.regularExpressionString(e),`i`)}};e.Address6=y;var b=Object.keys(o.TYPES).map(e=>[new y(e),o.TYPES[e]]),x=new y(`2001::/32`),S=new y(`2002::/16`),C=new y(`fc00::/7`),w=new y(`fe80::/10`),T=[new y(`2001:db8::/32`),new y(`3fff::/20`)],E=new y(`2001:2::/48`),D=new y(`2000::/3`),O=o.SPECIAL_PURPOSE.map(([e,,t])=>({subnet:new y(e),reachable:t})),k=new y(`::ffff:0:0/96`),A=new y(`64:ff9b::/96`),j=new y(`64:ff9b:1::/48`)})),yS=r((e=>{var t=e&&e.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||(`get`in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),n=e&&e.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),r=e&&e.__importStar||function(e){if(e&&e.__esModule)return e;var r={};if(e!=null)for(var i in e)i!=="default"&&Object.prototype.hasOwnProperty.call(e,i)&&t(r,e,i);return n(r,e),r};Object.defineProperty(e,"__esModule",{value:!0}),e.v6=e.AddressError=e.Address6=e.Address4=void 0;var i=mS();Object.defineProperty(e,"Address4",{enumerable:!0,get:function(){return i.Address4}});var a=vS();Object.defineProperty(e,"Address6",{enumerable:!0,get:function(){return a.Address6}});var o=dS();Object.defineProperty(e,"AddressError",{enumerable:!0,get:function(){return o.AddressError}}),e.v6={helpers:r(gS())}}))(),bS=n(cl(),1),xS=new yS.Address6(`::/96`);function SS(e,t=56){if(ia(e)){let n=new yS.Address6(e);if(n.isMapped4()||n.is4()&&n.isInSubnet(xS))return n.to4().correctForm();if(t)return new yS.Address6(`${e}/${t}`).networkForm()}return e}var CS=class{constructor(e){this.validations=e,this.previous=new Map,this.current=new Map,this.localKeys=!0}init(e){this.windowMs=e.windowMs,this.validations?.windowMs(this.windowMs),this.interval&&clearInterval(this.interval),this.interval=setInterval(()=>{this.clearExpired()},this.windowMs),this.interval.unref?.()}async get(e){return this.current.get(e)??this.previous.get(e)}async increment(e){let t=this.getClient(e),n=Date.now();return t.resetTime.getTime()<=n&&this.resetClient(t,n),t.totalHits++,t}async decrement(e){let t=this.getClient(e);t.totalHits>0&&t.totalHits--}async resetKey(e){this.current.delete(e),this.previous.delete(e)}async resetAll(){this.current.clear(),this.previous.clear()}shutdown(){clearInterval(this.interval),this.resetAll()}resetClient(e,t=Date.now()){return e.totalHits=0,e.resetTime.setTime(t+this.windowMs),e}getClient(e){if(this.current.has(e))return this.current.get(e);let t;return this.previous.has(e)?(t=this.previous.get(e),this.previous.delete(e)):(t={totalHits:0,resetTime:new Date},this.resetClient(t)),this.current.set(e,t),t}clearExpired(){this.previous=this.current,this.current=new Map}},wS={warn(...e){console.warn(...e.reverse())},error(...e){console.error(...e.reverse())}},TS=[`draft-6`,`draft-7`,`draft-8`],ES=(e,t)=>{let n;if(t){let e=Math.ceil((t.getTime()-Date.now())/1e3);n=Math.max(0,e)}else n=Math.ceil(e/1e3);return n},DS=e=>{let t=aa(`sha256`);t.update(e);let n=t.digest(`hex`).slice(0,12);return ea.from(n).toString(`base64`)},OS=(e,t)=>{e.headersSent||(e.setHeader(`X-RateLimit-Limit`,t.limit.toString()),e.setHeader(`X-RateLimit-Remaining`,t.remaining.toString()),t.resetTime instanceof Date&&(e.setHeader(`Date`,new Date().toUTCString()),e.setHeader(`X-RateLimit-Reset`,Math.ceil(t.resetTime.getTime()/1e3).toString())))},kS=(e,t,n)=>{if(e.headersSent)return;let r=Math.ceil(n/1e3),i=ES(n,t.resetTime);e.setHeader(`RateLimit-Policy`,`${t.limit};w=${r}`),e.setHeader(`RateLimit-Limit`,t.limit.toString()),e.setHeader(`RateLimit-Remaining`,t.remaining.toString()),typeof i==`number`&&e.setHeader(`RateLimit-Reset`,i.toString())},AS=(e,t,n)=>{if(e.headersSent)return;let r=Math.ceil(n/1e3),i=ES(n,t.resetTime);e.setHeader(`RateLimit-Policy`,`${t.limit};w=${r}`),e.setHeader(`RateLimit`,`limit=${t.limit}, remaining=${t.remaining}, reset=${i}`)},jS=(e,t,n,r,i)=>{if(e.headersSent)return;let a=Math.ceil(n/1e3),o=ES(n,t.resetTime),s=DS(i),c=`r=${t.remaining}; t=${o}`,l=`q=${t.limit}; w=${a}; pk=:${s}:`;e.append(`RateLimit`,`"${r}"; ${c}`),e.append(`RateLimit-Policy`,`"${r}"; ${l}`)},MS=(e,t,n,r)=>{if(e.headersSent)return;let i=r??ES(n,t.resetTime);e.setHeader(`Retry-After`,i.toString())},NS=e=>{let t={};for(let n of Object.keys(e)){let r=n;e[r]!==void 0&&(t[r]=e[r])}return t},PS=class extends Error{constructor(e,t){let n=`https://express-rate-limit.github.io/${e}/`;super(`${t} See ${n} for more information.`),this.name=this.constructor.name,this.code=e,this.help=n}},FS=class extends PS{},IS=new Set,LS=new WeakMap,RS={enabled:{default:!0},disable(){for(let e of Object.keys(this.enabled))this.enabled[e]=!1},ip(e){if(e===void 0)throw new PS(`ERR_ERL_UNDEFINED_IP_ADDRESS`,`An undefined 'request.ip' was detected. This might indicate a misconfiguration or the connection being destroyed prematurely.`);if(!na(e))throw new PS(`ERR_ERL_INVALID_IP_ADDRESS`,`An invalid 'request.ip' (${e}) was detected. Consider passing a custom 'keyGenerator' function to the rate limiter.`)},trustProxy(e){if(e.app.get(`trust proxy`)===!0)throw new PS(`ERR_ERL_PERMISSIVE_TRUST_PROXY`,`The Express 'trust proxy' setting is true, which allows anyone to trivially bypass IP-based rate limiting.`)},xForwardedForHeader(e){if(e.headers[`x-forwarded-for`]&&e.app.get(`trust proxy`)===!1)throw new PS(`ERR_ERL_UNEXPECTED_X_FORWARDED_FOR`,`The 'X-Forwarded-For' header is set but the Express 'trust proxy' setting is false (default). This could indicate a misconfiguration which would prevent express-rate-limit from accurately identifying users.`)},forwardedHeader(e){if(e.headers.forwarded&&e.ip===e.socket?.remoteAddress)throw new PS(`ERR_ERL_FORWARDED_HEADER`,`The 'Forwarded' header (standardized X-Forwarded-For) is set but currently being ignored. Add a custom keyGenerator to use a value from this header.`)},positiveHits(e){if(typeof e!=`number`||e<1||e!==Math.round(e))throw new PS(`ERR_ERL_INVALID_HITS`,`The totalHits value returned from the store must be a positive integer, got ${e}`)},unsharedStore(e){if(IS.has(e)){let t=e?.localKeys?``:` (with a unique prefix)`;throw new PS(`ERR_ERL_STORE_REUSE`,`A Store instance must not be shared across multiple rate limiters. Create a new instance of ${e.constructor.name}${t} for each limiter instead.`)}IS.add(e)},singleCount(e,t,n){let r=LS.get(e);r||(r=new Map,LS.set(e,r));let i=t.localKeys?t:t.constructor.name,a=r.get(i);a||(a=[],r.set(i,a));let o=`${t.prefix??``}${n}`;if(a.includes(o))throw new PS(`ERR_ERL_DOUBLE_COUNT`,`The hit count for ${n} was incremented more than once for a single request.`);a.push(o)},limit(e){if(e===0)throw new FS(`WRN_ERL_MAX_ZERO`,`Setting limit or max to 0 disables rate limiting in express-rate-limit v6 and older, but will cause all requests to be blocked in v7`)},draftPolliHeaders(e){if(e)throw new FS(`WRN_ERL_DEPRECATED_DRAFT_POLLI_HEADERS`,`The draft_polli_ratelimit_headers configuration option is deprecated and has been removed in express-rate-limit v7, please set standardHeaders: 'draft-6' instead.`)},onLimitReached(e){if(e)throw new FS(`WRN_ERL_DEPRECATED_ON_LIMIT_REACHED`,`The onLimitReached configuration option is deprecated and has been removed in express-rate-limit v7.`)},headersDraftVersion(e){if(typeof e!=`string`||!TS.includes(e))throw new PS(`ERR_ERL_HEADERS_UNSUPPORTED_DRAFT_VERSION`,`standardHeaders: only the following versions of the IETF draft specification are supported: ${TS.join(`, `)}.`)},headersResetTime(e){if(!e)throw new PS(`ERR_ERL_HEADERS_NO_RESET`,`standardHeaders: 'draft-7' requires a 'resetTime', but the store did not provide one. The 'windowMs' value will be used instead, which may cause clients to wait longer than necessary.`)},knownOptions(e){if(!e)return;let t=Object.keys({windowMs:!0,limit:!0,message:!0,statusCode:!0,legacyHeaders:!0,standardHeaders:!0,identifier:!0,retryAfter:!0,requestPropertyName:!0,skipFailedRequests:!0,skipSuccessfulRequests:!0,keyGenerator:!0,ipv6Subnet:!0,handler:!0,skip:!0,requestWasSuccessful:!0,store:!0,validate:!0,headers:!0,max:!0,passOnStoreError:!0,logger:!0}).concat(`draft_polli_ratelimit_headers`,`delayAfter`,`delayMs`,`maxDelayMs`);for(let n of Object.keys(e))if(!t.includes(n))throw new PS(`ERR_ERL_UNKNOWN_OPTION`,`Unexpected configuration option: ${n}`)},validationsConfig(){let e=Object.keys(this).filter(e=>![`enabled`,`disable`].includes(e));e.push(`default`);for(let t of Object.keys(this.enabled))if(!e.includes(t))throw new PS(`ERR_ERL_UNKNOWN_VALIDATION`,`options.validate.${t} is not recognized. Supported validate options are: ${e.join(`, `)}.`)},creationStack(e){let{stack:t}=Error(`express-rate-limit validation check (set options.validate.creationStack=false to disable)`);if(t?.includes(`Layer.handle [as handle_request]`)||t?.includes(`Layer.handleRequest`))throw e.localKeys?new PS(`ERR_ERL_CREATED_IN_REQUEST_HANDLER`,`express-rate-limit instance should be created at app initialization, not when responding to a request.`):new PS(`ERR_ERL_CREATED_IN_REQUEST_HANDLER`,`express-rate-limit instance should *usually* be created at app initialization, not when responding to a request.`)},ipv6Subnet(e){if(e!==!1&&(!Number.isInteger(e)||e<32||e>64))throw new PS(`ERR_ERL_IPV6_SUBNET`,`Unexpected ipv6Subnet value: ${e}. Expected an integer between 32 and 64 (usually 48-64).`)},ipv6SubnetOrKeyGenerator(e){if(e.ipv6Subnet!==void 0&&e.keyGenerator)throw new PS(`ERR_ERL_IPV6SUBNET_OR_KEYGENERATOR`,`Incompatible options: the 'ipv6Subnet' option is ignored when a custom 'keyGenerator' function is also set.`)},keyGeneratorIpFallback(e){if(!e)return;let t=e.toString();if((t.includes(`req.ip`)||t.includes(`request.ip`))&&!t.includes(`ipKeyGenerator`))throw new PS(`ERR_ERL_KEY_GEN_IPV6`,`Custom keyGenerator appears to use request IP without calling the ipKeyGenerator helper function for IPv6 addresses. This could allow IPv6 users to bypass limits.`)},windowMs(e){let t=2**31-1;if(typeof e!=`number`||Number.isNaN(e)||e<1||e>t)throw new PS(`ERR_ERL_WINDOW_MS`,`Invalid windowMs value: ${e}${typeof e==`number`?``:` (${typeof e})`}, must be a number between 1 and ${t} when using the default MemoryStore`)}};function zS(e){if(typeof e!=`object`||typeof e.error!=`function`||typeof e.warn!=`function`)throw TypeError(`Provided logger does not implement the Logger interface`)}var BS=(e,t)=>{zS(t);let n;n=typeof e==`boolean`?{default:e}:{default:!0,...e};let r={enabled:n};for(let[e,i]of Object.entries(RS))typeof i==`function`&&(r[e]=(...a)=>{if(n[e]??n.default){n[e]=!1;try{i.apply(r,a)}catch(e){e instanceof FS?t.warn(e):t.error(e)}}});let i=Symbol.for(`nodejs.util.inspect.custom`);return i&&(r[i]=()=>r.enabled),r},VS=e=>typeof e.incr==`function`&&typeof e.increment!=`function`,HS=e=>{if(!VS(e))return e;let t=e;class n{async increment(e){return new Promise((n,r)=>{t.incr(e,(e,t,i)=>{e&&r(e),n({totalHits:t,resetTime:i})})})}async decrement(e){return t.decrement(e)}async resetKey(e){return t.resetKey(e)}async resetAll(){if(typeof t.resetAll==`function`)return t.resetAll()}}return new n},US=e=>{let{validations:t,...n}=e;return{...n,validate:t.enabled}},WS=e=>{let t=NS(e),n=e.logger??wS,r=BS(t?.validate??!0,n);r.validationsConfig(),r.knownOptions(e),r.draftPolliHeaders(t.draft_polli_ratelimit_headers),r.onLimitReached(t.onLimitReached),t.ipv6Subnet!==void 0&&typeof t.ipv6Subnet!=`function`&&r.ipv6Subnet(t.ipv6Subnet),r.keyGeneratorIpFallback(t.keyGenerator),r.ipv6SubnetOrKeyGenerator(t);let i=t.standardHeaders??!1;i===!0&&(i=`draft-6`);let a={windowMs:6e4,limit:e.max??5,message:`Too many requests, please try again later.`,statusCode:429,legacyHeaders:e.headers??!0,identifier(e,t){let n=``,{limit:r}=e[a.requestPropertyName],i=a.windowMs/1e3,o=a.windowMs/6e4,s=a.windowMs/36e5,c=a.windowMs/864e5;return n=i<60?`${i}sec`:o<60?`${o}min`:s<24?`${s}hr${s>1?`s`:``}`:`${c}day${c>1?`s`:``}`,`${r}-in-${n}`},requestPropertyName:`rateLimit`,skipFailedRequests:!1,skipSuccessfulRequests:!1,requestWasSuccessful:(e,t)=>t.statusCode<400,skip:(e,t)=>!1,async keyGenerator(e,t){r.ip(e.ip),r.trustProxy(e),r.xForwardedForHeader(e),r.forwardedHeader(e);let n=e.ip,i=56;return ia(n)&&(i=typeof a.ipv6Subnet==`function`?await a.ipv6Subnet(e,t):a.ipv6Subnet,typeof a.ipv6Subnet==`function`&&r.ipv6Subnet(i)),SS(n,i)},ipv6Subnet:56,async handler(e,t,n,r){t.status(a.statusCode);let i=typeof a.message==`function`?await a.message(e,t):a.message;t.writableEnded||t.send(i)},passOnStoreError:!1,...t,standardHeaders:i,store:HS(t.store??new CS(r)),validations:r,logger:n};if(typeof a.store.increment!=`function`||typeof a.store.decrement!=`function`||typeof a.store.resetKey!=`function`||a.store.resetAll!==void 0&&typeof a.store.resetAll!=`function`||a.store.init!==void 0&&typeof a.store.init!=`function`)throw TypeError("An invalid store was passed. Please ensure that the store is a class that implements the `Store` interface.");return a},GS=e=>async(t,n,r)=>{try{await Promise.resolve(e(t,n,r)).catch(r)}catch(e){r(e)}},KS=e=>{let t=WS(e??{}),n=US(t),r=(0,bS.default)(`express-rate-limit`);r(`creating new rate limiter with %o`,t.store.constructor.name);for(let[e,n]of Object.entries(t))r(`set %s to %o`,e,n);if(t.validations.creationStack(t.store),t.validations.unsharedStore(t.store),typeof t.store.init==`function`){r(`executing init for store`);try{let e=t.store.init(n);e instanceof Promise&&e.catch(e=>t.logger.error(e,`express-rate-limit: async error during store initialization.`))}catch(e){t.logger.error(e,`express-rate-limit: error during store initialization.`)}}let i=GS(async(e,i,a)=>{let o=t.skipFailedRequests&&new Promise(e=>i.once(`close`,e)),s=(t.skipFailedRequests||t.skipSuccessfulRequests)&&new Promise(e=>i.once(`finish`,e)),c=t.skipFailedRequests&&new Promise(e=>i.once(`error`,e));if(r(`requested %o`,e.originalUrl),r(`request from ip %o`,e.ip),await t.skip(e,i)){r(`skipping request`),a();return}let l=e,u=await t.keyGenerator(e,i);r(`computed key %o`,u),r(`incrementing count`);let d=0,f;try{let e=await t.store.increment(u);d=e.totalHits,f=e.resetTime}catch(e){if(t.passOnStoreError){t.logger.error(e,`express-rate-limit: error from store, allowing request without rate-limiting.`),a();return}throw e}t.validations.positiveHits(d),t.validations.singleCount(e,t.store,u);let p=await(typeof t.limit==`function`?t.limit(e,i):t.limit);t.validations.limit(p);let m={limit:p,used:d,remaining:Math.max(p-d,0),resetTime:f,key:u};for(let[e,n]of Object.entries(m))r(`set request.%s.%s to be %o`,t.requestPropertyName,e,n);if(Object.defineProperty(m,"current",{configurable:!1,enumerable:!1,value:d}),l[t.requestPropertyName]=m,t.legacyHeaders&&!i.headersSent&&(r(`set legacy headers`),OS(i,m)),t.standardHeaders&&!i.headersSent)switch(t.standardHeaders){case`draft-6`:r(`set ietf draft 6 headers`),kS(i,m,t.windowMs);break;case`draft-7`:r(`set ietf draft 7 headers`),t.validations.headersResetTime(m.resetTime),AS(i,m,t.windowMs);break;case`draft-8`:{let n=await(typeof t.identifier==`function`?t.identifier(e,i):t.identifier);r(`set ietf draft 8 headers`),r(`set name to %o`,n),t.validations.headersResetTime(m.resetTime),jS(i,m,t.windowMs,n,u);break}default:t.validations.headersDraftVersion(t.standardHeaders)}if(t.skipFailedRequests||t.skipSuccessfulRequests){let n=!1,a=async()=>{if(!n){if(f&&Date.now()>=f.getTime())return;r(`decrementing count`),await t.store.decrement(u),n=!0}};t.skipFailedRequests&&(s&&s.then(async()=>{let n=await t.requestWasSuccessful(e,i);r(`computed requestWasSuccessful as %o`,n),n||await a()}),o&&o.then(async()=>{i.writableEnded||await a()}),c&&c.then(async()=>{await a()})),t.skipSuccessfulRequests&&s&&s.then(async()=>{let n=await t.requestWasSuccessful(e,i);r(`computed requestWasSuccessful as %o`,n),n&&await a()})}if(d>p){if(r(`limit exceeded`),t.legacyHeaders||t.standardHeaders){r(`set retry-after header`);let n=await(typeof t.retryAfter==`function`?t.retryAfter(e,i):t.retryAfter);MS(i,m,t.windowMs,n)}t.handler(e,i,a,n);return}a()});return i.resetKey=t.store.resetKey.bind(t.store),i.getKey=typeof t.store.get==`function`?t.store.get.bind(t.store):()=>{throw Error(`The current store does not support the get/getKey method`)},i},qS=Xi.map(({operationId:e,method:t,path:n,parameter:r})=>({operationId:e,method:t,path:n,authorizationPath:ke(n,Object.fromEntries(r.filter(e=>e.in===`path`).map(e=>e.schemaEnum?.[0]===void 0?e.schemaFormat===`uuid`?[e.name,oa()]:e.schemaType===`integer`||e.schemaType===`number`?[e.name,1]:[e.name,`authorization-probe`]:[e.name,e.schemaEnum[0]])),e)})),JS={ttlMs:ni,maxEntries:128,verificationDeadlineMs:1e4,degradedGrantMaxAgeMs:ni+6e5,maxConcurrentVerifications:16,maxOverBudgetVerifications:2},YS=()=>new Sr({status:429,title:`Too Many Requests`,type:`about:blank`,detail:`Too many credential verifications are in progress; retry shortly.`,retryAfterSeconds:1}),XS=e=>e instanceof Sr?e.problem.status!==429&&Kr(e.problem.status,e.problem):Ot(e);function ZS(e){if(!e.includes(`.`))return 1/0;try{let{exp:t}=wt(e);return t===void 0?1/0:t*1e3}catch(e){if(!(e instanceof It))throw e;return 1/0}}var QS=(e,t)=>`${aa(`sha256`).update(e).digest(`hex`)} ${t?.href??``}`;function $S(e=JS){let t=new Map,n={limit:e.maxConcurrentVerifications,inFlight:0},r={limit:e.maxOverBudgetVerifications,inFlight:0},i=(i,a,o)=>{let s=QS(i,a),c=t.get(s);if(c!==void 0&&c.expiresAt>Date.now())return t.delete(s),t.set(s,c),c.verification;let l=c?.grant,u=t=>{let n=l===void 0?1/0:Date.now()-l.grantedAt,r=n<e.degradedGrantMaxAgeMs&&ZS(i)>Date.now();if(l===void 0||!r||!XS(t))throw t;return ae({component:`aventure-mcp-server`,event:`authentication_degraded`,fields:{requestId:we(),grantAgeMs:n},error:t}),l.authorization},d=o?[n,r]:[n];if(d.some(({inFlight:e,limit:t})=>e>=t))return Promise.reject(YS());t.delete(s);for(let e of d)e.inFlight+=1;let f=()=>{for(let e of d)--e.inFlight},p=Wt(i,a,qS,e.verificationDeadlineMs).catch(u),m={verification:p,expiresAt:1/0,grant:l};t.set(s,m);for(let n of t.keys()){if(t.size<=e.maxEntries)break;t.delete(n)}let h=()=>{t.get(s)===m&&t.delete(s)};return p.then(t=>{f(),t===null||t===`forbidden`?h():t===l?.authorization?m.expiresAt=0:(m.grant={authorization:t,grantedAt:Date.now()},m.expiresAt=Math.min(Date.now()+e.ttlMs,ZS(i)))},()=>{f(),h()}),p},a=(e,n)=>{let r=Mr(e.header(`authorization`));if(r===void 0)return!1;let i=t.get(QS(r,n))?.expiresAt;return i!==void 0&&Number.isFinite(i)&&i>Date.now()},o=async(e,t,n)=>{let r=e.header(`authorization`),a=Mr(r);if(a===void 0)return{ok:!1,reason:`missing_credential`,hasAuthorization:!1};try{let e=await i(a,t,n);if(e===`forbidden`)return{ok:!1,reason:`forbidden`,hasAuthorization:!0};if(e!==null)return{ok:!0,scope:e.operationAccess===`READ`?`read`:`write`,userBearerToken:a,authorization:e}}catch(e){if(!(e instanceof It))throw e;ae({component:`aventure-mcp-server`,event:`invalid_bearer_jwt`,fields:{requestId:we()},error:e})}return{ok:!1,reason:`credential_mismatch`,hasAuthorization:!0}},s=new WeakMap,c=(e,t,n=!1)=>{let r=s.get(e);if(r!==void 0&&r.resourceHref===t?.href)return r.decision;let i=o(e,t,n);return s.set(e,{resourceHref:t?.href,decision:i}),i};return Object.assign((e,t)=>c(e,t),{holdsGrant:a,admitsOverBudget:(e,t)=>Mr(e.header(`authorization`))===void 0?Promise.resolve(!1):c(e,t,!0).then(e=>e.ok,()=>!1)})}function eC(e,t){let n=new WeakMap;return[KS({windowMs:6e4,limit:120,skipSuccessfulRequests:!0,skip:async n=>e.holdsGrant(n,await t()),handler:(...[e,,t,r])=>{n.set(e,r),t()}}),async(r,i,a)=>{let o=n.get(r);o===void 0||await e.admitsOverBudget(r,await t())?a():i.status(o.statusCode).send(o.message)},KS({windowMs:6e4,limit:120,keyGenerator:tC})]}function tC(e){let t=Mr(e.header(`authorization`));return t===void 0?SS(e.ip??``):aa(`sha256`).update(t).digest(`base64url`)}function nC(e,t){let n=`an API key from https://aventure.vc/settings/api-keys as Authorization: Bearer <key>`,r=t?`Sign in with OAuth through the authorization server in this server's resource metadata; a client that cannot register itself needs the OAuth client ID at https://docs.aventure.vc/mcp. Or send ${n}.`:`Send ${n}. This server advertises no OAuth authorization server.`;return e===`forbidden`?`The supplied credential is valid, but its account may not use this MCP server.`:e===`missing_credential`?r:`The supplied credential was rejected or expired; reconnect this server in the MCP client to sign in again. ${r}`}var rC=1024,iC=rC*rC,aC=1,oC=2,sC=`b`,cC=`kb`,lC=`mb`,uC=/^(\d+(?:\.\d+)?)\s*(b|kb|mb)?$/u;function dC(e){let t=pC(e.limit),n=fC(e.path);return(r,i,a)=>{if(t===void 0||r.method!==`POST`||fC(r.path)!==n){a();return}let o=mC(r.header(`content-length`));if(o===void 0||o<=t){a();return}i.setHeader(`Connection`,`close`),e.reject(i)}}function fC(e){let t=e.endsWith(`/`)?e.slice(0,-1):e;return t===``?`/`:t}function pC(e){if(typeof e==`number`)return Number.isFinite(e)&&e>=0?e:void 0;let t=uC.exec(e.trim().toLowerCase());if(t===null)return;let n=Number(t[aC]);if(Number.isFinite(n))switch(t[oC]??sC){case lC:return Math.floor(n*iC);case cC:return Math.floor(n*rC);case sC:return Math.floor(n)}}function mC(e){if(e===void 0)return;let t=Number(e);return Number.isInteger(t)&&t>=0?t:void 0}var hC=256e3,gC=16e3,_C=256,vC=31,yC=127,bC=36e5,xC=`openai/session`,SC=`mcpCallOutcome`;function CC(e,t){let n=`${t??``} ${e??``}`.toLowerCase();return n.includes(`openai-mcp`)||n.includes(`chatgpt`)?`chatgpt`:n.includes(`claude-user`)||n.includes(`claude-ai`)||n.includes(`claude.ai`)?`claude_ai`:n.includes(`claude-code`)||n.includes(`claude code`)?`claude_code`:n.includes(`grok`)?`grok`:n.includes(`codex`)?`codex`:n.includes(`cursor`)?`cursor`:n.includes(`gemini`)||n.includes(`antigravity`)?`gemini`:`other`}function wC(e){let t=typeof e==`object`&&e?Reflect.get(e,`params`):void 0;if(typeof t!=`object`||!t)return{};let n=Reflect.get(t,`_meta`),r=Reflect.get(t,`clientInfo`)??(typeof n==`object`&&n?Reflect.get(n,`io.modelcontextprotocol/clientInfo`):void 0);if(typeof r!=`object`||!r)return{};let i=Reflect.get(r,`name`),a=Reflect.get(r,`version`);return{name:typeof i==`string`?i:void 0,version:typeof a==`string`?a:void 0}}function TC(e,t){let n=t.locals[SC];return{...uS(e.body,lS(t)),client:CC(e.get(`user-agent`),wC(e.body).name),outcome:EC(n)?n:`none`}}function EC(e){return e===`ok`||e===`caller_error`||e===`tool_error`||e===`protocol_error`||e===`aborted`}function DC(e,t){let n=[],r=0,i=(e,t)=>{if(r>=hC||e==null)return;let i=typeof e==`string`?Buffer.from(e,typeof t==`string`&&Buffer.isEncoding(t)?t:`utf8`):e instanceof Uint8Array?Buffer.from(e):void 0;i!==void 0&&(n.push(i.subarray(0,hC-r)),r+=i.length)},a=e.write.bind(e),o=e.end.bind(e);e.write=((t,n,r)=>(i(t,n),Reflect.apply(a,e,[t,n,r].filter(e=>e!==void 0)))),e.end=((r,a,s)=>(typeof r!=`function`&&i(r,a),t(Buffer.concat(n).toString(`utf8`)),Reflect.apply(o,e,[r,a,s].filter(e=>e!==void 0))))}function OC(e,t){let n=e.trimStart().startsWith(`{`)?[e]:e.split(`
145
- `).filter(e=>e.startsWith(`data:`)).map(e=>e.slice(5).trim());for(let e of n){let n;try{n=JSON.parse(e)}catch(e){return{outcome:`protocol_error`,text:``,summary:`unparseable reply: ${String(e)}`}}let r=rr.safeParse(n);if(!r.success||!(`id`in r.data)||r.data.id!==t)continue;if(`error`in r.data)return{outcome:`protocol_error`,text:``,summary:r.data.error.message};if(!(`result`in r.data))continue;let i=Br.safeParse(r.data.result);if(!i.success)return{outcome:`protocol_error`,text:``,summary:`malformed tool result`};let a=Pi(i.data.structuredContent),o=i.data.content.find(e=>e.type===`text`),s=a?.httpStatus??a?.problem?.status;return{outcome:kC(i.data.isError===!0,s),text:o?.type===`text`?o.text:``,httpStatus:s,problemType:a?.problem?.type,summary:a?.summary}}return{outcome:`protocol_error`,text:``,summary:`no JSON-RPC reply to this call`}}function kC(e,t){return e?t!==void 0&&Fi(t)?`caller_error`:`tool_error`:`ok`}function AC(e,t){return typeof e==`object`&&e?Reflect.get(e,t):void 0}function jC(e){return MC(typeof e==`object`&&e?Object.keys(e).join(`,`):``)}function MC(e){let t=``;for(let n=0;n<e.length;n+=1){let r=e[n]??``,i=e.charCodeAt(n);t+=i<=vC||i===yC?`�`:r}return t.length>_C?`${t.slice(0,255)}…`:t}function NC(e,t){let n=AC(t,xC);return typeof n==`string`&&n.length>0?`${e}:${MC(n)}`:`${e}:${aa(`sha256`).update(ge()??`anonymous`).digest(`hex`).slice(0,16)}:${Math.floor(Date.now()/bC)}`}var PC=e=>e.length>gC?`${e.slice(0,gC)}…`:e;async function FC(e,t,n){let r=er.safeParse(e.body),i=typeof e.body==`object`&&e.body!==null?Reflect.get(e.body,`id`):void 0;if(!r.success||typeof i!=`string`&&typeof i!=`number`){await n();return}let a=performance.now(),o=e.get(`user-agent`),s=wC(e.body),c=CC(o,s.name),l=Reflect.get(r.data.params,`_meta`),u=r.data.params.arguments,d=typeof u?.operationId==`string`?MC(u.operationId):void 0,f=s.name===void 0?void 0:MC(s.name),p=s.version===void 0?void 0:MC(s.version),m=o===void 0?void 0:MC(o),h=NC(c,l),g=uS(e.body,lS(t)).toolName,_=MC(r.data.params.name),v=AC(l,Rr),y=be(`mcp ${g}`,{"langfuse.trace.name":`mcp ${g}`,"langfuse.session.id":h,"langfuse.trace.tags":[`mcp`,c,g],"langfuse.observation.type":`tool`,"langfuse.observation.input":PC(JSON.stringify(u??{})),"langfuse.environment":ce()[`deployment.environment.name`]??`unknown`,...process.env.GIT_SHA===void 0?{}:{"langfuse.release":process.env.GIT_SHA},"langfuse.trace.metadata.client":c,"langfuse.trace.metadata.client_name":f??``,"langfuse.trace.metadata.client_version":p??``,"langfuse.trace.metadata.user_agent":m??``,"langfuse.trace.metadata.operation_id":d??``,"langfuse.trace.metadata.meta_keys":jC(l),"aventure.request_id":we()??``,"mcp.tool.name":g,"mcp.tool.requested_name":_},typeof v==`string`?v:void 0);DC(t,n=>{let r=t.destroyed||e.socket.destroyed?{outcome:`aborted`,text:``}:OC(n,i);t.locals[SC]=r.outcome;let o=r.outcome===`tool_error`||r.outcome===`protocol_error`,s={requestId:we(),toolName:g,requestedToolName:_,operationId:d,client:c,clientName:f,clientVersion:p,userAgent:m,metaKeys:jC(l),sessionId:h,outcome:r.outcome,httpStatus:r.httpStatus,problemType:r.problemType,resultChars:r.text.length,durationMs:Math.round(performance.now()-a),traceId:y?.spanContext().traceId};(o?ae:k)({component:`aventure-mcp-server`,event:`tool_call`,fields:s}),y!==void 0&&Te(y,{"langfuse.observation.output":PC(r.text),"langfuse.observation.level":o?`ERROR`:`DEFAULT`,...r.summary===void 0?{}:{"langfuse.observation.status_message":r.summary},"langfuse.trace.metadata.outcome":r.outcome,"langfuse.trace.metadata.http_status":String(r.httpStatus??``),"langfuse.trace.metadata.problem_type":r.problemType??``,"mcp.tool.outcome":r.outcome},o)}),y===void 0?await n():await Se(Ee(y),n)}var IC=400,LC=400,RC=413,zC=`10mb`,BC=`127.0.0.1`,VC=/^[\w.:/-]{1,128}$/,HC=`0.0.0.0`;async function UC(e){let t=e.jsonBodyLimit??zC,n=$S(),r=e.host??BC,i=r!==HC,a=(t,n)=>{let r=`${t.protocol}://${t.host}`;return URL.canParse(e.path,r)&&new URL(e.path,r).href===n?.resourceUrl.href?n:void 0},o=(0,af.default)();o.disable(`x-powered-by`),o.set(`trust proxy`,1),o.use((e,t,n)=>{let r=e.get(`x-client-request-id`)??``,i=VC.test(r)?r:oa(),a=performance.now(),o={requestId:i,method:e.method,path:e.path,host:e.hostname,userAgent:e.get(`user-agent`)},s=KC(e);s||k({component:`aventure-mcp-server`,event:`http_request`,fields:o}),t.on(`finish`,()=>{let n=Math.round(performance.now()-a),r=e.route,i=typeof r==`object`&&r?Reflect.get(r,`path`):null,c=TC(e,t);zb(e.method,typeof i==`string`?i:`unmatched`,t.statusCode,n,c),!(s&&t.statusCode<IC)&&(t.statusCode>=IC&&!s?ae:k)({component:`aventure-mcp-server`,event:`http_response`,fields:{...o,...c,status:t.statusCode,durationMs:n}})}),De(i,()=>n())}),o.use(i?(0,rf.default)({origin:GC}):(0,rf.default)()),o.use(dC({path:e.path,limit:t,reject:e=>qC(e,RC,`Payload Too Large`,`Request JSON body exceeds the MCP transport size limit.`)})),o.use(af.json({limit:t})),o.get(`/health`,(...e)=>{let t=e[1],n=process.env.GIT_SHA?.trim();t.setHeader(`X-Aventure-Revision`,n&&/^[0-9a-f]{40}$/i.test(n)?n.slice(0,7):`unknown`),t.status(200).json({status:`UP`})}),o.get([`/.well-known/oauth-protected-resource`,`/.well-known/oauth-protected-resource${e.path}`],(0,rf.default)(),async(t,n,r)=>{let i=await e.resolveOAuthDiscovery();if(i===void 0){qC(n,503,`Service Unavailable`,`OAuth discovery is unavailable: the API published no OAuth resource indicator for this server.`);return}let o=a(t,i);if(o===void 0){r();return}n.status(200).json({resource:o.resourceUrl.href,authorization_servers:[o.client.authorizationServer],scopes_supported:o.client.scope})}),Bb(o,e.metricsScrapeSecret),xe(),o.get(`/`,(...t)=>{t[1].status(200).json({name:`aventure-mcp-server`,mcp:e.path,health:`/health`,transport:`streamable-http`,method:`POST`})}),o.get(`/favicon.ico`,(...e)=>e[1].redirect(302,`${M}/favicon.ico`));let s=eC(n,async()=>(await e.resolveOAuthDiscovery())?.resourceUrl);return o.post(e.path,s,async(t,r)=>{let o=we(),s=t.header(`origin`);if(i&&!WC(s)){ae({component:`aventure-mcp-server`,event:`foreign_origin_rejected`,fields:{requestId:o,method:t.method,path:t.path,origin:s}}),qC(r,403,`Forbidden`,`A self-hosted MCP transport accepts loopback browser origins only.`);return}let c,l;try{let r=await e.resolveOAuthDiscovery();l=a(t,r),c=await n(t,r?.resourceUrl)}catch(e){Xc(e,`authentication_unavailable`),N({component:`aventure-mcp-server`,event:`authentication_unavailable`,fields:{requestId:o,method:t.method,path:t.path},error:e});let n=e instanceof Sr&&(e.problem.status===429||ki(e.problem.status))?e.problem:void 0;n===void 0?qC(r,503,`Service Unavailable`,`Authentication service is temporarily unavailable.`):(typeof n.retryAfterSeconds==`number`&&r.set(`Retry-After`,String(n.retryAfterSeconds)),JC(r,n));return}if(!c.ok){ae({component:`aventure-mcp-server`,event:`unauthorized_request`,fields:{requestId:o,method:t.method,path:t.path,reason:c.reason,hasAuthorization:c.hasAuthorization}});let e=[l===void 0?void 0:`resource_metadata="${jv(l.resourceUrl)}"`,l===void 0?void 0:`scope="${l.client.scope.join(` `)}"`,c.reason===`credential_mismatch`?`error="invalid_token"`:void 0,c.reason===`credential_mismatch`?`error_description="The bearer token is invalid or expired"`:void 0,c.reason===`forbidden`?`error="insufficient_scope"`:void 0].filter(e=>e!==void 0);r.set(`WWW-Authenticate`,e.length===0?`Bearer`:`Bearer ${e.join(`, `)}`);let n=c.reason===`forbidden`;qC(r,n?403:401,n?`Forbidden`:`Unauthorized`,nC(c.reason,l!==void 0));return}let u=t.header(`accept`)??`*/*`;if(!u.includes(`*/*`)&&(!u.includes(`application/json`)||!u.includes(`text/event-stream`))){qC(r,406,`Not Acceptable`,`MCP Streamable HTTP requires Accept: application/json, text/event-stream.`);return}cS(r,c.scope,c.authorization),k({component:`aventure-mcp-server`,event:`mcp_request_authorized`,fields:{requestId:o,method:t.method,path:t.path,scope:c.scope}});let d=[],f=e=>{Xc(e,`transport_error`),N({component:`aventure-mcp-server`,event:`transport_error`,message:le(e),fields:{requestId:o,method:t.method,path:t.path},error:e})},p=My(()=>aS(c.scope,c.authorization),{onerror:e=>d.push(e),maxSubscriptions:0}),m=async()=>{await Qy(p,{onerror:f})(t,r,t.body);for(let e of d)ki(r.statusCode)?f(e):(r.statusCode<IC?k:ae)({component:`aventure-mcp-server`,event:`mcp_request_rejected`,message:le(e),fields:{requestId:o,method:t.method,path:t.path,status:r.statusCode}})},h=()=>FC(t,r,m);c.userBearerToken===void 0?await h():await Ce(c.userBearerToken,h)}),o.all(e.path,(...e)=>qC(e[1],405,`Method Not Allowed`,`MCP transport accepts POST requests only.`)),o.use((e,t,n,r)=>{if(n.headersSent){r(e);return}let i=YC(e);if(i===void 0){r(e);return}ae({component:`aventure-mcp-server`,event:`json_body_rejected`,message:i.message,fields:{requestId:we(),method:t.method,path:t.path,status:i.status}}),qC(n,i.status,i.status===RC?`Payload Too Large`:`Bad Request`,i.status===RC?`Request JSON body exceeds the MCP transport size limit.`:`Request body must be valid JSON.`)}),await new Promise((t,n)=>{let i;i=o.listen(e.port,r,()=>{t({server:i,close:async()=>{await new Promise((e,t)=>{i.close(n=>n?t(n):e()),i.closeIdleConnections()}),await Promise.all([Vb(),ye()])}})}),i.on(`error`,n)})}function WC(e){if(e===void 0)return!0;if(!URL.canParse(e))return!1;let{hostname:t}=new URL(e);return t===`localhost`?!0:t.startsWith(`[`)?t===`[::1]`:ra(t)&&t.startsWith(`127.`)}var GC=(e,t)=>t(null,WC(e)),KC=e=>e.method===`GET`&&/^\/(?:robots\.txt|health)\/?$/iu.test(e.path);function qC(e,t,n,r){JC(e,{type:`about:blank`,title:n,status:t,detail:r})}function JC(e,t){e.status(t.status).type(`application/problem+json`).json(t)}function YC(e){if(typeof e!=`object`||!e||!(`type`in e)||!(`status`in e))return;let t=e.type===`entity.too.large`?RC:e.type===`entity.parse.failed`?LC:e.status===RC||e.status===LC?e.status:void 0;return t===void 0?void 0:{status:t,message:`message`in e&&typeof e.message==`string`?e.message:`JSON body rejected`}}var XC=65535,ZC=55e3,QC=Ii(ta(import.meta.url)),{host:$C}=(await new p().name(QC.bin[0]).description(`Serve aVenture tools over MCP Streamable HTTP.`).version(QC.version).option(`--host <address>`,`Bind this address instead of 127.0.0.1; 0.0.0.0 exposes the server to the network.`).addHelpText(`after`,`
145
+ `).filter(e=>e.startsWith(`data:`)).map(e=>e.slice(5).trim());for(let e of n){let n;try{n=JSON.parse(e)}catch(e){return{outcome:`protocol_error`,text:``,summary:`unparseable reply: ${String(e)}`}}let r=rr.safeParse(n);if(!r.success||!(`id`in r.data)||r.data.id!==t)continue;if(`error`in r.data)return{outcome:`protocol_error`,text:``,summary:r.data.error.message};if(!(`result`in r.data))continue;let i=Br.safeParse(r.data.result);if(!i.success)return{outcome:`protocol_error`,text:``,summary:`malformed tool result`};let a=Pi(i.data.structuredContent),o=i.data.content.find(e=>e.type===`text`),s=a?.httpStatus??a?.problem?.status;return{outcome:kC(i.data.isError===!0,s),text:o?.type===`text`?o.text:``,httpStatus:s,problemType:a?.problem?.type,summary:a?.summary}}return{outcome:`protocol_error`,text:``,summary:`no JSON-RPC reply to this call`}}function kC(e,t){return e?t!==void 0&&Fi(t)?`caller_error`:`tool_error`:`ok`}function AC(e,t){return typeof e==`object`&&e?Reflect.get(e,t):void 0}function jC(e){return MC(typeof e==`object`&&e?Object.keys(e).join(`,`):``)}function MC(e){let t=``;for(let n=0;n<e.length;n+=1){let r=e[n]??``,i=e.charCodeAt(n);t+=i<=vC||i===yC?`�`:r}return t.length>_C?`${t.slice(0,255)}…`:t}function NC(e,t){let n=AC(t,xC);return typeof n==`string`&&n.length>0?`${e}:${MC(n)}`:`${e}:${aa(`sha256`).update(ge()??`anonymous`).digest(`hex`).slice(0,16)}:${Math.floor(Date.now()/bC)}`}var PC=e=>e.length>gC?`${e.slice(0,gC)}…`:e;async function FC(e,t,n){let r=er.safeParse(e.body),i=typeof e.body==`object`&&e.body!==null?Reflect.get(e.body,`id`):void 0;if(!r.success||typeof i!=`string`&&typeof i!=`number`){await n();return}let a=performance.now(),o=e.get(`user-agent`),s=wC(e.body),c=CC(o,s.name),l=Reflect.get(r.data.params,`_meta`),u=r.data.params.arguments,d=typeof u?.operationId==`string`?MC(u.operationId):void 0,f=s.name===void 0?void 0:MC(s.name),p=s.version===void 0?void 0:MC(s.version),m=o===void 0?void 0:MC(o),h=NC(c,l),g=uS(e.body,lS(t)).toolName,_=MC(r.data.params.name),v=AC(l,Rr),y=be(`mcp ${g}`,{"langfuse.trace.name":`mcp ${g}`,"langfuse.session.id":h,"langfuse.trace.tags":[`mcp`,c,g],"langfuse.observation.type":`tool`,"langfuse.observation.input":PC(JSON.stringify(u??{})),"langfuse.environment":ce()[`deployment.environment.name`]??`unknown`,...process.env.GIT_SHA===void 0?{}:{"langfuse.release":process.env.GIT_SHA},"langfuse.trace.metadata.client":c,"langfuse.trace.metadata.client_name":f??``,"langfuse.trace.metadata.client_version":p??``,"langfuse.trace.metadata.user_agent":m??``,"langfuse.trace.metadata.operation_id":d??``,"langfuse.trace.metadata.meta_keys":jC(l),"aventure.request_id":we()??``,"mcp.tool.name":g,"mcp.tool.requested_name":_},typeof v==`string`?v:void 0);DC(t,n=>{let r=t.destroyed||e.socket.destroyed?{outcome:`aborted`,text:``}:OC(n,i);t.locals[SC]=r.outcome;let o=r.outcome===`tool_error`||r.outcome===`protocol_error`,s={requestId:we(),toolName:g,requestedToolName:_,operationId:d,client:c,clientName:f,clientVersion:p,userAgent:m,metaKeys:jC(l),sessionId:h,outcome:r.outcome,httpStatus:r.httpStatus,problemType:r.problemType,resultChars:r.text.length,durationMs:Math.round(performance.now()-a),traceId:y?.spanContext().traceId};(o?ae:k)({component:`aventure-mcp-server`,event:`tool_call`,fields:s}),y!==void 0&&Te(y,{"langfuse.observation.output":PC(r.text),"langfuse.observation.level":o?`ERROR`:`DEFAULT`,...r.summary===void 0?{}:{"langfuse.observation.status_message":r.summary},"langfuse.trace.metadata.outcome":r.outcome,"langfuse.trace.metadata.http_status":String(r.httpStatus??``),"langfuse.trace.metadata.problem_type":r.problemType??``,"mcp.tool.outcome":r.outcome},o)}),y===void 0?await n():await Se(Ee(y),n)}var IC=400,LC=400,RC=413,zC=`10mb`,BC=`127.0.0.1`,VC=/^[\w.:/-]{1,128}$/,HC=`0.0.0.0`;async function UC(e){let t=e.jsonBodyLimit??zC,n=$S(),r=e.host??BC,i=r!==HC,a=(t,n)=>{let r=`${t.protocol}://${t.host}`;return URL.canParse(e.path,r)&&new URL(e.path,r).href===n?.resourceUrl.href?n:void 0},o=(0,af.default)();o.disable(`x-powered-by`),o.set(`trust proxy`,1),o.use((e,t,n)=>{let r=e.get(`x-client-request-id`)??``,i=VC.test(r)?r:oa(),a=performance.now(),o={requestId:i,method:e.method,path:e.path,host:e.hostname,userAgent:e.get(`user-agent`)},s=KC(e);s||k({component:`aventure-mcp-server`,event:`http_request`,fields:o}),t.on(`finish`,()=>{let n=Math.round(performance.now()-a),r=e.route,i=typeof r==`object`&&r?Reflect.get(r,`path`):null,c=TC(e,t);if(zb(e.method,typeof i==`string`?i:`unmatched`,t.statusCode,n,c),s&&t.statusCode<IC)return;let l=t.statusCode===401&&e.get(`authorization`)===void 0;(t.statusCode>=IC&&!s&&!l?ae:k)({component:`aventure-mcp-server`,event:`http_response`,fields:{...o,...c,status:t.statusCode,durationMs:n}})}),De(i,()=>n())}),o.use(i?(0,rf.default)({origin:GC}):(0,rf.default)()),o.use(dC({path:e.path,limit:t,reject:e=>qC(e,RC,`Payload Too Large`,`Request JSON body exceeds the MCP transport size limit.`)})),o.use(af.json({limit:t})),o.get(`/health`,(...e)=>{let t=e[1],n=process.env.GIT_SHA?.trim();t.setHeader(`X-Aventure-Revision`,n&&/^[0-9a-f]{40}$/i.test(n)?n.slice(0,7):`unknown`),t.status(200).json({status:`UP`})}),o.get([`/.well-known/oauth-protected-resource`,`/.well-known/oauth-protected-resource${e.path}`],(0,rf.default)(),async(t,n,r)=>{let i=await e.resolveOAuthDiscovery();if(i===void 0){qC(n,503,`Service Unavailable`,`OAuth discovery is unavailable: the API published no OAuth resource indicator for this server.`);return}let o=a(t,i);if(o===void 0){r();return}n.status(200).json({resource:o.resourceUrl.href,authorization_servers:[o.client.authorizationServer],scopes_supported:o.client.scope})}),Bb(o,e.metricsScrapeSecret),xe(),o.get(`/`,(...t)=>{t[1].status(200).json({name:`aventure-mcp-server`,mcp:e.path,health:`/health`,transport:`streamable-http`,method:`POST`})}),o.get(`/favicon.ico`,(...e)=>e[1].redirect(302,`${M}/favicon.ico`));let s=eC(n,async()=>(await e.resolveOAuthDiscovery())?.resourceUrl);return o.post(e.path,s,async(t,r)=>{let o=we(),s=t.header(`origin`);if(i&&!WC(s)){ae({component:`aventure-mcp-server`,event:`foreign_origin_rejected`,fields:{requestId:o,method:t.method,path:t.path,origin:s}}),qC(r,403,`Forbidden`,`A self-hosted MCP transport accepts loopback browser origins only.`);return}let c,l;try{let r=await e.resolveOAuthDiscovery();l=a(t,r),c=await n(t,r?.resourceUrl)}catch(e){Xc(e,`authentication_unavailable`),N({component:`aventure-mcp-server`,event:`authentication_unavailable`,fields:{requestId:o,method:t.method,path:t.path},error:e});let n=e instanceof Sr&&(e.problem.status===429||ki(e.problem.status))?e.problem:void 0;n===void 0?qC(r,503,`Service Unavailable`,`Authentication service is temporarily unavailable.`):(typeof n.retryAfterSeconds==`number`&&r.set(`Retry-After`,String(n.retryAfterSeconds)),JC(r,n));return}if(!c.ok){(c.reason===`missing_credential`?k:ae)({component:`aventure-mcp-server`,event:`unauthorized_request`,fields:{requestId:o,method:t.method,path:t.path,reason:c.reason,hasAuthorization:c.hasAuthorization}});let e=[l===void 0?void 0:`resource_metadata="${jv(l.resourceUrl)}"`,l===void 0?void 0:`scope="${l.client.scope.join(` `)}"`,c.reason===`credential_mismatch`?`error="invalid_token"`:void 0,c.reason===`credential_mismatch`?`error_description="The bearer token is invalid or expired"`:void 0,c.reason===`forbidden`?`error="insufficient_scope"`:void 0].filter(e=>e!==void 0);r.set(`WWW-Authenticate`,e.length===0?`Bearer`:`Bearer ${e.join(`, `)}`);let n=c.reason===`forbidden`;qC(r,n?403:401,n?`Forbidden`:`Unauthorized`,nC(c.reason,l!==void 0));return}let u=t.header(`accept`)??`*/*`;if(!u.includes(`*/*`)&&(!u.includes(`application/json`)||!u.includes(`text/event-stream`))){qC(r,406,`Not Acceptable`,`MCP Streamable HTTP requires Accept: application/json, text/event-stream.`);return}cS(r,c.scope,c.authorization),k({component:`aventure-mcp-server`,event:`mcp_request_authorized`,fields:{requestId:o,method:t.method,path:t.path,scope:c.scope}});let d=[],f=e=>{Xc(e,`transport_error`),N({component:`aventure-mcp-server`,event:`transport_error`,message:le(e),fields:{requestId:o,method:t.method,path:t.path},error:e})},p=My(()=>aS(c.scope,c.authorization),{onerror:e=>d.push(e),maxSubscriptions:0}),m=async()=>{await Qy(p,{onerror:f})(t,r,t.body);for(let e of d)ki(r.statusCode)?f(e):(r.statusCode<IC?k:ae)({component:`aventure-mcp-server`,event:`mcp_request_rejected`,message:le(e),fields:{requestId:o,method:t.method,path:t.path,status:r.statusCode}})},h=()=>FC(t,r,m);c.userBearerToken===void 0?await h():await Ce(c.userBearerToken,h)}),o.all(e.path,(...e)=>qC(e[1],405,`Method Not Allowed`,`MCP transport accepts POST requests only.`)),o.use((e,t,n,r)=>{if(n.headersSent){r(e);return}let i=YC(e);if(i===void 0){r(e);return}ae({component:`aventure-mcp-server`,event:`json_body_rejected`,message:i.message,fields:{requestId:we(),method:t.method,path:t.path,status:i.status}}),qC(n,i.status,i.status===RC?`Payload Too Large`:`Bad Request`,i.status===RC?`Request JSON body exceeds the MCP transport size limit.`:`Request body must be valid JSON.`)}),await new Promise((t,n)=>{let i;i=o.listen(e.port,r,()=>{t({server:i,close:async()=>{await new Promise((e,t)=>{i.close(n=>n?t(n):e()),i.closeIdleConnections()}),await Promise.all([Vb(),ye()])}})}),i.on(`error`,n)})}function WC(e){if(e===void 0)return!0;if(!URL.canParse(e))return!1;let{hostname:t}=new URL(e);return t===`localhost`?!0:t.startsWith(`[`)?t===`[::1]`:ra(t)&&t.startsWith(`127.`)}var GC=(e,t)=>t(null,WC(e)),KC=e=>e.method===`GET`&&/^\/(?:robots\.txt|health)\/?$/iu.test(e.path);function qC(e,t,n,r){JC(e,{type:`about:blank`,title:n,status:t,detail:r})}function JC(e,t){e.status(t.status).type(`application/problem+json`).json(t)}function YC(e){if(typeof e!=`object`||!e||!(`type`in e)||!(`status`in e))return;let t=e.type===`entity.too.large`?RC:e.type===`entity.parse.failed`?LC:e.status===RC||e.status===LC?e.status:void 0;return t===void 0?void 0:{status:t,message:`message`in e&&typeof e.message==`string`?e.message:`JSON body rejected`}}var XC=65535,ZC=55e3,QC=Ii(ta(import.meta.url)),{host:$C}=(await new p().name(QC.bin[0]).description(`Serve aVenture tools over MCP Streamable HTTP.`).version(QC.version).option(`--host <address>`,`Bind this address instead of 127.0.0.1; 0.0.0.0 exposes the server to the network.`).addHelpText(`after`,`
146
146
  Connect an MCP client to the server's /mcp URL and send
147
147
  Authorization: Bearer <credential> using an OAuth access token or API key from
148
148
  aventure.vc. The hosted
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aventurevc/mcp-server",
3
- "version": "0.8.219",
3
+ "version": "0.8.220",
4
4
  "private": false,
5
5
  "description": "MCP server that gives AI assistants access to aVenture research data on companies, people, funding, and news.",
6
6
  "homepage": "https://docs.aventure.vc/mcp",
@@ -28,9 +28,9 @@
28
28
  },
29
29
  "aventurePublicApi": {
30
30
  "repository": "aventurevc/aventure-docs",
31
- "commit": "dcbd423d3068ad6de570b214db50c0dbfd1181a2",
31
+ "commit": "b81c8ba5c4a68213ceb4231b35bb543089d85c2e",
32
32
  "openapiPath": "openapi/openapi.json",
33
- "openapiSha256": "8469458c61d32fc53cfebe93bb5c744990a9d009011de12235413ec43eaf3d62"
33
+ "openapiSha256": "25557d56bff4670293dc0c0ab3223b52e75c17bd34f5a93022c7666e25b6056a"
34
34
  },
35
35
  "scripts": {}
36
36
  }