@onyxsecurity/mcp-gateway 1.0.59 → 1.0.61

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.
@@ -1,3 +1,3 @@
1
1
  #!/usr/bin/env node
2
- import{hideBin as e,setupProxyDispatcher as t,yargs_default as n}from"../helpers-Cwd-UJrA.js";await t();const r=n(e(process.argv)).parserConfiguration({"populate--":!0,"unknown-options-as-args":!0}).option(`access-control-url`,{type:`string`}).option(`scanner-api-key`,{type:`string`}).option(`scanner-fail-open`,{type:`boolean`}).option(`scanner-timeout-ms`,{type:`number`}).option(`scanner-url`,{type:`string`}).help(!1).version(!1).parseSync();r.accessControlUrl&&(process.env.MCP_GATEWAY_ACCESS_CONTROL_URL=r.accessControlUrl),r.scannerApiKey&&(process.env.MCP_GATEWAY_SCANNER_API_KEY=r.scannerApiKey),r.scannerFailOpen!==void 0&&(process.env.MCP_GATEWAY_SCANNER_FAIL_OPEN=String(r.scannerFailOpen)),r.scannerTimeoutMs!==void 0&&(process.env.MCP_GATEWAY_SCANNER_TIMEOUT_MS=String(r.scannerTimeoutMs)),r.scannerUrl&&(process.env.MCP_GATEWAY_SCANNER_URL=r.scannerUrl);const{main:i}=await import(`../main-Bn1n-fs1.js`);await i();export{};
2
+ import{hideBin as e,setupProxyDispatcher as t,yargs_default as n}from"../helpers-DJo6DVLx.js";await t();const r=n(e(process.argv)).parserConfiguration({"populate--":!0,"unknown-options-as-args":!0}).option(`access-control-url`,{type:`string`}).option(`oauth-providers-url`,{type:`string`}).option(`scanner-api-key`,{type:`string`}).option(`scanner-fail-open`,{type:`boolean`}).option(`scanner-timeout-ms`,{type:`number`}).option(`scanner-url`,{type:`string`}).help(!1).version(!1).parseSync();if(String(r._[0]??``)===`probe`){let{runProbeCli:e}=await import(`../cli-BDQGMkyL.js`);process.exitCode=await e()}else{r.accessControlUrl&&(process.env.MCP_GATEWAY_ACCESS_CONTROL_URL=r.accessControlUrl),r.oauthProvidersUrl&&(process.env.MCP_GATEWAY_OAUTH_PROVIDERS_URL=r.oauthProvidersUrl),r.scannerApiKey&&(process.env.MCP_GATEWAY_SCANNER_API_KEY=r.scannerApiKey),r.scannerFailOpen!==void 0&&(process.env.MCP_GATEWAY_SCANNER_FAIL_OPEN=String(r.scannerFailOpen)),r.scannerTimeoutMs!==void 0&&(process.env.MCP_GATEWAY_SCANNER_TIMEOUT_MS=String(r.scannerTimeoutMs)),r.scannerUrl&&(process.env.MCP_GATEWAY_SCANNER_URL=r.scannerUrl);let{main:e}=await import(`../main-f8nUbpFM.js`);await e()}export{};
3
3
  //# sourceMappingURL=mcp-gateway.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"mcp-gateway.js","names":["yargs"],"sources":["../../src/bin/mcp-gateway.ts"],"sourcesContent":["#!/usr/bin/env node\n\n/**\n * MCP Gateway Entry Point\n *\n * This file implements a pre-parse + dynamic import pattern to allow CLI arguments\n * to override environment variables BEFORE the config module is loaded.\n *\n * The problem: ES module imports are hoisted, so `import { config } from \"../config/env.js\"`\n * runs before any CLI parsing code. The config reads from process.env at import time.\n *\n * The solution:\n * 1. Pre-parse only the config-related CLI args with a minimal yargs setup\n * 2. Set process.env values from CLI args (CLI takes priority)\n * 3. Dynamically import the main module (which will read the updated process.env)\n *\n * This approach allows the scanner to use direct CLI args like:\n * npx -y @onyxsecurity/mcp-gateway --scanner-url URL --scanner-api-key KEY -- npx -y @original/server\n *\n * Instead of shell wrappers that cause console popups on Windows:\n * powershell -Command \"$env:MCP_GATEWAY_SCANNER_URL='URL'; npx -y @onyxsecurity/mcp-gateway -- ...\"\n */\n\n// PHASE 0: Configure proxy-aware global fetch dispatcher BEFORE any outbound requests.\n// See ../lib/proxySetup.ts for the rationale and behavior.\nimport { setupProxyDispatcher } from \"../lib/proxySetup.js\";\n\nawait setupProxyDispatcher();\n\nimport yargs from \"yargs\";\nimport { hideBin } from \"yargs/helpers\";\n\n// PHASE 1: Pre-parse config-related CLI args BEFORE any other imports\n// We use a minimal yargs setup that only extracts the config options we need\nconst preArgv = yargs(hideBin(process.argv))\n .parserConfiguration({\n // Populate the -- separator array\n \"populate--\": true,\n // Don't fail on unknown options - main.ts will handle all parsing\n \"unknown-options-as-args\": true,\n })\n .option(\"access-control-url\", { type: \"string\" })\n .option(\"scanner-api-key\", { type: \"string\" })\n .option(\"scanner-fail-open\", { type: \"boolean\" })\n .option(\"scanner-timeout-ms\", { type: \"number\" })\n .option(\"scanner-url\", { type: \"string\" })\n .help(false) // Disable help in pre-parse (main.ts handles it)\n .version(false) // Disable version in pre-parse\n .parseSync();\n\n// PHASE 2: Set process.env from CLI args (CLI takes priority over existing env vars)\n// Only set if the CLI arg was explicitly provided\nif (preArgv.accessControlUrl) {\n process.env.MCP_GATEWAY_ACCESS_CONTROL_URL = preArgv.accessControlUrl;\n}\nif (preArgv.scannerApiKey) {\n process.env.MCP_GATEWAY_SCANNER_API_KEY = preArgv.scannerApiKey;\n}\nif (preArgv.scannerFailOpen !== undefined) {\n process.env.MCP_GATEWAY_SCANNER_FAIL_OPEN = String(preArgv.scannerFailOpen);\n}\nif (preArgv.scannerTimeoutMs !== undefined) {\n process.env.MCP_GATEWAY_SCANNER_TIMEOUT_MS = String(preArgv.scannerTimeoutMs);\n}\nif (preArgv.scannerUrl) {\n process.env.MCP_GATEWAY_SCANNER_URL = preArgv.scannerUrl;\n}\n\n// PHASE 3: NOW dynamically import the main module\n// At this point process.env has been updated with CLI args, so config will read the correct values\nconst { main } = await import(\"./main.js\");\n\nawait main();\n"],"mappings":";8FA2BA,MAAM,GAAsB,CAO5B,MAAM,EAAUA,EAAM,EAAQ,QAAQ,KAAK,CAAC,CACzC,oBAAoB,CAEnB,aAAc,GAEd,0BAA2B,GAC5B,CAAC,CACD,OAAO,qBAAsB,CAAE,KAAM,SAAU,CAAC,CAChD,OAAO,kBAAmB,CAAE,KAAM,SAAU,CAAC,CAC7C,OAAO,oBAAqB,CAAE,KAAM,UAAW,CAAC,CAChD,OAAO,qBAAsB,CAAE,KAAM,SAAU,CAAC,CAChD,OAAO,cAAe,CAAE,KAAM,SAAU,CAAC,CACzC,KAAK,GAAM,CACX,QAAQ,GAAM,CACd,WAAW,CAIV,EAAQ,mBACV,QAAQ,IAAI,+BAAiC,EAAQ,kBAEnD,EAAQ,gBACV,QAAQ,IAAI,4BAA8B,EAAQ,eAEhD,EAAQ,kBAAoB,IAAA,KAC9B,QAAQ,IAAI,8BAAgC,OAAO,EAAQ,gBAAgB,EAEzE,EAAQ,mBAAqB,IAAA,KAC/B,QAAQ,IAAI,+BAAiC,OAAO,EAAQ,iBAAiB,EAE3E,EAAQ,aACV,QAAQ,IAAI,wBAA0B,EAAQ,YAKhD,KAAM,CAAE,QAAS,MAAM,OAAO,uBAE9B,MAAM,GAAM"}
