@redocly/cli 2.41.2 → 2.42.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/README.md +15 -0
  2. package/THIRD_PARTY_NOTICES +3 -2
  3. package/lib/chunks/32XCOMOR.js +7 -0
  4. package/lib/chunks/4S2W4DOH.js +7 -0
  5. package/lib/chunks/55GMSQDD.js +7 -0
  6. package/lib/chunks/62KMHHXM.js +93 -0
  7. package/lib/chunks/7J6QXKSL.js +59 -0
  8. package/lib/chunks/7TEHO26G.js +3132 -0
  9. package/lib/chunks/AE6JGTY4.js +7 -0
  10. package/lib/chunks/B62AKN6U.js +7 -0
  11. package/lib/chunks/BZ7PKRCP.js +2317 -0
  12. package/lib/chunks/D5T6ETPZ.js +8 -0
  13. package/lib/chunks/DNYSY7SK.js +8 -0
  14. package/lib/chunks/E2UJUSIU.js +11 -0
  15. package/lib/chunks/ECZUPR2N.js +7 -0
  16. package/lib/chunks/EU6GURJZ.js +7 -0
  17. package/lib/chunks/F4DGJH6G.js +8 -0
  18. package/lib/chunks/GELB6SHC.js +22 -0
  19. package/lib/chunks/HJ6KJBQG.js +9 -0
  20. package/lib/chunks/HXR6INJN.js +22 -0
  21. package/lib/chunks/IP2FG3VC.js +19 -0
  22. package/lib/chunks/KLY5RV3W.js +7 -0
  23. package/lib/chunks/LSG6IYBM.js +47 -0
  24. package/lib/chunks/NEWT5A6S.js +159 -0
  25. package/lib/chunks/O6MCQRCP.js +59 -0
  26. package/lib/chunks/O6PRCLSV.js +13 -0
  27. package/lib/chunks/OFAMJNQ6.js +7 -0
  28. package/lib/chunks/P26PQ2RU.js +7 -0
  29. package/lib/chunks/QQOKWPJZ.js +184 -0
  30. package/lib/chunks/RFWIIJFG.js +7 -0
  31. package/lib/chunks/RS5PUOTT.js +18 -0
  32. package/lib/chunks/SPVQTYE2.js +7 -0
  33. package/lib/chunks/TXOARWFE.js +7 -0
  34. package/lib/chunks/UPPWQBGX.js +7 -0
  35. package/lib/chunks/UYZXI3NO.js +7 -0
  36. package/lib/chunks/WZXA5XPB.js +7 -0
  37. package/lib/chunks/XYO6U5CE.js +31 -0
  38. package/lib/chunks/ZGSJFP2Z.js +8 -0
  39. package/lib/index.js +226 -13885
  40. package/package.json +1 -1
  41. package/lib/chunks/3CX2Z7JI.js +0 -496
  42. package/lib/chunks/3UUTQVCJ.js +0 -3614
  43. package/lib/chunks/4FB5ZIPP.js +0 -1133
  44. package/lib/chunks/5ILQMFXK.js +0 -59
  45. package/lib/chunks/7F5O43EU.js +0 -1756
  46. package/lib/chunks/7IX44JLO.js +0 -16
  47. package/lib/chunks/7MOL2QVN.js +0 -92635
  48. package/lib/chunks/A3VFVVHD.js +0 -25
  49. package/lib/chunks/A6JSOHCP.js +0 -41
  50. package/lib/chunks/AIT3U3JT.js +0 -22
  51. package/lib/chunks/ASYQPOQY.js +0 -681
  52. package/lib/chunks/BVP23YP7.js +0 -13374
  53. package/lib/chunks/FO6BDVGE.js +0 -25
  54. package/lib/chunks/GFU5KGSW.js +0 -92
  55. package/lib/chunks/ICPYP2LP.js +0 -401
  56. package/lib/chunks/KPMZLKQG.js +0 -79
  57. package/lib/chunks/KRMBH6JF.js +0 -17902
  58. package/lib/chunks/NLIKC7UP.js +0 -528
  59. package/lib/chunks/NW3XJZXQ.js +0 -175
  60. package/lib/chunks/P6UGG7F6.js +0 -414
  61. package/lib/chunks/RRC5IDC3.js +0 -2416
  62. package/lib/chunks/T6UZU3XM.js +0 -17
  63. package/lib/chunks/TS33ZDKX.js +0 -35
  64. package/lib/chunks/UUU33DK3.js +0 -125
  65. package/lib/chunks/VUDTNFRL.js +0 -42
  66. package/lib/chunks/VXIQEZPR.js +0 -2564
  67. package/lib/chunks/W7G5WVPB.js +0 -44
  68. package/lib/chunks/XB6C62FW.js +0 -18497
  69. package/lib/chunks/XHPY6UJF.js +0 -1638
  70. package/lib/chunks/Y6DTFCLS.js +0 -15
  71. package/lib/chunks/Z2664VV5.js +0 -39331
  72. package/lib/chunks/Z2I5YXYN.js +0 -20272
  73. package/lib/chunks/ZK3QRKL5.js +0 -129