1
+ {"version":3,"file":"mcp-gateway.js","names":["yargs"],"sources":["../../src/bin/mcp-gateway.ts"],"sourcesContent":["#!/usr/bin/env node\n\n/**\n * MCP Gateway Entry Point\n *\n * This file implements a pre-parse + dynamic import pattern to allow CLI arguments\n * to override environment variables BEFORE the config module is loaded.\n *\n * The problem: ES module imports are hoisted, so `import { config } from \"../config/env.js\"`\n * runs before any CLI parsing code. The config reads from process.env at import time.\n *\n * The solution:\n * 1. Pre-parse only the config-related CLI args with a minimal yargs setup\n * 2. Set process.env values from CLI args (CLI takes priority)\n * 3. Dynamically import the main module (which will read the updated process.env)\n *\n * This approach allows the scanner to use direct CLI args like:\n * npx -y @onyxsecurity/mcp-gateway --scanner-url URL --scanner-api-key KEY -- npx -y @original/server\n *\n * Instead of shell wrappers that cause console popups on Windows:\n * powershell -Command \"$env:MCP_GATEWAY_SCANNER_URL='URL'; npx -y @onyxsecurity/mcp-gateway -- ...\"\n */\n\n// PHASE 0: Configure proxy-aware global fetch dispatcher BEFORE any outbound requests.\n// See ../lib/proxySetup.ts for the rationale and behavior.\nimport { setupProxyDispatcher } from \"../lib/proxySetup.js\";\n\nawait setupProxyDispatcher();\n\nimport yargs from \"yargs\";\nimport { hideBin } from \"yargs/helpers\";\n\n// PHASE 1: Pre-parse config-related CLI args BEFORE any other imports\n// We use a minimal yargs setup that only extracts the config options we need\nconst preArgv = yargs(hideBin(process.argv))\n .parserConfiguration({\n // Populate the -- separator array\n \"populate--\": true,\n // Don't fail on unknown options - main.ts will handle all parsing\n \"unknown-options-as-args\": true,\n })\n .option(\"access-control-url\", { type: \"string\" })\n .option(\"oauth-providers-url\", { type: \"string\" })\n .option(\"scanner-api-key\", { type: \"string\" })\n .option(\"scanner-fail-open\", { type: \"boolean\" })\n .option(\"scanner-timeout-ms\", { type: \"number\" })\n .option(\"scanner-url\", { type: \"string\" })\n .help(false) // Disable help in pre-parse (main.ts handles it)\n .version(false) // Disable version in pre-parse\n .parseSync();\n\n// PHASE 1.5: Short-circuit for standalone subcommands that don't need the proxy\n// env setup. The `probe` subcommand runs a DCR/auth probe over a batch of MCP\n// server URLs and exits — it doesn't start the proxy or need SCANNER_URL etc.\nconst firstCommand = String(preArgv._[0] ?? \"\");\nif (firstCommand === \"probe\") {\n const { runProbeCli } = await import(\"../probe/cli.js\");\n // Set process.exitCode and let the process exit naturally instead of\n // calling process.exit(). The scanner reads our stdout JSON via a\n // pipe, and process.exit() terminates Node before pending async\n // stdout writes flush — that truncates the payload mid-object and\n // the scanner reports it as probe_parse_error. Using exitCode lets\n // the event loop drain remaining writes before exiting.\n process.exitCode = await runProbeCli();\n} else {\n // PHASE 2: Set process.env from CLI args (CLI takes priority over existing env vars)\n // Only set if the CLI arg was explicitly provided\n if (preArgv.accessControlUrl) {\n process.env.MCP_GATEWAY_ACCESS_CONTROL_URL = preArgv.accessControlUrl;\n }\n if (preArgv.oauthProvidersUrl) {\n process.env.MCP_GATEWAY_OAUTH_PROVIDERS_URL = preArgv.oauthProvidersUrl;\n }\n if (preArgv.scannerApiKey) {\n process.env.MCP_GATEWAY_SCANNER_API_KEY = preArgv.scannerApiKey;\n }\n if (preArgv.scannerFailOpen !== undefined) {\n process.env.MCP_GATEWAY_SCANNER_FAIL_OPEN = String(preArgv.scannerFailOpen);\n }\n if (preArgv.scannerTimeoutMs !== undefined) {\n process.env.MCP_GATEWAY_SCANNER_TIMEOUT_MS = String(preArgv.scannerTimeoutMs);\n }\n if (preArgv.scannerUrl) {\n process.env.MCP_GATEWAY_SCANNER_URL = preArgv.scannerUrl;\n }\n\n // PHASE 3: NOW dynamically import the main module\n // At this point process.env has been updated with CLI args, so config will read the correct values\n const { main } = await import(\"./main.js\");\n\n await main();\n}\n"],"mappings":";8FA2BA,MAAM,GAAsB,CAO5B,MAAM,EAAUA,EAAM,EAAQ,QAAQ,KAAK,CAAC,CACzC,oBAAoB,CAEnB,aAAc,GAEd,0BAA2B,GAC5B,CAAC,CACD,OAAO,qBAAsB,CAAE,KAAM,SAAU,CAAC,CAChD,OAAO,sBAAuB,CAAE,KAAM,SAAU,CAAC,CACjD,OAAO,kBAAmB,CAAE,KAAM,SAAU,CAAC,CAC7C,OAAO,oBAAqB,CAAE,KAAM,UAAW,CAAC,CAChD,OAAO,qBAAsB,CAAE,KAAM,SAAU,CAAC,CAChD,OAAO,cAAe,CAAE,KAAM,SAAU,CAAC,CACzC,KAAK,GAAM,CACX,QAAQ,GAAM,CACd,WAAW,CAMd,GADqB,OAAO,EAAQ,EAAE,IAAM,GAAG,GAC1B,QAAS,CAC5B,GAAM,CAAE,eAAgB,MAAM,OAAO,sBAOrC,QAAQ,SAAW,MAAM,GAAa,KACjC,CAGD,EAAQ,mBACV,QAAQ,IAAI,+BAAiC,EAAQ,kBAEnD,EAAQ,oBACV,QAAQ,IAAI,gCAAkC,EAAQ,mBAEpD,EAAQ,gBACV,QAAQ,IAAI,4BAA8B,EAAQ,eAEhD,EAAQ,kBAAoB,IAAA,KAC9B,QAAQ,IAAI,8BAAgC,OAAO,EAAQ,gBAAgB,EAEzE,EAAQ,mBAAqB,IAAA,KAC/B,QAAQ,IAAI,+BAAiC,OAAO,EAAQ,iBAAiB,EAE3E,EAAQ,aACV,QAAQ,IAAI,wBAA0B,EAAQ,YAKhD,GAAM,CAAE,QAAS,MAAM,OAAO,uBAE9B,MAAM,GAAM"}
@@ -0,0 +1,3 @@
1
+ import"./streamableHttp-DM0LA7pR.js";import{AuthServerDiscoveryError as e,discoverAuthServer as t,findProviderForUrl as n,walkTransports as r}from"./transportDetection-DquHtdNu.js";async function i(e,t={}){let n=t.perServerTimeoutMs??15e3,r=t.maxRetries??1,i=t.retryDelayMs??200;return{results:await Promise.all(e.servers.map(e=>g(e.url,n,r,i)))}}async function a(e,t,n){let r=await fetch(e,{body:JSON.stringify(t),headers:{Accept:`application/json`,"Content-Type":`application/json`},method:`POST`,signal:n});if(r.status===200||r.status===201)try{let e=await r.json();return typeof e.client_id!=`string`||e.client_id.length===0?{status:r.status}:{body:e,status:r.status}}catch{return{status:r.status}}let i;try{i=(await r.text()).trim()}catch{}let a;return(r.status===429||r.status>=500)&&(a=p(r.headers.get(`Retry-After`))),{errorBody:i,retryAfterMs:a,status:r.status}}async function o(e,t){let{result:n}=await r(async n=>{let r=n===`streamable-http`?await m(e,t):await u(e,t);if(r.body?.cancel().catch(()=>{}),r.status===404||r.status===405)throw Object.assign(Error(`${n} returned ${r.status}`),{status:r.status});return r});return n}function s(e){return e<=0?0:Math.min(e,5e3)}function c(e){return e instanceof Error?e.message:String(e)}function l(e){if(e){try{let t=JSON.parse(e);if(t.error_description)return t.error_description;if(t.error)return t.error}catch{}return e.length>200?`${e.slice(0,200)}...`:e}}async function u(e,t){return fetch(e,{headers:{Accept:`text/event-stream`},method:`GET`,signal:t})}function d(e){return!!(e.reason===`network_error`&&!e.authServer||e.reason===`dcr_rejected`&&f(e.httpStatus))}function f(e){return e?e===429?!0:e>=500&&e<600:!1}function p(e){if(!e)return;let t=e.trim();if(!t)return;let n=Number(t);if(Number.isFinite(n))return s(n*1e3);let r=Date.parse(t);if(Number.isFinite(r)){let e=r-Date.now();return e>0?s(e):0}}async function m(e,t){return fetch(e,{body:JSON.stringify({id:1,jsonrpc:`2.0`,method:`initialize`,params:{capabilities:{},clientInfo:{name:`mcp-gateway-probe`,version:`1.0`},protocolVersion:`2024-11-05`}}),headers:{Accept:`application/json, text/event-stream`,"Content-Type":`application/json`},method:`POST`,signal:t})}async function h(r,i){let s=new URL(r);if(n(s))return{authType:`oauth_pre_registered`,reason:`pre_registered_provider`,url:r};let u;try{u=await o(r,i)}catch(e){return{authType:`probe_failed`,errorDetail:c(e),reason:`network_error`,url:r}}if(u.ok)return{authType:`public`,reason:`no_auth_required`,url:r};if(u.status!==401)return{authType:`probe_failed`,errorDetail:`initialize returned status ${u.status}`,httpStatus:u.status,reason:`network_error`,url:r};let d,f;try{let e=await t(s,{signal:i});d=e.authMetadata,f=e.authServerUrl}catch(t){return{authServer:t instanceof e?t.authServerUrl.toString():void 0,authType:`probe_failed`,errorDetail:c(t),reason:`auth_metadata_discovery_failed`,url:r}}if(!d)return{authServer:f.toString(),authType:`oauth_dcr_not_supported`,reason:`no_auth_metadata`,url:r};if(!d.registration_endpoint)return{authServer:f.toString(),authType:`oauth_dcr_not_supported`,reason:`no_registration_endpoint`,url:r};let p={client_name:`MCP Gateway`,grant_types:[`authorization_code`,`refresh_token`],redirect_uris:[`http://localhost:0/callback`],response_types:[`code`],token_endpoint_auth_method:`none`},m;try{m=await a(d.registration_endpoint,p,i)}catch(e){return{authServer:f.toString(),authType:`probe_failed`,errorDetail:c(e),reason:`network_error`,url:r}}return m.status!==200&&m.status!==201?{authServer:f.toString(),authType:`oauth_dcr_not_supported`,errorDetail:l(m.errorBody),httpStatus:m.status,reason:`dcr_rejected`,retryAfterMs:m.retryAfterMs,url:r}:m.body?{authServer:f.toString(),authType:`oauth_dcr`,reason:`dcr_success`,url:r}:{authServer:f.toString(),authType:`oauth_dcr_not_supported`,errorDetail:`DCR returned ${m.status} with unparseable body`,httpStatus:m.status,reason:`dcr_rejected`,url:r}}async function g(e,t,n,r){let i=await _(e,t);for(let a=0;a<n;a++){if(!d(i))return i;let n=Math.max(r,i.retryAfterMs??0);n>0&&await new Promise(e=>setTimeout(e,n)),i=await _(e,t)}return i}async function _(e,t){let n=new AbortController,r,i=new Promise(i=>{r=setTimeout(()=>{n.abort(),i({authType:`probe_failed`,errorDetail:`probe timed out after ${t}ms`,reason:`probe_timeout`,url:e})},t)}),a=h(e,n.signal).catch(r=>({authType:`probe_failed`,errorDetail:n.signal.aborted?`probe timed out after ${t}ms`:c(r),reason:n.signal.aborted?`probe_timeout`:`network_error`,url:e}));try{return await Promise.race([a,i])}finally{r&&clearTimeout(r)}}async function v(){let e;try{e=await b()}catch(e){let t=e instanceof Error?e.message:String(e);return process.stderr.write(`probe: failed to read stdin: ${t}\n`),2}let t;try{t=JSON.parse(e)}catch(e){let t=e instanceof Error?e.message:String(e);return process.stderr.write(`probe: stdin was not valid JSON: ${t}\n`),2}if(!y(t))return process.stderr.write(`probe: invalid input — expected {"servers":[{"url":"..."}]}
2
+ `),2;let n=await i(t);return process.stdout.write(`${JSON.stringify(n)}\n`),0}function y(e){if(!e||typeof e!=`object`)return!1;let t=e.servers;return Array.isArray(t)?t.every(e=>e&&typeof e==`object`&&typeof e.url==`string`):!1}async function b(){let e=[];for await(let t of process.stdin)e.push(t);return Buffer.concat(e).toString(`utf8`)}export{v as runProbeCli};
3
+ //# sourceMappingURL=cli-BDQGMkyL.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli-BDQGMkyL.js","names":["errorBody: string | undefined","retryAfterMs: number | undefined","initResponse: Response","authMetadata: Awaited<ReturnType<typeof discoverAuthServer>>[\"authMetadata\"]","authServerUrl: URL","clientMetadata: OAuthClientMetadata","dcr: Awaited<ReturnType<typeof attemptDcr>>","timerId: ReturnType<typeof setTimeout> | undefined","raw: string","parsed: unknown","chunks: Buffer[]"],"sources":["../src/probe/index.ts","../src/probe/cli.ts"],"sourcesContent":["import type { OAuthClientMetadata } from \"@modelcontextprotocol/sdk/shared/auth.js\";\n\nimport { AuthServerDiscoveryError, discoverAuthServer } from \"../auth/discovery.js\";\nimport { findProviderForUrl } from \"../auth/providers.js\";\nimport { walkTransports } from \"../lib/transportDetection.js\";\n\nexport type AuthType =\n | \"oauth_dcr_not_supported\"\n | \"oauth_dcr\"\n | \"oauth_pre_registered\"\n | \"probe_failed\"\n | \"public\";\n\nexport interface ProbeInput {\n servers: Array<{ url: string }>;\n}\n\nexport interface ProbeOptions {\n /**\n * Maximum number of retries on transient pre-DCR network errors, on top of\n * the initial attempt. So `maxRetries=1` means up to 2 total attempts per\n * server. Defaults to 1.\n *\n * Retries fire only when the result is `network_error` AND no auth server\n * was discovered yet (i.e. POST initialize failed or returned a non-2xx\n * non-401 status). DCR network failures do NOT retry — they include the\n * discovered `authServer` in the result, which the retry filter excludes.\n * This prevents the rare case where a network blip after the DCR POST\n * was sent could cause duplicate orphan client registrations at the vendor.\n */\n maxRetries?: number;\n /** Per-server wall-clock timeout covering all HTTP calls for that server. */\n perServerTimeoutMs?: number;\n /** Delay between retry attempts. Defaults to 200ms. */\n retryDelayMs?: number;\n}\n\nexport interface ProbeOutput {\n results: ProbeResult[];\n}\n\nexport type ProbeReason =\n | \"auth_metadata_discovery_failed\"\n | \"dcr_rejected\"\n | \"dcr_success\"\n | \"network_error\"\n | \"no_auth_metadata\"\n | \"no_auth_required\"\n | \"no_registration_endpoint\"\n | \"pre_registered_provider\"\n | \"probe_timeout\";\n\nexport interface ProbeResult {\n authServer?: string;\n authType: AuthType;\n errorDetail?: string;\n httpStatus?: number;\n reason: ProbeReason;\n /**\n * For transient `dcr_rejected` results (429/5xx), the server's\n * `Retry-After` value in milliseconds, when provided. The retry wrapper\n * uses this as the inter-attempt delay; callers don't normally read it.\n */\n retryAfterMs?: number;\n url: string;\n}\n\n/**\n * The probe re-runs the same pre-browser steps as `performOAuthFlow` in\n * `oauthFlow.ts` — same SDK calls, same order — so we classify servers using\n * the exact code path the real OAuth flow would take. We stop just before the\n * browser-consent step (step 9+ in performOAuthFlow) because the probe runs\n * non-interactively at install time.\n *\n * Flow parity with performOAuthFlow:\n * - POST initialize (probe-specific: classify 200 vs 401 vs other)\n * - findProviderForUrl — same as performOAuthFlow step 2\n * - discoverOAuthProtectedResourceMetadata — same as step 3\n * - pick authorization_servers[0] with fallback — same as step 4\n * - discoverAuthorizationServerMetadata — same as step 5\n * - check registration_endpoint — same as step 7 precondition\n * - registerClient (SDK) — same as step 7\n * - return authType verdict (probe-only — OAuth flow would open browser here)\n *\n * authType mapping (kept alongside `reason` for callers that want diagnostics):\n * no_auth_required → public\n * pre_registered_provider → oauth_pre_registered\n * dcr_success → oauth_dcr\n * dcr_rejected → oauth_dcr_not_supported\n * no_registration_endpoint → oauth_dcr_not_supported\n * no_auth_metadata → oauth_dcr_not_supported\n * network_error → probe_failed\n */\n\nconst DCR_REDIRECT_URI = \"http://localhost:0/callback\";\nconst DEFAULT_PER_SERVER_TIMEOUT_MS = 15_000;\nconst DEFAULT_MAX_RETRIES = 1;\nconst DEFAULT_RETRY_DELAY_MS = 200;\n/**\n * Cap on `Retry-After` we'll honor before falling back to the default delay.\n * Prevents a misconfigured (or hostile) vendor from parking the install for\n * minutes/hours by setting `Retry-After: 3600`.\n */\nconst MAX_RETRY_AFTER_MS = 5_000;\n\nexport async function runProbeBatch(input: ProbeInput, options: ProbeOptions = {}): Promise<ProbeOutput> {\n const timeoutMs = options.perServerTimeoutMs ?? DEFAULT_PER_SERVER_TIMEOUT_MS;\n const maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES;\n const retryDelayMs = options.retryDelayMs ?? DEFAULT_RETRY_DELAY_MS;\n\n const results = await Promise.all(\n input.servers.map((srv) => probeOneWithRetry(srv.url, timeoutMs, maxRetries, retryDelayMs))\n );\n\n return { results };\n}\n\n/**\n * Attempts DCR directly via fetch rather than SDK's `registerClient`.\n *\n * Reason we don't use the SDK here specifically: `registerClient` consumes the\n * response and throws, dropping the numeric HTTP status on success-with-bad-body\n * and on 4xx with a well-formed OAuth error body (e.g. Airtable). Probe needs\n * the status code for monitoring and to distinguish dcr_rejected from\n * network_error precisely. Everything else (discovery of resource and auth\n * server metadata) still goes through the SDK.\n *\n * Returns:\n * - { status, body } on 2xx with parseable JSON → caller classifies dcr_success\n * - { status, errorBody? } on non-2xx → caller classifies dcr_rejected\n * - throws on network failure/timeout → caller classifies network_error\n */\nasync function attemptDcr(\n registrationEndpoint: string,\n clientMetadata: OAuthClientMetadata,\n signal: AbortSignal\n): Promise<{\n body?: Record<string, unknown>;\n errorBody?: string;\n retryAfterMs?: number;\n status: number;\n}> {\n const res = await fetch(registrationEndpoint, {\n body: JSON.stringify(clientMetadata),\n headers: {\n Accept: \"application/json\",\n \"Content-Type\": \"application/json\",\n },\n method: \"POST\",\n signal,\n });\n\n if (res.status === 200 || res.status === 201) {\n try {\n const body = (await res.json()) as Record<string, unknown>;\n // RFC 7591 §3.2.1 requires `client_id` in a successful registration\n // response. Some servers return a 2xx with a JSON error envelope or\n // a partial/malformed body; treating those as success would\n // false-positive `oauth_dcr` even though the OAuth flow can't\n // proceed. Require the mandatory field before classifying success.\n if (typeof body.client_id !== \"string\" || body.client_id.length === 0) {\n return { status: res.status };\n }\n return { body, status: res.status };\n } catch {\n // 2xx with unparseable body — caller treats as failure.\n return { status: res.status };\n }\n }\n\n // Non-2xx — try to surface the error body to errorDetail for humans.\n let errorBody: string | undefined;\n try {\n errorBody = (await res.text()).trim();\n } catch {\n // ignore\n }\n\n // Capture Retry-After (RFC 7231) on rate-limit / server-error responses so\n // probeOneWithRetry can wait the requested interval before re-attempting.\n // Anything outside the transient class (429 / 5xx) doesn't need this — we\n // won't retry those anyway.\n let retryAfterMs: number | undefined;\n if (res.status === 429 || res.status >= 500) {\n retryAfterMs = parseRetryAfter(res.headers.get(\"Retry-After\"));\n }\n\n return { errorBody, retryAfterMs, status: res.status };\n}\n\n/**\n * Performs the per-transport liveness/auth probe, falling back from Streamable\n * HTTP to SSE on 404/405 (the same priority order the runtime proxy uses via\n * `connectWithTransportFallback`). Returns the first response whose status is\n * not \"transport not supported\"; throws on any non-fallback error.\n *\n * The response body is cancelled before returning — the probe classifies on\n * `status` only and never reads body or headers. For SSE 200 responses this is\n * load-bearing: the event stream stays open indefinitely otherwise, leaking\n * connections at batch scale.\n */\nasync function attemptInitialize(url: string, signal: AbortSignal): Promise<Response> {\n const { result } = await walkTransports(async (transportType) => {\n const response =\n transportType === \"streamable-http\"\n ? await postInitialize(url, signal)\n : await getSseHandshake(url, signal);\n // Probe never reads body — cancel to avoid leaking SSE streams on 200.\n response.body?.cancel().catch(() => {\n /* already closed */\n });\n if (response.status === 404 || response.status === 405) {\n // Throw a status-bearing error so walkTransports' isTransportNotSupportedError\n // check matches and falls through to the next transport.\n throw Object.assign(new Error(`${transportType} returned ${response.status}`), {\n status: response.status,\n });\n }\n return response;\n });\n return result;\n}\n\nfunction clampRetryAfter(ms: number): number {\n if (ms <= 0) return 0;\n return Math.min(ms, MAX_RETRY_AFTER_MS);\n}\n\nfunction errMsg(err: unknown): string {\n if (err instanceof Error) return err.message;\n return String(err);\n}\n\n/** Parses an OAuth error body (RFC 6749) into a human-friendly one-liner. */\nfunction formatDcrErrorBody(body: string | undefined): string | undefined {\n if (!body) return undefined;\n try {\n const parsed = JSON.parse(body) as { error?: string; error_description?: string };\n if (parsed.error_description) return parsed.error_description;\n if (parsed.error) return parsed.error;\n } catch {\n // Non-JSON body — return as-is, capped to avoid dumping HTML pages.\n }\n return body.length > 200 ? `${body.slice(0, 200)}...` : body;\n}\n\nasync function getSseHandshake(url: string, signal: AbortSignal): Promise<Response> {\n return fetch(url, {\n headers: { Accept: \"text/event-stream\" },\n method: \"GET\",\n signal,\n });\n}\n\nfunction isRetryableResult(result: ProbeResult): boolean {\n // Pre-DCR network error — fetch threw before discovery finished.\n if (result.reason === \"network_error\" && !result.authServer) return true;\n // DCR returned a transient HTTP status — server responded but can't help yet.\n if (result.reason === \"dcr_rejected\" && isTransientStatus(result.httpStatus)) return true;\n return false;\n}\n\nfunction isTransientStatus(status: number | undefined): boolean {\n if (!status) return false;\n if (status === 429) return true;\n return status >= 500 && status < 600;\n}\n\n/**\n * Parses the Retry-After header (RFC 7231) in either of its two forms:\n * - delta-seconds: \"120\"\n * - HTTP-date: \"Wed, 21 Oct 2026 07:28:00 GMT\"\n *\n * Caps the result at MAX_RETRY_AFTER_MS so a misconfigured / malicious\n * server can't park our install for an hour. Returns undefined for\n * missing/unparseable values; callers fall back to the default delay.\n */\nfunction parseRetryAfter(header: null | string): number | undefined {\n if (!header) return undefined;\n const trimmed = header.trim();\n if (!trimmed) return undefined;\n\n const asNumber = Number(trimmed);\n if (Number.isFinite(asNumber)) {\n return clampRetryAfter(asNumber * 1000);\n }\n\n const asDate = Date.parse(trimmed);\n if (Number.isFinite(asDate)) {\n const ms = asDate - Date.now();\n return ms > 0 ? clampRetryAfter(ms) : 0;\n }\n\n return undefined;\n}\n\nasync function postInitialize(url: string, signal: AbortSignal): Promise<Response> {\n return fetch(url, {\n body: JSON.stringify({\n id: 1,\n jsonrpc: \"2.0\",\n method: \"initialize\",\n params: {\n capabilities: {},\n clientInfo: { name: \"mcp-gateway-probe\", version: \"1.0\" },\n protocolVersion: \"2024-11-05\",\n },\n }),\n headers: {\n Accept: \"application/json, text/event-stream\",\n \"Content-Type\": \"application/json\",\n },\n method: \"POST\",\n signal,\n });\n}\n\nasync function probeOne(url: string, signal: AbortSignal): Promise<ProbeResult> {\n const serverUrlObj = new URL(url);\n\n // Step 0: pre-configured OAuth provider — short-circuit before any network\n // call. OAUTH_PROVIDERS holds servers we've baked credentials into the\n // gateway for at build time; if a URL matches, we already know it needs\n // OAuth and we already have credentials, so probing the server itself\n // is wasted work.\n //\n // performOAuthFlow does this check at its step 2 (after starting a callback\n // server), but the probe never opens a browser, so we can hoist it earlier\n // and avoid the network calls oauthFlow's structure forces.\n if (findProviderForUrl(serverUrlObj)) {\n return { authType: \"oauth_pre_registered\", reason: \"pre_registered_provider\", url };\n }\n\n // Step 1: liveness/auth probe with transport fallback (Streamable HTTP → SSE,\n // matching the runtime proxy's priority order). Classify:\n // 200 → wrap (no_auth_required)\n // 401 → continue with auth discovery (same path performOAuthFlow takes)\n // else → skip (network_error)\n // attemptInitialize walks transports via walkTransports and falls through\n // 404/405 — so a server like cf-docs (POST /sse 404, GET /sse 200) classifies\n // as public on the SSE attempt rather than failing on the streamable-HTTP one.\n let initResponse: Response;\n try {\n initResponse = await attemptInitialize(url, signal);\n } catch (err) {\n return { authType: \"probe_failed\", errorDetail: errMsg(err), reason: \"network_error\", url };\n }\n if (initResponse.ok) {\n return { authType: \"public\", reason: \"no_auth_required\", url };\n }\n if (initResponse.status !== 401) {\n return {\n authType: \"probe_failed\",\n errorDetail: `initialize returned status ${initResponse.status}`,\n httpStatus: initResponse.status,\n reason: \"network_error\",\n url,\n };\n }\n\n // Steps 3-5: shared discovery with performOAuthFlow — see ../auth/discovery.ts.\n // The helper performs resource-metadata lookup, auth-server-URL selection, and\n // auth-server-metadata lookup in that order. It silences resource-metadata\n // errors (soft-fail) but throws AuthServerDiscoveryError when the auth-server\n // metadata call fails — preserving the computed authServerUrl on the error.\n let authMetadata: Awaited<ReturnType<typeof discoverAuthServer>>[\"authMetadata\"];\n let authServerUrl: URL;\n try {\n // Pass the per-server signal so a probeOneWithTimeout abort cancels the\n // SDK's well-known fetches too — otherwise orphaned requests outlive\n // the probe verdict and leak connections in batch runs.\n const discovered = await discoverAuthServer(serverUrlObj, { signal });\n authMetadata = discovered.authMetadata;\n authServerUrl = discovered.authServerUrl;\n } catch (err) {\n const authServer =\n err instanceof AuthServerDiscoveryError ? err.authServerUrl.toString() : undefined;\n // Thrown errors here are transport failures (DNS/timeout/5xx) on the\n // auth-server metadata fetch, NOT the \"metadata is genuinely absent\"\n // case. Folding them into oauth_dcr_not_supported would let the\n // server-side cache persist a transient outage as a permanent\n // negative verdict. Surface as probe_failed instead so the scanner\n // filter drops it from the cache write (transient state stays\n // transient). The definitive metadata-absent path lives in the\n // !authMetadata branch below.\n return {\n authServer,\n authType: \"probe_failed\",\n errorDetail: errMsg(err),\n reason: \"auth_metadata_discovery_failed\",\n url,\n };\n }\n if (!authMetadata) {\n return {\n authServer: authServerUrl.toString(),\n authType: \"oauth_dcr_not_supported\",\n reason: \"no_auth_metadata\",\n url,\n };\n }\n\n // Step 7 precondition: registration_endpoint present?\n // (performOAuthFlow throws here; probe classifies as oauth_dcr_not_supported instead.)\n if (!authMetadata.registration_endpoint) {\n return {\n authServer: authServerUrl.toString(),\n authType: \"oauth_dcr_not_supported\",\n reason: \"no_registration_endpoint\",\n url,\n };\n }\n\n // Step 7: DCR. Same body/method as performOAuthFlow, but attemptDcr gives us\n // the raw status code so we can distinguish dcr_rejected (4xx/5xx) from\n // network_error (fetch throw) and report httpStatus for monitoring.\n const clientMetadata: OAuthClientMetadata = {\n client_name: \"MCP Gateway\",\n grant_types: [\"authorization_code\", \"refresh_token\"],\n redirect_uris: [DCR_REDIRECT_URI],\n response_types: [\"code\"],\n token_endpoint_auth_method: \"none\",\n };\n let dcr: Awaited<ReturnType<typeof attemptDcr>>;\n try {\n dcr = await attemptDcr(authMetadata.registration_endpoint, clientMetadata, signal);\n } catch (err) {\n // fetch itself threw — network layer failure, not a policy decision\n // from the auth server.\n return {\n authServer: authServerUrl.toString(),\n authType: \"probe_failed\",\n errorDetail: errMsg(err),\n reason: \"network_error\",\n url,\n };\n }\n\n if (dcr.status !== 200 && dcr.status !== 201) {\n return {\n authServer: authServerUrl.toString(),\n authType: \"oauth_dcr_not_supported\",\n errorDetail: formatDcrErrorBody(dcr.errorBody),\n httpStatus: dcr.status,\n reason: \"dcr_rejected\",\n retryAfterMs: dcr.retryAfterMs,\n url,\n };\n }\n if (!dcr.body) {\n // 2xx but body didn't parse — treat as rejection rather than silently wrap.\n return {\n authServer: authServerUrl.toString(),\n authType: \"oauth_dcr_not_supported\",\n errorDetail: `DCR returned ${dcr.status} with unparseable body`,\n httpStatus: dcr.status,\n reason: \"dcr_rejected\",\n url,\n };\n }\n\n // NOTE: performOAuthFlow would open the browser and complete the flow here.\n // The probe stops at successful DCR.\n return {\n authServer: authServerUrl.toString(),\n authType: \"oauth_dcr\",\n reason: \"dcr_success\",\n url,\n };\n}\n\n/**\n * Wraps `probeOneWithTimeout` with retry-on-transient-error.\n *\n * Retries up to `maxRetries` times when the result is transient. Two\n * categories of transient are recognized:\n *\n * 1. Pre-DCR network error — `reason === \"network_error\" && !authServer`.\n * The fetch threw or returned non-401/non-2xx before discovery\n * finished. No registration request reached any vendor; retrying is\n * structurally safe (no orphan multiplication).\n *\n * 2. DCR transient — `reason === \"dcr_rejected\" && (httpStatus === 429\n * || httpStatus >= 500)`. The vendor responded definitively that they\n * can't help right now (rate-limited or server error). Because we got\n * a complete response, the server explicitly did NOT create a\n * registration; retrying is also safe and may succeed once the\n * transient condition clears.\n *\n * Notably NOT retried:\n * - DCR network failures (`network_error` WITH `authServer`) — fetch\n * threw mid-flight; the request may have arrived at the vendor.\n * - DCR 4xx (other than 429) — definitive policy refusal.\n * - `no_auth_metadata`, `no_registration_endpoint` — definitive answers.\n *\n * For DCR transients, the actual delay is `max(retryDelayMs, retryAfterMs)`\n * if the server provided a `Retry-After` header (capped to MAX_RETRY_AFTER_MS).\n */\nasync function probeOneWithRetry(\n url: string,\n timeoutMs: number,\n maxRetries: number,\n retryDelayMs: number\n): Promise<ProbeResult> {\n let result = await probeOneWithTimeout(url, timeoutMs);\n for (let attempt = 0; attempt < maxRetries; attempt++) {\n if (!isRetryableResult(result)) return result;\n const delay = Math.max(retryDelayMs, result.retryAfterMs ?? 0);\n if (delay > 0) {\n await new Promise<void>((resolve) => setTimeout(resolve, delay));\n }\n result = await probeOneWithTimeout(url, timeoutMs);\n }\n return result;\n}\n\nasync function probeOneWithTimeout(url: string, timeoutMs: number): Promise<ProbeResult> {\n const controller = new AbortController();\n let timerId: ReturnType<typeof setTimeout> | undefined;\n\n // Race the probe against a wall-clock timeout. AbortSignal alone isn't\n // enough — some fetch implementations (or test mocks) may ignore it. This\n // guarantees we always return within timeoutMs.\n const timeoutPromise = new Promise<ProbeResult>((resolve) => {\n timerId = setTimeout(() => {\n controller.abort();\n // Distinct reason \"probe_timeout\" — NOT \"network_error\". The\n // wall-clock timeout fires from outside probeOne, so we don't\n // know which phase aborted: discovery, registration POST, or\n // anything in between. If the timeout struck after the\n // registration POST went through, retrying would create a second\n // DCR client_id. Marking timeouts non-retryable (see\n // isRetryableResult) errs on the side of one orphan probe over\n // duplicate DCR registrations.\n resolve({\n authType: \"probe_failed\",\n errorDetail: `probe timed out after ${timeoutMs}ms`,\n reason: \"probe_timeout\",\n url,\n });\n }, timeoutMs);\n });\n\n const probePromise = probeOne(url, controller.signal).catch((err) => ({\n authType: \"probe_failed\" as const,\n errorDetail: controller.signal.aborted ? `probe timed out after ${timeoutMs}ms` : errMsg(err),\n // controller.signal.aborted means the wall-clock timeoutPromise\n // fired and aborted us mid-flight. Same retry-safety reasoning as\n // the timeoutPromise branch — surface as probe_timeout so we\n // don't reissue DCR.\n reason: controller.signal.aborted ? (\"probe_timeout\" as const) : (\"network_error\" as const),\n url,\n }));\n\n try {\n return await Promise.race([probePromise, timeoutPromise]);\n } finally {\n if (timerId) clearTimeout(timerId);\n }\n}\n","import type { ProbeInput } from \"./index.js\";\n\nimport { runProbeBatch } from \"./index.js\";\n\nconst EXIT_OK = 0;\nconst EXIT_BAD_INPUT = 2;\n\n/**\n * Entry point for the `mcp-gateway probe` subcommand.\n *\n * Reads a JSON batch of server URLs from stdin, runs the DCR/auth probe for\n * each in parallel, and writes the aggregated result JSON to stdout.\n *\n * Intended to be invoked by the scanner during install to decide which remote\n * MCP servers are safe to wrap vs. leave alone.\n */\nexport async function runProbeCli(): Promise<number> {\n let raw: string;\n try {\n raw = await readStdin();\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n process.stderr.write(`probe: failed to read stdin: ${msg}\\n`);\n return EXIT_BAD_INPUT;\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n process.stderr.write(`probe: stdin was not valid JSON: ${msg}\\n`);\n return EXIT_BAD_INPUT;\n }\n\n if (!isValidInput(parsed)) {\n process.stderr.write(`probe: invalid input — expected {\"servers\":[{\"url\":\"...\"}]}\\n`);\n return EXIT_BAD_INPUT;\n }\n\n const output = await runProbeBatch(parsed);\n process.stdout.write(`${JSON.stringify(output)}\\n`);\n return EXIT_OK;\n}\n\nfunction isValidInput(value: unknown): value is ProbeInput {\n if (!value || typeof value !== \"object\") return false;\n const servers = (value as { servers?: unknown }).servers;\n if (!Array.isArray(servers)) return false;\n return servers.every((s) => s && typeof s === \"object\" && typeof (s as { url?: unknown }).url === \"string\");\n}\n\nasync function readStdin(): Promise<string> {\n const chunks: Buffer[] = [];\n for await (const chunk of process.stdin) {\n chunks.push(chunk as Buffer);\n }\n return Buffer.concat(chunks).toString(\"utf8\");\n}\n"],"mappings":"qLAyGA,eAAsB,EAAc,EAAmB,EAAwB,EAAE,CAAwB,CACvG,IAAM,EAAY,EAAQ,oBAAsB,KAC1C,EAAa,EAAQ,YAAc,EACnC,EAAe,EAAQ,cAAgB,IAM7C,MAAO,CAAE,QAJO,MAAM,QAAQ,IAC5B,EAAM,QAAQ,IAAK,GAAQ,EAAkB,EAAI,IAAK,EAAW,EAAY,EAAa,CAAC,CAC5F,CAEiB,CAkBpB,eAAe,EACb,EACA,EACA,EAMC,CACD,IAAM,EAAM,MAAM,MAAM,EAAsB,CAC5C,KAAM,KAAK,UAAU,EAAe,CACpC,QAAS,CACP,OAAQ,mBACR,eAAgB,mBACjB,CACD,OAAQ,OACR,SACD,CAAC,CAEF,GAAI,EAAI,SAAW,KAAO,EAAI,SAAW,IACvC,GAAI,CACF,IAAM,EAAQ,MAAM,EAAI,MAAM,CAS9B,OAHI,OAAO,EAAK,WAAc,UAAY,EAAK,UAAU,SAAW,EAC3D,CAAE,OAAQ,EAAI,OAAQ,CAExB,CAAE,OAAM,OAAQ,EAAI,OAAQ,MAC7B,CAEN,MAAO,CAAE,OAAQ,EAAI,OAAQ,CAKjC,IAAIA,EACJ,G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AAM,EAAc,EAAO,CAE1C,OADA,QAAQ,OAAO,MAAM,GAAG,KAAK,UAAU,EAAO,CAAC,IAAI,CAC5C,EAGT,SAAS,EAAa,EAAqC,CACzD,GAAI,CAAC,GAAS,OAAO,GAAU,SAAU,MAAO,GAChD,IAAM,EAAW,EAAgC,QAEjD,OADK,MAAM,QAAQ,EAAQ,CACpB,EAAQ,MAAO,GAAM,GAAK,OAAO,GAAM,UAAY,OAAQ,EAAwB,KAAQ,SAAS,CADvE,GAItC,eAAe,GAA6B,CAC1C,IAAMC,EAAmB,EAAE,CAC3B,UAAW,IAAM,KAAS,QAAQ,MAChC,EAAO,KAAK,EAAgB,CAE9B,OAAO,OAAO,OAAO,EAAO,CAAC,SAAS,OAAO"}
@@ -89,4 +89,4 @@ complete -o bashdefault -o default -F _{{app_name}}_yargs_completions {{app_name
89
89
  `),void 0,`versionWarning`),I(this,q,`f`).key[e]=!0,t.alias&&this.alias(e,t.alias);let n=t.deprecate||t.deprecated;n&&this.deprecateOption(e,n);let r=t.demand||t.required||t.require;r&&this.demand(e,r),t.demandOption&&this.demandOption(e,typeof t.demandOption==`string`?t.demandOption:void 0),t.conflicts&&this.conflicts(e,t.conflicts),`default`in t&&this.default(e,t.default),t.implies!==void 0&&this.implies(e,t.implies),t.nargs!==void 0&&this.nargs(e,t.nargs),t.config&&this.config(e,t.configParser),t.normalize&&this.normalize(e),t.choices&&this.choices(e,t.choices),t.coerce&&this.coerce(e,t.coerce),t.group&&this.group(e,t.group),(t.boolean||t.type===`boolean`)&&(this.boolean(e),t.alias&&this.boolean(t.alias)),(t.array||t.type===`array`)&&(this.array(e),t.alias&&this.array(t.alias)),(t.number||t.type===`number`)&&(this.number(e),t.alias&&this.number(t.alias)),(t.string||t.type===`string`)&&(this.string(e),t.alias&&this.string(t.alias)),(t.count||t.type===`count`)&&this.count(e),typeof t.global==`boolean`&&this.global(e,t.global),t.defaultDescription&&(I(this,q,`f`).defaultDescription[e]=t.defaultDescription),t.skipValidation&&this.skipValidation(e);let i=t.describe||t.description||t.desc,a=I(this,Z,`f`).getDescriptions();(!Object.prototype.hasOwnProperty.call(a,e)||typeof i==`string`)&&this.describe(e,i),t.hidden&&this.hide(e),t.requiresArg&&this.requiresArg(e)}return this}options(e,t){return this.option(e,t)}parse(e,t,n){P(`[string|array] [function|boolean|object] [function]`,[e,t,n],arguments.length),this[Mn](),e===void 0&&(e=I(this,Y,`f`)),typeof t==`object`&&(F(this,yn,t,`f`),t=n),typeof t==`function`&&(F(this,J,t,`f`),t=!1),t||F(this,Y,e,`f`),I(this,J,`f`)&&F(this,V,!1,`f`);let r=this[or](e,!!t),i=this.parsed;return I(this,R,`f`).setParsed(this.parsed),M(r)?r.then(e=>(I(this,J,`f`)&&I(this,J,`f`).call(this,I(this,B,`f`),e,I(this,K,`f`)),e)).catch(e=>{throw I(this,J,`f`)&&I(this,J,`f`)(e,this.parsed.argv,I(this,K,`f`)),e}).finally(()=>{this[Kn](),this.parsed=i}):(I(this,J,`f`)&&I(this,J,`f`).call(this,I(this,B,`f`),r,I(this,K,`f`)),this[Kn](),this.parsed=i,r)}parseAsync(e,t,n){let r=this.parse(e,t,n);return M(r)?r:Promise.resolve(r)}parseSync(e,t,n){let r=this.parse(e,t,n);if(M(r))throw new N(`.parseSync() must not be used with asynchronous builders, handlers, or middleware`);return r}parserConfiguration(e){return P(`<object>`,[e],arguments.length),F(this,vn,e,`f`),this}pkgConf(e,t){P(`<string> [string]`,[e,t],arguments.length);let n=null,r=this[zn](t||I(this,ln,`f`));return r[e]&&typeof r[e]==`object`&&(n=an(r[e],t||I(this,ln,`f`),this[Pn]()[`deep-merge-config`]||!1,I(this,X,`f`)),I(this,q,`f`).configObjects=(I(this,q,`f`).configObjects||[]).concat(n)),this}positional(e,t){P(`<string> <object>`,[e,t],arguments.length);let n=[`default`,`defaultDescription`,`implies`,`normalize`,`choices`,`conflicts`,`coerce`,`type`,`describe`,`desc`,`description`,`alias`];t=Vt(t,(e,t)=>e===`type`&&![`string`,`number`,`boolean`].includes(t)?!1:n.includes(e));let r=I(this,un,`f`).fullCommands[I(this,un,`f`).fullCommands.length-1],i=r?I(this,L,`f`).cmdToParseOptions(r):{array:[],alias:{},default:{},demand:{}};return Ct(i).forEach(n=>{let r=i[n];Array.isArray(r)?r.indexOf(e)!==-1&&(t[n]=!0):r[e]&&!(n in t)&&(t[n]=r[e])}),this.group(e,I(this,Z,`f`).getPositionalGroupName()),this.option(e,t)}recommendCommands(e=!0){return P(`[boolean]`,[e],arguments.length),F(this,Sn,e,`f`),this}required(e,t,n){return this.demand(e,t,n)}require(e,t,n){return this.demand(e,t,n)}requiresArg(e){return P(`<array|string|object> [number]`,[e],arguments.length),typeof e==`string`&&I(this,q,`f`).narg[e]||this[Vn](this.requiresArg.bind(this),`narg`,e,NaN),this}showCompletionScript(e,t){return P(`[string] [string]`,[e,t],arguments.length),e||=this.$0,I(this,gn,`f`).log(I(this,R,`f`).generateCompletionScript(e,t||I(this,z,`f`)||`completion`)),this}showHelp(e){if(P(`[string|function]`,[e],arguments.length),F(this,W,!0,`f`),!I(this,Z,`f`).hasCachedHelpMessage()){if(!this.parsed){let t=this[or](I(this,Y,`f`),void 0,void 0,0,!0);if(M(t))return t.then(()=>{I(this,Z,`f`).showHelp(e)}),this}let t=I(this,L,`f`).runDefaultBuilderOn(this);if(M(t))return t.then(()=>{I(this,Z,`f`).showHelp(e)}),this}return I(this,Z,`f`).showHelp(e),this}scriptName(e){return this.customScriptName=!0,this.$0=e,this}showHelpOnFail(e,t){return P(`[boolean|string] [string]`,[e,t],arguments.length),I(this,Z,`f`).showHelpOnFail(e,t),this}showVersion(e){return P(`[string|function]`,[e],arguments.length),I(this,Z,`f`).showVersion(e),this}skipValidation(e){return P(`<array|string>`,[e],arguments.length),this[Bn](`skipValidation`,e),this}strict(e){return P(`[boolean]`,[e],arguments.length),F(this,Cn,e!==!1,`f`),this}strictCommands(e){return P(`[boolean]`,[e],arguments.length),F(this,wn,e!==!1,`f`),this}strictOptions(e){return P(`[boolean]`,[e],arguments.length),F(this,Tn,e!==!1,`f`),this}string(e){return P(`<array|string>`,[e],arguments.length),this[Bn](`string`,e),this[lr](e),this}terminalWidth(){return P([],0),I(this,X,`f`).process.stdColumns}updateLocale(e){return this.updateStrings(e)}updateStrings(e){return P(`<object>`,[e],arguments.length),F(this,fn,!1,`f`),I(this,X,`f`).y18n.updateLocale(e),this}usage(e,t,n,r){if(P(`<string|null|undefined> [string|boolean] [function|object] [function]`,[e,t,n,r],arguments.length),t!==void 0){if(j(e,null,I(this,X,`f`)),(e||``).match(/^\$0( |$)/))return this.command(e,t,n,r);throw new N(`.usage() description must start with $0 if being used as alias for .command()`)}else return I(this,Z,`f`).usage(e),this}usageConfiguration(e){return P(`<object>`,[e],arguments.length),F(this,En,e,`f`),this}version(e,t,n){let r=`version`;if(P(`[boolean|string] [string] [string]`,[e,t,n],arguments.length),I(this,Q,`f`)&&(this[An](I(this,Q,`f`)),I(this,Z,`f`).version(void 0),F(this,Q,null,`f`)),arguments.length===0)n=this[Ln](),e=r;else if(arguments.length===1){if(e===!1)return this;n=e,e=r}else arguments.length===2&&(n=t,t=void 0);return F(this,Q,typeof e==`string`?e:r,`f`),t||=I(this,Z,`f`).deferY18nLookup(`Show version number`),I(this,Z,`f`).version(n||void 0),this.boolean(I(this,Q,`f`)),this.describe(I(this,Q,`f`),t),this}wrap(e){return P(`<number|null|undefined>`,[e],arguments.length),I(this,Z,`f`).wrap(e),this}[(L=new WeakMap,ln=new WeakMap,un=new WeakMap,R=new WeakMap,z=new WeakMap,dn=new WeakMap,B=new WeakMap,fn=new WeakMap,pn=new WeakMap,V=new WeakMap,mn=new WeakMap,H=new WeakMap,U=new WeakMap,W=new WeakMap,G=new WeakMap,hn=new WeakMap,gn=new WeakMap,K=new WeakMap,q=new WeakMap,_n=new WeakMap,vn=new WeakMap,J=new WeakMap,yn=new WeakMap,bn=new WeakMap,xn=new WeakMap,Y=new WeakMap,Sn=new WeakMap,X=new WeakMap,Cn=new WeakMap,wn=new WeakMap,Tn=new WeakMap,Z=new WeakMap,En=new WeakMap,Q=new WeakMap,$=new WeakMap,On)](e){if(!e._||!e[`--`])return e;e._.push.apply(e._,e[`--`]);try{delete e[`--`]}catch{}return e}[kn](){return{log:(...e)=>{this[tr]()||console.log(...e),F(this,W,!0,`f`),I(this,K,`f`).length&&F(this,K,I(this,K,`f`)+`
90
90
  `,`f`),F(this,K,I(this,K,`f`)+e.join(` `),`f`)},error:(...e)=>{this[tr]()||console.error(...e),F(this,W,!0,`f`),I(this,K,`f`).length&&F(this,K,I(this,K,`f`)+`
91
91
  `,`f`),F(this,K,I(this,K,`f`)+e.join(` `),`f`)}}}[An](e){Ct(I(this,q,`f`)).forEach(t=>{if((e=>e===`configObjects`)(t))return;let n=I(this,q,`f`)[t];Array.isArray(n)?n.includes(e)&&n.splice(n.indexOf(e),1):typeof n==`object`&&delete n[e]}),delete I(this,Z,`f`).getDescriptions()[e]}[jn](e,t,n){I(this,pn,`f`)[n]||(I(this,X,`f`).process.emitWarning(e,t),I(this,pn,`f`)[n]=!0)}[Mn](){I(this,mn,`f`).push({options:I(this,q,`f`),configObjects:I(this,q,`f`).configObjects.slice(0),exitProcess:I(this,V,`f`),groups:I(this,U,`f`),strict:I(this,Cn,`f`),strictCommands:I(this,wn,`f`),strictOptions:I(this,Tn,`f`),completionCommand:I(this,z,`f`),output:I(this,K,`f`),exitError:I(this,B,`f`),hasOutput:I(this,W,`f`),parsed:this.parsed,parseFn:I(this,J,`f`),parseContext:I(this,yn,`f`)}),I(this,Z,`f`).freeze(),I(this,$,`f`).freeze(),I(this,L,`f`).freeze(),I(this,H,`f`).freeze()}[Nn](){let e=``,t;return t=/\b(node|iojs|electron)(\.exe)?$/.test(I(this,X,`f`).process.argv()[0])?I(this,X,`f`).process.argv().slice(1,2):I(this,X,`f`).process.argv().slice(0,1),e=t.map(e=>{let t=this[ir](I(this,ln,`f`),e);return e.match(/^(\/|([a-zA-Z]:)?\\)/)&&t.length<e.length?t:e}).join(` `).trim(),I(this,X,`f`).getEnv(`_`)&&I(this,X,`f`).getProcessArgvBin()===I(this,X,`f`).getEnv(`_`)&&(e=I(this,X,`f`).getEnv(`_`).replace(`${I(this,X,`f`).path.dirname(I(this,X,`f`).process.execPath())}/`,``)),e}[Pn](){return I(this,vn,`f`)}[Fn](){return I(this,En,`f`)}[In](){if(!I(this,fn,`f`))return;let e=I(this,X,`f`).getEnv(`LC_ALL`)||I(this,X,`f`).getEnv(`LC_MESSAGES`)||I(this,X,`f`).getEnv(`LANG`)||I(this,X,`f`).getEnv(`LANGUAGE`)||`en_US`;this.locale(e.replace(/[.:].*/,``))}[Ln](){return this[zn]().version||`unknown`}[Rn](e){let t=e[`--`]?e[`--`]:e._;for(let e=0,n;(n=t[e])!==void 0;e++)I(this,X,`f`).Parser.looksLikeNumber(n)&&Number.isSafeInteger(Math.floor(parseFloat(`${n}`)))&&(t[e]=Number(n));return e}[zn](e){let t=e||`*`;if(I(this,bn,`f`)[t])return I(this,bn,`f`)[t];let n={};try{let t=e||I(this,X,`f`).mainFilename;I(this,X,`f`).path.extname(t)&&(t=I(this,X,`f`).path.dirname(t));let r=I(this,X,`f`).findUp(t,(e,t)=>{if(t.includes(`package.json`))return`package.json`});j(r,void 0,I(this,X,`f`)),n=JSON.parse(I(this,X,`f`).readFileSync(r,`utf8`))}catch{}return I(this,bn,`f`)[t]=n||{},I(this,bn,`f`)[t]}[Bn](e,t){t=[].concat(t),t.forEach(t=>{t=this[Wn](t),I(this,q,`f`)[e].push(t)})}[Vn](e,t,n,r){this[Un](e,t,n,r,(e,t,n)=>{I(this,q,`f`)[e][t]=n})}[Hn](e,t,n,r){this[Un](e,t,n,r,(e,t,n)=>{I(this,q,`f`)[e][t]=(I(this,q,`f`)[e][t]||[]).concat(n)})}[Un](e,t,n,r,i){if(Array.isArray(n))n.forEach(t=>{e(t,r)});else if((e=>typeof e==`object`)(n))for(let t of Ct(n))e(t,n[t]);else i(t,this[Wn](n),r)}[Wn](e){return e===`__proto__`?`___proto___`:e}[Gn](e,t){return this[Vn](this[Gn].bind(this),`key`,e,t),this}[Kn](){var e,t,n,r,i,a,o,s,c,l,u,d;let f=I(this,mn,`f`).pop();j(f,void 0,I(this,X,`f`));let p;e=this,t=this,n=this,r=this,i=this,a=this,o=this,s=this,c=this,l=this,u=this,d=this,{options:{set value(t){F(e,q,t,`f`)}}.value,configObjects:p,exitProcess:{set value(e){F(t,V,e,`f`)}}.value,groups:{set value(e){F(n,U,e,`f`)}}.value,output:{set value(e){F(r,K,e,`f`)}}.value,exitError:{set value(e){F(i,B,e,`f`)}}.value,hasOutput:{set value(e){F(a,W,e,`f`)}}.value,parsed:this.parsed,strict:{set value(e){F(o,Cn,e,`f`)}}.value,strictCommands:{set value(e){F(s,wn,e,`f`)}}.value,strictOptions:{set value(e){F(c,Tn,e,`f`)}}.value,completionCommand:{set value(e){F(l,z,e,`f`)}}.value,parseFn:{set value(e){F(u,J,e,`f`)}}.value,parseContext:{set value(e){F(d,yn,e,`f`)}}.value}=f,I(this,q,`f`).configObjects=p,I(this,Z,`f`).unfreeze(),I(this,$,`f`).unfreeze(),I(this,L,`f`).unfreeze(),I(this,H,`f`).unfreeze()}[qn](e,t){return jt(t,t=>(e(t),t))}getInternalMethods(){return{getCommandInstance:this[Jn].bind(this),getContext:this[Yn].bind(this),getHasOutput:this[Xn].bind(this),getLoggerInstance:this[Zn].bind(this),getParseContext:this[Qn].bind(this),getParserConfiguration:this[Pn].bind(this),getUsageConfiguration:this[Fn].bind(this),getUsageInstance:this[$n].bind(this),getValidationInstance:this[er].bind(this),hasParseCallback:this[tr].bind(this),isGlobalContext:this[nr].bind(this),postProcess:this[rr].bind(this),reset:this[ar].bind(this),runValidation:this[sr].bind(this),runYargsParserAndExecuteCommands:this[or].bind(this),setHasOutput:this[cr].bind(this)}}[Jn](){return I(this,L,`f`)}[Yn](){return I(this,un,`f`)}[Xn](){return I(this,W,`f`)}[Zn](){return I(this,gn,`f`)}[Qn](){return I(this,yn,`f`)||{}}[$n](){return I(this,Z,`f`)}[er](){return I(this,$,`f`)}[tr](){return!!I(this,J,`f`)}[nr](){return I(this,hn,`f`)}[rr](e,t,n,r){return n||M(e)?e:(t||(e=this[On](e)),(this[Pn]()[`parse-positional-numbers`]||this[Pn]()[`parse-positional-numbers`]===void 0)&&(e=this[Rn](e)),r&&(e=At(e,this,I(this,H,`f`).getMiddleware(),!1)),e)}[ar](e={}){F(this,q,I(this,q,`f`)||{},`f`);let t={};t.local=I(this,q,`f`).local||[],t.configObjects=I(this,q,`f`).configObjects||[];let n={};return t.local.forEach(t=>{n[t]=!0,(e[t]||[]).forEach(e=>{n[e]=!0})}),Object.assign(I(this,xn,`f`),Object.keys(I(this,U,`f`)).reduce((e,t)=>{let r=I(this,U,`f`)[t].filter(e=>!(e in n));return r.length>0&&(e[t]=r),e},{})),F(this,U,{},`f`),[`array`,`boolean`,`string`,`skipValidation`,`count`,`normalize`,`number`,`hiddenOptions`].forEach(e=>{t[e]=(I(this,q,`f`)[e]||[]).filter(e=>!n[e])}),[`narg`,`key`,`alias`,`default`,`defaultDescription`,`config`,`choices`,`demandedOptions`,`demandedCommands`,`deprecatedOptions`].forEach(e=>{t[e]=Vt(I(this,q,`f`)[e],e=>!n[e])}),t.envPrefix=I(this,q,`f`).envPrefix,F(this,q,t,`f`),F(this,Z,I(this,Z,`f`)?I(this,Z,`f`).reset(n):Wt(this,I(this,X,`f`)),`f`),F(this,$,I(this,$,`f`)?I(this,$,`f`).reset(n):tn(this,I(this,Z,`f`),I(this,X,`f`)),`f`),F(this,L,I(this,L,`f`)?I(this,L,`f`).reset():Ft(I(this,Z,`f`),I(this,$,`f`),I(this,H,`f`),I(this,X,`f`)),`f`),I(this,R,`f`)||F(this,R,Xt(this,I(this,Z,`f`),I(this,L,`f`),I(this,X,`f`)),`f`),I(this,H,`f`).reset(),F(this,z,null,`f`),F(this,K,``,`f`),F(this,B,null,`f`),F(this,W,!1,`f`),this.parsed=!1,this}[ir](e,t){return I(this,X,`f`).path.relative(e,t)}[or](e,t,n,r=0,i=!1){let a=!!n||i;e||=I(this,Y,`f`),I(this,q,`f`).__=I(this,X,`f`).y18n.__,I(this,q,`f`).configuration=this[Pn]();let o=!!I(this,q,`f`).configuration[`populate--`],s=Object.assign({},I(this,q,`f`).configuration,{"populate--":!0}),c=I(this,X,`f`).Parser.detailed(e,Object.assign({},I(this,q,`f`),{configuration:{"parse-positional-numbers":!1,...s}})),l=Object.assign(c.argv,I(this,yn,`f`)),u,d=c.aliases,f=!1,p=!1;Object.keys(l).forEach(e=>{e===I(this,G,`f`)&&l[e]?f=!0:e===I(this,Q,`f`)&&l[e]&&(p=!0)}),l.$0=this.$0,this.parsed=c,r===0&&I(this,Z,`f`).clearCachedHelpMessage();try{if(this[In](),t)return this[rr](l,o,!!n,!1);I(this,G,`f`)&&[I(this,G,`f`)].concat(d[I(this,G,`f`)]||[]).filter(e=>e.length>1).includes(``+l._[l._.length-1])&&(l._.pop(),f=!0),F(this,hn,!1,`f`);let s=I(this,L,`f`).getCommands(),m=I(this,R,`f`)?.completionKey?[I(this,R,`f`)?.completionKey,...this.getAliases()[I(this,R,`f`)?.completionKey]??[]].some(e=>Object.prototype.hasOwnProperty.call(l,e)):!1,h=f||m||i;if(l._.length){if(s.length){let e;for(let t=r||0,a;l._[t]!==void 0;t++)if(a=String(l._[t]),s.includes(a)&&a!==I(this,z,`f`)){let e=I(this,L,`f`).runCommand(a,this,c,t+1,i,f||p||i);return this[rr](e,o,!!n,!1)}else if(!e&&a!==I(this,z,`f`)){e=a;break}!I(this,L,`f`).hasDefaultCommand()&&I(this,Sn,`f`)&&e&&!h&&I(this,$,`f`).recommendCommands(e,s)}I(this,z,`f`)&&l._.includes(I(this,z,`f`))&&!m&&(I(this,V,`f`)&&Ht(!0),this.showCompletionScript(),this.exit(0))}if(I(this,L,`f`).hasDefaultCommand()&&!h){let e=I(this,L,`f`).runCommand(null,this,c,0,i,f||p||i);return this[rr](e,o,!!n,!1)}if(m){I(this,V,`f`)&&Ht(!0),e=[].concat(e);let t=e.slice(e.indexOf(`--${I(this,R,`f`).completionKey}`)+1);return I(this,R,`f`).getCompletion(t,(e,t)=>{if(e)throw new N(e.message);(t||[]).forEach(e=>{I(this,gn,`f`).log(e)}),this.exit(0)}),this[rr](l,!o,!!n,!1)}if(I(this,W,`f`)||(f?(I(this,V,`f`)&&Ht(!0),a=!0,this.showHelp(e=>{I(this,gn,`f`).log(e),this.exit(0)})):p&&(I(this,V,`f`)&&Ht(!0),a=!0,I(this,Z,`f`).showVersion(`log`),this.exit(0))),!a&&I(this,q,`f`).skipValidation.length>0&&(a=Object.keys(l).some(e=>I(this,q,`f`).skipValidation.indexOf(e)>=0&&l[e]===!0)),!a){if(c.error)throw new N(c.error.message);if(!m){let e=this[sr](d,{},c.error);n||(u=At(l,this,I(this,H,`f`).getMiddleware(),!0)),u=this[qn](e,u??l),M(u)&&!n&&(u=u.then(()=>At(l,this,I(this,H,`f`).getMiddleware(),!1)))}}}catch(e){if(e instanceof N)I(this,Z,`f`).fail(e.message,e);else throw e}return this[rr](u??l,o,!!n,!0)}[sr](e,t,n,r){let i={...this.getDemandedOptions()};return a=>{if(n)throw new N(n.message);I(this,$,`f`).nonOptionCount(a),I(this,$,`f`).requiredArguments(a,i);let o=!1;I(this,wn,`f`)&&(o=I(this,$,`f`).unknownCommands(a)),I(this,Cn,`f`)&&!o?I(this,$,`f`).unknownArguments(a,e,t,!!r):I(this,Tn,`f`)&&I(this,$,`f`).unknownArguments(a,e,{},!1,!1),I(this,$,`f`).limitedChoices(a),I(this,$,`f`).implications(a),I(this,$,`f`).conflicting(a)}}[cr](){F(this,W,!0,`f`)}[lr](e){if(typeof e==`string`)I(this,q,`f`).key[e]=!0;else for(let t of e)I(this,q,`f`).key[t]=!0}};function dr(e){return!!e&&typeof e.getInternalMethods==`function`}var fr=Dn(xt);export{re as emitProxySetupLog,it as hideBin,b as setupProxyDispatcher,fr as yargs_default};
92
- //# sourceMappingURL=helpers-Cwd-UJrA.js.map
92
+ //# sourceMappingURL=helpers-DJo6DVLx.js.map