@@ -0,0 +1,8 @@
1
+ import { createRequire as __createRequire } from 'node:module';
2
+ import { fileURLToPath as __fileURLToPath } from 'node:url';
3
+ import { dirname as __pathDirname } from 'node:path';
4
+ const require = __createRequire(import.meta.url);
5
+ var __filename = __fileURLToPath(import.meta.url);
6
+ var __dirname = __pathDirname(__filename);
7
+ import{a}from"./AE6JGTY4.js";import{b as s,c as u}from"./KLY5RV3W.js";import{c,f as d}from"./RFWIIJFG.js";var g=c(e=>{Object.defineProperty(e,"__esModule",{value:!0});e.getMachineId=void 0;var o=a(),l=(u(),d(s));async function f(){try{let i=(await(0,o.execAsync)('ioreg -rd1 -c "IOPlatformExpertDevice"')).stdout.split(`
8
+ `).find(r=>r.includes("IOPlatformUUID"));if(!i)return;let n=i.split('" = "');if(n.length===2)return n[1].slice(0,-1)}catch(t){l.diag.debug(`error reading machine id: ${t}`)}}e.getMachineId=f});export default g();
@@ -0,0 +1,8 @@
1
+ import { createRequire as __createRequire } from 'node:module';
2
+ import { fileURLToPath as __fileURLToPath } from 'node:url';
3
+ import { dirname as __pathDirname } from 'node:path';
4
+ const require = __createRequire(import.meta.url);
5
+ var __filename = __fileURLToPath(import.meta.url);
6
+ var __dirname = __pathDirname(__filename);
7
+ import{a as ae}from"./WZXA5XPB.js";import"./RFWIIJFG.js";function se(e){return e}async function z(e){return typeof e=="function"?await e():e}function de(e){let t="";for(let n of new TextEncoder().encode(e))t+=String.fromCharCode(n);return btoa(t)}function ue(e,t){return e.kind==="apiKey"?t.auth?.apiKey?.[e.scheme]!==void 0:e.kind==="bearer"?t.auth?.bearer!==void 0:t.auth?.basic!==void 0}async function J(e,t){let n=e.find(d=>d.every(a=>ue(a,t)))??e[0]??[],o={},r={},s=[];for(let d of n)if(d.kind==="apiKey"){let a=t.auth?.apiKey?.[d.scheme];if(a===void 0)continue;let l=await z(a);d.in==="header"?o[d.name]=l:d.in==="query"?r[d.name]=l:s.push(`${d.name}=${encodeURIComponent(l)}`)}else if(d.kind==="bearer"){let a=t.auth?.bearer;a!==void 0&&(o.Authorization=`Bearer ${await z(a)}`)}else{let a=t.auth?.basic;a!==void 0&&(o.Authorization=`Basic ${de(`${a.username}:${a.password}`)}`)}return s.length>0&&(o.Cookie=s.join("; ")),{headers:o,query:r}}var x=class extends Error{url;status;statusText;body;constructor(t,n,o,r){super(`Request failed with status ${n}`),this.name="ApiError",this.url=t,this.status=n,this.statusText=o,this.body=r}};function j(e){let t=e.reason;return t instanceof Error?t:new DOMException("The operation was aborted.","AbortError")}async function L(e,t){if(t==="void"){if(e.status===204||e.status===205||e.status===304||!(e.headers.get("content-type")??"").toLowerCase().includes("json"))return;let s=await e.text().catch(()=>"");if(s==="")return;try{return JSON.parse(s)}catch{return}}if(e.status===204)return;if(t==="stream")return e.body;if(t==="blob")return e.blob();if(t==="arrayBuffer")return e.arrayBuffer();if(t==="formData")return e.formData();if(t==="text")return e.text();if(t==="json")return e.json();let n=(e.headers.get("content-type")??"").toLowerCase();if(n.includes("json"))return e.json();if(n.startsWith("text/"))return e.text();let o=await e.blob();return o.size>0?o:void 0}async function R(e){return(e.headers.get("content-type")??"").toLowerCase().includes("json")?e.json().catch(()=>{}):e.text().catch(()=>{})}var fe=new Set(["GET","HEAD","PUT","DELETE","OPTIONS"]),ce=new Set([408,429,500,502,503,504]);function _(e){return fe.has(e.request.method.toUpperCase())?e.response===void 0||ce.has(e.response.status):!1}function M(e,t,n){if(n){let s=Number(n);if(!Number.isNaN(s))return s*1e3;let d=Date.parse(n);if(!Number.isNaN(d))return Math.max(0,d-Date.now())}let o=e.retryDelay??1e3,r=e.retryStrategy==="fixed"?o:o*Math.pow(2,t-1);return e.jitter===!1?r:Math.random()*r}function k(e,t){return new Promise((n,o)=>{if(t?.aborted){o(j(t));return}let r=()=>{clearTimeout(s),o(j(t))},s=setTimeout(()=>{t&&t.removeEventListener("abort",r),n()},e);t&&t.addEventListener("abort",r,{once:!0})})}function O(e){if(e===void 0)return{};if(e instanceof Headers){let t={};return e.forEach((n,o)=>{t[o]=n}),t}return Array.isArray(e)?Object.fromEntries(e):e}function K(e){return[...e.onRequest||e.onResponse||e.onError?[{onRequest:e.onRequest,onResponse:e.onResponse,onError:e.onError}]:[],...e.middleware??[]]}async function T(e,t,n,o,r,s,d,a="application/json"){let{retry:l,...u}=o,i={...e.retry,...l},f=typeof e.headers=="function"?await e.headers():e.headers,p={Accept:a,...f,...O(u.headers)},c={url:n,method:u.method??"GET",headers:p,body:r,operation:t},y=K(e);for(let m of y)m.onRequest&&await m.onRequest(c);let b;if(c.body!==void 0){let m=c.body,h=m instanceof Blob||m instanceof ArrayBuffer||ArrayBuffer.isView(m),S=typeof FormData<"u"&&m instanceof FormData,v=m instanceof URLSearchParams;if(S||v||h||typeof m=="string")b=m;else if(s){if(!d.serializeMultipart)throw new Error("Multipart capability not wired: cannot serialize the request body");b=d.serializeMultipart(m)}else b=JSON.stringify(m),!("Content-Type"in c.headers)&&!("content-type"in c.headers)&&(c.headers["Content-Type"]="application/json")}let N=e.fetch??fetch,B=1+(i.retries??0),w=i.retryOn??_,E=u.signal??void 0,g=0;for(;;){if(g++,E?.aborted)throw j(E);let m;try{m=await N(c.url,{...u,method:c.method,headers:c.headers,body:b})}catch(h){if(g<B&&!E?.aborted&&await w({attempt:g,request:c,error:h})){await k(M(i,g,null),E);continue}throw h}for(let h=y.length-1;h>=0;h--){let S=y[h].onResponse;if(S){let v=await S(m,c);v&&v!==m&&(await m.body?.cancel().catch(()=>{}),m=v)}}if(!m.ok&&g<B&&!E?.aborted&&await w({attempt:g,request:c,response:m})){let h=m.headers.get("retry-after");await m.body?.cancel().catch(()=>{}),await k(M(i,g,h),E);continue}return{response:m,context:c}}}function P(e){return encodeURIComponent(e).replace(/%(3A|2F|3F|23|5B|5D|40|21|24|26|27|28|29|2A|2B|2C|3B|3D)/g,t=>decodeURIComponent(t))}function G(e,t){return e.replace(/\{([^{}]+)\}/g,(n,o)=>{let r=t[o];if(r===void 0)throw new Error(`Missing path parameter "${o}"`);return encodeURIComponent(String(r))})}function W(e,t,n,o){let r=e.length;for(;r>0&&e.charCodeAt(r-1)===47;)r--;let s=e.slice(0,r)+t;if(!n)return s;let d=new URLSearchParams,a=[];for(let[u,i]of Object.entries(n)){if(i==null)continue;let f=o?.[u];if(!f){if(Array.isArray(i))for(let p of i)p!=null&&d.append(u,String(p));else if(Object(i)===i)for(let[p,c]of Object.entries(i))c!=null&&d.append(`${u}[${p}]`,String(c));else d.append(u,String(i));continue}if(Array.isArray(i)){let p=i.filter(c=>c!=null).map(String);if(f.style==="form"&&f.explode)for(let c of p)f.allowReserved?a.push(`${u}=${P(c)}`):d.append(u,c);else{let c=f.style==="pipeDelimited"?"|":f.style==="spaceDelimited"?"%20":",",y=f.allowReserved?P:encodeURIComponent;a.push(`${encodeURIComponent(u)}=${p.map(y).join(c)}`)}}else if(Object(i)===i)for(let[p,c]of Object.entries(i))c!=null&&(f.allowReserved?a.push(`${u}[${p}]=${P(String(c))}`):d.append(`${u}[${p}]`,String(c)));else f.allowReserved?a.push(`${u}=${P(String(i))}`):d.append(u,String(i))}let l=[d.toString(),...a].filter(Boolean).join("&");return l?`${s}?${l}`:s}function X(e){return e==="text"?"text/*":e==="blob"||e==="arrayBuffer"||e==="stream"||e==="formData"?"*/*":"application/json"}function Y(e){return e.responseKind==="void"||e.responseKind==="blob"||e.responseKind==="text"?e.responseKind:"auto"}function le(e,t){let n={},o=new Set;for(let r of e.params??[])r.in==="path"&&(o.add(r.name),n[r.name]=t[r.name]);for(let r of Object.keys(t))if(!(r==="params"||r==="body"||r==="headers"||r==="cookies")&&!o.has(r))throw new TypeError(`Unknown argument "${r}" for operation "${e.id}". Query parameters go under params: { \u2026 } and the request body under body; valid keys are params, body, headers, cookies`+(o.size>0?`, and the path parameters (${[...o].join(", ")}).`:"."));return{path:n,query:t.params,body:t.body,headers:t.headers,cookies:t.cookies}}function pe(e){let t;for(let n of e.params??[])n.in!=="query"||!(n.style!==void 0&&n.style!=="form"||n.explode===!1||n.allowReserved===!0)||(t??={},t[n.name]={style:n.style??"form",explode:n.explode??!0,allowReserved:n.allowReserved});return t}function me(e){let t={};for(let[n,o]of Object.entries(e??{}))o!=null&&(t[n]=String(o));return t}async function U(e,t,n,o,r){let{path:s,query:d,body:a,headers:l,cookies:u}=le(t,n),i=t.security?.length&&r.resolveAuth?await r.resolveAuth(t.security,e):{headers:{},query:{}},f=Object.entries(u??{}).filter(([,b])=>b!=null).map(([b,N])=>`${b}=${encodeURIComponent(String(N))}`);f.length>0&&(i.headers.Cookie=[i.headers.Cookie,...f].filter(Boolean).join("; "));let p={...d,...i.query},c=W(e.serverUrl??"",G(t.path,s),Object.keys(p).length>0?p:void 0,pe(t)),y={...o,method:t.method.toUpperCase(),headers:{...i.headers,...me(l),...O(o.headers)}};return{url:c,init:y,body:a}}async function ye(e,t,n,o,r){let s=await U(e,t,n,o,r),d={id:t.id,path:t.path,tags:[...t.tags??[]]},{parseAs:a,...l}=s.init,u=a??Y(t),{response:i,context:f}=await T(e,d,s.url,l,s.body,t.body?.multipart===!0,r,X(u));if(e.errorMode==="result")return i.ok?{data:await L(i,u),error:void 0,response:i}:{data:void 0,error:await R(i),response:i};if(!i.ok){let p=new x(f.url,i.status,i.statusText,await R(i));for(let c of K(e))c.onError&&(p=await c.onError(p,f));throw p}return L(i,u)}function q(e,t){if(!e.paginate)throw new Error(`Pagination capability not wired: cannot iterate operation "${t.id}"`);return e.paginate}function V(e,t){return t.errorMode!=="result"?e:async(n,o)=>{let r=await e(n,o);if(!r.response.ok){let{response:s}=r;throw new x(s.url,s.status,s.statusText,r.error)}return r.data}}function Q(e,t,n){return async(o={},r={})=>{let s=await U(e,t,o,r,n),{parseAs:d,...a}=s.init,l=d??Y(t),u={id:t.id,path:t.path,tags:[...t.tags??[]]},{response:i}=await T(e,u,s.url,a,s.body,t.body?.multipart===!0,n,X(l));if(!i.ok)throw new x(s.url,i.status,i.statusText,await R(i));return{page:await L(i,l),linkHeader:i.headers.get("link"),url:i.url===""?s.url:i.url}}}function Z(e,t={},n={}){let o=t,r={...o,middleware:[...o.middleware??[]]},s={};for(let[d,a]of Object.entries(e))if(a.responseKind==="sse"){let l=(u={},i={})=>{if(!n.sse)throw new Error(`SSE capability not wired: cannot stream operation "${a.id}"`);let f=n.sse;return(async function*(){let p={id:a.id,path:a.path,tags:[...a.tags??[]]};yield*f(r,p,async()=>{let y=await U(r,a,u,i,n);return{url:y.url,init:y.init,body:y.body}},a.sseDataKind??"text")})()};Object.defineProperty(l,"name",{value:d}),Object.defineProperty(l,"operationId",{value:a.id}),s[d]=l}else{let l=(i={},f={})=>ye(r,a,i,f,n);Object.defineProperty(l,"name",{value:d}),Object.defineProperty(l,"operationId",{value:a.id});let u=a.pagination;s[d]=u===void 0?l:u.style==="link"?Object.assign(l,{pages:(i,f)=>q(n,a).pagesByLink(Q(r,a,n),i,f),items:(i,f)=>q(n,a).itemsByLink(Q(r,a,n),u,i,f)}):Object.assign(l,{pages:(i,f)=>q(n,a).pages(V(l,r),u,i,f),items:(i,f)=>q(n,a).items(V(l,r),u,i,f)})}return s.configure=d=>{let{errorMode:a,auth:l,...u}=d;Object.assign(r,u),l&&(r.auth={...r.auth,...l,...l.apiKey?{apiKey:{...r.auth?.apiKey,...l.apiKey}}:{}})},s.use=(...d)=>{r.middleware=[...r.middleware??[],...d]},s.auth={bearer(d){r.auth={...r.auth,bearer:d}},basic(d,a){r.auth={...r.auth,basic:{username:d,password:a}}},apiKey(d,a){r.auth={...r.auth,apiKey:{...r.auth?.apiKey,[d]:a}}}},s}function ee(e){let t=new FormData,n=(o,r)=>{r!=null&&(r instanceof Blob||typeof r=="string"?t.append(o,r):r instanceof Date?t.append(o,r.toISOString()):Object(r)===r?t.append(o,JSON.stringify(r)):t.append(o,String(r)))};for(let[o,r]of Object.entries(e))if(Array.isArray(r))for(let s of r)n(o,s);else n(o,r);return t}function $(e,t){if(t==="")return e;if(!t.startsWith("/"))return;let n=e;for(let o of t.slice(1).split("/")){let r=o.replaceAll("~1","/").replaceAll("~0","~");if(Array.isArray(n)){if(!/^(0|[1-9]\d*)$/.test(r))return;n=n[Number(r)]}else if(Object(n)===n&&r in n)n=n[r];else return}return n}async function*F(e,t,n={},o){if(t.style==="cursor"){let r=n.params?.[t.param];for(;;){let s={...n.params};r!==void 0&&(s[t.param]=r);let d=await e({...n,params:s},o);if(yield d,t.hasMore!==void 0&&$(d,t.hasMore)===!1)return;let a=$(d,t.nextCursor);if(a==null||a==="")return;if(typeof a!="string"&&typeof a!="number")throw new Error(`Pagination cursor at ${t.nextCursor} is not a string or number`);if(a===r)throw new Error("Pagination did not advance: operation returned the same cursor twice");r=a}}else{if(t.style==="link")throw new Error("link-style pagination iterates via pagesByLink");{let r=n.params?.[t.param],s=t.style==="page"?1:0,a=r==null||r===""||Number.isNaN(Number(r))?s:Number(r),l;for(;;){let u=await e({...n,params:{...n.params,[t.param]:a}},o),i=$(u,t.items),f=Array.isArray(i)?JSON.stringify(i):void 0;if(f!==void 0&&f===l)throw new Error("Pagination did not advance: the operation returned the same page twice");if(yield u,!Array.isArray(i)||i.length===0)return;l=f,a+=t.style==="page"?1:i.length}}}}async function*te(e,t,n,o){for await(let r of F(e,t,n,o)){let s=$(r,t.items);Array.isArray(s)&&(yield*s)}}function he(e){if(e!==null)for(let t of e.split(/,\s*(?=<)/)){let n=/^\s*<([^>]*)>(.*)$/.exec(t);if(!n)continue;let o=/;\s*rel\s*=\s*"?([^";]+)"?/i.exec(n[2]);if(o&&o[1].split(/\s+/).includes("next"))return n[1]}}async function*H(e,t={},n){let o=t.params,r;for(;;){let{page:s,linkHeader:d,url:a}=await e({...t,params:o},n);yield s;let l=he(d);if(l===void 0)return;let u=new URL(a,"http://relative.invalid"),i=new URL(l,u).toString();if(i===r||i===u.toString())throw new Error('Pagination did not advance: the Link rel="next" target repeats');r=i;let f={};for(let[p,c]of new URL(i).searchParams){let y=f[p];y===void 0?f[p]=c:Array.isArray(y)?y.push(c):f[p]=[y,c]}o={...t.params,...f}}}async function*re(e,t,n,o){for await(let r of H(e,n,o)){let s=$(r,t.items);Array.isArray(s)&&(yield*s)}}var we=/(?:\r\n|\r|\n){2}/,D=class extends Error{};async function*oe(e,t,n,o="text"){let r,s,d=0;for(;;){let{url:a,init:l,body:u}=await n(),{reconnect:i=!0,reconnectDelay:f,...p}=l,c=p.signal??void 0;if(c?.aborted)return;let y={Accept:"text/event-stream",...O(p.headers)},b=r===void 0?y:{...y,"Last-Event-ID":r};try{let{response:w}=await T(e,t,a,{...p,method:p.method??"GET",headers:b},u,!1,{});if(!w.ok){let S=await R(w);throw new x(a,w.status,w.statusText,S)}d=0;let E=w.body;if(!E)return;let g=E.getReader(),m=new TextDecoder,h="";try{for(;;){let{done:S,value:v}=await g.read();h+=S?m.decode():m.decode(v,{stream:!0});let I;for(;(I=we.exec(h))!==null;){let A=h.slice(0,I.index);h=h.slice(I.index+I[0].length);let C=ne(A,o);C&&(C.id!==void 0&&(r=C.id),C.retry!==void 0&&(s=C.retry),yield C)}if(S){let A=h.length>0?ne(h,o):void 0;A&&(A.id!==void 0&&(r=A.id),A.retry!==void 0&&(s=A.retry),yield A);return}if(h.length>1048576)throw new D("SSE frame exceeded 1048576 characters without a delimiter")}}finally{await g.cancel().catch(()=>{})}}catch(w){if(c?.aborted)return;if(w instanceof x||w instanceof D||!i)throw w}d++;let B=Math.min((s??f??1e3)*Math.pow(2,d-1),3e4);try{await k(Math.random()*B,c)}catch{return}}}function ne(e,t){let n,o=[],r,s,d=!1;for(let u of e.split(/\r\n|\n|\r/)){if(u===""||u.startsWith(":"))continue;let i=u.indexOf(":"),f=i===-1?u:u.slice(0,i),p=i===-1?"":u.slice(i+1);p.startsWith(" ")&&(p=p.slice(1)),d=!0,f==="event"?n=p:f==="data"?o.push(p):f==="id"?r=p:f==="retry"&&/^\d+$/.test(p)&&(s=Number(p))}if(!d)return;let a=o.join(`
8
+ `),l=a;if(t==="json"&&a!=="")try{l=JSON.parse(a)}catch(u){throw new D(`Failed to parse SSE event data as JSON: ${u instanceof Error?u.message:String(u)}`)}return{event:n,data:l,id:r,retry:s}}function ie(e,t={}){return{...e?.config,...t,middleware:[...e?.middleware??[],...t.middleware??[]]}}function be(e,t){return Z(e,t,{serializeMultipart:ee,resolveAuth:J,sse:oe,paginate:{pages:F,items:te,pagesByLink:H,itemsByLink:re}})}function xe(e,t){let n={...e};for(let[o,r]of Object.entries(t))r!==void 0&&(n[o]=r);return n}function Ye(e){return e}async function et(e){return(await import("./BZ7PKRCP.js")).generateClient(e)}export{x as ApiError,ae as NotSupportedError,be as createClient,se as defineClientSetup,Ye as defineGenerator,et as generateClient,xe as mergeConfig,ie as mergeSetup};
@@ -0,0 +1,11 @@
1
+ import { createRequire as __createRequire } from 'node:module';
2
+ import { fileURLToPath as __fileURLToPath } from 'node:url';
3
+ import { dirname as __pathDirname } from 'node:path';
4
+ const require = __createRequire(import.meta.url);
5
+ var __filename = __fileURLToPath(import.meta.url);
6
+ var __dirname = __pathDirname(__filename);
7
+ import{a as x}from"./HJ6KJBQG.js";import{a as v,b as y,c as R,d as u}from"./GELB6SHC.js";import{c as f,d as w}from"./F4DGJH6G.js";import{a as g,b as m}from"./SPVQTYE2.js";import{O as a}from"./QQOKWPJZ.js";import"./NEWT5A6S.js";import"./RFWIIJFG.js";import{mkdir as A,writeFile as C}from"node:fs/promises";import S from"node:path";async function F(e){let i=await w(e.trafficPath);if(i.length===0)throw new Error("No traffic files found in the provided traffic path.");let t=y.create({openApiIndex:e.openApiIndex,matchMode:e.matchMode,ignoreCookies:e.ignoreCookies,ignoreHeaders:e.ignoreHeaders,previewFindingsLimit:e.previewFindingsLimit,activeRules:e.activeRules,server:e.server,minSeverity:e.minSeverity}),r=0,o=0;for(let n of i){let s=await x(n,e.format);if(!s){a.warn(`Skipping traffic file with unrecognized format: ${n}
8
+ `);continue}r+=1;for await(let c of s.parse(n))await t.process({...c,index:o}),o+=1}if(r===0)throw new Error("No supported traffic files found. In auto mode, files must match built-in traffic parser signatures.");if(o===0)throw new Error("No HTTP exchanges were parsed from the provided traffic files.");return t.finalize()}var E=!!process.stdout.isTTY&&process.env.NO_COLOR===void 0;function T(e){let i=new Set;for(let t of e.operationsByMethod.values())for(let r of t)for(let o of r.servers)i.add(o.rawUrl);return Array.from(i).sort()}function I(e,i,t){let r=e.totalExchanges-e.skippedExchanges;if(r===0&&e.skippedExchanges>0){a.warn(`All ${e.skippedExchanges} exchange(s) were outside the --server "${t}" and were skipped. Check that the server matches the traffic URLs.
9
+ `);return}if(e.documentedExchanges>0||r===0)return;let o=T(i),n=t?`Check that the --server "${t}" matches the traffic URLs and that the description paths align with the remainder.`:e.hostCompatibleExchanges===r?`The traffic hosts are compatible with the description servers (${o.join(", ")}), so the endpoints are likely undocumented; if they should be documented, check that the description base paths and paths align with the traffic URLs, or use --server to declare the server the traffic was captured against.`:`Check that the traffic host and base path match the description servers (${o.join(", ")}), or use --server to declare the server the traffic was captured against.`;a.warn(`None of the ${r} validated exchange(s) matched a documented operation. ${n}
10
+ `)}async function $(e,i){let t=f(e);await A(S.dirname(t),{recursive:!0}),await C(t,i,"utf8")}async function q({argv:e,config:i}){let t=f(e.traffic),r=e["traffic-format"],o=e.rules?u(e.rules):void 0,n=e["ignore-headers"]?u(e["ignore-headers"]):void 0,s=e.server;if(s&&e["match-mode"])return m("The --server and --match-mode options are mutually exclusive: --match-mode controls how requests are located via the description servers, while --server replaces the description servers with the one the traffic was captured against.");let c=e["match-mode"]??"strict-host",d=f(e.api),p=await R(d,i);if(p.loadedOperations===0)return m(`No OpenAPI operations were loaded from: ${d}`);let{runId:k,summary:h,findings:O}=await F({trafficPath:t,format:r,matchMode:c,ignoreCookies:e["ignore-cookies"],ignoreHeaders:n,previewFindingsLimit:e["max-findings"],activeRules:o,openApiIndex:p,server:s,minSeverity:e["min-severity"]});I(h,p,s);let l=v({runId:k,summary:h,findings:O,meta:{specSource:d,trafficPath:t,format:r,matchMode:c,server:s}},{format:e["report-format"],color:E&&e["report-format"]==="pretty"&&!e.output,maxFindings:e["max-findings"]});if(e.output?(await $(e.output,l),a.info(`Drift report written to: ${f(e.output)}
11
+ `)):a.output(l),h.findingsBySeverity.error>0)throw new g("Drift detected.")}export{q as handleDrift};
@@ -0,0 +1,7 @@
1
+ import { createRequire as __createRequire } from 'node:module';
2
+ import { fileURLToPath as __fileURLToPath } from 'node:url';
3
+ import { dirname as __pathDirname } from 'node:path';
4
+ const require = __createRequire(import.meta.url);
5
+ var __filename = __fileURLToPath(import.meta.url);
6
+ var __dirname = __pathDirname(__filename);
7
+ import{b as t,c as i}from"./KLY5RV3W.js";import{c as d,f as n}from"./RFWIIJFG.js";var a=d(e=>{Object.defineProperty(e,"__esModule",{value:!0});e.getMachineId=void 0;var u=(i(),n(t));async function r(){u.diag.debug("could not read machine-id: unsupported platform")}e.getMachineId=r});export default a();
@@ -0,0 +1,7 @@
1
+ import { createRequire as __createRequire } from 'node:module';
2
+ import { fileURLToPath as __fileURLToPath } from 'node:url';
3
+ import { dirname as __pathDirname } from 'node:path';
4
+ const require = __createRequire(import.meta.url);
5
+ var __filename = __fileURLToPath(import.meta.url);
6
+ var __dirname = __pathDirname(__filename);
7
+ import{b as d,c as s}from"./KLY5RV3W.js";import{a as n,c,f as a}from"./RFWIIJFG.js";var f=c(e=>{Object.defineProperty(e,"__esModule",{value:!0});e.getMachineId=void 0;var u=n("fs"),o=(s(),a(d));async function h(){let i=["/etc/machine-id","/var/lib/dbus/machine-id"];for(let r of i)try{return(await u.promises.readFile(r,{encoding:"utf8"})).trim()}catch(t){o.diag.debug(`error reading machine id: ${t}`)}}e.getMachineId=h});export default f();
@@ -0,0 +1,8 @@
1
+ import { createRequire as __createRequire } from 'node:module';
2
+ import { fileURLToPath as __fileURLToPath } from 'node:url';
3
+ import { dirname as __pathDirname } from 'node:path';
4
+ const require = __createRequire(import.meta.url);
5
+ var __filename = __fileURLToPath(import.meta.url);
6
+ var __dirname = __pathDirname(__filename);
7
+ import{c}from"./QQOKWPJZ.js";import{open as C,readdir as N,stat as P}from"node:fs/promises";import d from"node:path";var $=new Set([".yaml",".yml",".json"]);async function D(e){let n=[];async function t(r){let o=await N(r,{withFileTypes:!0});for(let s of o){if(s.name.startsWith("."))continue;let i=d.join(r,s.name);if(s.isDirectory()){await t(i);continue}s.isFile()&&$.has(d.extname(s.name).toLowerCase())&&n.push(i)}}return await t(e),n.sort(),n}async function _(e,n=4096){let t=await C(e,"r");try{let r=Buffer.allocUnsafe(n),{bytesRead:o}=await t.read(r,0,n,0);return r.toString("utf8",0,o)}finally{await t.close()}}function M(e){return d.resolve(process.cwd(),e)}async function K(e){let n=await P(e);if(n.isFile())return[e];if(!n.isDirectory())return[];let t=[];async function r(o){let s=await N(o,{withFileTypes:!0});for(let i of s){if(i.name.startsWith("."))continue;let a=d.join(o,i.name);if(i.isDirectory()){await r(a);continue}i.isFile()&&t.push(a)}}return await r(e),t.sort(),t}var k="drift.local",O=`http://${k}`;function u(e){return e===k}var U=new Set(["accept","accept-charset","accept-encoding","accept-language","authorization","baggage","cache-control","cdn-loop","cookie","connection","content-length","content-type","dpr","dnt","downlink","ect","forwarded","host","if-match","if-modified-since","if-none-match","if-range","if-unmodified-since","origin","pragma","priority","range","referer","sec-fetch-dest","sec-fetch-mode","sec-fetch-site","sec-fetch-user","sec-gpc","sentry-trace","te","traceparent","tracestate","upgrade","upgrade-insecure-requests","user-agent","via","x-client-trace-id","x-cloud-trace-context","x-correlation-id","x-http-method-override","x-hub-signature","x-hub-signature-256","x-method-override","x-real-ip","x-request-id","x-forwarded-for","x-forwarded-host","x-forwarded-port","x-forwarded-proto"]),J=["cf-","sec-ch-","sec-fetch-","x-amz-","x-amzn-","x-b3-","x-envoy-","x-forwarded-","x-github-"],R=`
8
+ `;function Y(e){return e.split(R)}function g(e,n,t){let r=n.toLowerCase(),o=e[r];if(o===void 0){e[r]=t;return}e[r]=r==="set-cookie"?`${o}${R}${t}`:`${o},${t}`}function p(e){if(!c(e)&&!Array.isArray(e))return{};let n={};if(Array.isArray(e)){for(let t of e){if(!c(t))continue;let{name:r,value:o}=t;typeof r=="string"&&o!==void 0&&g(n,r,String(o))}return n}for(let[t,r]of Object.entries(e))if(r!=null){if(Array.isArray(r)){for(let o of r)g(n,t,String(o));continue}g(n,t,String(r))}return n}function f(e){try{return new URL(e)}catch{return new URL(e,O)}}function m(e){return e.length>1&&e.endsWith("/")?e.slice(0,-1):e}function L(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function V(e){let n=[],t=0,r=e.startsWith("/")?e:`/${e}`,s=m(r).split("/").map(i=>{if(!i)return"";let a=i.match(/^\{([^}]+)\}$/);return a?(n.push(a[1]),"([^/]+)"):(t+=2,L(i))}).join("/");return{regex:new RegExp(`^${s||"/"}$`),params:n,score:t}}function l(e,n){if(n&&A(e))try{return JSON.parse(n)}catch{return}}function E(e){return e?e.split(";")[0]?.trim().toLowerCase()??"":""}function A(e){let n=E(e);return n==="application/json"||n.endsWith("+json")}function Q(e,n){let t=E(n);if(!t)return e["application/json"]??e["*/*"];if(e[t]!==void 0)return e[t];let[r,o]=t.split("/");if(r&&o){let s=`${r}/*`;if(e[s]!==void 0)return e[s]}return e["*/*"]}function Z(e){let n=new Set,t=[];for(let r of e){let o=r.trim().toLowerCase();o.length!==0&&(o.endsWith("*")?t.push(o.slice(0,-1)):n.add(o))}return{names:n,prefixes:t}}function v(e,n){let t=e.toLowerCase();return t.startsWith(":")||U.has(t)||J.some(r=>t.startsWith(r))?!0:n?n.names.has(t)||n.prefixes.some(r=>t.startsWith(r)):!1}import{createReadStream as q}from"node:fs";import{readFile as B}from"node:fs/promises";import{createInterface as F}from"node:readline";function I(e){if(e!=null){if(typeof e=="string")return e;if(Buffer.isBuffer(e))return e.toString("utf8");if(c(e)||Array.isArray(e))try{return JSON.stringify(e)}catch{return String(e)}return String(e)}}function se(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"&&e.trim()!==""){let n=Number(e);if(Number.isFinite(n))return n}}function H(e,n){if(e!=null){if(n==="base64"&&typeof e=="string")try{return Buffer.from(e,"base64").toString("utf8")}catch{return e}return I(e)}}function ae(e,n,t){let r=e.method?.toUpperCase(),o=e.url;if(!r||!o)return null;let s=p(e.requestHeaders),i=f(o);if(u(i.host)&&s.host)try{i=new URL(`${i.protocol}//${s.host}${i.pathname}${i.search}`)}catch{i=f(o)}let a=e.requestContentType??s["content-type"],y=H(e.requestBody),T={method:r,url:i.toString(),path:i.pathname,query:i.searchParams,protocol:i.protocol,protocolKnown:e.schemeKnown??/^https?:\/\//i.test(o),host:u(i.host)?void 0:i.host||void 0,headers:s,contentType:a,bodyText:y,bodyJson:l(a,y)},h,x=e.responseStatus;if(x!==void 0){let w=p(e.responseHeaders),S=e.responseContentType??w["content-type"],b=H(e.responseBody);h={status:x,statusText:e.responseStatusText,headers:w,contentType:S,bodyText:b,bodyJson:l(S,b)}}return{index:n,source:t,startedAt:e.startedAt,request:T,response:h,raw:e.raw}}async function*ce(e){let n=q(e,{encoding:"utf8"}),t=F({input:n,crlfDelay:1/0});for await(let r of t){let o=r.trim();if(o)try{let s=JSON.parse(o);c(s)&&(yield s)}catch{}}}async function*ue(e,n){let t=await B(e,"utf8"),r=JSON.parse(t);if(n)for(let o of n.split("."))r=c(r)?r[o]:void 0;if(Array.isArray(r))for(let o of r)c(o)&&(yield o)}function fe(e){return p(e)["content-type"]}function ge(e){return e?.replace(/\/+$/,"")||void 0}function z(e,n){if(!n||n==="/")return e||"/";if(e===n)return"/";if(e.startsWith(`${n}/`))return e.slice(n.length)||"/"}function me(e,n){if(n.startsWith("/"))return z(e.path,n);let t=f(n.includes("://")?n:`http://${n}`);if(!(u(t.host)||e.host!==void 0&&e.host.toLowerCase()!==t.host))return z(e.path,m(t.pathname))}export{D as a,_ as b,M as c,K as d,u as e,Y as f,f as g,m as h,V as i,E as j,A as k,Q as l,Z as m,v as n,I as o,se as p,H as q,ae as r,ce as s,ue as t,fe as u,ge as v,me as w};
@@ -0,0 +1,22 @@
1
+ import { createRequire as __createRequire } from 'node:module';
2
+ import { fileURLToPath as __fileURLToPath } from 'node:url';
3
+ import { dirname as __pathDirname } from 'node:path';
4
+ const require = __createRequire(import.meta.url);
5
+ var __filename = __fileURLToPath(import.meta.url);
6
+ var __dirname = __pathDirname(__filename);
7
+ import{a as oe,e as ae,f as ue,g as ce,h as b,i as de,k as H,l as V,m as pe,n as le,v as he,w as me}from"./F4DGJH6G.js";import{D as X,E as g,F as O,G as Z,H as $,I as C,K as S,M as y,O as w,Q as ee,R as te,S as Je,W as ne,Y as re,_ as se,aa as ie,c as l,p as Y,u as Q,x as We}from"./QQOKWPJZ.js";import{e as J}from"./RFWIIJFG.js";import fe from"node:path";function R(t){return t?t.trim():""}function T(t){let e=R(t.operationId)||R(t.path);return[R(t.ruleId),R(t.severity),R(t.message),e,R(t.target),R(t.schemaPath)].join("")}var F=t=>X(S(t));function Ye(t){return t==="error"?"error":t==="warning"?"warning":"note"}function Qe(t){if(t==null)return"";let e=String(t);return!e.includes(",")&&!e.includes('"')&&!e.includes(`
8
+ `)?e:`"${e.replace(/"/g,'""')}"`}function Xe(t){return fe.isAbsolute(t)?fe.relative(process.cwd(),t)||".":t}function Ze(t){if(!t)return null;let e=t.operationPathTemplate;return typeof e=="string"&&e.length>0?e:null}function et(t){return Object.entries(t).sort((e,r)=>{let n=r[1]-e[1];return n!==0?n:e[0].localeCompare(r[0])})}function tt(t){let e=[],r=new Map;for(let n of t){let s=T({ruleId:n.ruleId,severity:n.severity,message:n.message,operationId:n.operationId,path:n.path,target:n.target,schemaPath:n.schemaPath}),i=r.get(s);if(i!==void 0){e[i].occurrences+=1;continue}r.set(s,e.length),e.push({finding:n,occurrences:1})}return e}function nt(t){let e=tt(t.findings).map(n=>({occurrences:n.occurrences,exchangeIndex:n.finding.exchangeIndex,ruleId:n.finding.ruleId,severity:n.finding.severity,category:n.finding.category,message:n.finding.message,operationId:n.finding.operationId,specSource:n.finding.specSource,target:n.finding.target,schemaPath:n.finding.schemaPath,dataPath:n.finding.dataPath,details:n.finding.details,method:n.finding.method,url:n.finding.url,path:n.finding.path,status:n.finding.status})),r={run:{id:t.runId,specSource:t.meta.specSource,trafficPath:t.meta.trafficPath,format:t.meta.format,matchMode:t.meta.matchMode,server:t.meta.server,totalExchanges:t.summary.totalExchanges,documentedExchanges:t.summary.documentedExchanges,undocumentedExchanges:t.summary.undocumentedExchanges,skippedExchanges:t.summary.skippedExchanges,findingsBySeverity:t.summary.findingsBySeverity,findingsByRule:t.summary.findingsByRule,totalProblems:t.summary.totalProblemGroups,durationMs:t.summary.durationMs},problems:e};return`${JSON.stringify(r,null,2)}
9
+ `}function rt(t){let e=["run_id","finding_id","exchange_index","severity","category","rule_id","message","method","path","url","status","operation_id","spec_source","target","schema_path","data_path"],r=t.findings.map(s=>[t.runId,s.id,s.exchangeIndex,s.severity,s.category,s.ruleId,s.message,s.method,s.path,s.url,s.status,s.operationId,s.specSource,s.target,s.schemaPath,s.dataPath]);return`${[e,...r].map(s=>s.map(Qe).join(",")).join(`
10
+ `)}
11
+ `}function st(t){let e=new Map;for(let s of t.findings)e.has(s.ruleId)||e.set(s.ruleId,{id:s.ruleId,name:s.ruleId,shortDescription:{text:`${s.category} detection`}});let r=t.findings.map(s=>{let i=s.specSource??s.url??void 0;return{ruleId:s.ruleId,level:Ye(s.severity),message:{text:s.message},locations:i?[{physicalLocation:{artifactLocation:{uri:i}}}]:void 0,properties:{runId:t.runId,exchangeIndex:s.exchangeIndex,method:s.method,path:s.path,status:s.status,operationId:s.operationId,target:s.target,schemaPath:s.schemaPath,dataPath:s.dataPath}}}),n={$schema:"https://json.schemastore.org/sarif-2.1.0.json",version:"2.1.0",runs:[{tool:{driver:{name:"drift",rules:Array.from(e.values())}},results:r}]};return`${JSON.stringify(n,null,2)}
12
+ `}function it(t){return t.findingsBySeverity.error+t.findingsBySeverity.warning+t.findingsBySeverity.info}function ot(t){return t>=500?O:t>=400?$:t>=300?C:t>=200?Z:y}function at(t,e,r){let n=(h,f)=>e?f(h):h,s=h=>h==="error"?n("\u2716",O):h==="warning"?n("\u25B2",$):n("\u25CF",C),i=h=>h==="error"?n("ERROR",O):h==="warning"?n("WARN",$):n("INFO",C),{summary:o,meta:a}=t,c=it(o),p=o.previewFindings.slice(0,r),u=[];if(u.push(n("\u250F\u2501 Drift Report",F)),u.push(`\u2503 Run: ${t.runId}`),u.push(`\u2503 Spec: ${a.specSource}`),u.push(`\u2503 Traffic: ${a.trafficPath}`),u.push(a.server?`\u2503 Server: ${a.server} (overrides description servers)`:`\u2503 Match mode: ${a.matchMode}`),u.push(`\u2503 Traffic format: ${a.format}${a.format==="auto"?" (auto-detect)":""}`),u.push(`\u2503 Exchanges: total=${o.totalExchanges} documented=${o.documentedExchanges} undocumented=${o.undocumentedExchanges}${o.skippedExchanges>0?` skipped=${o.skippedExchanges}`:""}`),u.push(`\u2503 Findings: total=${c} ${n(`error=${o.findingsBySeverity.error}`,O)} ${n(`warning=${o.findingsBySeverity.warning}`,$)} ${n(`info=${o.findingsBySeverity.info}`,C)}`),u.push(`\u2503 Problems: total=${o.totalProblemGroups}`),u.push(`\u2517 Duration: ${o.durationMs}ms`),c===0)return u.push(""),u.push(n("\u2714 No findings.",S)),`${u.join(`
13
+ `)}
14
+ `;u.push(""),u.push(n(`Types (${Object.keys(o.problemGroupsByRule).length})`,F));for(let[h,f]of et(o.problemGroupsByRule)){let v=o.findingsByRule[h]??f;u.push(` ${n("\u2022",y)} ${h}: ${f} problems / ${v} findings`)}let m=new Map;for(let h of p)m.has(h.ruleId)||m.set(h.ruleId,[]),m.get(h.ruleId).push(h);let x=Array.from(m.keys()).sort((h,f)=>{let v=(o.problemGroupsByRule[f]??0)-(o.problemGroupsByRule[h]??0);return v!==0?v:h.localeCompare(f)});u.push(""),u.push(n(`Problems by type (showing first ${p.length} of ${o.totalProblemGroups})`,F));let q=0;for(let h of x){let f=m.get(h);if(!f||f.length===0)continue;let v=o.problemGroupsByRule[h]??f.length,ze=o.findingsByRule[h]??v;u.push(""),u.push(`${n("\u25C9",S)} ${n(h,F)} ${n(`(${f.length} problems shown / ${v} total, ${ze} findings)`,y)}`);for(let d of f){q+=1;let U=d.occurrences,De=d.status!==void 0?n(String(d.status),ot(d.status)):n("-",y),Ke=Ze(d.details)??d.path,Ue=d.operationId?` ${n(d.operationId,g)}`:"";if(u.push(`${s(d.severity)} ${i(d.severity)} #${q}${U>1?` ${n(`\xD7${U}`,y)}`:""} ${n("\u2192",y)} ${d.message}`),u.push(` \u21B3 sample exchange=${d.exchangeIndex} ${n(d.method,S)} ${Ke} (${De})${Ue}`),u.push(""),u.push(` ${n(d.url,y)}`),(d.specSource||d.schemaPath||d.dataPath)&&(u.push(""),d.specSource&&u.push(` ${n("spec:",g)} ${n(Xe(d.specSource),S)}`),d.schemaPath&&u.push(` ${n("schemaPath=",g)} ${n(d.schemaPath,g)}`),d.dataPath&&u.push(` ${n("dataPath=",g)} ${n(d.dataPath,S)}`)),d.details)if(u.push(""),d.ruleId==="security-baseline"&&typeof d.details.summary=="string")u.push(` ${n("security:",g)} ${d.details.summary}`);else if(d.ruleId==="owasp-api-top10"&&typeof d.details.summary=="string"){let k=typeof d.details.issueId=="string"?d.details.issueId:null,A=typeof d.details.issueTitle=="string"?d.details.issueTitle:null;u.push(` ${n("owasp:",g)} ${d.details.summary}`),(k||A)&&u.push(` ${n("issue:",g)} ${[k,A].filter(Boolean).join(" - ")}`)}else if(d.ruleId==="schema-consistency"&&typeof d.details.summary=="string"){let k=typeof d.details.path=="string"?d.details.path:null,A=typeof d.details.expected=="string"?d.details.expected:null,G=typeof d.details.actual=="string"?d.details.actual:null,W=typeof d.details.suggestion=="string"?d.details.suggestion:null;if(u.push(` ${n("schema:",g)} ${d.details.summary}`),k&&u.push(` ${n("path:",g)} ${n(k,S)}`),A&&u.push(` ${n("expected:",g)} ${A}`),G&&u.push(` ${n("actual:",g)} ${G}`),W){u.push(` ${n("hint:",g)}`);for(let Ge of W.split(`
15
+ `))u.push(` ${Ge}`)}}else u.push(` ${n("details:",g)} ${JSON.stringify(d.details)}`);u.push("")}}let P=o.totalProblemGroups-p.length;return P>0?(u[u.length-1]!==""&&u.push(""),u.push(n(`\u2026 ${P} problems omitted from terminal output. Use --format json/csv/sarif for the complete export.`,y))):u[u.length-1]===""&&u.pop(),`${u.join(`
16
+ `)}
17
+ `}function Hn(t,e){let r=e.maxFindings??10;switch(e.format){case"json":return nt(t);case"csv":return rt(t);case"sarif":return st(t);case"pretty":return at(t,e.color??!1,r);default:throw new Error(`Unsupported report format: ${e.format}`)}}import{randomUUID as Be}from"node:crypto";function ut(t,e){let r=b(t||"/")||"/",n=b(e.basePath||"/")||"/";return n==="/"?r:r===n?"/":r.startsWith(`${n}/`)?r.slice(n.length)||"/":null}function ct(t,e){return!t.host||!e?!0:t.host===e.toLowerCase()}function dt(t){try{return decodeURIComponent(t)}catch{return t}}function pt(t,e,r){let n=r==="strict-host"?e.host?20:5:0;return t.pathScore*10+n}function ge(t,e){let r={};for(let n=0;n<t.pathParams.length;n+=1){let s=t.pathParams[n],i=e[n+1];s&&i!==void 0&&(r[s]=dt(i))}return r}function lt(t,e){let r=b(e)||"/";for(let n of t){let s=n.pathRegex.exec(r);if(s)return{operation:n,pathParams:ge(n,s)}}return null}function ye(t,e,r,n){let s=e.request.method.toLowerCase(),i=t.operationsByMethod.get(s);if(!i||i.length===0)return null;if(n!==void 0)return lt(i,n);let o=null;for(let a of i)for(let c of a.servers){if(r==="strict-host"&&!ct(c,e.request.host))continue;let p=ut(e.request.path,c);if(!p)continue;let u=a.pathRegex.exec(p);if(!u)continue;let m={score:pt(a,c,r),matched:{operation:a,pathParams:ge(a,u)}};(!o||m.score>o.score)&&(o=m)}return o?.matched??null}var Se=6,ht=2e3,mt=50,ft=5,gt=1e6,yt=/(?:token|api[_-]?key|apikey|password|passwd|secret|authorization|jwt)/i,St=/(?:password|passwd|secret|api[_-]?key|access[_-]?token|refresh[_-]?token|private[_-]?key|ssn|credit[_-]?card|card[_-]?number|cvv)/i,vt=new Set(["page","limit","offset","cursor","per_page","perpage","size","start","after","before"]),ve=4,wt=ve*2;function Rt(t){return t.length<=wt?"***":`${t.slice(0,ve)}\u2026`}function It(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}function Pt(t){return typeof t=="string"||typeof t=="number"}function bt(t){let e=t.toLowerCase();return e.includes("secret")||e.includes("token")||e.includes("key")?e.startsWith("is")||e.startsWith("has")||e.startsWith("can")||e.startsWith("should")||e.startsWith("enable")||e.startsWith("allow"):!1}function xt(t){if(typeof t=="number")return t===0||t===1;let e=t.trim().toLowerCase();return e==="true"||e==="false"||e==="0"||e==="1"}function kt(t){if(!l(t)&&!Array.isArray(t))return[];let e=[],r=[{value:t,path:""}],n=0;for(;r.length>0&&n<ht&&e.length<Se;){let s=r.pop();if(!s)break;if(n+=1,Array.isArray(s.value)){let i=Math.min(s.value.length,mt);for(let o=0;o<i;o+=1){let a=s.value[o];(l(a)||Array.isArray(a))&&r.push({value:a,path:`${s.path}/${o}`})}continue}if(l(s.value))for(let[i,o]of Object.entries(s.value)){let a=`${s.path}/${It(i)}`;if(St.test(i)&&Pt(o)){let c=String(o);if(bt(i)&&xt(o))continue;if(c.length>0&&(e.push(a||"/"),e.length>=Se))break}(l(o)||Array.isArray(o))&&r.push({value:o,path:a})}}return e}function At(t){for(let e of t.keys())if(vt.has(e.toLowerCase()))return!0;return!1}function I(t,e,r,n,s){return{ruleId:"owasp-api-top10",severity:n,category:"security",message:e,exchangeIndex:t.exchange.index,operationId:t.matchedOperation?.operation.operationId,specSource:t.matchedOperation?.operation.specSource,target:r,details:s}}function Ot(t){let e=[];for(let[r,n]of t.exchange.request.query.entries())if(yt.test(r)&&(e.push({key:r,valuePreview:Rt(n)}),e.length>=ft))break;return e.length===0?[]:[I(t,"Sensitive credential-like query parameters detected","request","warning",{issueId:"API2:2023",issueTitle:"Broken Authentication",summary:"Authentication data should not be passed via query parameters because it can leak via logs, browser history, and referrers.",sensitiveQueryParams:e})]}function $t(t){let e=t.exchange.response;if(!e)return[];let r=e.headers["access-control-allow-origin"]?.trim(),n=e.headers["access-control-allow-credentials"]?.trim().toLowerCase();return r!=="*"||n!=="true"?[]:[I(t,"Insecure CORS policy: wildcard origin with credentials enabled","response","error",{issueId:"API8:2023",issueTitle:"Security Misconfiguration",summary:'Access-Control-Allow-Origin is "*" while Access-Control-Allow-Credentials is true. Browsers may expose authenticated API responses to untrusted origins.',headers:{accessControlAllowOrigin:r,accessControlAllowCredentials:n}})]}function Ct(t){let e=t.exchange.response;if(!e)return[];let r=e.headers["set-cookie"];if(!r)return[];let n=[];for(let s of ue(r)){let i=new Set(s.split(";").slice(1).map(o=>o.split("=")[0].trim().toLowerCase()));t.exchange.request.protocol==="https:"&&!i.has("secure")&&n.push(I(t,'Set-Cookie header is missing "Secure" attribute',"response","warning",{issueId:"API2:2023",issueTitle:"Broken Authentication",summary:'Session cookies over HTTPS should include "Secure" to prevent transmission over plain HTTP.',setCookiePreview:s.slice(0,200)})),i.has("httponly")||n.push(I(t,'Set-Cookie header is missing "HttpOnly" attribute',"response","warning",{issueId:"API2:2023",issueTitle:"Broken Authentication",summary:'Session cookies should include "HttpOnly" to reduce risk of token theft via client-side script access.',setCookiePreview:s.slice(0,200)})),i.has("samesite")||n.push(I(t,'Set-Cookie header is missing "SameSite" attribute',"response","info",{issueId:"API8:2023",issueTitle:"Security Misconfiguration",summary:'Set "SameSite" on session cookies to reduce CSRF risk for state-changing requests.',setCookiePreview:s.slice(0,200)}))}return n}function Et(t){let e=t.exchange.response;if(!e||e.bodyJson===void 0)return[];let r=kt(e.bodyJson);return r.length===0?[]:[I(t,"Potential sensitive data exposure in response payload","response","warning",{issueId:"API3:2019",issueTitle:"Excessive Data Exposure",summary:`Sensitive-looking fields detected in response payload: ${r.join(", ")}`,exposedPaths:r})]}function qt(t){let e=t.exchange.response;return!e||e.status>=400||t.exchange.request.method!=="GET"?[]:!e.bodyText||e.bodyText.length<gt?[]:At(t.exchange.request.query)?[]:[I(t,"Large response without pagination parameters (possible resource-consumption risk)","response","info",{issueId:"API4:2023",issueTitle:"Unrestricted Resource Consumption",summary:"A large response was returned without common pagination query parameters. Consider explicit page/limit controls for large collections.",responseBytes:e.bodyText.length})]}var M=class{id="owasp-api-top10";analyze(e){return e.matchedOperation?[...Ot(e),...$t(e),...Ct(e),...Et(e),...qt(e)]:[]}};var we=200;function Re(t){return t!==void 0&&t!==""}function Tt(t){if(!t)return{};let e={};for(let r of t.split(";")){let[n,...s]=r.trim().split("=");if(!n)continue;let i=s.join("=").trim();e[n]=i}return e}function Ft(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function Mt(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}function jt(t){return!t||t==="#"?"":t.startsWith("#")?t.slice(1):t}function N(t){let e=jt(t);return!e||e==="/"?[]:e.split("/").slice(1).map(r=>Ft(r))}function Ie(t,e){return`/${[...N(t),Mt(e)].join("/")}`}function Bt(t,e){let r=N(e),n=t;for(let s of r){if(Array.isArray(n)){let i=Number.parseInt(s,10);if(!Number.isInteger(i)||i<0||i>=n.length)return;n=n[i];continue}if(!l(n))return;n=n[s]}return n}function z(t){let e=t.instancePath??"",r=t.params??{};return t.keyword==="required"&&typeof r.missingProperty=="string"?Ie(e,r.missingProperty):t.keyword==="additionalProperties"&&typeof r.additionalProperty=="string"?Ie(e,r.additionalProperty):e}function Lt(t){let e=N(t);if(e.length===0)return"root";let r=[];for(let n of e)/^\d+$/.test(n)?r.push(`[${n}]`):r.length===0?r.push(n):r.push(`.${n}`);return r.join("")}function _t(t){if(t===void 0)return"[missing]";let e=JSON.stringify(t);return e?e.length>we?`${e.slice(0,we)}\u2026`:e:String(t)}function Ht(t){let e=t.params??{};if(t.keyword==="required"&&typeof e.missingProperty=="string")return`required field "${e.missingProperty}"`;if(t.keyword==="type"&&typeof e.type=="string")return`type "${e.type}"`;if(t.keyword==="additionalProperties")return"no additional undocumented properties";if(t.keyword==="format"&&typeof e.format=="string")return`format "${e.format}"`}function Vt(t,e,r){let n=t==="request"?"Request":"Response",s=e.params??{},i=Lt(r);return e.keyword==="required"&&typeof s.missingProperty=="string"?`${n} is missing required field "${i}".`:e.keyword==="additionalProperties"&&typeof s.additionalProperty=="string"?`${n} has undocumented field "${i}".`:e.keyword==="type"&&typeof s.type=="string"?`${n} field "${i}" must be ${s.type}.`:e.keyword==="enum"?`${n} field "${i}" has a value outside allowed enum values.`:e.keyword==="format"&&typeof s.format=="string"?`${n} field "${i}" does not match format "${s.format}".`:`${n} schema mismatch at "${i}": ${e.message??"validation error"}`}function be(t,e,r){let n=z(e),s=Bt(t,n);return{summary:Vt(r,e,n),keyword:e.keyword??null,path:n||"/",expected:Ht(e)??null,actual:_t(s),suggestion:null,params:e.params??{},ajvMessage:e.message??"validation error"}}function Nt(t,e,r,n){if(e==null||!t.schema)return;let s=r.validateSchema(t.schema,e,{coerce:!0});if(!s.valid)for(let i of s.errors){let o=be(e,i,"request");n.push({ruleId:"schema-consistency",severity:"error",category:"schema",message:`Invalid ${t.in} parameter "${t.name}": ${typeof o.summary=="string"?o.summary:i.message??"schema mismatch"}`,exchangeIndex:r.exchange.index,operationId:r.matchedOperation?.operation.operationId,specSource:r.matchedOperation?.operation.specSource,target:"request",schemaPath:i.schemaPath,dataPath:z(i),details:{...o,parameter:{name:t.name,in:t.in}}})}}var zt=/^([^[\]]+)\[([^[\]]+)\]$/;function xe(t){let e=t.match(zt);return e?{parameterName:e[1],property:e[2]}:void 0}function Dt(t,e){let r;for(let[n,s]of e){let i=xe(n);i?.parameterName===t&&(r??={},r[i.property]=s)}return r}function Kt(t,e,r){switch(t.in){case"path":return e.matchedOperation?.pathParams[t.name];case"query":{if(t.style==="deepObject")return Dt(t.name,e.exchange.request.query);let n=e.exchange.request.query.getAll(t.name);return n.length===0?void 0:(l(t.schema)?t.schema.type:void 0)==="array"||n.length>1?n:n[0]}case"header":return e.exchange.request.headers[t.name.toLowerCase()];case"cookie":return r[t.name];default:return}}function Ut(t,e){let r=[],n={query:new Set,header:new Set,cookie:new Set},s=new Set;for(let i of e.operation.requestParameters)i.in==="header"?n.header.add(i.name.toLowerCase()):(i.in==="query"||i.in==="cookie")&&(n[i.in].add(i.name),i.in==="query"&&i.style==="deepObject"&&s.add(i.name));for(let i of new Set(t.exchange.request.query.keys())){if(n.query.has(i))continue;let o=xe(i);o&&s.has(o.parameterName)||r.push({ruleId:"schema-consistency",severity:"warning",category:"documentation",message:`Undocumented query parameter in traffic: "${i}"`,exchangeIndex:t.exchange.index,operationId:e.operation.operationId,specSource:e.operation.specSource,target:"request"})}for(let i of Object.keys(t.exchange.request.headers))le(i,t.ignoreHeaders)||n.header.has(i.toLowerCase())||r.push({ruleId:"schema-consistency",severity:"info",category:"documentation",message:`Undocumented header in traffic: "${i}"`,exchangeIndex:t.exchange.index,operationId:e.operation.operationId,specSource:e.operation.specSource,target:"request"});return r}function Gt(t){let e=t.exchange.response;return e!==void 0&&e.status>=400&&e.status<500}function Wt(t,e){let r=t.exchange.response;if(!r)return;let n=String(r.status),s=`${Math.floor(r.status/100)}XX`,i=e.operation.responseBodyContent[n]??e.operation.responseBodyContent[s]??e.operation.responseBodyContent[s.toLowerCase()]??e.operation.responseBodyContent.default;if(i)return V(i,r.contentType)}function Pe(t,e,r,n){let s=r.validateSchema(t,e,{target:n});return s.valid?[]:s.errors.map(i=>{let o=be(e,i,n);return{ruleId:"schema-consistency",severity:"error",category:"schema",message:typeof o.summary=="string"?o.summary:`Schema mismatch (${n}): ${i.message??"validation error"}`,exchangeIndex:r.exchange.index,operationId:r.matchedOperation?.operation.operationId,specSource:r.matchedOperation?.operation.specSource,target:n,schemaPath:i.schemaPath,dataPath:z(i),details:o}})}var j=class{id="schema-consistency";analyze(e){let r=e.matchedOperation;if(!r)return[];let n=[],s=Tt(e.exchange.request.headers.cookie);if(n.push(...Ut(e,r)),!Gt(e)){for(let p of r.operation.requestParameters){if(e.ignoreCookies&&p.in==="cookie")continue;let u=Kt(p,e,s);if(p.required&&u==null){n.push({ruleId:this.id,severity:"error",category:"documentation",message:`Missing required ${p.in} parameter: "${p.name}"`,exchangeIndex:e.exchange.index,operationId:r.operation.operationId,specSource:r.operation.specSource,target:"request"});continue}Nt(p,u,e,n)}let o=e.exchange.request.contentType,a=V(r.operation.requestBodyContent,o),c=Re(e.exchange.request.bodyText);r.operation.requestBodyRequired&&!c&&n.push({ruleId:this.id,severity:"error",category:"documentation",message:"Missing required request body",exchangeIndex:e.exchange.index,operationId:r.operation.operationId,specSource:r.operation.specSource,target:"request"}),a&&c&&H(o)&&(e.exchange.request.bodyJson===void 0?n.push({ruleId:this.id,severity:"error",category:"schema",message:"Request body is not valid JSON for JSON content-type",exchangeIndex:e.exchange.index,operationId:r.operation.operationId,specSource:r.operation.specSource,target:"request"}):n.push(...Pe(a,e.exchange.request.bodyJson,e,"request")))}let i=Wt(e,r);if(i&&e.exchange.response&&Re(e.exchange.response.bodyText)){let o=e.exchange.response.contentType;H(o)&&(e.exchange.response.bodyJson===void 0?n.push({ruleId:this.id,severity:"error",category:"schema",message:"Response body is not valid JSON for JSON content-type",exchangeIndex:e.exchange.index,operationId:r.operation.operationId,specSource:r.operation.specSource,target:"response"}):n.push(...Pe(i,e.exchange.response.bodyJson,e,"response")))}return n}};function D(t){if(!t)return null;let[e]=t.trim().split(/\s+/,1);return e?e.toLowerCase():null}function Ae(t){return!!t.exchange.request.headers.authorization}function Jt(t,e){return t?t.split(";").map(r=>r.trim()).some(r=>r.startsWith(`${e}=`)):!1}function Yt(t,e){let r=t.matchedOperation?.operation;if(!r)return{schemeName:e,schemeType:"unknown",satisfied:!0,reason:"No matched OpenAPI operation."};let n=r.securitySchemes[e];if(!n)return{schemeName:e,schemeType:"missing",satisfied:!1,reason:"Security scheme is referenced but not defined in components.securitySchemes."};let s=String(n.type??"unknown");if(n.type==="apiKey"){let i=String(n.name??""),o=String(n.in??"header");if(!i)return{schemeName:e,schemeType:s,satisfied:!1,reason:'apiKey scheme is missing the "name" field in the OpenAPI spec.'};if(o==="header"){let a=!!t.exchange.request.headers[i.toLowerCase()];return{schemeName:e,schemeType:s,satisfied:a,reason:a?`Found required apiKey header "${i}".`:`Missing required apiKey header "${i}".`}}if(o==="query"){let a=t.exchange.request.query.has(i);return{schemeName:e,schemeType:s,satisfied:a,reason:a?`Found required apiKey query parameter "${i}".`:`Missing required apiKey query parameter "${i}".`}}if(o==="cookie"){if(t.ignoreCookies)return{schemeName:e,schemeType:s,satisfied:!0,skipped:!0,reason:`Skipped apiKey cookie "${i}" validation because --ignore-cookies is enabled.`};let a=Jt(t.exchange.request.headers.cookie,i);return{schemeName:e,schemeType:s,satisfied:a,reason:a?`Found required apiKey cookie "${i}".`:`Missing required apiKey cookie "${i}".`}}return{schemeName:e,schemeType:s,satisfied:!1,reason:`Unsupported apiKey location "${o}" in OpenAPI security scheme.`}}if(n.type==="http"){let i=t.exchange.request.headers.authorization;if(!i)return{schemeName:e,schemeType:s,satisfied:!1,reason:"Missing Authorization header."};let o=String(n.scheme??"").toLowerCase(),a=D(i);if(!o)return{schemeName:e,schemeType:s,satisfied:!0,reason:"Authorization header is present and no specific HTTP auth scheme is documented."};if(!a)return{schemeName:e,schemeType:s,satisfied:!1,reason:"Authorization header is malformed and does not include an auth scheme."};let c=a===o;return{schemeName:e,schemeType:s,satisfied:c,reason:c?`Authorization uses expected "${o}" scheme.`:`Authorization uses "${a}" but "${o}" is required.`}}if(n.type==="oauth2"||n.type==="openIdConnect"){let i=t.exchange.request.headers.authorization;if(!i)return{schemeName:e,schemeType:s,satisfied:!1,reason:"Missing Authorization header for OAuth2/OpenID Connect scheme."};let o=D(i),a=o==="bearer";return{schemeName:e,schemeType:s,satisfied:a,reason:a?"Authorization uses bearer token as expected for OAuth2/OpenID Connect.":`Authorization scheme "${o??"unknown"}" does not satisfy OAuth2/OpenID Connect (expected bearer).`}}return n.type==="mutualTLS"?{schemeName:e,schemeType:s,satisfied:!0,reason:"mutualTLS cannot be validated from HTTP traffic logs alone."}:{schemeName:e,schemeType:s,satisfied:!1,reason:`Unsupported security scheme type "${s}".`}}function Qt(t){let e=t.matchedOperation?.operation.security;if(!e)return{satisfied:!0,requirements:[]};if(e.length===0)return{satisfied:!0,requirements:[]};let r=e.map((n,s)=>{let i=Object.keys(n);if(i.length===0)return{requirementIndex:s,satisfied:!0,schemeResults:[]};let o=i.map(a=>Yt(t,a));return{requirementIndex:s,satisfied:o.every(a=>a.satisfied),schemeResults:o}});return{satisfied:r.some(n=>n.satisfied),requirements:r}}function Xt(t){let e=[];for(let r of t.requirements)for(let n of r.schemeResults)n.satisfied||e.push({requirement:r.requirementIndex+1,schemeName:n.schemeName,reason:n.reason});return e}function ke(t){let e=[];for(let r of t.requirements)for(let n of r.schemeResults)n.skipped&&e.push({requirement:r.requirementIndex+1,schemeName:n.schemeName,reason:n.reason});return e}function Zt(t){if(t.length===0)return"All documented security requirements are satisfied.";let e=new Map;for(let n of t){let s=e.get(n.requirement);s?s.push(n):e.set(n.requirement,[n])}let r=Array.from(e.entries()).sort((n,s)=>n[0]-s[0]).map(([n,s])=>{let i=s.map(a=>a.schemeName).join(" + "),o=s.map(a=>a.reason).join(" ");return`Option ${n} (${i}): ${o}`});return r.length===1?`Authentication check failed. ${r[0]}`:`None of the documented authentication options matched. Any one of these options would satisfy the OpenAPI security requirements: ${r.join(" | ")}`}function en(t){return Array.from(t.exchange.request.query.keys()).filter(e=>{let r=e.toLowerCase();return r.includes("token")||r.includes("apikey")||r.includes("api_key")||r.includes("access_key")})}var tn=/^(?:(?:.+\.)?localhost|127(?:\.\d{1,3}){3}|::1)$/i;function nn(t){let e;try{e=new URL(t.url).hostname}catch{e=t.host?.replace(/:\d+$/,"")}return e?tn.test(e.replace(/^\[|\]$/g,"")):!1}function rn(t){if(t.exchange.request.protocol!=="http:"||!t.exchange.request.protocolKnown||nn(t.exchange.request))return{flag:!1,hasAuthHeader:!1,sensitiveQueryKeys:[]};let e=Ae(t),r=en(t);return{flag:e||r.length>0,hasAuthHeader:e,sensitiveQueryKeys:r}}var B=class{id="security-baseline";analyze(e){if(!e.matchedOperation)return[];let r=[],n=Qt(e);if(n.satisfied){let i=ke(n);i.length>0&&r.push({ruleId:this.id,severity:"info",category:"security",message:"Some documented cookie-based security checks were skipped",exchangeIndex:e.exchange.index,operationId:e.matchedOperation.operation.operationId,specSource:e.matchedOperation.operation.specSource,target:"request",details:{summary:i.map(o=>`Skipped option ${o.requirement} (${o.schemeName}): ${o.reason}`).join(" "),skippedChecks:i}})}else{let i=Xt(n);r.push({ruleId:this.id,severity:"error",category:"security",message:"Request does not satisfy documented OpenAPI security requirements",exchangeIndex:e.exchange.index,operationId:e.matchedOperation.operation.operationId,specSource:e.matchedOperation.operation.specSource,target:"request",details:{summary:Zt(i),failedChecks:i,skippedChecks:ke(n),authorizationScheme:D(e.exchange.request.headers.authorization),hasAuthorizationHeader:Ae(e)}})}let s=rn(e);return s.flag&&r.push({ruleId:this.id,severity:"warning",category:"security",message:"Potential credential exposure over insecure HTTP transport",exchangeIndex:e.exchange.index,operationId:e.matchedOperation.operation.operationId,specSource:e.matchedOperation.operation.specSource,target:"request",details:{protocol:e.exchange.request.protocol,hasAuthorizationHeader:s.hasAuthHeader,sensitiveQueryKeys:s.sensitiveQueryKeys}}),r}};var L=class{id="undocumented-endpoint";analyze(e){if(e.matchedOperation)return[];let{method:r,path:n,host:s}=e.exchange.request,o=e.matchMode==="strict-host"&&!e.hostCompatibleWithSpecServers?`Undocumented server: ${r} ${n} was sent to "${s}", which does not match any server in the description`:`Undocumented endpoint: ${r} ${n}`;return[{ruleId:this.id,severity:"error",category:"documentation",message:o,exchangeIndex:e.exchange.index,target:"request"}]}};var K={"undocumented-endpoint":()=>new L,"schema-consistency":()=>new j,"security-baseline":()=>new B,"owasp-api-top10":()=>new M},sn=Object.keys(K),on=["undocumented-endpoint","schema-consistency","security-baseline"];function Oe(t){return!t||t.length===0?on.map(e=>K[e]()):[...new Set(t)].map(e=>{let r=K[e];if(!r)throw new Error(`Unknown rule id: "${e}". Available rules: ${sn.join(", ")}`);return r()})}var Ee=J(We(),1);var qe=J(Je(),1),$e=Ee.default,Ce=qe.default;function an(t,e){return l(t)?e==="request"?t.readOnly===!0:t.writeOnly===!0:!1}function Te(t,e,r,n=new WeakSet){if(!l(t)||n.has(t))return!1;n.add(t);let s=t.properties;return l(s)&&an(s[e],r)?!0:[t.allOf,t.oneOf,t.anyOf].some(i=>Array.isArray(i)&&i.some(o=>Te(o,e,r,n)))}var un=new Set(["items","additionalItems","additionalProperties","unevaluatedItems","unevaluatedProperties","contains","propertyNames","not","if","then","else"]),cn=new Set(["allOf","anyOf","oneOf","prefixItems"]),dn=new Set(["properties","patternProperties","dependentSchemas","$defs","definitions"]);function Fe(t,e,r=new WeakSet){if(!l(t))return t;if(r.has(t))return!0;r.add(t);let n=i=>Fe(i,e,r),s={};for(let[i,o]of Object.entries(t))un.has(i)?s[i]=Array.isArray(o)?o.map(n):n(o):cn.has(i)&&Array.isArray(o)?s[i]=o.map(n):dn.has(i)&&l(o)?s[i]=Object.fromEntries(Object.entries(o).map(([a,c])=>[a,n(c)])):s[i]=o;return Array.isArray(t.required)&&(s.required=t.required.filter(i=>typeof i!="string"||!Te(t,i,e))),r.delete(t),s}var E=class{ajv;fallbackAjv;objectSchemaCaches={none:new WeakMap,request:new WeakMap,response:new WeakMap};scalarSchemaCache=new Map;constructor(e){let r={strict:!1,allErrors:!0,allowUnionTypes:!0,discriminator:!0,coerceTypes:e?.coerceTypes?"array":!1,validateFormats:!0,verbose:!0,formats:{enum:!0}};this.ajv=new $e(r),this.fallbackAjv=new $e({...r,discriminator:!1}),Ce(this.ajv),Ce(this.fallbackAjv)}validate(e,r,n){if(e===void 0)return{valid:!0,errors:[]};let s;try{s=this.getOrCompileValidator(e,n)}catch(a){return{valid:!1,errors:[{message:`Schema compilation failed: ${a.message}`}]}}let i=!!s(r),o=s.errors??[];return{valid:i,errors:o}}getOrCompileValidator(e,r){if(l(e)){let o=this.objectSchemaCaches[r??"none"],a=o.get(e);if(a)return a;let c=r?Fe(e,r):e,p=this.compileSchema(c);return o.set(e,p),p}let n=`${r??"none"}:${JSON.stringify(e)}`,s=this.scalarSchemaCache.get(n);if(s)return s;let i=this.compileSchema(e);return this.scalarSchemaCache.set(n,i),i}compileSchema(e){try{return this.ajv.compile(e)}catch{return this.fallbackAjv.compile(e)}}};var pn=10,Me={info:0,warning:1,error:2};function ln(){return{totalExchanges:0,documentedExchanges:0,undocumentedExchanges:0,skippedExchanges:0,hostCompatibleExchanges:0,findingsBySeverity:{info:0,warning:0,error:0},findingsByRule:{}}}function hn(t,e){t.findingsBySeverity[e.severity]+=1,t.findingsByRule[e.ruleId]=(t.findingsByRule[e.ruleId]??0)+1}function mn(t,e){return{...t,id:Be(),method:e.request.method,url:e.request.url,path:e.request.path,status:e.response?.status}}function fn(t,e){return{exchangeIndex:t.exchangeIndex,ruleId:t.ruleId,severity:t.severity,category:t.category,message:t.message,occurrences:1,operationId:t.operationId,specSource:t.specSource,target:t.target,schemaPath:t.schemaPath,dataPath:t.dataPath,details:t.details,method:e.request.method,url:e.request.url,path:e.request.path,status:e.response?.status}}function gn(t,e){if(!e)return;t.operationId||(t.operationId=e.operation.operationId),t.specSource||(t.specSource=e.operation.specSource);let r=t.details??{};if(!l(r)){t.details={operationPathTemplate:e.operation.pathTemplate};return}typeof r.operationPathTemplate!="string"&&(r.operationPathTemplate=e.operation.pathTemplate),t.details=r}function yn(t){let e=new Set,r=!1;for(let n of t.operationsByMethod.values())for(let s of n)for(let i of s.servers)i.host?e.add(i.host):r=!0;return{specServerHosts:e,hasHostlessSpecServer:r}}async function Sn(t,e){let r=[];for(let n of t)try{let s=await n.analyze(e);s.length>0&&r.push(...s)}catch(s){w.warn(`Rule "${n.id}" failed to execute: ${s.message}
18
+ `)}return r}var je=class t{startedAt=Date.now();runId=Be();previewLimit;rules;schemaValidator=new E;coercingSchemaValidator=new E({coerceTypes:!0});options;counters=ln();findings=[];previewFindings=[];problemGroupsByRule={};problemKeyStats=new Map;totalProblemGroups=0;server;ignoreHeaders;minSeverityRank;specServerHosts;hasHostlessSpecServer;constructor(e,r){this.options=e,this.rules=r,this.server=he(e.server),this.ignoreHeaders=e.ignoreHeaders?pe(e.ignoreHeaders):void 0;let{specServerHosts:n,hasHostlessSpecServer:s}=yn(e.openApiIndex);this.specServerHosts=n,this.hasHostlessSpecServer=s,this.minSeverityRank=Me[e.minSeverity??"info"],this.previewLimit=e.previewFindingsLimit&&e.previewFindingsLimit>0?e.previewFindingsLimit:pn}static create(e){if(e.openApiIndex.loadedOperations===0)throw new Error("No OpenAPI operations available to validate traffic against.");return new t(e,Oe(e.activeRules))}async process(e){this.counters.totalExchanges+=1;let r;if(this.server!==void 0&&(r=me(e.request,this.server),r===void 0))return this.counters.skippedExchanges+=1,[];let n=this.isHostCompatible(e.request.host);n&&(this.counters.hostCompatibleExchanges+=1);let s=ye(this.options.openApiIndex,e,this.options.matchMode,r);s?this.counters.documentedExchanges+=1:this.counters.undocumentedExchanges+=1;let i=await Sn(this.rules,{exchange:e,matchedOperation:s,matchMode:this.options.matchMode,hostCompatibleWithSpecServers:r!==void 0||n,ignoreCookies:this.options.ignoreCookies??!1,ignoreHeaders:this.ignoreHeaders,validateSchema:(a,c,p)=>p?.coerce?this.coercingSchemaValidator.validate(a,c,p?.target):this.schemaValidator.validate(a,c,p?.target)}),o=[];for(let a of i){if(Me[a.severity]<this.minSeverityRank)continue;gn(a,s);let c=mn(a,e);this.findings.push(c),o.push(c),hn(this.counters,a);let p=T({ruleId:a.ruleId,severity:a.severity,message:a.message,operationId:a.operationId,path:e.request.path,target:a.target,schemaPath:a.schemaPath}),u=this.problemKeyStats.get(p);if(u){u.occurrences+=1,u.previewIndex!==null&&(this.previewFindings[u.previewIndex].occurrences=u.occurrences);continue}if(this.totalProblemGroups+=1,this.problemGroupsByRule[a.ruleId]=(this.problemGroupsByRule[a.ruleId]??0)+1,this.previewFindings.length<this.previewLimit){let m=this.previewFindings.length;this.previewFindings.push(fn(a,e)),this.problemKeyStats.set(p,{occurrences:1,previewIndex:m});continue}this.problemKeyStats.set(p,{occurrences:1,previewIndex:null})}return o}isHostCompatible(e){return!e||this.hasHostlessSpecServer||this.specServerHosts.has(e.toLowerCase())}finalize(){let e={runId:this.runId,totalExchanges:this.counters.totalExchanges,documentedExchanges:this.counters.documentedExchanges,undocumentedExchanges:this.counters.undocumentedExchanges,skippedExchanges:this.counters.skippedExchanges,hostCompatibleExchanges:this.counters.hostCompatibleExchanges,findingsBySeverity:this.counters.findingsBySeverity,findingsByRule:this.counters.findingsByRule,problemGroupsByRule:this.problemGroupsByRule,totalProblemGroups:this.totalProblemGroups,durationMs:Date.now()-this.startedAt,previewFindings:this.previewFindings,previewLimit:this.previewLimit,previewTruncated:this.totalProblemGroups>this.previewFindings.length};return{runId:this.runId,summary:e,findings:this.findings}}};import{stat as vn}from"node:fs/promises";function _(t,e){let r=t.replace(/\{([^}]+)\}/g,(i,o)=>{let a=e?.[o];return a?.default!==void 0?String(a.default):Array.isArray(a?.enum)&&a.enum.length>0?String(a.enum[0]):""}),n=ce(r),s=!!(n.host&&!ae(n.host));return{rawUrl:t,protocol:s?n.protocol:void 0,host:s?n.host.toLowerCase():void 0,basePath:b(n.pathname||"/")}}function Le(t){return t?t.startsWith("/")?t:`/${t}`:"/"}var wn=["get","put","post","delete","patch","head","options","trace"],Rn=new Set(["query","header","path","cookie"]);function In(t){return wn.includes(t)}function Pn(t){return Rn.has(t)}function _e(t){if(!Array.isArray(t))return[];let e=[];for(let r of t){if(!l(r))continue;let n=r.in;typeof n!="string"||!Pn(n)||e.push({name:String(r.name??""),in:n,required:!!r.required||n==="path",style:typeof r.style=="string"?r.style:void 0,schema:r.schema})}return e}function He(t){let e=t.in==="header";return`${t.in}:${e?t.name.toLowerCase():t.name}`}function bn(t,e){let r=new Map;for(let n of t)r.set(He(n),n);for(let n of e)r.set(He(n),n);return Array.from(r.values())}function Ne(t){let e={};if(!l(t))return e;for(let[r,n]of Object.entries(t))l(n)&&"schema"in n&&(e[r.toLowerCase()]=n.schema);return e}function xn(t){return l(t)?Ne(t.content):{}}function kn(t){if(!l(t))return{};let e={};for(let[r,n]of Object.entries(t))!l(n)||!("content"in n)||(e[r]=Ne(n.content));return e}function An(t,e,r){let n=t??e??r;return!Array.isArray(n)||n.length===0?[_("/")]:n.map(s=>{if(!l(s))return _("/");let i=typeof s.url=="string"?s.url:"/",o=l(s.variables)?s.variables:void 0;return _(i,o)})}function On(t,e,r){return r||`${t.toUpperCase()} ${e}`}function $n(t){try{let e=te(t.parsed);return ee(e)==="oas3"?e:null}catch{return null}}function Ve(t){return Array.isArray(t)?t:void 0}function Cn(t,e){let r,n,s={},i="/",o=[],a;return{Root:{enter(c){r=c.servers,n=c.security;let p=l(c.components)?c.components.securitySchemes:void 0;s=l(p)?p:{}}},Paths:{PathItem:{enter(c,p){i=Le(String(p.key)),o=_e(c.parameters),a=c.servers},Operation:{enter(c,p){let u=String(p.key);if(!In(u))return;let m=bn(o,_e(c.parameters)),x=de(i),q=An(c.servers,a,r),P=c.requestBody,h={operationId:On(u,i,typeof c.operationId=="string"?c.operationId:void 0),method:u,pathTemplate:i,pathRegex:x.regex,pathParams:x.params,pathScore:x.score,servers:q,requestParameters:m,requestBodyContent:xn(P),requestBodyRequired:l(P)&&!!P.required,responseBodyContent:kn(c.responses),security:Ve(c.security)??Ve(n),securitySchemes:s,specSource:t},f=e.get(u)??[];f.push(h),e.set(u,f)}}}}}}function En(t,e,r,n,s){let i=Y(r.extendTypes(Q(e),e),r),o=new Map,a={problems:[],specVersion:e,config:r,visitorsData:{}},c=re([{severity:"warn",ruleId:"drift-index",visitor:Cn(n,s)}],i);se({document:t,rootType:i.Root,normalizedVisitors:c,resolvedRefMap:o,ctx:a})}function qn(t){return`${t.host??""}|${t.basePath}`}function Tn(t){for(let e of t.values()){let r=new Map;for(let n of e){let s=r.get(n.pathRegex.source)??[];s.push(n),r.set(n.pathRegex.source,s)}for(let n of r.values()){let s=new Map;for(let i of n)for(let o of i.servers){let a=qn(o),c=s.get(a)??new Set;c.add(i.specSource),s.set(a,c)}for(let i of s.values())if(i.size>1){let[o]=n;w.warn(`"${o.method.toUpperCase()} ${o.pathTemplate}" is documented for the same server in multiple descriptions (${Array.from(i).join(", ")}). Matching traffic is validated against only one of them.
19
+ `);break}}}}function Fn(t,e){for(let n of t.values())n.sort((s,i)=>i.pathScore-s.pathScore);let r=Array.from(t.values()).reduce((n,s)=>n+s.length,0);return{operationsByMethod:t,loadedSpecs:e,loadedOperations:r}}async function Mn(t){return(await vn(t)).isDirectory()?{specFiles:await oe(t),fromDirectory:!0}:{specFiles:[t],fromDirectory:!1}}async function Rr(t,e){let{specFiles:r,fromDirectory:n}=await Mn(t),s=new Map,i=new ne(e.resolve),o=0;for(let a of r){let c=await i.resolveDocument(null,a,!0);if(c instanceof Error){w.warn(`Failed to load OpenAPI description ${a}: ${c.message}
20
+ `);continue}let p=$n(c);if(!p){n||w.warn(`Skipping ${a}: not an OpenAPI 3.x description.
21
+ `);continue}let u;try{let{bundle:m}=await ie({config:e,doc:c,externalRefResolver:i,dereference:!0});u=m}catch(m){w.warn(`Failed to bundle OpenAPI description ${a}: ${m.message}
22
+ `);continue}o+=1,En(u,p,e,a,s)}return o>1&&Tn(s),Fn(s,o)}function Pr(t){return t.split(",").map(e=>e.trim()).filter(Boolean)}export{Hn as a,je as b,Rr as c,Pr as d};
@@ -0,0 +1,9 @@
1
+ import { createRequire as __createRequire } from 'node:module';
2
+ import { fileURLToPath as __fileURLToPath } from 'node:url';
3
+ import { dirname as __pathDirname } from 'node:path';
4
+ const require = __createRequire(import.meta.url);
5
+ var __filename = __fileURLToPath(import.meta.url);
6
+ var __dirname = __pathDirname(__filename);
7
+ import{b as m,j as C,o as a,p,q as T,r as l,s as h,t as f,u as d}from"./F4DGJH6G.js";import{c as g}from"./QQOKWPJZ.js";import A from"node:path";function L(e,n){if(C(e)!=="application/x-www-form-urlencoded"||!Array.isArray(n))return;let o=new URLSearchParams;for(let s of n){if(!g(s))continue;let t=a(s.name);t!==void 0&&o.append(t,a(s.value)??"")}return o.size>0?o.toString():void 0}function K(e,n,o){let s=e?.request,t=e?.response;if(!s)return null;let r=s?.postData,i=a(r?.mimeType),u=r?.text??L(i,r?.params),c=a(r?.encoding),y=t?.content?.text,S=a(t?.content?.encoding),q=p(t?.status);return l({method:a(s?.method),url:a(s?.url),requestHeaders:s?.headers,requestBody:T(u,c),requestContentType:i,responseStatus:q===0?void 0:q,responseStatusText:a(t?.statusText),responseHeaders:t?.headers,responseBody:T(y,S),responseContentType:a(t?.content?.mimeType),startedAt:a(e?.startedDateTime),raw:e},n,o)}var b=class{id="har";canParse(n,o){if(A.extname(n).toLowerCase()===".har")return!0;let t=o.toLowerCase();return t.includes('"log"')&&t.includes('"entries"')}async*parse(n){let o=0;for await(let s of f(n,"log.entries")){let t=K(s,o,n);t&&(yield t),o+=1}}};import $ from"node:path";function H(e){let n=a(e.url??e.uri);if(n)return{url:n};let o=a(e.host??e.headers?.host),s=a(e.path??e.request_uri),t=a(e.scheme??e.forwarded_proto);return o&&s?{url:`${t??"http"}://${o}${s}`,schemeKnown:!!t}:{url:s,schemeKnown:!!t}}function z(e,n,o){let s=e?.request??e?.req??e?.http?.request;if(!s)return null;let t=e?.response??e?.res??e?.http?.response,r=t?.body??t?.raw_body??t?.payload??t?.data,i=s?.body??s?.raw_body??s?.payload??s?.data,{url:u,schemeKnown:c}=H(s);return l({method:a(s?.method??s?.http_method),url:u,schemeKnown:c,requestHeaders:s?.headers,requestBody:i,requestContentType:d(s?.headers),responseStatus:p(t?.status??t?.statusCode),responseHeaders:t?.headers,responseBody:r,responseContentType:d(t?.headers),startedAt:a(e?.started_at??e?.startedAt??e?.timestamp),raw:e},n,o)}var x=class{id="kong";canParse(n,o){if($.extname(n).toLowerCase()===".kong")return!0;let t=o.toLowerCase();return t.includes('"latencies"')||t.includes('"request"')&&t.includes('"response"')&&t.includes('"route"')}async*parse(n){let o=(await m(n,16)).trim().slice(0,1),s=0;if(o==="["){for await(let t of f(n)){let r=z(t,s,n);r&&(yield r),s+=1}return}for await(let t of h(n)){let r=z(t,s,n);r&&(yield r),s+=1}}};import R from"node:path";function U(e){return e?.request??e?.req??e?.httpRequest??e?.http?.request??e}function I(e){return e?.response??e?.res??e?.httpResponse??e?.http?.response}function O(e,n){let o=a(n?.url??n?.uri??n?.requestUrl??e?.url);if(o)return{url:o};let s=a(n?.host??n?.headers?.host??e?.host),t=a(n?.path??e?.path??n?.pathname),r=a(n?.scheme??e?.scheme);return s&&t?{url:`${r??"http"}://${s}${t}`,schemeKnown:!!r}:{url:t,schemeKnown:!!r}}function k(e,n,o){let s=U(e),t=I(e),r=s?.body??s?.bodyText??s?.payload??s?.data??s?.rawBody,i=t?.body??t?.bodyText??t?.payload??t?.data??t?.rawBody,{url:u,schemeKnown:c}=O(e,s);return l({method:a(s?.method??s?.httpMethod??e?.method??e?.httpMethod),url:u,schemeKnown:c,requestHeaders:s?.headers,requestBody:r,requestContentType:d(s?.headers),responseStatus:p(t?.status??t?.statusCode??e?.status??e?.statusCode),responseHeaders:t?.headers,responseBody:i,responseContentType:d(t?.headers),startedAt:a(e?.startedAt??e?.timestamp??e?.time),raw:e},n,o)}var w=class{id="ndjson";canParse(n,o){let s=R.extname(n).toLowerCase();if(s===".ndjson"||s===".jsonl"||s===".jsonlines")return!0;let t=o.lastIndexOf(`
8
+ `),i=(t===-1?o:o.slice(0,t)).split(`
9
+ `).map(u=>u.trim()).find(Boolean);if(!i?.startsWith("{")||!i.endsWith("}"))return!1;try{return JSON.parse(i),!0}catch{return!1}}async*parse(n){let o=0;for await(let s of h(n)){let t=k(s,o,n);t&&(yield t),o+=1}}};import J from"node:path";function P(e){if(!e)return{};let n=e.trim().split(/\s+/);return n.length<2?{}:{method:n[0],path:n[1],protocol:n[2]}}function W(e,n){let o=a(n?.url??n?.request_uri??n?.uri??e?.url??e?.request_url??e?.absolute_uri),s=P(a(e?.request??n?.request_line)),t=a(n?.request_uri??n?.uri??n?.path??e?.request_uri??e?.uri)??s.path;if(o?.startsWith("http://")||o?.startsWith("https://"))return{url:o};let r=a(n?.host??n?.headers?.host??e?.host??e?.http_host??e?.server_name??e?.vhost),i=a(e?.scheme??n?.scheme??e?.request_scheme),u=!!i;if(r&&(o||t)){let c=i??"http",y=o??t;return y?.startsWith("/")?{url:`${c}://${r}${y}`,schemeKnown:u}:{url:`${c}://${r}/${y}`,schemeKnown:u}}return{url:o??t,schemeKnown:u}}function E(e,n,o){let s=g(e?.request)?e.request:e,t=g(e?.response)?e.response:void 0,r=P(a(e?.request)),i=a(s?.method??s?.request_method??e?.request_method??e?.method)??r.method,{url:u,schemeKnown:c}=W(e,s);return l({method:i,url:u,schemeKnown:c,requestHeaders:s?.headers??s?.request_headers??e?.request_headers??e?.headers,requestBody:s?.body??s?.request_body??e?.request_body??e?.body,requestContentType:d(s?.headers??s?.request_headers??e?.request_headers),responseStatus:p(t?.status??t?.status_code??e?.status??e?.status_code??e?.response_status),responseHeaders:t?.headers??t?.response_headers??e?.response_headers??e?.headers_out,responseBody:t?.body??t?.response_body??e?.response_body,responseContentType:d(t?.headers??t?.response_headers??e?.response_headers),startedAt:a(e?.time_iso8601??e?.timestamp??e?.time??e?.time_local??e?.["@timestamp"]),raw:e},n,o)}async function*j(e){if((await m(e,16)).trim().slice(0,1)==="["){yield*f(e);return}for await(let o of h(e))yield o}var N=class{id="nginx-json";canParse(n,o){let s=J.extname(n).toLowerCase(),t=n.toLowerCase();if(s===".ndjson"&&t.includes("nginx"))return!0;let r=o.toLowerCase();return r.includes('"request_uri"')||r.includes('"time_iso8601"')||r.includes('"upstream_response_time"')||r.includes('"remote_addr"')}async*parse(n){let o=0;for await(let s of j(n)){let t=E(s,o,n);t&&(yield t),o+=1}}},_=class{id="apache-json";canParse(n,o){let s=J.extname(n).toLowerCase(),t=n.toLowerCase();if(s===".ndjson"&&t.includes("apache"))return!0;let r=o.toLowerCase();return r.includes('"request_method"')||r.includes('"request_uri"')||r.includes('"vhost"')||r.includes('"response_status"')}async*parse(n){let o=0;for await(let s of j(n)){let t=E(s,o,n);t&&(yield t),o+=1}}};var B=[new b,new x,new N,new _,new w];async function le(e,n){if(n!=="auto"){let s=B.find(t=>t.id===n);if(!s)throw new Error(`Unsupported parser format: ${n}`);return s}let o=await m(e);return B.find(s=>s.canParse(e,o))}export{le as a};
@@ -0,0 +1,22 @@
1
+ import { createRequire as __createRequire } from 'node:module';
2
+ import { fileURLToPath as __fileURLToPath } from 'node:url';
3
+ import { dirname as __pathDirname } from 'node:path';
4
+ const require = __createRequire(import.meta.url);
5
+ var __filename = __fileURLToPath(import.meta.url);
6
+ var __dirname = __pathDirname(__filename);
7
+ import{c as p}from"./P26PQ2RU.js";import{a as O}from"./RS5PUOTT.js";import{a as R}from"./TXOARWFE.js";import{a as I}from"./O6MCQRCP.js";import{G as T,I as w,O as a}from"./QQOKWPJZ.js";import{e as C}from"./RFWIIJFG.js";import{Buffer as P}from"node:buffer";import y from"node:crypto";import{mkdirSync as j,existsSync as F,writeFileSync as q,readFileSync as z,rmSync as M}from"node:fs";import{homedir as H}from"node:os";import B from"node:path";var l={us:"https://app.cloud.redocly.com",eu:"https://app.cloud.eu.redocly.com"};function G(){return process.env.REDOCLY_DOMAIN||l.us}var U=D((o,e)=>{try{let t=e||o?.resolvedConfig.residency;return W(t)?l[t]:t?new URL(t).origin:o?.resolvedConfig.scorecard?.fromProjectUrl?new URL(o.resolvedConfig.scorecard.fromProjectUrl).origin:l.us}catch{throw new f}});function x(o){try{U(void 0,o)}catch{return!1}return!0}function D(o){return(...e)=>{let t=o(...e);if(!t.startsWith("https://"))throw new f;return t}}var f=class extends Error{constructor(){super("Invalid Reunite URL")}};function W(o){return typeof o=="string"&&o in l}import*as k from"node:child_process";var g=C(I(),1);var N=C(O(),1);function b(){return process.env.HTTPS_PROXY||process.env.HTTP_PROXY||process.env.http_proxy||process.env.https_proxy}function S(o){let e=process.env.NO_PROXY||process.env.no_proxy;if(!e)return!1;let t=e.split(",").map(s=>s.trim().toLowerCase()).filter(Boolean);if(t.length===0)return!1;let r;try{r=new URL(o).hostname.toLowerCase()}catch{return!1}return t.some(s=>!!(s==="*"||r===s||s.startsWith(".")&&r.endsWith(s)||!s.startsWith(".")&&r.endsWith("."+s)))}var _=async(o,{timeout:e,...t}={})=>{let r=b(),s=r&&!S(o),n,i=e?{connect:{timeout:e}}:{};return s?n=new g.ProxyAgent({uri:r,...i}):e&&(n=new g.Agent(i)),await fetch(o,{signal:e?AbortSignal.timeout(e):void 0,...t,dispatcher:n})};var c=class extends Error{constructor(t,r){super(t);this.status=r}status},h=class{constructor(e){this.command=e}command;sunsetWarnings=[];async request(e,t){let r={...t.headers,"user-agent":`redocly-cli/${R} ${this.command}`};try{let s=await _(e,{...t,headers:r});return this.collectSunsetWarning(s),s}catch(s){let n="Failed to fetch.";throw s.cause&&(n+=` Caused by ${s.cause.message||s.cause.name}.`),(s.code||s.cause?.code)&&(n+=` Code: ${s.code||s.cause?.code}`),new Error(n)}}collectSunsetWarning(e){let t=this.getSunsetDate(e);if(!t)return;let r=new Date(t);t>Date.now()?this.sunsetWarnings.push({sunsetDate:r,isSunsetExpired:!1}):this.sunsetWarnings.push({sunsetDate:r,isSunsetExpired:!0})}getSunsetDate(e){let{headers:t}=e;if(!t)return;let r=t.get("sunset")||t.get("Sunset");if(r)return Date.parse(r)}},v=class{constructor(e,t,r){this.client=e;this.domain=t;this.apiKey=r}client;domain;apiKey;async getParsedResponse(e){let t=await e.json();if(e.ok)return t;throw new c(`${t.title||e.statusText||"Unknown error"}.`,e.status)}async getDefaultBranch(e,t){try{let r=await this.client.request(`${this.domain}/api/orgs/${e}/projects/${t}/source`,{timeout:p,method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}});return(await this.getParsedResponse(r)).branchName}catch(r){let s=`Failed to fetch default branch. ${r.message}`;throw r instanceof c?new c(s,r.status):new Error(s)}}async upsert(e,t,r){try{let s=await this.client.request(`${this.domain}/api/orgs/${e}/projects/${t}/remotes`,{timeout:p,method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`},body:JSON.stringify({mountPath:r.mountPath,mountBranchName:r.mountBranchName,type:"CICD",autoMerge:!0})});return await this.getParsedResponse(s)}catch(s){let n=`Failed to upsert remote. ${s.message}`;throw s instanceof c?new c(n,s.status):new Error(n)}}async push(e,t,r,s){let n=new globalThis.FormData;n.append("remoteId",r.remoteId),n.append("commit[message]",r.commit.message),n.append("commit[author][name]",r.commit.author.name),n.append("commit[author][email]",r.commit.author.email),n.append("commit[branchName]",r.commit.branchName),r.commit.url&&n.append("commit[url]",r.commit.url),r.commit.namespace&&n.append("commit[namespaceId]",r.commit.namespace),r.commit.sha&&n.append("commit[sha]",r.commit.sha),r.commit.repository&&n.append("commit[repositoryId]",r.commit.repository),r.commit.createdAt&&n.append("commit[createdAt]",r.commit.createdAt);for(let i of s){let u=Buffer.isBuffer(i.stream)?new Blob([i.stream]):new Blob([await L(i.stream)]);n.append(`files[${i.path}]`,u,i.path)}r.isMainBranch&&n.append("isMainBranch","true");try{let i=await this.client.request(`${this.domain}/api/orgs/${e}/projects/${t}/pushes`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`},body:n});return await this.getParsedResponse(i)}catch(i){let u=`Failed to push. ${i.message}`;throw i instanceof c?new c(u,i.status):new Error(u)}}async getRemotesList({organizationId:e,projectId:t,mountPath:r}){try{let s=await this.client.request(`${this.domain}/api/orgs/${e}/projects/${t}/remotes?filter=mountPath:/${r}/`,{timeout:p,method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}});return await this.getParsedResponse(s)}catch(s){let n=`Failed to get remote list. ${s.message}`;throw s instanceof c?new c(n,s.status):new Error(n)}}async getPush({organizationId:e,projectId:t,pushId:r}){try{let s=await this.client.request(`${this.domain}/api/orgs/${e}/projects/${t}/pushes/${r}`,{timeout:p,method:"GET",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}});return await this.getParsedResponse(s)}catch(s){let n=`Failed to get push status. ${s.message}`;throw s instanceof c?new c(n,s.status):new Error(n)}}},$=class{apiClient;command;remotes;constructor({domain:e,apiKey:t,command:r}){this.command=r,this.apiClient=new h(this.command),this.remotes=new v(this.apiClient,e,t)}reportSunsetWarnings(){let e=this.apiClient.sunsetWarnings;if(e.length){let[{isSunsetExpired:t,sunsetDate:r}]=e.sort((n,i)=>n.isSunsetExpired!==i.isSunsetExpired?n.isSunsetExpired?-1:1:n.sunsetDate>i.sunsetDate?1:-1),s='Update to the latest version by running "npm install @redocly/cli@latest".';t?a.error(`The "${this.command}" command is not compatible with your version of Redocly CLI. ${s}
8
+
9
+ `):a.warn(`The "${this.command}" command will be incompatible with your version of Redocly CLI after ${r.toLocaleString()}. ${s}
10
+
11
+ `)}}};async function L(o){let e=[];for await(let t of o)e.push(t);return Buffer.concat(e)}var d=class{constructor(e){this.baseUrl=e;this.apiClient=new h("login")}baseUrl;apiClient;clientName="redocly-cli";async run(){let e=await this.getDeviceCode();a.output(`Attempting to automatically open the SSO authorization page in your default browser.
12
+ `),a.output(`If the browser does not open or you wish to use a different device to authorize this request, open the following URL:
13
+
14
+ `),a.output(w(e.verificationUri)),a.output(`
15
+
16
+ `),a.output(`Then enter the code:
17
+
18
+ `),a.output(w(e.userCode)),a.output(`
19
+
20
+ `),this.openBrowser(e.verificationUriComplete);let t=await this.pollingAccessToken(e.deviceCode,e.interval,e.expiresIn);return a.output(T(`\u2705 Logged in
21
+
22
+ `)),this.withResidency(t)}openBrowser(e){try{let t=process.platform==="win32"?`start ${e}`:process.platform==="darwin"?`open ${e}`:`xdg-open ${e}`;k.execSync(t)}catch{}}async verifyToken(e){try{return!!(await this.sendRequest("/session","GET",void 0,{Cookie:`accessToken=${e};`})).user}catch{return!1}}async verifyApiKey(e){try{return!!(await this.sendRequest("/api-keys-verify","POST",{apiKey:e})).success}catch{return!1}}async refreshToken(e){let t=await this.sendRequest("/device-rotate-token","POST",{grant_type:"refresh_token",client_name:this.clientName,refresh_token:e});if(!t.access_token)throw new Error("Failed to refresh token");return this.withResidency({access_token:t.access_token,refresh_token:t.refresh_token,expires_in:t.expires_in})}async pollingAccessToken(e,t,r){return new Promise((s,n)=>{let i=setInterval(async()=>{let m=await this.getAccessToken(e);m.access_token&&(clearInterval(i),clearTimeout(u),s(m)),m.error&&m.error!=="authorization_pending"&&(clearInterval(i),clearTimeout(u),n(m.error_description))},t*1e3),u=setTimeout(async()=>{clearInterval(i),clearTimeout(u),n("Authorization has expired. Please try again.")},r*1e3)})}async getAccessToken(e){return await this.sendRequest("/device-token","POST",{client_name:this.clientName,device_code:e,grant_type:"urn:ietf:params:oauth:grant-type:device_code"})}async getDeviceCode(){let{device_code:e,user_code:t,verification_uri:r,verification_uri_complete:s,interval:n=10,expires_in:i=300}=await this.sendRequest("/device-authorize","POST",{client_name:this.clientName});return{deviceCode:e,userCode:t,verificationUri:r,verificationUriComplete:s,interval:n,expiresIn:i}}async sendRequest(e,t="GET",r=void 0,s={}){let n=`${this.baseUrl}/api${e}`,i=await this.apiClient.request(n,{body:r&&JSON.stringify(r),method:t,headers:{"Content-Type":"application/json",...s},timeout:p});return i.status===204?{success:!0}:await i.json()}withResidency(e){return{...e,residency:this.baseUrl}}};var K="4618dbc9-8aed-4e27-aaf0-225f4603e5a4",A="aes-256-cbc",E=class{credentialsFolderPath;credentialsFilePath;credentialsFileName;key;iv;constructor(){let e=H();this.credentialsFolderPath=B.join(e,".redocly"),this.credentialsFileName="credentials",this.credentialsFilePath=B.join(this.credentialsFolderPath,this.credentialsFileName),this.key=y.createHash("sha256").update(`${this.credentialsFolderPath}${K}`).digest(),this.iv=y.createHash("md5").update(this.credentialsFolderPath).digest(),j(this.credentialsFolderPath,{recursive:!0})}async login(e){let r=await new d(e).run();if(!r)throw new Error("Failed to login. No credentials received.");this.saveCredentials(r)}async logout(){try{this.removeCredentials()}catch{}}async isAuthorized(e,t){return t?new d(e).verifyApiKey(t):!!await this.getAccessToken(e)}getAccessToken=async e=>{let t=new d(e),r=await this.readCredentials();if(!r||!x(e)||r.residency&&r.residency!==e)return null;if(await t.verifyToken(r.access_token))return r.access_token;try{let n=await t.refreshToken(r.refresh_token);return await this.saveCredentials(n),n.access_token}catch{return null}};async saveCredentials(e){try{let t=this.encryptCredentials(e);q(this.credentialsFilePath,t,"utf8")}catch(t){a.error(`Failed to save credentials: ${t.message}`)}}async readCredentials(){if(!F(this.credentialsFilePath))return null;try{let e=z(this.credentialsFilePath,"utf8");return this.decryptCredentials(e)}catch{return null}}async removeCredentials(){F(this.credentialsFilePath)&&M(this.credentialsFilePath)}encryptCredentials(e){let t=y.createCipheriv(A,this.key,this.iv);return P.concat([t.update(JSON.stringify(e),"utf8"),t.final()]).toString("hex")}decryptCredentials(e){let t=y.createDecipheriv(A,this.key,this.iv),r=P.concat([t.update(P.from(e,"hex")),t.final()]);return JSON.parse(r.toString("utf8"))}};export{G as a,U as b,b as c,S as d,_ as e,c as f,$ as g,E as h};