@redocly/cli 2.71.2 → 2.72.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/THIRD_PARTY_NOTICES +29 -7
- package/lib/chunks/{EHJ3FMW6.js → 2AW4F6ZZ.js} +1 -1
- package/lib/chunks/{3EQNI6CT.js → 2MF3MKAD.js} +1 -1
- package/lib/chunks/{UYZXI3NO.js → 2X2KHSF3.js} +1 -1
- package/lib/chunks/{YF4FMOTE.js → 3FA5W77S.js} +1 -1
- package/lib/chunks/{VPTYPV6P.js → 3FVHXIZN.js} +1 -1
- package/lib/chunks/{P5T6BIKW.js → 3N53VPSU.js} +1 -1
- package/lib/chunks/{KLGUZBJO.js → 3N73A66H.js} +1 -1
- package/lib/chunks/{JO76DPXR.js → 3WOXO2JS.js} +1 -1
- package/lib/chunks/{ORWIUECT.js → 4A5R4H5W.js} +1 -1
- package/lib/chunks/{NXREEI2S.js → 4LTPQZBP.js} +1 -1
- package/lib/chunks/{L325HIGK.js → 4QC7OVHI.js} +1 -1
- package/lib/chunks/{FDKY4PGX.js → 542GVIYM.js} +1 -1
- package/lib/chunks/5JF6EUWW.js +9 -0
- package/lib/chunks/{6X42UQ3O.js → 5MZU5MHZ.js} +1 -1
- package/lib/chunks/{DZT5NLUB.js → 5UPBGRBZ.js} +1 -1
- package/lib/chunks/{WO6IIVA3.js → 6LZX65VY.js} +8 -8
- package/lib/chunks/{NEWT5A6S.js → 6RTITFQA.js} +1 -1
- package/lib/chunks/{IQLQH23V.js → 6Y6B2SKE.js} +1 -1
- package/lib/chunks/765BYRQR.js +7 -0
- package/lib/chunks/{2TG3DP4I.js → 7NZS5HXU.js} +1 -1
- package/lib/chunks/{5CR6AOLY.js → A65OW7M7.js} +3 -3
- package/lib/chunks/ARUYNQHA.js +7 -0
- package/lib/chunks/BJ6Z66KZ.js +7 -0
- package/lib/chunks/{T77BOGYV.js → BWGBTYNU.js} +1 -1
- package/lib/chunks/{DM4EUYBB.js → BZTZIEWS.js} +2 -2
- package/lib/chunks/{4S6LRPCX.js → CBFNHKDJ.js} +1 -1
- package/lib/chunks/{OFIQ2EST.js → CYCPHJNX.js} +33 -33
- package/lib/chunks/DSBDKSRR.js +53 -0
- package/lib/chunks/E2CEKR6N.js +22 -0
- package/lib/chunks/{HRZLSSOF.js → EMWHLZB6.js} +1 -1
- package/lib/chunks/{DWXDCKZ7.js → ENIFTFYK.js} +1 -1
- package/lib/chunks/{BIS2ZFGS.js → ETJMQLWJ.js} +1 -1
- package/lib/chunks/{ADACRYTN.js → EU5WR2O3.js} +1 -1
- package/lib/chunks/{FAFMGLT6.js → FLQQ3VRQ.js} +1 -1
- package/lib/chunks/{BPJTNQBC.js → FZZACVYL.js} +1 -1
- package/lib/chunks/{N4GCIKY4.js → G7A4OE2M.js} +1 -1
- package/lib/chunks/{HP7UD4BA.js → GCAL2PYM.js} +1 -1
- package/lib/chunks/{MJ2NI6MR.js → GGHLD27S.js} +1 -1
- package/lib/chunks/{U4MI7HDM.js → GMPHU6KM.js} +1 -1
- package/lib/chunks/{HTFKP5HH.js → GWBLS542.js} +1 -1
- package/lib/chunks/{U2F3JOT2.js → GXILNSWK.js} +1 -1
- package/lib/chunks/{5AVTCY6F.js → HM7M6465.js} +1 -1
- package/lib/chunks/{5HPO77VR.js → I2JZXLJ6.js} +2 -2
- package/lib/chunks/I3YF3GEY.js +13 -0
- package/lib/chunks/{YWRFPTTI.js → IIQW437Z.js} +1 -1
- package/lib/chunks/{4H3DPQDW.js → IM4YIUUN.js} +1 -1
- package/lib/chunks/{LET2MPMU.js → JDMRVD45.js} +1 -1
- package/lib/chunks/{XVS7B4RZ.js → KIFXQTTL.js} +1 -1
- package/lib/chunks/{UVKUPD4U.js → L4VSY42B.js} +1 -1
- package/lib/chunks/LH3ONQEX.js +17 -0
- package/lib/chunks/{SSEMMWPY.js → LUNR7GV4.js} +1 -1
- package/lib/chunks/{LY6BDOEF.js → LY5MGNMA.js} +1 -1
- package/lib/chunks/{XQEXWC5L.js → MAACTVYP.js} +1 -1
- package/lib/chunks/{GFSMOHUE.js → MTKICX4T.js} +1 -1
- package/lib/chunks/{ZXOX7NF2.js → NMAWU5S4.js} +1 -1
- package/lib/chunks/{I4TK6NG7.js → PJHQKG7X.js} +1 -1
- package/lib/chunks/PTBPNZRZ.js +7 -0
- package/lib/chunks/{CZX7WE2R.js → PUZ5QSL3.js} +1 -1
- package/lib/chunks/{JRVXIEVC.js → PW2XFZOB.js} +1 -1
- package/lib/chunks/{TH44RKLO.js → QAT3DPT3.js} +1 -1
- package/lib/chunks/{QXXAC25O.js → R67IVFZH.js} +1 -1
- package/lib/chunks/RA4FAJM3.js +59 -0
- package/lib/chunks/{AZ5LIJEO.js → RF5LL2UZ.js} +1 -1
- package/lib/chunks/{JOUEVI3E.js → RQPH22PV.js} +1 -1
- package/lib/chunks/S3B562IT.js +7 -0
- package/lib/chunks/{3FR3456Q.js → S43EG4DB.js} +1 -1
- package/lib/chunks/{CER2D6ZD.js → S7VIXBKD.js} +7 -7
- package/lib/chunks/{VJZDR6KS.js → TFPMT2XD.js} +1529 -4
- package/lib/chunks/{AXGFQS75.js → U56BQ2BR.js} +2 -2
- package/lib/chunks/{KJNBOXDI.js → UOTHMCTM.js} +3 -3
- package/lib/chunks/{CR5TYFBN.js → VHZJNDWE.js} +2 -2
- package/lib/chunks/{BOTTA3HA.js → VOYPXV3Z.js} +1 -1
- package/lib/chunks/{UTEOWLD5.js → VS4MTPCM.js} +1 -1
- package/lib/chunks/{QTSECOQB.js → WEPGHS5R.js} +2 -2
- package/lib/chunks/{LKNL5LEV.js → WRKMMY3F.js} +1 -1
- package/lib/chunks/{7JS7JGWP.js → WTJ3S4D7.js} +1 -1
- package/lib/chunks/X22IMAJK.js +199 -0
- package/lib/chunks/{W7TN2XCW.js → X3FFOCXC.js} +1 -1
- package/lib/chunks/{CRJEY7P3.js → XTI7EXWX.js} +1 -1
- package/lib/chunks/{BH4FA7AH.js → YA5KTHFN.js} +1 -1
- package/lib/chunks/{Z6GFQV2Y.js → YA6D5EUI.js} +1 -1
- package/lib/chunks/{HMYFTLS7.js → ZFET6WME.js} +1 -1
- package/lib/chunks/{R32HBYOH.js → ZXB5O6JQ.js} +1 -1
- package/lib/eject-assets/AGENTS.md +1 -1
- package/lib/eject-assets/generators/cli/docs.ts +1 -1
- package/lib/eject-assets/generators/cli/engine-source.ts +1 -1
- package/lib/eject-assets/generators/cli/index.ts +2 -2
- package/lib/eject-assets/generators/cli/render.ts +1 -1
- package/lib/eject-assets/generators/go/client.ts +1 -1
- package/lib/eject-assets/generators/go/descriptor.ts +1 -1
- package/lib/eject-assets/generators/go/index.ts +2 -2
- package/lib/eject-assets/generators/go/models.ts +1 -1
- package/lib/eject-assets/generators/go/naming.ts +1 -1
- package/lib/eject-assets/generators/go/operations.ts +1 -1
- package/lib/eject-assets/generators/go/pagination.ts +1 -1
- package/lib/eject-assets/generators/go/types.ts +1 -1
- package/lib/eject-assets/generators/java/client.ts +66 -0
- package/lib/eject-assets/generators/java/descriptor.ts +72 -0
- package/lib/eject-assets/generators/java/index.ts +245 -0
- package/lib/eject-assets/generators/java/models.ts +362 -0
- package/lib/eject-assets/generators/java/naming.ts +135 -0
- package/lib/eject-assets/generators/java/operations.ts +300 -0
- package/lib/eject-assets/generators/java/pagination.ts +94 -0
- package/lib/eject-assets/generators/java/types.ts +103 -0
- package/lib/eject-assets/generators/mock/faker.ts +1 -1
- package/lib/eject-assets/generators/mock/index.ts +2 -2
- package/lib/eject-assets/generators/mock/render.ts +1 -1
- package/lib/eject-assets/generators/mock/sample.ts +1 -1
- package/lib/eject-assets/generators/mock/values.ts +1 -1
- package/lib/eject-assets/generators/php/client.ts +1 -1
- package/lib/eject-assets/generators/php/descriptor.ts +1 -1
- package/lib/eject-assets/generators/php/index.ts +2 -2
- package/lib/eject-assets/generators/php/models.ts +1 -1
- package/lib/eject-assets/generators/php/naming.ts +1 -1
- package/lib/eject-assets/generators/php/operations.ts +1 -1
- package/lib/eject-assets/generators/php/pagination.ts +1 -1
- package/lib/eject-assets/generators/php/types.ts +1 -1
- package/lib/eject-assets/generators/python/client.ts +1 -1
- package/lib/eject-assets/generators/python/descriptor.ts +1 -1
- package/lib/eject-assets/generators/python/index.ts +2 -2
- package/lib/eject-assets/generators/python/models.ts +1 -1
- package/lib/eject-assets/generators/python/naming.ts +1 -1
- package/lib/eject-assets/generators/python/operations.ts +1 -1
- package/lib/eject-assets/generators/python/pagination.ts +1 -1
- package/lib/eject-assets/generators/python/types.ts +1 -1
- package/lib/eject-assets/generators/swr/index.ts +2 -2
- package/lib/eject-assets/generators/swr/render.ts +1 -1
- package/lib/eject-assets/generators/tanstack-query/index.ts +2 -2
- package/lib/eject-assets/generators/tanstack-query/render.ts +1 -1
- package/lib/eject-assets/generators/transformers/index.ts +2 -2
- package/lib/eject-assets/generators/transformers/render.ts +1 -1
- package/lib/eject-assets/generators/typescript/banner.ts +1 -1
- package/lib/eject-assets/generators/typescript/client.ts +1 -1
- package/lib/eject-assets/generators/typescript/descriptor.ts +1 -1
- package/lib/eject-assets/generators/typescript/index.ts +2 -2
- package/lib/eject-assets/generators/typescript/inline-runtime.ts +1 -1
- package/lib/eject-assets/generators/typescript/operation-signature.ts +1 -1
- package/lib/eject-assets/generators/typescript/operation-types.ts +1 -1
- package/lib/eject-assets/generators/typescript/operations.ts +1 -1
- package/lib/eject-assets/generators/typescript/response-headers.ts +1 -1
- package/lib/eject-assets/generators/typescript/type-guards.ts +1 -1
- package/lib/eject-assets/generators/typescript/types.ts +1 -1
- package/lib/eject-assets/generators/zod/index.ts +2 -2
- package/lib/eject-assets/generators/zod/schemas.ts +1 -1
- package/lib/eject-assets/skills/client-generators/SKILL.md +1 -1
- package/lib/eject-assets/skills/java-generator/SKILL.md +161 -0
- package/lib/index.js +91 -90
- package/lib/skills/redocly-cli/SKILL.md +3 -1
- package/package.json +1 -1
- package/lib/chunks/2ZEKFWJQ.js +0 -13
- package/lib/chunks/3VOQMXIZ.js +0 -7
- package/lib/chunks/7GADNOVY.js +0 -9
- package/lib/chunks/FRQHCFKP.js +0 -199
- package/lib/chunks/J2EPFEBO.js +0 -17
- package/lib/chunks/JZATGVUO.js +0 -53
- package/lib/chunks/KNMNSDHR.js +0 -7
- package/lib/chunks/U5DIFWGH.js +0 -7
|
@@ -4,7 +4,7 @@ import { dirname as __pathDirname } from 'node:path';
|
|
|
4
4
|
const require = __createRequire(import.meta.url);
|
|
5
5
|
var __filename = __fileURLToPath(import.meta.url);
|
|
6
6
|
var __dirname = __pathDirname(__filename);
|
|
7
|
-
import{b as G}from"./VJZDR6KS.js";import{b as A,c as U,d as L,e as F,f as re,g as ie,h as se,i as ae,j as oe}from"./DM4EUYBB.js";import{a as ee,c as T,d as h,e as v,f as N,g as D,h as _,i as ne,j,k as I,l as W,n as te}from"./5CR6AOLY.js";var M=T.php,x=class extends ee{constructor(){super(" ")}typeName(n){return h(n,{style:"pascal",reserved:M})}memberName(n){return h(n,{style:"camel",reserved:M})}identifier(n){return h(n,{style:"camel",reserved:M})}identifiers(n,s){return v(n,{style:"camel",reserved:M,taken:s})}string(n){return`'${n.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}'`}literal(n){return n==null?"null":typeof n=="boolean"||typeof n=="number"?String(n):typeof n=="string"?this.string(n):Array.isArray(n)?`[${n.map(r=>this.literal(r)).join(", ")}]`:`[${Object.entries(n).map(([r,i])=>`${this.string(r)} => ${this.literal(i)}`).join(", ")}]`}comment(n){for(let s of W(n))this.line(s===""?"//":`// ${s}`);return this}doc(n,s,r=[]){let i=W(s);if(i.length===0&&r.length===0)return this;let t=i.length===0?n:`${n} \u2014 ${i.join(" ")}`;if(r.length===0)return this.line(`/** ${t} */`);this.line("/**"),this.line(` * ${t}`),this.line(" *");for(let o of r)this.line(` * ${o}`);return this.line(" */")}};var y=T.php,K=new x;function g(e){return K.typeName(e)}function k(e){return K.memberName(e)}function c(e){return K.string(e)}function ce(e){return h(e.name,{style:"camel",reserved:y})}function J(e){let n=e.services.flatMap(r=>r.operations),s=v(n.map(r=>r.name),{style:"camel",reserved:y});return new Map(n.map((r,i)=>[r.name,s[i]]))}function ye(e){return ie(e).map(s=>s.kind==="literal"?c(s.value):`$${k(s.name)}`).join(" . ")}function le(e,n){let s=n.servers??[];if(s.length===0)return;let r=new Set;e.line("/** The declared servers; variables default to the values from the description. */"),e.line("final class Servers"),e.block("{",()=>{s.forEach((i,t)=>{let o=h(i.description??`server${t+1}`,{style:"camel",reserved:y});r.has(o)&&(o=`${o}${t+1}`),r.add(o);let u=i.variables.map(a=>`string $${k(a.name)} = ${c(a.default)}`);t>0&&e.blank(),e.line(`public static function ${o}(${u.join(", ")}): string`),e.block("{",()=>{e.line(`return ${ye(i)};`)},"}")})},"}"),e.blank()}function V(e,n){let s=se(e,n).map(r=>`[${r.map(t=>t.kind==="apiKey"?`['kind' => 'apiKey', 'scheme' => ${c(t.scheme)}, 'name' => ${c(t.name)}, 'in' => ${c(t.in)}]`:`['kind' => ${c(t.kind)}, 'scheme' => ${c(t.scheme)}]`).join(", ")}]`);if(s.length!==0)return`[${s.join(", ")}]`}function O(e,n){return V(e,n)===void 0?"[]":"$op['security']"}function ue(e){return`[${[`'style' => ${c(e.style)}`,...e.param!==void 0?[`'param' => ${c(e.param)}`]:[],...e.nextCursor!==void 0?[`'nextCursor' => ${c(e.nextCursor)}`]:[],...e.hasMore!==void 0?[`'hasMore' => ${c(e.hasMore)}`]:[],...e.nextLink!==void 0?[`'nextLink' => ${c(e.nextLink)}`]:[],...e.limitParam!==void 0?[`'limitParam' => ${c(e.limitParam)}`]:[],...e.items!==void 0?[`'items' => ${c(e.items)}`]:[]].join(", ")}]`}function $e(e,n){let s=new Set;return`[${(e.successResponseHeaders??[]).map(i=>{let t=h(i.name,{style:"camel",reserved:y}),o=2;for(;s.has(t);)t=`${h(i.name,{style:"camel",reserved:y})}_${o++}`;s.add(t);let u=te(i.schema,n);return`[${c(i.name)}, ${c(t)}, ${c(u)}]`}).join(", ")}]`}function C(e,n){let s=n.schemas.find(t=>t.name===e);if(s===void 0)return"other";let r=s.schema,i=I(r);return i!==void 0&&(i.scalar==="string"||i.scalar==="integer")?"enum":(r.kind==="object"||r.kind==="intersection")&&D(r,n)!==void 0?"class":"other"}function p(e,n,s="string"){if(ne(e)){let r=p(j(e),n,s);return E(r)}switch(e.kind){case"scalar":return s==="Date"&&e.scalar==="string"&&z(e)?"\\DateTimeImmutable":{string:"string",integer:"int",number:"float",boolean:"bool"}[e.scalar];case"array":case"record":return"array";case"ref":{let r=C(e.name,n);if(r==="class"||r==="enum")return g(e.name);let i=N(e,n);if(i===void 0)return"mixed";let t=p(i,n,s);if(!(_(i,n)!==void 0)||t==="mixed"||t.split("|").includes("array"))return t;let u=t.startsWith("?")||t.endsWith("|null"),a=t.startsWith("?")?t.slice(1):t.replace(/\|null$/,"");return u?E(`${a}|array`):`${a}|array`}case"enum":return{string:"string",integer:"int",number:"float",boolean:"bool"}[e.scalar];case"literal":return typeof e.value=="string"?"string":typeof e.value=="boolean"?"bool":"float";case"omit":return g(e.base);case"union":return ge(e.members,n,s);case"null":case"object":case"intersection":case"unknown":return"mixed"}}function z(e){let n=e.metadata?.format;return n==="date"||n==="date-time"}function E(e){return e==="mixed"||e.startsWith("?")||e.endsWith("|null")?e:e.includes("|")?`${e}|null`:`?${e}`}function ge(e,n,s){let r=[];for(let i of e){if(i.kind==="null")continue;let t=p(i,n,s);if(t==="mixed")return"mixed";let o=t.startsWith("?")?t.slice(1):t;r.includes(o)||r.push(o),t.startsWith("?")&&!r.includes("null")&&r.push("null")}return r.length===0?"mixed":r.join("|")}function Q(e,n,s){if(e===void 0)return;let r=j(e);if(r.kind==="ref"){let t=N(r,n);return C(r.name,n)==="other"?Q(t,n,s):void 0}if(r.kind!=="array")return;let i=p(r.items,n,s);return i==="mixed"?void 0:i}function de(e,n){let s=n.schemas.find(r=>r.name===e);return s!==void 0&&_(s.schema,n)!==void 0}function P(e,n,s,r){let i=j(e);if(r==="Date"&&i.kind==="scalar"&&i.scalar==="string"&&z(i))return`new \\DateTimeImmutable(${n})`;if(i.kind==="omit")return P({kind:"ref",name:i.base},n,s,r);if(i.kind==="ref"){let t=C(i.name,s);if(t==="class")return`${g(i.name)}::fromArray(${n})`;if(t==="enum")return`${g(i.name)}::from(${n})`;if(de(i.name,s))return`unmarshal${g(i.name)}(${n})`;let o=N(i,s);return o===void 0?void 0:P(o,n,s,r)}if(i.kind==="array"){let t=P(i.items,"$item",s,r);return t===void 0?void 0:`array_map(static fn ($item) => ${t}, ${n})`}if(i.kind==="record"){let t=P(i.value,"$item",s,r);return t===void 0?void 0:`array_map(static fn ($item) => ${t}, ${n})`}}function H(e,n,s,r="string"){let i=j(e);if(r==="Date"&&i.kind==="scalar"&&i.scalar==="string"){if(i.metadata?.format==="date")return`${n}->format('Y-m-d')`;if(i.metadata?.format==="date-time")return`${n}->format(\\DateTimeInterface::ATOM)`}if(i.kind==="omit")return H({kind:"ref",name:i.base},n,s,r);if(i.kind==="ref"){let t=C(i.name,s);if(t==="class")return`${n}->toArray()`;if(t==="enum")return`${n}->value`;if(de(i.name,s))return`is_object(${n}) ? ${n}->toArray() : ${n}`;let o=N(i,s);return o===void 0?void 0:H(o,n,s,r)}if(i.kind==="array"||i.kind==="record"){let t=i.kind==="array"?i.items:i.value,o=H(t,"$item",s,r);return o===void 0?void 0:`array_map(static fn ($item) => ${o}, ${n})`}}function be(e,n,s,r,i,t){let o=s.map(a=>a.writeOnly?{...a,required:!1}:a),u=[...o.filter(a=>a.required),...o.filter(a=>!a.required)];e.doc(g(n),t),e.line(`final class ${g(n)}`),e.block("{",()=>{e.block("public function __construct(",()=>{for(let a of u){let l=p(a.schema,r,i);if(a.required)e.line(`public ${l} $${k(a.name)},`);else{let $=E(l);e.line(`public ${$} $${k(a.name)} = null,`)}}},") {"),e.line("}"),e.blank(),e.line("public static function fromArray(array $data): self"),e.block("{",()=>{e.block("return new self(",()=>{for(let a of u){let l=`$data[${c(a.name)}]`,$=P(a.schema,l,r,i),f=k(a.name);a.required?e.line(`${f}: ${$??l},`):$===void 0?e.line(`${f}: ${l} ?? null,`):e.line(`${f}: isset(${l}) ? ${$} : null,`)}},");")},"}"),e.blank(),e.line("public function toArray(): array"),e.block("{",()=>{e.line("$data = [];");for(let a of u){let l=`$this->${k(a.name)}`,$=H(a.schema,l,r,i)??l;a.required?e.line(`$data[${c(a.name)}] = ${$};`):e.block(`if (${l} !== null) {`,()=>{e.line(`$data[${c(a.name)}] = ${$};`)},"}")}e.line("return $data;")},"}")},"}"),e.blank()}function Y(e,n="string"){let s=new x;for(let{name:r,schema:i}of e.schemas){let t=I(i);if(t!==void 0&&(t.scalar==="string"||t.scalar==="integer")){let u=t.scalar==="string"?"string":"int";s.doc(g(r),i.description),s.line(`enum ${g(r)}: ${u}`),s.block("{",()=>{let a=v(t.values.map(l=>String(l)),{style:"pascal",reserved:y});t.values.forEach((l,$)=>{let f=typeof l=="string"?c(l):String(l);s.line(`case ${a[$]} = ${f};`)})},"}"),s.blank();continue}if(i.kind==="object"||i.kind==="intersection"){let u=D(i,e);if(u!==void 0){be(s,r,u.properties,e,n,u.description??i.description);continue}}let o=_(i,e);if(o!==void 0){let u=g(r),a=o.cases.map(l=>`${l.value} -> ${g(l.schemaName)}`).join(", ");s.line(`/** ${u} is a discriminated union (${c(o.property)}): ${a}. */`),s.line(`function unmarshal${u}(array $data): mixed`),s.block("{",()=>{s.block(`return match ($data[${c(o.property)}] ?? null) {`,()=>{for(let l of o.cases){let $={kind:"ref",name:l.schemaName},f=P($,"$data",e,n)??"$data";s.line(`${c(l.value)} => ${f},`)}s.line("default => $data,")},"};")},"}"),s.blank();continue}}return s.toString()}var fe=new Set(["post","put","patch"]),ke=["body","headers","idempotencyKey"];function me(e){return F(e)||e.requestBody!==void 0&&re(e.requestBody.contentType)}function X(e,n,s,r){let i=v([...e.pathParams,...e.queryParams].map(a=>a.name),{style:"camel",reserved:y,taken:ke}),t=e.pathParams.map((a,l)=>({php:i[l],wire:a.name,type:p(a.schema,n,r)})),o=e.queryParams.map((a,l)=>{let $=i[e.pathParams.length+l];return{php:$,wire:a.name,type:p(a.schema,n,r),value:H(a.schema,`$${$}`,n,r)??`$${$}`}}),u=[...t.map(({php:a,type:l})=>`${l} $${a}`),...s&&e.requestBody?[`${me(e)?"mixed":L(e)?"array":p(e.requestBody.schema,n,r)} $body`]:[],...o.map(({php:a,type:l})=>`${E(l)} $${a} = null`),"?array $headers = null",...s&&fe.has(e.method.toLowerCase())?["?string $idempotencyKey = null"]:[]];return{pathArgs:t,queryArgs:o,signature:u}}function Pe(e,n,s,r){e.line(`$op = self::OPERATIONS[${c(n.specName??n.name)}];`),e.line(`[$authHeaders, $query, $cookies] = resolveAuth(${O(n,s)}, $this->config->auth);`);for(let{php:t,wire:o,value:u}of r.queryArgs)e.block(`if ($${t} !== null) {`,()=>{e.line(`$query[${c(o)}] = ${u};`)},"}");let i=r.pathArgs.map(({php:t,wire:o})=>`${c(o)} => $${t}`).join(", ");e.line(`$url = buildUrl($this->config->serverUrl, $op['path'], [${i}]);`),e.line("$requestHeaders = array_merge($authHeaders, $headers ?? []);"),e.block("if ($cookies !== []) {",()=>{e.line("$requestHeaders['Cookie'] = implode('; ', $cookies);")},"}")}function Z(e,n,s,r,i,t=!1){let o=X(n,r,!0,i),u=U(n),a=A(n),l=u===void 0&&a===void 0&&n.successResponses.some(b=>b.contentType!==""),$=t?"Envelope":u!==void 0?"\\Generator":a!==void 0?p(a,r,i):l?"string":"void",f=t?`${s}WithHeaders`:s,q=t?void 0:Q(a,r,i);e.doc(f,t?`Like ${s}(), returning an Envelope with the declared response headers.`:n.summary??`${n.method.toUpperCase()} ${n.path}`,q===void 0?[]:[`@return ${q.includes("|")?`(${q})`:q}[]`]),e.line(`public function ${f}(${o.signature.join(", ")}): ${$}`),e.block("{",()=>{if(Pe(e,n,r,o),u!==void 0){let m=u.schema!==void 0&&u.schema.kind!=="unknown";e.line("$url = appendQuery($url, $query);"),e.block("$open = function (array $extraHeaders) use ($url, $requestHeaders): \\CurlHandle {",()=>{e.line("$handle = curl_init($url);"),e.line("$lines = [];"),e.block("foreach (array_merge($requestHeaders, $extraHeaders) as $name => $value) {",()=>{e.line("$lines[] = $name . ': ' . $value;")},"}"),e.line("curl_setopt($handle, CURLOPT_HTTPHEADER, $lines);"),e.line("return $handle;")},"};"),e.line(`yield from iterSse($open, ${m?"true":"false"});`);return}let b=["'operationId' => $op['id']","'method' => $op['method']","'url' => $url","'headers' => $requestHeaders","'query' => $query"];if(F(n))e.line("[$contentType, $encoded] = multipartBody($body);"),b.push("'body' => $encoded","'contentType' => $contentType");else if(n.requestBody&&me(n))b.push("'body' => binaryBody($body)",`'contentType' => ${c(n.requestBody.contentType)}`);else if(n.requestBody&&L(n))e.line("[$contentType, $encoded] = toMultipart($body);"),b.push("'body' => $encoded","'contentType' => $contentType");else if(n.requestBody){let m=H(n.requestBody.schema,"$body",r,i)??"$body";e.line(`$payload = json_encode(${m});`),b.push("'body' => $payload",`'contentType' => ${c(n.requestBody.contentType)}`)}fe.has(n.method.toLowerCase())&&n.requestBody&&b.push("'idempotencyKey' => $idempotencyKey"),e.line(`$response = send($this->config, [${b.join(", ")}]);`),e.block("if ($response['status'] >= 400) {",()=>{e.line("throw apiErrorFrom($response);")},"}");let d=l?"$response['body']":(a===void 0?void 0:P(a,"decodeJson($response)",r,i))??"decodeJson($response)";if(t){e.line(`$data = ${d};`),e.line(`return new Envelope(data: $data, headers: readEnvelopeHeaders($response, ${$e(n,r)}), status: $response['status']);`);return}if(l){e.line("return $response['body'];");return}if($==="void"){e.line("decodeJson($response);");return}e.line(`return ${d};`)},"}"),e.blank()}function pe(e,n,s,r,i,t,o,u,a){let l=X(n,r,!1,i),$=s,f=()=>{e.line(`$op = self::OPERATIONS[${c(n.specName??n.name)}];`),e.line("$base = [];");for(let{php:m,wire:S,value:w}of l.queryArgs)e.block(`if ($${m} !== null) {`,()=>{e.line(`$base[${c(S)}] = ${w};`)},"}");let d=l.pathArgs.map(({php:m,wire:S})=>`${c(S)} => $${m}`).join(", ");e.block("$call = function (array $params) use ($op, $headers): array {",()=>{e.line(`[$authHeaders, $authQuery, $cookies] = resolveAuth(${O(n,r)}, $this->config->auth);`),e.line(`$url = buildUrl($this->config->serverUrl, $op['path'], [${d}]);`),e.line("$requestHeaders = array_merge($authHeaders, $headers ?? []);"),e.block("if ($cookies !== []) {",()=>{e.line("$requestHeaders['Cookie'] = implode('; ', $cookies);")},"}"),e.line("$response = send($this->config, ['operationId' => $op['id'], 'method' => $op['method'], 'url' => $url, 'headers' => $requestHeaders, 'query' => array_merge($params, $authQuery)]);"),e.block("if ($response['status'] >= 400) {",()=>{e.line("throw apiErrorFrom($response);")},"}"),e.line("return [decodeJson($response), $response];")},"};")},q=p(A(n)??{kind:"unknown"},r,i),b=q==="mixed"?"mixed":q;e.line("/**"),e.line(` * ${$} response pages, following the pagination rule automatically.`),e.line(" *"),e.line(` * @return \\Generator<int, ${b}>`),e.line(" */"),e.line(`public function ${$}Pages(${l.signature.join(", ")}): \\Generator`),e.block("{",()=>{f(),e.block("foreach (iterPages($call, $op['pagination'], $base) as $page) {",()=>{e.line(`yield ${t??"$page"};`)},"}")},"}"),e.blank(),e.line("/**"),e.line(` * The items of every ${$} page.`),e.line(" *"),e.line(` * @return \\Generator<int, ${a}>`),e.line(" */"),e.line(`public function ${$}Items(${l.signature.join(", ")}): \\Generator`),e.block("{",()=>{f(),e.block("foreach (iterPages($call, $op['pagination'], $base) as $page) {",()=>{e.line(`$items = resolvePointer($page, ${c(u??"")});`),e.block("foreach (is_array($items) ? $items : [] as $item) {",()=>{e.line(`yield ${o??"$item"};`)},"}")},"}")},"}"),e.blank()}function Se(e){let n=e.split(`
|
|
7
|
+
import{c as G}from"./TFPMT2XD.js";import{b as A,c as U,d as L,e as F,f as re,g as ie,h as se,i as ae,j as oe}from"./BZTZIEWS.js";import{a as ee,c as T,d as h,e as v,f as N,g as D,h as _,i as ne,j,k as I,l as W,n as te}from"./A65OW7M7.js";var M=T.php,x=class extends ee{constructor(){super(" ")}typeName(n){return h(n,{style:"pascal",reserved:M})}memberName(n){return h(n,{style:"camel",reserved:M})}identifier(n){return h(n,{style:"camel",reserved:M})}identifiers(n,s){return v(n,{style:"camel",reserved:M,taken:s})}string(n){return`'${n.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}'`}literal(n){return n==null?"null":typeof n=="boolean"||typeof n=="number"?String(n):typeof n=="string"?this.string(n):Array.isArray(n)?`[${n.map(r=>this.literal(r)).join(", ")}]`:`[${Object.entries(n).map(([r,i])=>`${this.string(r)} => ${this.literal(i)}`).join(", ")}]`}comment(n){for(let s of W(n))this.line(s===""?"//":`// ${s}`);return this}doc(n,s,r=[]){let i=W(s);if(i.length===0&&r.length===0)return this;let t=i.length===0?n:`${n} \u2014 ${i.join(" ")}`;if(r.length===0)return this.line(`/** ${t} */`);this.line("/**"),this.line(` * ${t}`),this.line(" *");for(let o of r)this.line(` * ${o}`);return this.line(" */")}};var y=T.php,K=new x;function g(e){return K.typeName(e)}function k(e){return K.memberName(e)}function c(e){return K.string(e)}function ce(e){return h(e.name,{style:"camel",reserved:y})}function J(e){let n=e.services.flatMap(r=>r.operations),s=v(n.map(r=>r.name),{style:"camel",reserved:y});return new Map(n.map((r,i)=>[r.name,s[i]]))}function ye(e){return ie(e).map(s=>s.kind==="literal"?c(s.value):`$${k(s.name)}`).join(" . ")}function le(e,n){let s=n.servers??[];if(s.length===0)return;let r=new Set;e.line("/** The declared servers; variables default to the values from the description. */"),e.line("final class Servers"),e.block("{",()=>{s.forEach((i,t)=>{let o=h(i.description??`server${t+1}`,{style:"camel",reserved:y});r.has(o)&&(o=`${o}${t+1}`),r.add(o);let u=i.variables.map(a=>`string $${k(a.name)} = ${c(a.default)}`);t>0&&e.blank(),e.line(`public static function ${o}(${u.join(", ")}): string`),e.block("{",()=>{e.line(`return ${ye(i)};`)},"}")})},"}"),e.blank()}function V(e,n){let s=se(e,n).map(r=>`[${r.map(t=>t.kind==="apiKey"?`['kind' => 'apiKey', 'scheme' => ${c(t.scheme)}, 'name' => ${c(t.name)}, 'in' => ${c(t.in)}]`:`['kind' => ${c(t.kind)}, 'scheme' => ${c(t.scheme)}]`).join(", ")}]`);if(s.length!==0)return`[${s.join(", ")}]`}function O(e,n){return V(e,n)===void 0?"[]":"$op['security']"}function ue(e){return`[${[`'style' => ${c(e.style)}`,...e.param!==void 0?[`'param' => ${c(e.param)}`]:[],...e.nextCursor!==void 0?[`'nextCursor' => ${c(e.nextCursor)}`]:[],...e.hasMore!==void 0?[`'hasMore' => ${c(e.hasMore)}`]:[],...e.nextLink!==void 0?[`'nextLink' => ${c(e.nextLink)}`]:[],...e.limitParam!==void 0?[`'limitParam' => ${c(e.limitParam)}`]:[],...e.items!==void 0?[`'items' => ${c(e.items)}`]:[]].join(", ")}]`}function $e(e,n){let s=new Set;return`[${(e.successResponseHeaders??[]).map(i=>{let t=h(i.name,{style:"camel",reserved:y}),o=2;for(;s.has(t);)t=`${h(i.name,{style:"camel",reserved:y})}_${o++}`;s.add(t);let u=te(i.schema,n);return`[${c(i.name)}, ${c(t)}, ${c(u)}]`}).join(", ")}]`}function C(e,n){let s=n.schemas.find(t=>t.name===e);if(s===void 0)return"other";let r=s.schema,i=I(r);return i!==void 0&&(i.scalar==="string"||i.scalar==="integer")?"enum":(r.kind==="object"||r.kind==="intersection")&&D(r,n)!==void 0?"class":"other"}function p(e,n,s="string"){if(ne(e)){let r=p(j(e),n,s);return E(r)}switch(e.kind){case"scalar":return s==="Date"&&e.scalar==="string"&&z(e)?"\\DateTimeImmutable":{string:"string",integer:"int",number:"float",boolean:"bool"}[e.scalar];case"array":case"record":return"array";case"ref":{let r=C(e.name,n);if(r==="class"||r==="enum")return g(e.name);let i=N(e,n);if(i===void 0)return"mixed";let t=p(i,n,s);if(!(_(i,n)!==void 0)||t==="mixed"||t.split("|").includes("array"))return t;let u=t.startsWith("?")||t.endsWith("|null"),a=t.startsWith("?")?t.slice(1):t.replace(/\|null$/,"");return u?E(`${a}|array`):`${a}|array`}case"enum":return{string:"string",integer:"int",number:"float",boolean:"bool"}[e.scalar];case"literal":return typeof e.value=="string"?"string":typeof e.value=="boolean"?"bool":"float";case"omit":return g(e.base);case"union":return ge(e.members,n,s);case"null":case"object":case"intersection":case"unknown":return"mixed"}}function z(e){let n=e.metadata?.format;return n==="date"||n==="date-time"}function E(e){return e==="mixed"||e.startsWith("?")||e.endsWith("|null")?e:e.includes("|")?`${e}|null`:`?${e}`}function ge(e,n,s){let r=[];for(let i of e){if(i.kind==="null")continue;let t=p(i,n,s);if(t==="mixed")return"mixed";let o=t.startsWith("?")?t.slice(1):t;r.includes(o)||r.push(o),t.startsWith("?")&&!r.includes("null")&&r.push("null")}return r.length===0?"mixed":r.join("|")}function Q(e,n,s){if(e===void 0)return;let r=j(e);if(r.kind==="ref"){let t=N(r,n);return C(r.name,n)==="other"?Q(t,n,s):void 0}if(r.kind!=="array")return;let i=p(r.items,n,s);return i==="mixed"?void 0:i}function de(e,n){let s=n.schemas.find(r=>r.name===e);return s!==void 0&&_(s.schema,n)!==void 0}function P(e,n,s,r){let i=j(e);if(r==="Date"&&i.kind==="scalar"&&i.scalar==="string"&&z(i))return`new \\DateTimeImmutable(${n})`;if(i.kind==="omit")return P({kind:"ref",name:i.base},n,s,r);if(i.kind==="ref"){let t=C(i.name,s);if(t==="class")return`${g(i.name)}::fromArray(${n})`;if(t==="enum")return`${g(i.name)}::from(${n})`;if(de(i.name,s))return`unmarshal${g(i.name)}(${n})`;let o=N(i,s);return o===void 0?void 0:P(o,n,s,r)}if(i.kind==="array"){let t=P(i.items,"$item",s,r);return t===void 0?void 0:`array_map(static fn ($item) => ${t}, ${n})`}if(i.kind==="record"){let t=P(i.value,"$item",s,r);return t===void 0?void 0:`array_map(static fn ($item) => ${t}, ${n})`}}function H(e,n,s,r="string"){let i=j(e);if(r==="Date"&&i.kind==="scalar"&&i.scalar==="string"){if(i.metadata?.format==="date")return`${n}->format('Y-m-d')`;if(i.metadata?.format==="date-time")return`${n}->format(\\DateTimeInterface::ATOM)`}if(i.kind==="omit")return H({kind:"ref",name:i.base},n,s,r);if(i.kind==="ref"){let t=C(i.name,s);if(t==="class")return`${n}->toArray()`;if(t==="enum")return`${n}->value`;if(de(i.name,s))return`is_object(${n}) ? ${n}->toArray() : ${n}`;let o=N(i,s);return o===void 0?void 0:H(o,n,s,r)}if(i.kind==="array"||i.kind==="record"){let t=i.kind==="array"?i.items:i.value,o=H(t,"$item",s,r);return o===void 0?void 0:`array_map(static fn ($item) => ${o}, ${n})`}}function be(e,n,s,r,i,t){let o=s.map(a=>a.writeOnly?{...a,required:!1}:a),u=[...o.filter(a=>a.required),...o.filter(a=>!a.required)];e.doc(g(n),t),e.line(`final class ${g(n)}`),e.block("{",()=>{e.block("public function __construct(",()=>{for(let a of u){let l=p(a.schema,r,i);if(a.required)e.line(`public ${l} $${k(a.name)},`);else{let $=E(l);e.line(`public ${$} $${k(a.name)} = null,`)}}},") {"),e.line("}"),e.blank(),e.line("public static function fromArray(array $data): self"),e.block("{",()=>{e.block("return new self(",()=>{for(let a of u){let l=`$data[${c(a.name)}]`,$=P(a.schema,l,r,i),f=k(a.name);a.required?e.line(`${f}: ${$??l},`):$===void 0?e.line(`${f}: ${l} ?? null,`):e.line(`${f}: isset(${l}) ? ${$} : null,`)}},");")},"}"),e.blank(),e.line("public function toArray(): array"),e.block("{",()=>{e.line("$data = [];");for(let a of u){let l=`$this->${k(a.name)}`,$=H(a.schema,l,r,i)??l;a.required?e.line(`$data[${c(a.name)}] = ${$};`):e.block(`if (${l} !== null) {`,()=>{e.line(`$data[${c(a.name)}] = ${$};`)},"}")}e.line("return $data;")},"}")},"}"),e.blank()}function Y(e,n="string"){let s=new x;for(let{name:r,schema:i}of e.schemas){let t=I(i);if(t!==void 0&&(t.scalar==="string"||t.scalar==="integer")){let u=t.scalar==="string"?"string":"int";s.doc(g(r),i.description),s.line(`enum ${g(r)}: ${u}`),s.block("{",()=>{let a=v(t.values.map(l=>String(l)),{style:"pascal",reserved:y});t.values.forEach((l,$)=>{let f=typeof l=="string"?c(l):String(l);s.line(`case ${a[$]} = ${f};`)})},"}"),s.blank();continue}if(i.kind==="object"||i.kind==="intersection"){let u=D(i,e);if(u!==void 0){be(s,r,u.properties,e,n,u.description??i.description);continue}}let o=_(i,e);if(o!==void 0){let u=g(r),a=o.cases.map(l=>`${l.value} -> ${g(l.schemaName)}`).join(", ");s.line(`/** ${u} is a discriminated union (${c(o.property)}): ${a}. */`),s.line(`function unmarshal${u}(array $data): mixed`),s.block("{",()=>{s.block(`return match ($data[${c(o.property)}] ?? null) {`,()=>{for(let l of o.cases){let $={kind:"ref",name:l.schemaName},f=P($,"$data",e,n)??"$data";s.line(`${c(l.value)} => ${f},`)}s.line("default => $data,")},"};")},"}"),s.blank();continue}}return s.toString()}var fe=new Set(["post","put","patch"]),ke=["body","headers","idempotencyKey"];function me(e){return F(e)||e.requestBody!==void 0&&re(e.requestBody.contentType)}function X(e,n,s,r){let i=v([...e.pathParams,...e.queryParams].map(a=>a.name),{style:"camel",reserved:y,taken:ke}),t=e.pathParams.map((a,l)=>({php:i[l],wire:a.name,type:p(a.schema,n,r)})),o=e.queryParams.map((a,l)=>{let $=i[e.pathParams.length+l];return{php:$,wire:a.name,type:p(a.schema,n,r),value:H(a.schema,`$${$}`,n,r)??`$${$}`}}),u=[...t.map(({php:a,type:l})=>`${l} $${a}`),...s&&e.requestBody?[`${me(e)?"mixed":L(e)?"array":p(e.requestBody.schema,n,r)} $body`]:[],...o.map(({php:a,type:l})=>`${E(l)} $${a} = null`),"?array $headers = null",...s&&fe.has(e.method.toLowerCase())?["?string $idempotencyKey = null"]:[]];return{pathArgs:t,queryArgs:o,signature:u}}function Pe(e,n,s,r){e.line(`$op = self::OPERATIONS[${c(n.specName??n.name)}];`),e.line(`[$authHeaders, $query, $cookies] = resolveAuth(${O(n,s)}, $this->config->auth);`);for(let{php:t,wire:o,value:u}of r.queryArgs)e.block(`if ($${t} !== null) {`,()=>{e.line(`$query[${c(o)}] = ${u};`)},"}");let i=r.pathArgs.map(({php:t,wire:o})=>`${c(o)} => $${t}`).join(", ");e.line(`$url = buildUrl($this->config->serverUrl, $op['path'], [${i}]);`),e.line("$requestHeaders = array_merge($authHeaders, $headers ?? []);"),e.block("if ($cookies !== []) {",()=>{e.line("$requestHeaders['Cookie'] = implode('; ', $cookies);")},"}")}function Z(e,n,s,r,i,t=!1){let o=X(n,r,!0,i),u=U(n),a=A(n),l=u===void 0&&a===void 0&&n.successResponses.some(b=>b.contentType!==""),$=t?"Envelope":u!==void 0?"\\Generator":a!==void 0?p(a,r,i):l?"string":"void",f=t?`${s}WithHeaders`:s,q=t?void 0:Q(a,r,i);e.doc(f,t?`Like ${s}(), returning an Envelope with the declared response headers.`:n.summary??`${n.method.toUpperCase()} ${n.path}`,q===void 0?[]:[`@return ${q.includes("|")?`(${q})`:q}[]`]),e.line(`public function ${f}(${o.signature.join(", ")}): ${$}`),e.block("{",()=>{if(Pe(e,n,r,o),u!==void 0){let m=u.schema!==void 0&&u.schema.kind!=="unknown";e.line("$url = appendQuery($url, $query);"),e.block("$open = function (array $extraHeaders) use ($url, $requestHeaders): \\CurlHandle {",()=>{e.line("$handle = curl_init($url);"),e.line("$lines = [];"),e.block("foreach (array_merge($requestHeaders, $extraHeaders) as $name => $value) {",()=>{e.line("$lines[] = $name . ': ' . $value;")},"}"),e.line("curl_setopt($handle, CURLOPT_HTTPHEADER, $lines);"),e.line("return $handle;")},"};"),e.line(`yield from iterSse($open, ${m?"true":"false"});`);return}let b=["'operationId' => $op['id']","'method' => $op['method']","'url' => $url","'headers' => $requestHeaders","'query' => $query"];if(F(n))e.line("[$contentType, $encoded] = multipartBody($body);"),b.push("'body' => $encoded","'contentType' => $contentType");else if(n.requestBody&&me(n))b.push("'body' => binaryBody($body)",`'contentType' => ${c(n.requestBody.contentType)}`);else if(n.requestBody&&L(n))e.line("[$contentType, $encoded] = toMultipart($body);"),b.push("'body' => $encoded","'contentType' => $contentType");else if(n.requestBody){let m=H(n.requestBody.schema,"$body",r,i)??"$body";e.line(`$payload = json_encode(${m});`),b.push("'body' => $payload",`'contentType' => ${c(n.requestBody.contentType)}`)}fe.has(n.method.toLowerCase())&&n.requestBody&&b.push("'idempotencyKey' => $idempotencyKey"),e.line(`$response = send($this->config, [${b.join(", ")}]);`),e.block("if ($response['status'] >= 400) {",()=>{e.line("throw apiErrorFrom($response);")},"}");let d=l?"$response['body']":(a===void 0?void 0:P(a,"decodeJson($response)",r,i))??"decodeJson($response)";if(t){e.line(`$data = ${d};`),e.line(`return new Envelope(data: $data, headers: readEnvelopeHeaders($response, ${$e(n,r)}), status: $response['status']);`);return}if(l){e.line("return $response['body'];");return}if($==="void"){e.line("decodeJson($response);");return}e.line(`return ${d};`)},"}"),e.blank()}function pe(e,n,s,r,i,t,o,u,a){let l=X(n,r,!1,i),$=s,f=()=>{e.line(`$op = self::OPERATIONS[${c(n.specName??n.name)}];`),e.line("$base = [];");for(let{php:m,wire:S,value:w}of l.queryArgs)e.block(`if ($${m} !== null) {`,()=>{e.line(`$base[${c(S)}] = ${w};`)},"}");let d=l.pathArgs.map(({php:m,wire:S})=>`${c(S)} => $${m}`).join(", ");e.block("$call = function (array $params) use ($op, $headers): array {",()=>{e.line(`[$authHeaders, $authQuery, $cookies] = resolveAuth(${O(n,r)}, $this->config->auth);`),e.line(`$url = buildUrl($this->config->serverUrl, $op['path'], [${d}]);`),e.line("$requestHeaders = array_merge($authHeaders, $headers ?? []);"),e.block("if ($cookies !== []) {",()=>{e.line("$requestHeaders['Cookie'] = implode('; ', $cookies);")},"}"),e.line("$response = send($this->config, ['operationId' => $op['id'], 'method' => $op['method'], 'url' => $url, 'headers' => $requestHeaders, 'query' => array_merge($params, $authQuery)]);"),e.block("if ($response['status'] >= 400) {",()=>{e.line("throw apiErrorFrom($response);")},"}"),e.line("return [decodeJson($response), $response];")},"};")},q=p(A(n)??{kind:"unknown"},r,i),b=q==="mixed"?"mixed":q;e.line("/**"),e.line(` * ${$} response pages, following the pagination rule automatically.`),e.line(" *"),e.line(` * @return \\Generator<int, ${b}>`),e.line(" */"),e.line(`public function ${$}Pages(${l.signature.join(", ")}): \\Generator`),e.block("{",()=>{f(),e.block("foreach (iterPages($call, $op['pagination'], $base) as $page) {",()=>{e.line(`yield ${t??"$page"};`)},"}")},"}"),e.blank(),e.line("/**"),e.line(` * The items of every ${$} page.`),e.line(" *"),e.line(` * @return \\Generator<int, ${a}>`),e.line(" */"),e.line(`public function ${$}Items(${l.signature.join(", ")}): \\Generator`),e.block("{",()=>{f(),e.block("foreach (iterPages($call, $op['pagination'], $base) as $page) {",()=>{e.line(`$items = resolvePointer($page, ${c(u??"")});`),e.block("foreach (is_array($items) ? $items : [] as $item) {",()=>{e.line(`yield ${o??"$item"};`)},"}")},"}")},"}"),e.blank()}function Se(e){let n=e.split(`
|
|
8
8
|
`),s=0;for(let r=0;r<n.length;r++)if(n[r].trim().startsWith("namespace ")){s=r+1;break}return n.slice(s).join(`
|
|
9
9
|
`).trim()}var mn=({model:e,output:n,banner:s,emit:r,pagination:i})=>{let t=new x,o=r.dateType??"string",u=h(e.title,{style:"pascal",reserved:y});t.line("<?php"),t.blank(),t.line(`// Code generated by @redocly/client-generator (php) from ${c(e.title)} ${e.version}. DO NOT EDIT.`),t.line("// Regenerate with `redocly generate-client`. PHP >= 8.1, curl extension \u2014 zero Composer dependencies."),t.blank(),t.line("declare(strict_types=1);"),t.blank(),t.line(`namespace ${u};`),t.blank(),t.line(Y(e,o)),le(t,e),r.runtime==="module"?(t.line("// \u2500\u2500\u2500 Runtime (a real file beside this one, written by the same run) \u2500\u2500\u2500"),t.line("require_once __DIR__ . '/runtime.php';"),t.blank()):(t.line("// \u2500\u2500\u2500 Embedded runtime (@redocly/client-generator php runtime) \u2500\u2500\u2500"),t.line(Se(G)),t.blank());let a=e.services.flatMap(d=>d.operations),l=J(e),$=new Map;for(let d of a){let m=i?.get(d.name)?.spec;m!==void 0&&$.set(d.name,m)}t.doc("Client",`Client for ${e.title} (${e.version}).`),t.line("class Client"),t.block("{",()=>{t.block("public const OPERATIONS = [",()=>{for(let d of a){let m=d.specName??d.name,S=V(d,e),w=$.get(d.name),B=[`'id' => ${c(m)}`,`'method' => ${c(d.method.toUpperCase())}`,`'path' => ${c(d.path)}`,...S!==void 0?[`'security' => ${S}`]:[],...w!==void 0?[`'pagination' => ${ue(w)}`]:[]];t.line(`${c(m)} => [${B.join(", ")}],`)}},"];"),t.blank(),t.line("public function __construct(private Config $config)"),t.block("{",()=>{t.block("if ($this->config->serverUrl === '') {",()=>{t.line(`$this->config->serverUrl = ${c(r.serverUrl??e.serverUrl??"")};`)},"}")},"}"),t.blank();for(let d of a){let m=l.get(d.name);Z(t,d,m,e,o),U(d)===void 0&&(d.successResponseHeaders?.length??0)>0&&Z(t,d,m,e,o,!0);let S=$.get(d.name);if(S===void 0)continue;let w=A(d),B=w===void 0?void 0:P(w,"$page",e,o),R=ae(w,S.items,e),he=R===void 0?void 0:P(R,"$item",e,o);pe(t,d,m,e,o,B,he,S.items,R===void 0?"mixed":p(R,e,o))}},"}");let f={path:n.path.replace(/\.[^.\\/]+$/,".php"),content:t.toString()};if(r.runtime!=="module")return[f];let q=s.map(d=>`// ${d}`).join(`
|
|
10
10
|
`),b=G.replace(/^namespace .*$/m,`namespace ${u};`).replace(/^<\?php\n/,`<?php
|
|
@@ -4,7 +4,7 @@ import { dirname as __pathDirname } from 'node:path';
|
|
|
4
4
|
const require = __createRequire(import.meta.url);
|
|
5
5
|
var __filename = __fileURLToPath(import.meta.url);
|
|
6
6
|
var __dirname = __pathDirname(__filename);
|
|
7
|
-
import{a as B,e as U,g as K,h as O,k as V}from"./
|
|
7
|
+
import{a as B,e as U,g as K,h as O,k as V}from"./ZXB5O6JQ.js";import{g as F,i as L,m as q,o as J}from"./A65OW7M7.js";import{c as g}from"./X22IMAJK.js";import{join as he}from"node:path";var j=class{code;constructor(n){this.code=n}};function Y(e,n,r={}){let t=new Map(n.map(o=>[o.name,o.schema])),s=b(e,t,new Set,r.dateType??"string");return s===x?null:s}var x=Symbol("cycle");function Z(e,n){if(e.kind==="union"){for(let t of e.members){let s=Z(t,n);if(s)return s}return}if(e.kind!=="scalar")return;let r=e.metadata?.format;if(r==="binary")return new j("new Blob([])");if(n==="Date"){if(r==="date-time")return new j('new Date("2024-01-01T00:00:00Z")');if(r==="date")return new j('new Date("2024-01-01")')}}function C(e,n){let r=new Map,t=[],s=!1;for(let o of e){if(o.kind==="unknown")continue;let a=ne(o,n);if(a?.kind!=="object"){t.push(o);continue}s=!0;for(let i of a.properties){let u=H(i.schema,n,new Set),c=r.get(i.name);(c===void 0||u>=c.rank)&&r.set(i.name,{schema:i.schema,required:i.required||(c?.required??!1),writeOnly:i.writeOnly===!0||(c?.writeOnly??!1),rank:u})}}return s?{merged:{kind:"object",properties:[...r.entries()].map(([o,a])=>({name:o,schema:a.schema,required:a.required,...a.writeOnly?{writeOnly:!0}:{}}))},rest:t}:{merged:void 0,rest:t}}function ne(e,n){let r=new Set,t=e;for(;t?.kind==="ref";){if(r.has(t.name))return;r.add(t.name),t=n.get(t.name)}return t}function H(e,n,r){switch(e.kind){case"literal":return 40;case"enum":return e.values.length===1?40:30;case"union":return Math.max(0,...e.members.map(t=>H(t,n,r)))-1;case"ref":{if(r.has(e.name))return 20;let t=n.get(e.name);return t===void 0?20:H(t,n,new Set(r).add(e.name))}case"null":case"unknown":return 10;default:return 20}}function b(e,n,r,t){let s=Z(e,t);if(s)return s;let o=e.metadata,a=i=>{if(i===null)return e.kind==="null"||e.kind==="union"&&e.members.some(u=>u.kind==="null");if(e.kind==="enum")return e.values.includes(i);if(e.kind==="literal")return i===e.value;if(e.kind==="scalar"&&(e.scalar==="integer"||e.scalar==="number")&&typeof i=="number"){let{min:u,max:c,step:d}=E(e.scalar,o);return(d===void 0||Number.isInteger(Number((i/d).toPrecision(12))))&&(u===void 0||i>=u)&&(c===void 0||i<=c)}return!0};if(o?.example!==void 0&&a(o.example))return o.example;if(o?.default!==void 0&&a(o.default))return o.default;switch(e.kind){case"scalar":return te(e.scalar,o);case"array":{let i=b(e.items,n,r,t);return i===x?[]:[i]}case"object":return Object.fromEntries(e.properties.flatMap(i=>{if(A(i))return[];let u=b(i.schema,n,r,t);return u===x?i.required?[[i.name,null]]:[]:[[i.name,u]]}));case"record":{let i=b(e.value,n,r,t);return i===x?{}:{key:i}}case"enum":return e.values[0];case"literal":return e.value;case"union":{for(let i of e.members){let u=b(i,n,r,t);if(u!==x)return u}return e.members.length>0?x:null}case"intersection":{let{merged:i,rest:u}=C(e.members,n),c=u.map(m=>b(m,n,r,t)).filter(m=>m!==x);if(i){let m=b(i,n,r,t),y=g(m)?m:{};for(let k of c)g(k)&&Object.assign(y,k);return y}let d=c.filter(g);return d.length>0?d.reduce((m,y)=>Object.assign(m,y),{}):c.length>0?c[0]:{}}case"omit":{let i=n.get(e.base);if(!i)return null;let u=b(i,n,r,t);if(g(u)){let c={...u};for(let d of e.keys)delete c[d];return c}return u}case"ref":{if(r.has(e.name))return x;let i=n.get(e.name);if(!i)return null;r.add(e.name);let u=b(i,n,r,t);return r.delete(e.name),u}case"null":case"unknown":return null}}function A(e){return e.writeOnly===!0&&!e.required}function E(e,n){let r=n?.multipleOf??(e==="integer"?1:void 0),t=(u,c,d)=>Number((d(u/c)*c).toPrecision(15)),s=[],o=[];if(n?.minimum!==void 0){let u=n.minimum;s.push(r===void 0?u:t(u,r,Math.ceil))}if(n?.exclusiveMinimum!==void 0){let u=n.exclusiveMinimum;s.push(r===void 0?u+1:t(u,r,c=>Math.floor(c)+1))}if(n?.maximum!==void 0){let u=n.maximum;o.push(r===void 0?u:t(u,r,Math.floor))}if(n?.exclusiveMaximum!==void 0){let u=n.exclusiveMaximum;o.push(r===void 0?u-1:t(u,r,c=>Math.ceil(c)-1))}let a=s.length>0?Math.max(...s):void 0,i=o.length>0?Math.min(...o):void 0;if(r===void 0&&a!==void 0&&i!==void 0&&a>i){let u=Math.max(n?.minimum??-1/0,n?.exclusiveMinimum??-1/0),c=Math.min(n?.maximum??1/0,n?.exclusiveMaximum??1/0),d=(u+c)/2;return{min:d,max:d}}return{min:a,max:i,step:r}}function re(e,n){let{min:r,max:t}=E(e,n);return r!==void 0&&r>0?r:t!==void 0&&t<0?t:0}function te(e,n){if(e==="boolean")return!0;if(e==="integer"||e==="number")return re(e,n);switch(n?.format){case"email":return"user@example.com";case"uuid":return"00000000-0000-4000-8000-000000000000";case"date-time":return"2024-01-01T00:00:00Z";case"date":return"2024-01-01";case"uri":case"url":return"https://example.com";default:return"string"}}var f=e=>({kind:"expr",text:e}),p=e=>({kind:"object",entries:e});function l(e){return e.kind==="object"}function P(e,n){return l(e)?p([...e.entries,{spread:n}]):e}var G=" ";function w(e,n){switch(e.kind){case"expr":return e.text;case"wrap":return`${e.before}${w(e.value,n)}${e.after}`;case"array":{if(e.items.length===0)return"[]";let r=n+G;return`[
|
|
8
8
|
${e.items.map((s,o)=>`${r}${w(s,r)}${o===e.items.length-1?"":","}`).join(`
|
|
9
9
|
`)}
|
|
10
10
|
${n}]`}case"object":{if(e.entries.length===0)return"{}";let r=n+G;return`{
|
|
@@ -4,20 +4,20 @@ import { dirname as __pathDirname } from 'node:path';
|
|
|
4
4
|
const require = __createRequire(import.meta.url);
|
|
5
5
|
var __filename = __fileURLToPath(import.meta.url);
|
|
6
6
|
var __dirname = __pathDirname(__filename);
|
|
7
|
-
import{a as we,e as Re,f as be,g as k,h as A,i as Oe,j as Ie,k as S,l as x,m as Pe,n as ke,v as Ae,w as xe}from"./
|
|
8
|
-
`)?e:`"${e.replace(/"/g,'""')}"`}function gt(t){return Ce.isAbsolute(t)?Ce.relative(process.cwd(),t)||".":t}function yt(t){if(!t)return null;let e=t.operationPathTemplate;return typeof e=="string"&&e.length>0?e:null}function St(t){return Object.entries(t).sort((e,n)=>{let r=n[1]-e[1];return r!==0?r:e[0].localeCompare(n[0])})}function vt(t){let e=[],n=new Map;for(let r of t){let s=L({ruleId:r.ruleId,severity:r.severity,message:r.message,operationId:r.operationId,path:r.path,target:r.target,schemaPath:r.schemaPath}),i=n.get(s);if(i!==void 0){e[i].occurrences+=1;continue}n.set(s,e.length),e.push({finding:r,occurrences:1})}return e}function wt(t){let e=vt(t.findings).map(r=>({occurrences:r.occurrences,exchangeIndex:r.finding.exchangeIndex,ruleId:r.finding.ruleId,severity:r.finding.severity,category:r.finding.category,message:r.finding.message,operationId:r.finding.operationId,specSource:r.finding.specSource,target:r.finding.target,schemaPath:r.finding.schemaPath,dataPath:r.finding.dataPath,details:r.finding.details,method:r.finding.method,url:r.finding.url,path:r.finding.path,status:r.finding.status})),n={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
|
|
7
|
+
import{a as we,e as Re,f as be,g as k,h as A,i as Oe,j as Ie,k as S,l as x,m as Pe,n as ke,v as Ae,w as xe}from"./G7A4OE2M.js";import{$ as fe,A as de,M as lt,X as le,_ as ft,aa as g,ba as E,c as d,ca as me,da as q,ea as T,ga as b,ia as w,ka as R,la as he,ma as ge,na as ye,oa as Se,p as pe,ta as ve}from"./X22IMAJK.js";import{e as ce}from"./RFWIIJFG.js";import Ce from"node:path";function O(t){return t?t.trim():""}function L(t){let e=O(t.operationId)||O(t.path);return[O(t.ruleId),O(t.severity),O(t.message),e,O(t.target),O(t.schemaPath)].join("")}var N=t=>fe(b(t));function mt(t){return t==="error"?"error":t==="warning"?"warning":"note"}function ht(t){if(t==null)return"";let e=String(t);return!e.includes(",")&&!e.includes('"')&&!e.includes(`
|
|
8
|
+
`)?e:`"${e.replace(/"/g,'""')}"`}function gt(t){return Ce.isAbsolute(t)?Ce.relative(process.cwd(),t)||".":t}function yt(t){if(!t)return null;let e=t.operationPathTemplate;return typeof e=="string"&&e.length>0?e:null}function St(t){return Object.entries(t).sort((e,n)=>{let r=n[1]-e[1];return r!==0?r:e[0].localeCompare(n[0])})}function vt(t){let e=[],n=new Map;for(let r of t){let s=L({ruleId:r.ruleId,severity:r.severity,message:r.message,operationId:r.operationId,path:r.path,target:r.target,schemaPath:r.schemaPath}),i=n.get(s);if(i!==void 0){e[i].occurrences+=1;continue}n.set(s,e.length),e.push({finding:r,occurrences:1})}return e}function wt(t){let e=vt(t.findings).map(r=>({occurrences:r.occurrences,exchangeIndex:r.finding.exchangeIndex,ruleId:r.finding.ruleId,severity:r.finding.severity,category:r.finding.category,message:r.finding.message,operationId:r.finding.operationId,specSource:r.finding.specSource,target:r.finding.target,schemaPath:r.finding.schemaPath,dataPath:r.finding.dataPath,details:r.finding.details,method:r.finding.method,url:r.finding.url,path:r.finding.path,status:r.finding.status})),n={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},problems:e};return`${JSON.stringify(n,null,2)}
|
|
9
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"],n=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,...n].map(s=>s.map(ht).join(",")).join(`
|
|
10
10
|
`)}
|
|
11
11
|
`}function bt(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 n=t.findings.map(s=>{let i=s.specSource??s.url??void 0;return{ruleId:s.ruleId,level:mt(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}}}),r={$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:n}]};return`${JSON.stringify(r,null,2)}
|
|
12
|
-
`}function Ot(t){return t.findingsBySeverity.error+t.findingsBySeverity.warning+t.findingsBySeverity.info}function It(t){return t>=500?E:t>=400?q:t>=300?T:t>=200?me:w}function Pt(t,e,n){let r=(f,h)=>e?h(f):f,s=f=>f==="error"?r("\u2716",E):f==="warning"?r("\u25B2",q):r("\u25CF",T),i=f=>f==="error"?r("ERROR",E):f==="warning"?r("WARN",q):r("INFO",T),{summary:o,meta:a}=t,u=Ot(o),l=o.previewFindings.slice(0,n),c=[];if(c.push(r("\u250F\u2501 Drift Report",N)),c.push(`\u2503 Run: ${t.runId}`),c.push(`\u2503 Spec: ${a.specSource}`),c.push(`\u2503 Traffic: ${a.trafficPath}`),c.push(a.server?`\u2503 Server: ${a.server} (overrides description servers)`:`\u2503 Match mode: ${a.matchMode}`),c.push(`\u2503 Traffic format: ${a.format}${a.format==="auto"?" (auto-detect)":""}`),c.push(`\u2503 Exchanges: total=${o.totalExchanges} documented=${o.documentedExchanges} undocumented=${o.undocumentedExchanges}${o.skippedExchanges>0?` skipped=${o.skippedExchanges}`:""}`),c.push(`\u2503 Findings: total=${u} ${r(`error=${o.findingsBySeverity.error}`,E)} ${r(`warning=${o.findingsBySeverity.warning}`,q)} ${r(`info=${o.findingsBySeverity.info}`,T)}`),c.push(`\
|
|
12
|
+
`}function Ot(t){return t.findingsBySeverity.error+t.findingsBySeverity.warning+t.findingsBySeverity.info}function It(t){return t>=500?E:t>=400?q:t>=300?T:t>=200?me:w}function Pt(t,e,n){let r=(f,h)=>e?h(f):f,s=f=>f==="error"?r("\u2716",E):f==="warning"?r("\u25B2",q):r("\u25CF",T),i=f=>f==="error"?r("ERROR",E):f==="warning"?r("WARN",q):r("INFO",T),{summary:o,meta:a}=t,u=Ot(o),l=o.previewFindings.slice(0,n),c=[];if(c.push(r("\u250F\u2501 Drift Report",N)),c.push(`\u2503 Run: ${t.runId}`),c.push(`\u2503 Spec: ${a.specSource}`),c.push(`\u2503 Traffic: ${a.trafficPath}`),c.push(a.server?`\u2503 Server: ${a.server} (overrides description servers)`:`\u2503 Match mode: ${a.matchMode}`),c.push(`\u2503 Traffic format: ${a.format}${a.format==="auto"?" (auto-detect)":""}`),c.push(`\u2503 Exchanges: total=${o.totalExchanges} documented=${o.documentedExchanges} undocumented=${o.undocumentedExchanges}${o.skippedExchanges>0?` skipped=${o.skippedExchanges}`:""}`),c.push(`\u2503 Findings: total=${u} ${r(`error=${o.findingsBySeverity.error}`,E)} ${r(`warning=${o.findingsBySeverity.warning}`,q)} ${r(`info=${o.findingsBySeverity.info}`,T)}`),c.push(`\u2517 Problems: total=${o.totalProblemGroups}`),u===0)return c.push(""),c.push(r("\u2714 No findings.",b)),`${c.join(`
|
|
13
13
|
`)}
|
|
14
|
-
`;c.push(""),c.push(r(`Types (${Object.keys(o.problemGroupsByRule).length})`,N));for(let[f,h]of St(o.problemGroupsByRule)){let y=o.findingsByRule[f]??h;c.push(` ${r("\u2022",w)} ${f}: ${h} problems / ${y} findings`)}let m=new Map;for(let f of l)m.has(f.ruleId)||m.set(f.ruleId,[]),m.get(f.ruleId).push(f);let v=Array.from(m.keys()).sort((f,h)=>{let y=(o.problemGroupsByRule[h]??0)-(o.problemGroupsByRule[f]??0);return y!==0?y:f.localeCompare(h)});c.push(""),c.push(r(`Problems by type (showing first ${l.length} of ${o.totalProblemGroups})`,N));let _=0;for(let f of v){let h=m.get(f);if(!h||h.length===0)continue;let y=o.problemGroupsByRule[f]??h.length,X=o.findingsByRule[f]??y;c.push(""),c.push(`${r("\u25C9",b)} ${r(f,N)} ${r(`(${h.length} problems shown / ${y} total, ${X} findings)`,w)}`);for(let
|
|
15
|
-
`))c.push(` ${
|
|
14
|
+
`;c.push(""),c.push(r(`Types (${Object.keys(o.problemGroupsByRule).length})`,N));for(let[f,h]of St(o.problemGroupsByRule)){let y=o.findingsByRule[f]??h;c.push(` ${r("\u2022",w)} ${f}: ${h} problems / ${y} findings`)}let m=new Map;for(let f of l)m.has(f.ruleId)||m.set(f.ruleId,[]),m.get(f.ruleId).push(f);let v=Array.from(m.keys()).sort((f,h)=>{let y=(o.problemGroupsByRule[h]??0)-(o.problemGroupsByRule[f]??0);return y!==0?y:f.localeCompare(h)});c.push(""),c.push(r(`Problems by type (showing first ${l.length} of ${o.totalProblemGroups})`,N));let _=0;for(let f of v){let h=m.get(f);if(!h||h.length===0)continue;let y=o.problemGroupsByRule[f]??h.length,X=o.findingsByRule[f]??y;c.push(""),c.push(`${r("\u25C9",b)} ${r(f,N)} ${r(`(${h.length} problems shown / ${y} total, ${X} findings)`,w)}`);for(let p of h){_+=1;let oe=p.occurrences,ut=p.status!==void 0?r(String(p.status),It(p.status)):r("-",w),ct=yt(p.details)??p.path,pt=p.operationId?` ${r(p.operationId,g)}`:"";if(c.push(`${s(p.severity)} ${i(p.severity)} #${_}${oe>1?` ${r(`\xD7${oe}`,w)}`:""} ${r("\u2192",w)} ${p.message}`),c.push(` \u21B3 sample exchange=${p.exchangeIndex} ${r(p.method,b)} ${ct} (${ut})${pt}`),c.push(""),c.push(` ${r(p.url,w)}`),(p.specSource||p.schemaPath||p.dataPath)&&(c.push(""),p.specSource&&c.push(` ${r("spec:",g)} ${r(gt(p.specSource),b)}`),p.schemaPath&&c.push(` ${r("schemaPath=",g)} ${r(p.schemaPath,g)}`),p.dataPath&&c.push(` ${r("dataPath=",g)} ${r(p.dataPath,b)}`)),p.details)if(c.push(""),p.ruleId==="security-baseline"&&typeof p.details.summary=="string")c.push(` ${r("security:",g)} ${p.details.summary}`);else if(p.ruleId==="owasp-api-top10"&&typeof p.details.summary=="string"){let C=typeof p.details.issueId=="string"?p.details.issueId:null,$=typeof p.details.issueTitle=="string"?p.details.issueTitle:null;c.push(` ${r("owasp:",g)} ${p.details.summary}`),(C||$)&&c.push(` ${r("issue:",g)} ${[C,$].filter(Boolean).join(" - ")}`)}else if(p.ruleId==="schema-consistency"&&typeof p.details.summary=="string"){let C=typeof p.details.path=="string"?p.details.path:null,$=typeof p.details.expected=="string"?p.details.expected:null,ae=typeof p.details.actual=="string"?p.details.actual:null,ue=typeof p.details.suggestion=="string"?p.details.suggestion:null;if(c.push(` ${r("schema:",g)} ${p.details.summary}`),C&&c.push(` ${r("path:",g)} ${r(C,b)}`),$&&c.push(` ${r("expected:",g)} ${$}`),ae&&c.push(` ${r("actual:",g)} ${ae}`),ue){c.push(` ${r("hint:",g)}`);for(let dt of ue.split(`
|
|
15
|
+
`))c.push(` ${dt}`)}}else c.push(` ${r("details:",g)} ${JSON.stringify(p.details)}`);c.push("")}}let P=o.totalProblemGroups-l.length;return P>0?(c[c.length-1]!==""&&c.push(""),c.push(r(`\u2026 ${P} problems omitted from terminal output. Use --format json/csv/sarif for the complete export.`,w))):c[c.length-1]===""&&c.pop(),`${c.join(`
|
|
16
16
|
`)}
|
|
17
|
-
`}function an(t,e){let n=e.maxFindings??10;switch(e.format){case"json":return wt(t);case"csv":return Rt(t);case"sarif":return bt(t);case"pretty":return Pt(t,e.color??!1,n);default:throw new Error(`Unsupported report format: ${e.format}`)}}import{randomUUID as st}from"node:crypto";function kt(t,e){let n=A(t||"/")||"/",r=A(e.basePath||"/")||"/";return r==="/"?n:n===r?"/":n.startsWith(`${r}/`)?n.slice(r.length)||"/":null}function At(t,e){return!t.host||!e?!0:t.host===e.toLowerCase()}function xt(t){try{return decodeURIComponent(t)}catch{return t}}function Ct(t,e,n){let r=n==="strict-host"?e.host?20:5:0;return t.pathScore*10+r}function $e(t,e){let n={};for(let r=0;r<t.pathParams.length;r+=1){let s=t.pathParams[r],i=e[r+1];s&&i!==void 0&&(n[s]=xt(i))}return n}function $t(t,e){let n=A(e)||"/";for(let r of t){let s=r.pathRegex.exec(n);if(s)return{operation:r,pathParams:$e(r,s)}}return null}function Ee(t,e,n,r){let s=e.request.method.toLowerCase(),i=t.operationsByMethod.get(s);if(!i||i.length===0)return null;if(r!==void 0)return $t(i,r);let o=null;for(let a of i)for(let u of a.servers){if(n==="strict-host"&&!At(u,e.request.host))continue;let l=kt(e.request.path,u);if(!l)continue;let c=a.pathRegex.exec(l);if(!c)continue;let m={score:Ct(a,u,n),matched:{operation:a,pathParams:$e(a,c)}};(!o||m.score>o.score)&&(o=m)}return o?.matched??null}var qe=6,Et=2e3,qt=50,Tt=5,Ft=1e6,Mt=/(?:token|api[_-]?key|apikey|password|passwd|secret|authorization|jwt)/i,jt=/(?:password|passwd|secret|api[_-]?key|access[_-]?token|refresh[_-]?token|private[_-]?key|ssn|credit[_-]?card|card[_-]?number|cvv)/i,Bt=new Set(["page","limit","offset","cursor","per_page","perpage","size","start","after","before"]),Te=4,_t=Te*2;function Lt(t){return t.length<=_t?"***":`${t.slice(0,Te)}\u2026`}function Nt(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}function zt(t){return typeof t=="string"||typeof t=="number"}function Vt(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 Kt(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 Ht(t){if(!p(t)&&!Array.isArray(t))return[];let e=[],n=[{value:t,path:""}],r=0;for(;n.length>0&&r<Et&&e.length<qe;){let s=n.pop();if(!s)break;if(r+=1,Array.isArray(s.value)){let i=Math.min(s.value.length,qt);for(let o=0;o<i;o+=1){let a=s.value[o];(p(a)||Array.isArray(a))&&n.push({value:a,path:`${s.path}/${o}`})}continue}if(p(s.value))for(let[i,o]of Object.entries(s.value)){let a=`${s.path}/${Nt(i)}`;if(jt.test(i)&&zt(o)){let u=String(o);if(Vt(i)&&Kt(o))continue;if(u.length>0&&(e.push(a||"/"),e.length>=qe))break}(p(o)||Array.isArray(o))&&n.push({value:o,path:a})}}return e}function Dt(t){for(let e of t.keys())if(Bt.has(e.toLowerCase()))return!0;return!1}function I(t,e,n,r,s){return{ruleId:"owasp-api-top10",severity:r,category:"security",message:e,exchangeIndex:t.exchange.index,operationId:t.matchedOperation?.operation.operationId,specSource:t.matchedOperation?.operation.specSource,target:n,details:s}}function Ut(t){let e=[];for(let[n,r]of t.exchange.request.query.entries())if(Mt.test(n)&&(e.push({key:n,valuePreview:Lt(r)}),e.length>=Tt))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 Jt(t){let e=t.exchange.response;if(!e)return[];let n=e.headers["access-control-allow-origin"]?.trim(),r=e.headers["access-control-allow-credentials"]?.trim().toLowerCase();return n!=="*"||r!=="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:n,accessControlAllowCredentials:r}})]}function Gt(t){let e=t.exchange.response;if(!e)return[];let n=e.headers["set-cookie"];if(!n)return[];let r=[];for(let s of be(n)){let i=new Set(s.split(";").slice(1).map(o=>o.split("=")[0].trim().toLowerCase()));t.exchange.request.protocol==="https:"&&!i.has("secure")&&r.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")||r.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")||r.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 r}function Wt(t){let e=t.exchange.response;if(!e||e.bodyJson===void 0)return[];let n=Ht(e.bodyJson);return n.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: ${n.join(", ")}`,exposedPaths:n})]}function Qt(t){let e=t.exchange.response;return!e||e.status>=400||t.exchange.request.method!=="GET"?[]:!e.bodyText||e.bodyText.length<Ft?[]:Dt(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 z=class{id="owasp-api-top10";analyze(e){return e.matchedOperation?[...Ut(e),...Jt(e),...Gt(e),...Wt(e),...Qt(e)]:[]}};function V(t,e){let n=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]):""}),r=k(n),s=!!(r.host&&!Re(r.host));return{rawUrl:t,protocol:s?r.protocol:void 0,host:s?r.host.toLowerCase():void 0,basePath:A(r.pathname||"/")}}function Fe(t){return t?t.startsWith("/")?t:`/${t}`:"/"}function K(t,e){let n=`${Math.floor(t/100)}XX`;return[String(t),n,n.toLowerCase(),"default"].find(r=>e.includes(r))}function Me(t){if(!t)return{};let e={};for(let n of t.split(";")){let[r,...s]=n.trim().split("=");if(!r)continue;let i=s.join("=").trim();e[r]=i}return e}var Yt=/^([^[\]]+)\[([^[\]]+)\]$/;function ee(t){let e=t.match(Yt);return e?{parameterName:e[1],property:e[2]}:void 0}function Xt(t,e){let n;for(let[r,s]of e){let i=ee(r);i?.parameterName===t&&(n??={},n[i.property]=s)}return n}var je="application/x-www-form-urlencoded",Zt=["additionalProperties","patternProperties","unevaluatedProperties"];function Be(t){let e={properties:new Map,arrayKeys:new Set,jsonKeys:new Set,checksOtherKeys:!1};Z(t,e,!0,new Set);for(let[n,r]of e.properties){let s=p(r)&&r.type==="array";s&&e.arrayKeys.add(n),_e(s?r.items:r,new Set)&&e.jsonKeys.add(n)}return e}function Z(t,e,n,r){if(!(!p(t)||r.has(t))){if(r.add(t),p(t.properties))for(let[s,i]of Object.entries(t.properties))e.properties.set(s,i);n&&Zt.some(s=>t[s]!==void 0)&&(e.checksOtherKeys=!0);for(let s of Array.isArray(t.allOf)?t.allOf:[])Z(s,e,n,r);for(let s of[t.oneOf,t.anyOf])for(let i of Array.isArray(s)?s:[])Z(i,e,!1,r)}}function _e(t,e){return!p(t)||e.has(t)?!1:(e.add(t),t.type!==void 0?Array.isArray(t.type)?t.type.includes("object"):t.type==="object":p(t.properties)||[t.allOf,t.oneOf,t.anyOf].some(n=>Array.isArray(n)&&n.some(r=>_e(r,e))))}function er(t){try{return JSON.parse(t)}catch{return t}}function tr(t,e){let{formSchema:n}=t;if(n){let i=[...new Set(e.query.keys())];return i.length===0?void 0:Object.fromEntries(i.map(o=>{let a=e.query.getAll(o),u=n.jsonKeys.has(o)?a.map(er):a;return[o,n.arrayKeys.has(o)||u.length>1?u:u[0]]}))}let r=k(e.url).search.slice(1);if(r==="")return;let s;try{s=decodeURIComponent(r)}catch{s=r}if(!S(t.mediaType))return s;try{return JSON.parse(s)}catch{return}}function H(t,e,n,r){switch(t.in){case"path":return n[t.name];case"query":{if(t.style==="deepObject")return Xt(t.name,e.query);let s=e.query.getAll(t.name);return s.length===0?void 0:(p(t.schema)?t.schema.type:void 0)==="array"||s.length>1?s:s[0]}case"querystring":return tr(t,e);case"header":return e.headers[t.name.toLowerCase()];case"cookie":return r[t.name];default:return}}var Le=200;function Ne(t){return t!==void 0&&t!==""}function rr(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function nr(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}function sr(t){return!t||t==="#"?"":t.startsWith("#")?t.slice(1):t}function te(t){let e=sr(t);return!e||e==="/"?[]:e.split("/").slice(1).map(n=>rr(n))}function ze(t,e){return`/${[...te(t),nr(e)].join("/")}`}function ir(t,e){let n=te(e),r=t;for(let s of n){if(Array.isArray(r)){let i=Number.parseInt(s,10);if(!Number.isInteger(i)||i<0||i>=r.length)return;r=r[i];continue}if(!p(r))return;r=r[s]}return r}function re(t){let e=t.instancePath??"",n=t.params??{};return t.keyword==="required"&&typeof n.missingProperty=="string"?ze(e,n.missingProperty):t.keyword==="additionalProperties"&&typeof n.additionalProperty=="string"?ze(e,n.additionalProperty):e}function or(t){let e=te(t);if(e.length===0)return"root";let n=[];for(let r of e)/^\d+$/.test(r)?n.push(`[${r}]`):n.length===0?n.push(r):n.push(`.${r}`);return n.join("")}function ar(t){if(t===void 0)return"[missing]";let e=JSON.stringify(t);return e?e.length>Le?`${e.slice(0,Le)}\u2026`:e:String(t)}function ur(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 cr(t,e,n){let r=t==="request"?"Request":"Response",s=e.params??{},i=or(n);return e.keyword==="required"&&typeof s.missingProperty=="string"?`${r} is missing required field "${i}".`:e.keyword==="additionalProperties"&&typeof s.additionalProperty=="string"?`${r} has undocumented field "${i}".`:e.keyword==="type"&&typeof s.type=="string"?`${r} field "${i}" must be ${s.type}.`:e.keyword==="enum"?`${r} field "${i}" has a value outside allowed enum values.`:e.keyword==="format"&&typeof s.format=="string"?`${r} field "${i}" does not match format "${s.format}".`:`${r} schema mismatch at "${i}": ${e.message??"validation error"}`}function Ke(t,e,n){let r=re(e),s=ir(t,r);return{summary:cr(n,e,r),keyword:e.keyword??null,path:r||"/",expected:ur(e)??null,actual:ar(s),suggestion:null,params:e.params??{},ajvMessage:e.message??"validation error"}}function dr(t,e,n,r){if(e===void 0||!t.schema)return;let s=n.validateSchema(t.schema,e,{coerce:!S(t.mediaType),target:"request"});if(!s.valid)for(let i of s.errors){let o=Ke(e,i,"request");r.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:n.exchange.index,operationId:n.matchedOperation?.operation.operationId,specSource:n.matchedOperation?.operation.specSource,target:"request",schemaPath:i.schemaPath,dataPath:re(i),details:{...o,parameter:{name:t.name,in:t.in}}})}}function pr(t,e){let n=[],r={query:new Set,header:new Set,cookie:new Set},s=new Set,i=!0;for(let a of e.operation.requestParameters)if(a.in==="querystring"){let{formSchema:u}=a;(!u||u.properties.size===0||u.checksOtherKeys&&!He(t))&&(i=!1);for(let l of u?.properties.keys()??[])r.query.add(l)}else a.in==="header"?r.header.add(a.name.toLowerCase()):(a.in==="query"||a.in==="cookie")&&(r[a.in].add(a.name),a.in==="query"&&a.style==="deepObject"&&s.add(a.name));let o=i?t.exchange.request.query.keys():[];for(let a of new Set(o)){if(r.query.has(a))continue;let u=ee(a);u&&s.has(u.parameterName)||n.push({ruleId:"schema-consistency",severity:"warning",category:"documentation",message:`Undocumented query parameter in traffic: "${a}"`,exchangeIndex:t.exchange.index,operationId:e.operation.operationId,specSource:e.operation.specSource,target:"request"})}for(let a of Object.keys(t.exchange.request.headers))ke(a,t.ignoreHeaders)||r.header.has(a.toLowerCase())||n.push({ruleId:"schema-consistency",severity:"info",category:"documentation",message:`Undocumented header in traffic: "${a}"`,exchangeIndex:t.exchange.index,operationId:e.operation.operationId,specSource:e.operation.specSource,target:"request"});return n}function He(t){let e=t.exchange.response;return e!==void 0&&e.status>=400&&e.status<500}function lr(t,e){let n=t.exchange.response;if(!n)return;let{responseStatuses:r,responseBodyContent:s}=e.operation,i=K(n.status,r);if(!(i===void 0||s[i]===void 0))return x(s[i],n.contentType)}function Ve(t,e,n,r){let s=n.validateSchema(t,e,{target:r});return s.valid?[]:s.errors.map(i=>{let o=Ke(e,i,r);return{ruleId:"schema-consistency",severity:"error",category:"schema",message:typeof o.summary=="string"?o.summary:`Schema mismatch (${r}): ${i.message??"validation error"}`,exchangeIndex:n.exchange.index,operationId:n.matchedOperation?.operation.operationId,specSource:n.matchedOperation?.operation.specSource,target:r,schemaPath:i.schemaPath,dataPath:re(i),details:o}})}var D=class{id="schema-consistency";analyze(e){let n=e.matchedOperation;if(!n)return[];let r=[];if(r.push(...pr(e,n)),!He(e)){for(let u of n.operation.requestParameters){if(e.ignoreCookies&&u.in==="cookie")continue;let l=H(u,e.exchange.request,n.pathParams,e.cookies);if(l===void 0&&S(u.mediaType)&&k(e.exchange.request.url).search!==""){r.push({ruleId:this.id,severity:"error",category:"schema",message:`Invalid ${u.in} parameter "${u.name}": the query string is not valid JSON.`,exchangeIndex:e.exchange.index,operationId:n.operation.operationId,specSource:n.operation.specSource,target:"request"});continue}if(u.required&&l===void 0){r.push({ruleId:this.id,severity:"error",category:"documentation",message:`Missing required ${u.in} parameter: "${u.name}"`,exchangeIndex:e.exchange.index,operationId:n.operation.operationId,specSource:n.operation.specSource,target:"request"});continue}dr(u,l,e,r)}let i=e.exchange.request.contentType,o=x(n.operation.requestBodyContent,i),a=Ne(e.exchange.request.bodyText);n.operation.requestBodyRequired&&!a&&r.push({ruleId:this.id,severity:"error",category:"documentation",message:"Missing required request body",exchangeIndex:e.exchange.index,operationId:n.operation.operationId,specSource:n.operation.specSource,target:"request"}),o&&a&&S(i)&&(e.exchange.request.bodyJson===void 0?r.push({ruleId:this.id,severity:"error",category:"schema",message:"Request body is not valid JSON for JSON content-type",exchangeIndex:e.exchange.index,operationId:n.operation.operationId,specSource:n.operation.specSource,target:"request"}):r.push(...Ve(o,e.exchange.request.bodyJson,e,"request")))}let s=lr(e,n);if(s&&e.exchange.response&&Ne(e.exchange.response.bodyText)){let i=e.exchange.response.contentType;S(i)&&(e.exchange.response.bodyJson===void 0?r.push({ruleId:this.id,severity:"error",category:"schema",message:"Response body is not valid JSON for JSON content-type",exchangeIndex:e.exchange.index,operationId:n.operation.operationId,specSource:n.operation.specSource,target:"response"}):r.push(...Ve(s,e.exchange.response.bodyJson,e,"response")))}return r}};function ne(t){if(!t)return null;let[e]=t.trim().split(/\s+/,1);return e?e.toLowerCase():null}function Ue(t){return!!t.exchange.request.headers.authorization}function fr(t,e){return t?t.split(";").map(n=>n.trim()).some(n=>n.startsWith(`${e}=`)):!1}function mr(t,e){let n=t.matchedOperation?.operation;if(!n)return{schemeName:e,schemeType:"unknown",satisfied:!0,reason:"No matched OpenAPI operation."};let r=n.securitySchemes[e];if(!r)return{schemeName:e,schemeType:"missing",satisfied:!1,reason:"Security scheme is referenced but not defined in components.securitySchemes."};let s=String(r.type??"unknown");if(r.type==="apiKey"){let i=String(r.name??""),o=String(r.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=fr(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(r.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(r.scheme??"").toLowerCase(),a=ne(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 u=a===o;return{schemeName:e,schemeType:s,satisfied:u,reason:u?`Authorization uses expected "${o}" scheme.`:`Authorization uses "${a}" but "${o}" is required.`}}if(r.type==="oauth2"||r.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=ne(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 r.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 hr(t){let e=t.matchedOperation?.operation.security;if(!e)return{satisfied:!0,requirements:[]};if(e.length===0)return{satisfied:!0,requirements:[]};let n=e.map((r,s)=>{let i=Object.keys(r);if(i.length===0)return{requirementIndex:s,satisfied:!0,schemeResults:[]};let o=i.map(a=>mr(t,a));return{requirementIndex:s,satisfied:o.every(a=>a.satisfied),schemeResults:o}});return{satisfied:n.some(r=>r.satisfied),requirements:n}}function gr(t){let e=[];for(let n of t.requirements)for(let r of n.schemeResults)r.satisfied||e.push({requirement:n.requirementIndex+1,schemeName:r.schemeName,reason:r.reason});return e}function De(t){let e=[];for(let n of t.requirements)for(let r of n.schemeResults)r.skipped&&e.push({requirement:n.requirementIndex+1,schemeName:r.schemeName,reason:r.reason});return e}function yr(t){if(t.length===0)return"All documented security requirements are satisfied.";let e=new Map;for(let r of t){let s=e.get(r.requirement);s?s.push(r):e.set(r.requirement,[r])}let n=Array.from(e.entries()).sort((r,s)=>r[0]-s[0]).map(([r,s])=>{let i=s.map(a=>a.schemeName).join(" + "),o=s.map(a=>a.reason).join(" ");return`Option ${r} (${i}): ${o}`});return n.length===1?`Authentication check failed. ${n[0]}`:`None of the documented authentication options matched. Any one of these options would satisfy the OpenAPI security requirements: ${n.join(" | ")}`}function Sr(t){return Array.from(t.exchange.request.query.keys()).filter(e=>{let n=e.toLowerCase();return n.includes("token")||n.includes("apikey")||n.includes("api_key")||n.includes("access_key")})}var vr=/^(?:(?:.+\.)?localhost|127(?:\.\d{1,3}){3}|::1)$/i;function wr(t){let e;try{e=new URL(t.url).hostname}catch{e=t.host?.replace(/:\d+$/,"")}return e?vr.test(e.replace(/^\[|\]$/g,"")):!1}function Rr(t){if(t.exchange.request.protocol!=="http:"||!t.exchange.request.protocolKnown||wr(t.exchange.request))return{flag:!1,hasAuthHeader:!1,sensitiveQueryKeys:[]};let e=Ue(t),n=Sr(t);return{flag:e||n.length>0,hasAuthHeader:e,sensitiveQueryKeys:n}}var U=class{id="security-baseline";analyze(e){if(!e.matchedOperation)return[];let n=[],r=hr(e);if(r.satisfied){let i=De(r);i.length>0&&n.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=gr(r);n.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:yr(i),failedChecks:i,skippedChecks:De(r),authorizationScheme:ne(e.exchange.request.headers.authorization),hasAuthorizationHeader:Ue(e)}})}let s=Rr(e);return s.flag&&n.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}}),n}};var J=class{id="undocumented-endpoint";analyze(e){if(e.matchedOperation)return[];let{method:n,path:r,host:s}=e.exchange.request,o=e.matchMode==="strict-host"&&!e.hostCompatibleWithSpecServers?`Undocumented server: ${n} ${r} was sent to "${s}", which does not match any server in the description`:`Undocumented endpoint: ${n} ${r}`;return[{ruleId:this.id,severity:"error",category:"documentation",message:o,exchangeIndex:e.exchange.index,target:"request"}]}};var se={"undocumented-endpoint":()=>new J,"schema-consistency":()=>new D,"security-baseline":()=>new U,"owasp-api-top10":()=>new z},br=Object.keys(se),Or=["undocumented-endpoint","schema-consistency","security-baseline"];function Je(t){return!t||t.length===0?Or.map(e=>se[e]()):[...new Set(t)].map(e=>{let n=se[e];if(!n)throw new Error(`Unknown rule id: "${e}". Available rules: ${br.join(", ")}`);return n()})}var Qe=ce(lt(),1);var Ye=ce(ft(),1),Ge=Qe.default,We=Ye.default;function G(t,e){if(!p(t))return!1;let n=e==="request"?"readOnly":"writeOnly";return t[n]===!0||Array.isArray(t.allOf)&&t.allOf.some(r=>p(r)&&r[n]===!0)}function Xe(t,e,n,r=new WeakSet){if(!p(t)||r.has(t))return!1;r.add(t);let s=t.properties;return p(s)&&G(s[e],n)?!0:[t.allOf,t.oneOf,t.anyOf].some(i=>Array.isArray(i)&&i.some(o=>Xe(o,e,n,r)))}var Ir=new Set(["items","additionalItems","additionalProperties","unevaluatedItems","unevaluatedProperties","contains","propertyNames","not","if","then","else"]),Pr=new Set(["allOf","anyOf","oneOf","prefixItems"]),kr=new Set(["properties","patternProperties","dependentSchemas","$defs","definitions"]);function Ze(t,e,n=new WeakSet){if(!p(t))return t;if(n.has(t))return!0;n.add(t);let r=i=>Ze(i,e,n),s={};for(let[i,o]of Object.entries(t))Ir.has(i)?s[i]=Array.isArray(o)?o.map(r):r(o):Pr.has(i)&&Array.isArray(o)?s[i]=o.map(r):kr.has(i)&&p(o)?s[i]=Object.fromEntries(Object.entries(o).map(([a,u])=>[a,r(u)])):s[i]=o;return Array.isArray(t.required)&&(s.required=t.required.filter(i=>typeof i!="string"||!Xe(t,i,e))),n.delete(t),s}var F=class{ajv;fallbackAjv;objectSchemaCaches={none:new WeakMap,request:new WeakMap,response:new WeakMap};scalarSchemaCache=new Map;constructor(e){let n={strict:!1,allErrors:!0,allowUnionTypes:!0,discriminator:!0,coerceTypes:e?.coerceTypes?"array":!1,validateFormats:!0,verbose:!0,formats:{enum:!0}};this.ajv=new Ge(n),this.fallbackAjv=new Ge({...n,discriminator:!1}),We(this.ajv),We(this.fallbackAjv)}validate(e,n,r){if(e===void 0)return{valid:!0,errors:[]};let s;try{s=this.getOrCompileValidator(e,r)}catch(a){return{valid:!1,errors:[{message:`Schema compilation failed: ${a.message}`}]}}let i=!!s(n),o=s.errors??[];return{valid:i,errors:o}}getOrCompileValidator(e,n){if(p(e)){let o=this.objectSchemaCaches[n??"none"],a=o.get(e);if(a)return a;let u=n?Ze(e,n):e,l=this.compileSchema(u);return o.set(e,l),l}let r=`${n??"none"}:${JSON.stringify(e)}`,s=this.scalarSchemaCache.get(r);if(s)return s;let i=this.compileSchema(e);return this.scalarSchemaCache.set(r,i),i}compileSchema(e){try{return this.ajv.compile(e)}catch{return this.fallbackAjv.compile(e)}}};function et(t){switch(t.kind){case"operation":return"operation";case"parameter":return`parameter:${t.in}:${t.name}`;case"response":return`response:${t.status}`;case"property":return`property:${t.target}:${t.status??""}:${t.path}`}}function Q(t,e){let n=et(e);t.has(n)||t.set(n,{item:e,covered:!1})}function M(t,e){let n=t.get(et(e));n&&(n.covered=!0)}function tt(t,e){return t?`${t}.${e}`:e}function j(t,e,n,r,s){if(!(!p(t)||s.has(t))){s.add(t);for(let i of[t.allOf,t.oneOf,t.anyOf])if(Array.isArray(i))for(let o of i)j(o,e,n,r,s);if(p(t.properties))for(let[i,o]of Object.entries(t.properties)){if(G(o,e.target))continue;let a=tt(n,i);Q(r,{kind:"property",...e,path:a}),j(o,e,a,r,s)}p(t.items)&&j(t.items,e,`${n}[]`,r,s),s.delete(t)}}function B(t,e,n,r,s,i){if(!(!p(e)||i.has(e))){i.add(e);for(let o of[e.allOf,e.oneOf,e.anyOf])if(Array.isArray(o))for(let a of o)B(t,a,n,r,s,i);if(p(e.properties)&&p(t))for(let[o,a]of Object.entries(e.properties)){if(t[o]===void 0)continue;let u=tt(r,o);M(s,{kind:"property",...n,path:u}),B(t[o],a,n,u,s,i)}if(p(e.items)&&Array.isArray(t))for(let o of t)B(o,e.items,n,`${r}[]`,s,i);i.delete(e)}}function Ar(t,e){let n=new Map;Q(n,{kind:"operation"});for(let r of t.requestParameters){if(e&&r.in==="cookie")continue;let s=[...r.formSchema?.properties??[]].filter(([,i])=>!G(i,"request")).map(([i])=>`${r.name}.${i}`);for(let i of s.length>0?s:[r.name])Q(n,{kind:"parameter",name:i,in:r.in})}for(let[r,s]of Object.entries(t.requestBodyContent))S(r)&&j(s,{target:"request"},"",n,new Set);for(let r of t.responseStatuses){Q(n,{kind:"response",status:r});for(let[s,i]of Object.entries(t.responseBodyContent[r]??{}))S(s)&&j(i,{target:"response",status:r},"",n,new Set)}return{operation:t,entries:n}}function xr(t){return t.request.bodyJson!==void 0||t.response?.bodyJson!==void 0}function W(t,e){let n={covered:0,total:0};for(let r of t)for(let s of r.entries.values())s.item.kind===e&&(n.total+=1,s.covered&&(n.covered+=1));return n}function Cr(t){let e={method:t.operation.method.toUpperCase(),path:t.operation.pathTemplate,operationId:t.operation.operationId,missing:[],covered:[]};for(let n of t.entries.values())(n.covered?e.covered:e.missing).push(n.item);return e}var Y=class{states=new Map;exchanges={total:0,matched:0,withBody:0};constructor(e){for(let n of e.openApiIndex.operationsByMethod.values())for(let r of n)this.states.set(r,Ar(r,e.ignoreCookies))}record(e,n,r){if(this.exchanges.total+=1,!n)return;let s=this.states.get(n.operation);if(!s)return;this.exchanges.matched+=1,xr(e)&&(this.exchanges.withBody+=1);let{operation:i,pathParams:o}=n,{entries:a}=s;M(a,{kind:"operation"});for(let c of i.requestParameters){let m=H(c,e.request,o,r);if(m!==void 0&&(M(a,{kind:"parameter",name:c.name,in:c.in}),c.formSchema&&p(m)))for(let v of Object.keys(m))M(a,{kind:"parameter",name:`${c.name}.${v}`,in:c.in})}if(e.request.bodyJson!==void 0){let c=x(i.requestBodyContent,e.request.contentType);B(e.request.bodyJson,c,{target:"request"},"",a,new Set)}let u=e.response;if(!u)return;let l=K(u.status,i.responseStatuses);if(l!==void 0&&(M(a,{kind:"response",status:l}),u.bodyJson!==void 0)){let c=x(i.responseBodyContent[l]??{},u.contentType);B(u.bodyJson,c,{target:"response",status:l},"",a,new Set)}}finalize(){let e=Array.from(this.states.values()).sort((n,r)=>n.operation.pathTemplate.localeCompare(r.operation.pathTemplate)||n.operation.method.localeCompare(r.operation.method));return{exchanges:this.exchanges,totals:{operations:W(e,"operation"),parameters:W(e,"parameter"),properties:W(e,"property"),responses:W(e,"response")},operations:e.map(Cr)}}};var $r=10,rt={info:0,warning:1,error:2};function Er(){return{totalExchanges:0,documentedExchanges:0,undocumentedExchanges:0,skippedExchanges:0,hostCompatibleExchanges:0,findingsBySeverity:{info:0,warning:0,error:0},findingsByRule:{}}}function qr(t,e){t.findingsBySeverity[e.severity]+=1,t.findingsByRule[e.ruleId]=(t.findingsByRule[e.ruleId]??0)+1}function Tr(t,e){return{...t,id:st(),method:e.request.method,url:e.request.url,path:e.request.path,status:e.response?.status}}function Fr(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 Mr(t,e){if(!e)return;t.operationId||(t.operationId=e.operation.operationId),t.specSource||(t.specSource=e.operation.specSource);let n=t.details??{};if(!p(n)){t.details={operationPathTemplate:e.operation.pathTemplate};return}typeof n.operationPathTemplate!="string"&&(n.operationPathTemplate=e.operation.pathTemplate),t.details=n}function jr(t){let e=new Set,n=!1;for(let r of t.operationsByMethod.values())for(let s of r)for(let i of s.servers)i.host?e.add(i.host):n=!0;return{specServerHosts:e,hasHostlessSpecServer:n}}async function Br(t,e){let n=[];for(let r of t)try{let s=await r.analyze(e);s.length>0&&n.push(...s)}catch(s){R.warn(`Rule "${r.id}" failed to execute: ${s.message}
|
|
18
|
-
`)}return n}var nt=class t{
|
|
17
|
+
`}function an(t,e){let n=e.maxFindings??10;switch(e.format){case"json":return wt(t);case"csv":return Rt(t);case"sarif":return bt(t);case"pretty":return Pt(t,e.color??!1,n);default:throw new Error(`Unsupported report format: ${e.format}`)}}import{randomUUID as st}from"node:crypto";function kt(t,e){let n=A(t||"/")||"/",r=A(e.basePath||"/")||"/";return r==="/"?n:n===r?"/":n.startsWith(`${r}/`)?n.slice(r.length)||"/":null}function At(t,e){return!t.host||!e?!0:t.host===e.toLowerCase()}function xt(t){try{return decodeURIComponent(t)}catch{return t}}function Ct(t,e,n){let r=n==="strict-host"?e.host?20:5:0;return t.pathScore*10+r}function $e(t,e){let n={};for(let r=0;r<t.pathParams.length;r+=1){let s=t.pathParams[r],i=e[r+1];s&&i!==void 0&&(n[s]=xt(i))}return n}function $t(t,e){let n=A(e)||"/";for(let r of t){let s=r.pathRegex.exec(n);if(s)return{operation:r,pathParams:$e(r,s)}}return null}function Ee(t,e,n,r){let s=e.request.method.toLowerCase(),i=t.operationsByMethod.get(s);if(!i||i.length===0)return null;if(r!==void 0)return $t(i,r);let o=null;for(let a of i)for(let u of a.servers){if(n==="strict-host"&&!At(u,e.request.host))continue;let l=kt(e.request.path,u);if(!l)continue;let c=a.pathRegex.exec(l);if(!c)continue;let m={score:Ct(a,u,n),matched:{operation:a,pathParams:$e(a,c)}};(!o||m.score>o.score)&&(o=m)}return o?.matched??null}var qe=6,Et=2e3,qt=50,Tt=5,Ft=1e6,jt=/(?:token|api[_-]?key|apikey|password|passwd|secret|authorization|jwt)/i,Mt=/(?:password|passwd|secret|api[_-]?key|access[_-]?token|refresh[_-]?token|private[_-]?key|ssn|credit[_-]?card|card[_-]?number|cvv)/i,Bt=new Set(["page","limit","offset","cursor","per_page","perpage","size","start","after","before"]),Te=4,_t=Te*2;function Lt(t){return t.length<=_t?"***":`${t.slice(0,Te)}\u2026`}function Nt(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}function zt(t){return typeof t=="string"||typeof t=="number"}function Vt(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 Kt(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 Ht(t){if(!d(t)&&!Array.isArray(t))return[];let e=[],n=[{value:t,path:""}],r=0;for(;n.length>0&&r<Et&&e.length<qe;){let s=n.pop();if(!s)break;if(r+=1,Array.isArray(s.value)){let i=Math.min(s.value.length,qt);for(let o=0;o<i;o+=1){let a=s.value[o];(d(a)||Array.isArray(a))&&n.push({value:a,path:`${s.path}/${o}`})}continue}if(d(s.value))for(let[i,o]of Object.entries(s.value)){let a=`${s.path}/${Nt(i)}`;if(Mt.test(i)&&zt(o)){let u=String(o);if(Vt(i)&&Kt(o))continue;if(u.length>0&&(e.push(a||"/"),e.length>=qe))break}(d(o)||Array.isArray(o))&&n.push({value:o,path:a})}}return e}function Dt(t){for(let e of t.keys())if(Bt.has(e.toLowerCase()))return!0;return!1}function I(t,e,n,r,s){return{ruleId:"owasp-api-top10",severity:r,category:"security",message:e,exchangeIndex:t.exchange.index,operationId:t.matchedOperation?.operation.operationId,specSource:t.matchedOperation?.operation.specSource,target:n,details:s}}function Ut(t){let e=[];for(let[n,r]of t.exchange.request.query.entries())if(jt.test(n)&&(e.push({key:n,valuePreview:Lt(r)}),e.length>=Tt))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 Jt(t){let e=t.exchange.response;if(!e)return[];let n=e.headers["access-control-allow-origin"]?.trim(),r=e.headers["access-control-allow-credentials"]?.trim().toLowerCase();return n!=="*"||r!=="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:n,accessControlAllowCredentials:r}})]}function Gt(t){let e=t.exchange.response;if(!e)return[];let n=e.headers["set-cookie"];if(!n)return[];let r=[];for(let s of be(n)){let i=new Set(s.split(";").slice(1).map(o=>o.split("=")[0].trim().toLowerCase()));t.exchange.request.protocol==="https:"&&!i.has("secure")&&r.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")||r.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")||r.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 r}function Wt(t){let e=t.exchange.response;if(!e||e.bodyJson===void 0)return[];let n=Ht(e.bodyJson);return n.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: ${n.join(", ")}`,exposedPaths:n})]}function Qt(t){let e=t.exchange.response;return!e||e.status>=400||t.exchange.request.method!=="GET"?[]:!e.bodyText||e.bodyText.length<Ft?[]:Dt(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 z=class{id="owasp-api-top10";analyze(e){return e.matchedOperation?[...Ut(e),...Jt(e),...Gt(e),...Wt(e),...Qt(e)]:[]}};function V(t,e){let n=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]):""}),r=k(n),s=!!(r.host&&!Re(r.host));return{rawUrl:t,protocol:s?r.protocol:void 0,host:s?r.host.toLowerCase():void 0,basePath:A(r.pathname||"/")}}function Fe(t){return t?t.startsWith("/")?t:`/${t}`:"/"}function K(t,e){let n=`${Math.floor(t/100)}XX`;return[String(t),n,n.toLowerCase(),"default"].find(r=>e.includes(r))}function je(t){if(!t)return{};let e={};for(let n of t.split(";")){let[r,...s]=n.trim().split("=");if(!r)continue;let i=s.join("=").trim();e[r]=i}return e}var Yt=/^([^[\]]+)\[([^[\]]+)\]$/;function ee(t){let e=t.match(Yt);return e?{parameterName:e[1],property:e[2]}:void 0}function Xt(t,e){let n;for(let[r,s]of e){let i=ee(r);i?.parameterName===t&&(n??={},n[i.property]=s)}return n}var Me="application/x-www-form-urlencoded",Zt=["additionalProperties","patternProperties","unevaluatedProperties"];function Be(t){let e={properties:new Map,arrayKeys:new Set,jsonKeys:new Set,checksOtherKeys:!1};Z(t,e,!0,new Set);for(let[n,r]of e.properties){let s=d(r)&&r.type==="array";s&&e.arrayKeys.add(n),_e(s?r.items:r,new Set)&&e.jsonKeys.add(n)}return e}function Z(t,e,n,r){if(!(!d(t)||r.has(t))){if(r.add(t),d(t.properties))for(let[s,i]of Object.entries(t.properties))e.properties.set(s,i);n&&Zt.some(s=>t[s]!==void 0)&&(e.checksOtherKeys=!0);for(let s of Array.isArray(t.allOf)?t.allOf:[])Z(s,e,n,r);for(let s of[t.oneOf,t.anyOf])for(let i of Array.isArray(s)?s:[])Z(i,e,!1,r)}}function _e(t,e){return!d(t)||e.has(t)?!1:(e.add(t),t.type!==void 0?Array.isArray(t.type)?t.type.includes("object"):t.type==="object":d(t.properties)||[t.allOf,t.oneOf,t.anyOf].some(n=>Array.isArray(n)&&n.some(r=>_e(r,e))))}function er(t){try{return JSON.parse(t)}catch{return t}}function tr(t,e){let{formSchema:n}=t;if(n){let i=[...new Set(e.query.keys())];return i.length===0?void 0:Object.fromEntries(i.map(o=>{let a=e.query.getAll(o),u=n.jsonKeys.has(o)?a.map(er):a;return[o,n.arrayKeys.has(o)||u.length>1?u:u[0]]}))}let r=k(e.url).search.slice(1);if(r==="")return;let s;try{s=decodeURIComponent(r)}catch{s=r}if(!S(t.mediaType))return s;try{return JSON.parse(s)}catch{return}}function H(t,e,n,r){switch(t.in){case"path":return n[t.name];case"query":{if(t.style==="deepObject")return Xt(t.name,e.query);let s=e.query.getAll(t.name);return s.length===0?void 0:(d(t.schema)?t.schema.type:void 0)==="array"||s.length>1?s:s[0]}case"querystring":return tr(t,e);case"header":return e.headers[t.name.toLowerCase()];case"cookie":return r[t.name];default:return}}var Le=200;function Ne(t){return t!==void 0&&t!==""}function rr(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function nr(t){return t.replace(/~/g,"~0").replace(/\//g,"~1")}function sr(t){return!t||t==="#"?"":t.startsWith("#")?t.slice(1):t}function te(t){let e=sr(t);return!e||e==="/"?[]:e.split("/").slice(1).map(n=>rr(n))}function ze(t,e){return`/${[...te(t),nr(e)].join("/")}`}function ir(t,e){let n=te(e),r=t;for(let s of n){if(Array.isArray(r)){let i=Number.parseInt(s,10);if(!Number.isInteger(i)||i<0||i>=r.length)return;r=r[i];continue}if(!d(r))return;r=r[s]}return r}function re(t){let e=t.instancePath??"",n=t.params??{};return t.keyword==="required"&&typeof n.missingProperty=="string"?ze(e,n.missingProperty):t.keyword==="additionalProperties"&&typeof n.additionalProperty=="string"?ze(e,n.additionalProperty):e}function or(t){let e=te(t);if(e.length===0)return"root";let n=[];for(let r of e)/^\d+$/.test(r)?n.push(`[${r}]`):n.length===0?n.push(r):n.push(`.${r}`);return n.join("")}function ar(t){if(t===void 0)return"[missing]";let e=JSON.stringify(t);return e?e.length>Le?`${e.slice(0,Le)}\u2026`:e:String(t)}function ur(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 cr(t,e,n){let r=t==="request"?"Request":"Response",s=e.params??{},i=or(n);return e.keyword==="required"&&typeof s.missingProperty=="string"?`${r} is missing required field "${i}".`:e.keyword==="additionalProperties"&&typeof s.additionalProperty=="string"?`${r} has undocumented field "${i}".`:e.keyword==="type"&&typeof s.type=="string"?`${r} field "${i}" must be ${s.type}.`:e.keyword==="enum"?`${r} field "${i}" has a value outside allowed enum values.`:e.keyword==="format"&&typeof s.format=="string"?`${r} field "${i}" does not match format "${s.format}".`:`${r} schema mismatch at "${i}": ${e.message??"validation error"}`}function Ke(t,e,n){let r=re(e),s=ir(t,r);return{summary:cr(n,e,r),keyword:e.keyword??null,path:r||"/",expected:ur(e)??null,actual:ar(s),suggestion:null,params:e.params??{},ajvMessage:e.message??"validation error"}}function pr(t,e,n,r){if(e===void 0||!t.schema)return;let s=n.validateSchema(t.schema,e,{coerce:!S(t.mediaType),target:"request"});if(!s.valid)for(let i of s.errors){let o=Ke(e,i,"request");r.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:n.exchange.index,operationId:n.matchedOperation?.operation.operationId,specSource:n.matchedOperation?.operation.specSource,target:"request",schemaPath:i.schemaPath,dataPath:re(i),details:{...o,parameter:{name:t.name,in:t.in}}})}}function dr(t,e){let n=[],r={query:new Set,header:new Set,cookie:new Set},s=new Set,i=!0;for(let a of e.operation.requestParameters)if(a.in==="querystring"){let{formSchema:u}=a;(!u||u.properties.size===0||u.checksOtherKeys&&!He(t))&&(i=!1);for(let l of u?.properties.keys()??[])r.query.add(l)}else a.in==="header"?r.header.add(a.name.toLowerCase()):(a.in==="query"||a.in==="cookie")&&(r[a.in].add(a.name),a.in==="query"&&a.style==="deepObject"&&s.add(a.name));let o=i?t.exchange.request.query.keys():[];for(let a of new Set(o)){if(r.query.has(a))continue;let u=ee(a);u&&s.has(u.parameterName)||n.push({ruleId:"schema-consistency",severity:"warning",category:"documentation",message:`Undocumented query parameter in traffic: "${a}"`,exchangeIndex:t.exchange.index,operationId:e.operation.operationId,specSource:e.operation.specSource,target:"request"})}for(let a of Object.keys(t.exchange.request.headers))ke(a,t.ignoreHeaders)||r.header.has(a.toLowerCase())||n.push({ruleId:"schema-consistency",severity:"info",category:"documentation",message:`Undocumented header in traffic: "${a}"`,exchangeIndex:t.exchange.index,operationId:e.operation.operationId,specSource:e.operation.specSource,target:"request"});return n}function He(t){let e=t.exchange.response;return e!==void 0&&e.status>=400&&e.status<500}function lr(t,e){let n=t.exchange.response;if(!n)return;let{responseStatuses:r,responseBodyContent:s}=e.operation,i=K(n.status,r);if(!(i===void 0||s[i]===void 0))return x(s[i],n.contentType)}function Ve(t,e,n,r){let s=n.validateSchema(t,e,{target:r});return s.valid?[]:s.errors.map(i=>{let o=Ke(e,i,r);return{ruleId:"schema-consistency",severity:"error",category:"schema",message:typeof o.summary=="string"?o.summary:`Schema mismatch (${r}): ${i.message??"validation error"}`,exchangeIndex:n.exchange.index,operationId:n.matchedOperation?.operation.operationId,specSource:n.matchedOperation?.operation.specSource,target:r,schemaPath:i.schemaPath,dataPath:re(i),details:o}})}var D=class{id="schema-consistency";analyze(e){let n=e.matchedOperation;if(!n)return[];let r=[];if(r.push(...dr(e,n)),!He(e)){for(let u of n.operation.requestParameters){if(e.ignoreCookies&&u.in==="cookie")continue;let l=H(u,e.exchange.request,n.pathParams,e.cookies);if(l===void 0&&S(u.mediaType)&&k(e.exchange.request.url).search!==""){r.push({ruleId:this.id,severity:"error",category:"schema",message:`Invalid ${u.in} parameter "${u.name}": the query string is not valid JSON.`,exchangeIndex:e.exchange.index,operationId:n.operation.operationId,specSource:n.operation.specSource,target:"request"});continue}if(u.required&&l===void 0){r.push({ruleId:this.id,severity:"error",category:"documentation",message:`Missing required ${u.in} parameter: "${u.name}"`,exchangeIndex:e.exchange.index,operationId:n.operation.operationId,specSource:n.operation.specSource,target:"request"});continue}pr(u,l,e,r)}let i=e.exchange.request.contentType,o=x(n.operation.requestBodyContent,i),a=Ne(e.exchange.request.bodyText);n.operation.requestBodyRequired&&!a&&r.push({ruleId:this.id,severity:"error",category:"documentation",message:"Missing required request body",exchangeIndex:e.exchange.index,operationId:n.operation.operationId,specSource:n.operation.specSource,target:"request"}),o&&a&&S(i)&&(e.exchange.request.bodyJson===void 0?r.push({ruleId:this.id,severity:"error",category:"schema",message:"Request body is not valid JSON for JSON content-type",exchangeIndex:e.exchange.index,operationId:n.operation.operationId,specSource:n.operation.specSource,target:"request"}):r.push(...Ve(o,e.exchange.request.bodyJson,e,"request")))}let s=lr(e,n);if(s&&e.exchange.response&&Ne(e.exchange.response.bodyText)){let i=e.exchange.response.contentType;S(i)&&(e.exchange.response.bodyJson===void 0?r.push({ruleId:this.id,severity:"error",category:"schema",message:"Response body is not valid JSON for JSON content-type",exchangeIndex:e.exchange.index,operationId:n.operation.operationId,specSource:n.operation.specSource,target:"response"}):r.push(...Ve(s,e.exchange.response.bodyJson,e,"response")))}return r}};function ne(t){if(!t)return null;let[e]=t.trim().split(/\s+/,1);return e?e.toLowerCase():null}function Ue(t){return!!t.exchange.request.headers.authorization}function fr(t,e){return t?t.split(";").map(n=>n.trim()).some(n=>n.startsWith(`${e}=`)):!1}function mr(t,e){let n=t.matchedOperation?.operation;if(!n)return{schemeName:e,schemeType:"unknown",satisfied:!0,reason:"No matched OpenAPI operation."};let r=n.securitySchemes[e];if(!r)return{schemeName:e,schemeType:"missing",satisfied:!1,reason:"Security scheme is referenced but not defined in components.securitySchemes."};let s=String(r.type??"unknown");if(r.type==="apiKey"){let i=String(r.name??""),o=String(r.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=fr(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(r.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(r.scheme??"").toLowerCase(),a=ne(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 u=a===o;return{schemeName:e,schemeType:s,satisfied:u,reason:u?`Authorization uses expected "${o}" scheme.`:`Authorization uses "${a}" but "${o}" is required.`}}if(r.type==="oauth2"||r.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=ne(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 r.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 hr(t){let e=t.matchedOperation?.operation.security;if(!e)return{satisfied:!0,requirements:[]};if(e.length===0)return{satisfied:!0,requirements:[]};let n=e.map((r,s)=>{let i=Object.keys(r);if(i.length===0)return{requirementIndex:s,satisfied:!0,schemeResults:[]};let o=i.map(a=>mr(t,a));return{requirementIndex:s,satisfied:o.every(a=>a.satisfied),schemeResults:o}});return{satisfied:n.some(r=>r.satisfied),requirements:n}}function gr(t){let e=[];for(let n of t.requirements)for(let r of n.schemeResults)r.satisfied||e.push({requirement:n.requirementIndex+1,schemeName:r.schemeName,reason:r.reason});return e}function De(t){let e=[];for(let n of t.requirements)for(let r of n.schemeResults)r.skipped&&e.push({requirement:n.requirementIndex+1,schemeName:r.schemeName,reason:r.reason});return e}function yr(t){if(t.length===0)return"All documented security requirements are satisfied.";let e=new Map;for(let r of t){let s=e.get(r.requirement);s?s.push(r):e.set(r.requirement,[r])}let n=Array.from(e.entries()).sort((r,s)=>r[0]-s[0]).map(([r,s])=>{let i=s.map(a=>a.schemeName).join(" + "),o=s.map(a=>a.reason).join(" ");return`Option ${r} (${i}): ${o}`});return n.length===1?`Authentication check failed. ${n[0]}`:`None of the documented authentication options matched. Any one of these options would satisfy the OpenAPI security requirements: ${n.join(" | ")}`}function Sr(t){return Array.from(t.exchange.request.query.keys()).filter(e=>{let n=e.toLowerCase();return n.includes("token")||n.includes("apikey")||n.includes("api_key")||n.includes("access_key")})}var vr=/^(?:(?:.+\.)?localhost|127(?:\.\d{1,3}){3}|::1)$/i;function wr(t){let e;try{e=new URL(t.url).hostname}catch{e=t.host?.replace(/:\d+$/,"")}return e?vr.test(e.replace(/^\[|\]$/g,"")):!1}function Rr(t){if(t.exchange.request.protocol!=="http:"||!t.exchange.request.protocolKnown||wr(t.exchange.request))return{flag:!1,hasAuthHeader:!1,sensitiveQueryKeys:[]};let e=Ue(t),n=Sr(t);return{flag:e||n.length>0,hasAuthHeader:e,sensitiveQueryKeys:n}}var U=class{id="security-baseline";analyze(e){if(!e.matchedOperation)return[];let n=[],r=hr(e);if(r.satisfied){let i=De(r);i.length>0&&n.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=gr(r);n.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:yr(i),failedChecks:i,skippedChecks:De(r),authorizationScheme:ne(e.exchange.request.headers.authorization),hasAuthorizationHeader:Ue(e)}})}let s=Rr(e);return s.flag&&n.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}}),n}};var J=class{id="undocumented-endpoint";analyze(e){if(e.matchedOperation)return[];let{method:n,path:r,host:s}=e.exchange.request,o=e.matchMode==="strict-host"&&!e.hostCompatibleWithSpecServers?`Undocumented server: ${n} ${r} was sent to "${s}", which does not match any server in the description`:`Undocumented endpoint: ${n} ${r}`;return[{ruleId:this.id,severity:"error",category:"documentation",message:o,exchangeIndex:e.exchange.index,target:"request"}]}};var se={"undocumented-endpoint":()=>new J,"schema-consistency":()=>new D,"security-baseline":()=>new U,"owasp-api-top10":()=>new z},br=Object.keys(se),Or=["undocumented-endpoint","schema-consistency","security-baseline"];function Je(t){return!t||t.length===0?Or.map(e=>se[e]()):[...new Set(t)].map(e=>{let n=se[e];if(!n)throw new Error(`Unknown rule id: "${e}". Available rules: ${br.join(", ")}`);return n()})}var Qe=ce(lt(),1);var Ye=ce(ft(),1),Ge=Qe.default,We=Ye.default;function G(t,e){if(!d(t))return!1;let n=e==="request"?"readOnly":"writeOnly";return t[n]===!0||Array.isArray(t.allOf)&&t.allOf.some(r=>d(r)&&r[n]===!0)}function Xe(t,e,n,r=new WeakSet){if(!d(t)||r.has(t))return!1;r.add(t);let s=t.properties;return d(s)&&G(s[e],n)?!0:[t.allOf,t.oneOf,t.anyOf].some(i=>Array.isArray(i)&&i.some(o=>Xe(o,e,n,r)))}var Ir=new Set(["items","additionalItems","additionalProperties","unevaluatedItems","unevaluatedProperties","contains","propertyNames","not","if","then","else"]),Pr=new Set(["allOf","anyOf","oneOf","prefixItems"]),kr=new Set(["properties","patternProperties","dependentSchemas","$defs","definitions"]);function Ze(t,e,n=new WeakSet){if(!d(t))return t;if(n.has(t))return!0;n.add(t);let r=i=>Ze(i,e,n),s={};for(let[i,o]of Object.entries(t))Ir.has(i)?s[i]=Array.isArray(o)?o.map(r):r(o):Pr.has(i)&&Array.isArray(o)?s[i]=o.map(r):kr.has(i)&&d(o)?s[i]=Object.fromEntries(Object.entries(o).map(([a,u])=>[a,r(u)])):s[i]=o;return Array.isArray(t.required)&&(s.required=t.required.filter(i=>typeof i!="string"||!Xe(t,i,e))),n.delete(t),s}var F=class{ajv;fallbackAjv;objectSchemaCaches={none:new WeakMap,request:new WeakMap,response:new WeakMap};scalarSchemaCache=new Map;constructor(e){let n={strict:!1,allErrors:!0,allowUnionTypes:!0,discriminator:!0,coerceTypes:e?.coerceTypes?"array":!1,validateFormats:!0,verbose:!0,formats:{enum:!0}};this.ajv=new Ge(n),this.fallbackAjv=new Ge({...n,discriminator:!1}),We(this.ajv),We(this.fallbackAjv)}validate(e,n,r){if(e===void 0)return{valid:!0,errors:[]};let s;try{s=this.getOrCompileValidator(e,r)}catch(a){return{valid:!1,errors:[{message:`Schema compilation failed: ${a.message}`}]}}let i=!!s(n),o=s.errors??[];return{valid:i,errors:o}}getOrCompileValidator(e,n){if(d(e)){let o=this.objectSchemaCaches[n??"none"],a=o.get(e);if(a)return a;let u=n?Ze(e,n):e,l=this.compileSchema(u);return o.set(e,l),l}let r=`${n??"none"}:${JSON.stringify(e)}`,s=this.scalarSchemaCache.get(r);if(s)return s;let i=this.compileSchema(e);return this.scalarSchemaCache.set(r,i),i}compileSchema(e){try{return this.ajv.compile(e)}catch{return this.fallbackAjv.compile(e)}}};function et(t){switch(t.kind){case"operation":return"operation";case"parameter":return`parameter:${t.in}:${t.name}`;case"response":return`response:${t.status}`;case"property":return`property:${t.target}:${t.status??""}:${t.path}`}}function Q(t,e){let n=et(e);t.has(n)||t.set(n,{item:e,covered:!1})}function j(t,e){let n=t.get(et(e));n&&(n.covered=!0)}function tt(t,e){return t?`${t}.${e}`:e}function M(t,e,n,r,s){if(!(!d(t)||s.has(t))){s.add(t);for(let i of[t.allOf,t.oneOf,t.anyOf])if(Array.isArray(i))for(let o of i)M(o,e,n,r,s);if(d(t.properties))for(let[i,o]of Object.entries(t.properties)){if(G(o,e.target))continue;let a=tt(n,i);Q(r,{kind:"property",...e,path:a}),M(o,e,a,r,s)}d(t.items)&&M(t.items,e,`${n}[]`,r,s),s.delete(t)}}function B(t,e,n,r,s,i){if(!(!d(e)||i.has(e))){i.add(e);for(let o of[e.allOf,e.oneOf,e.anyOf])if(Array.isArray(o))for(let a of o)B(t,a,n,r,s,i);if(d(e.properties)&&d(t))for(let[o,a]of Object.entries(e.properties)){if(t[o]===void 0)continue;let u=tt(r,o);j(s,{kind:"property",...n,path:u}),B(t[o],a,n,u,s,i)}if(d(e.items)&&Array.isArray(t))for(let o of t)B(o,e.items,n,`${r}[]`,s,i);i.delete(e)}}function Ar(t,e){let n=new Map;Q(n,{kind:"operation"});for(let r of t.requestParameters){if(e&&r.in==="cookie")continue;let s=[...r.formSchema?.properties??[]].filter(([,i])=>!G(i,"request")).map(([i])=>`${r.name}.${i}`);for(let i of s.length>0?s:[r.name])Q(n,{kind:"parameter",name:i,in:r.in})}for(let[r,s]of Object.entries(t.requestBodyContent))S(r)&&M(s,{target:"request"},"",n,new Set);for(let r of t.responseStatuses){Q(n,{kind:"response",status:r});for(let[s,i]of Object.entries(t.responseBodyContent[r]??{}))S(s)&&M(i,{target:"response",status:r},"",n,new Set)}return{operation:t,entries:n}}function xr(t){return t.request.bodyJson!==void 0||t.response?.bodyJson!==void 0}function W(t,e){let n={covered:0,total:0};for(let r of t)for(let s of r.entries.values())s.item.kind===e&&(n.total+=1,s.covered&&(n.covered+=1));return n}function Cr(t){let e={method:t.operation.method.toUpperCase(),path:t.operation.pathTemplate,operationId:t.operation.operationId,missing:[],covered:[]};for(let n of t.entries.values())(n.covered?e.covered:e.missing).push(n.item);return e}var Y=class{states=new Map;exchanges={total:0,matched:0,withBody:0};constructor(e){for(let n of e.openApiIndex.operationsByMethod.values())for(let r of n)this.states.set(r,Ar(r,e.ignoreCookies))}record(e,n,r){if(this.exchanges.total+=1,!n)return;let s=this.states.get(n.operation);if(!s)return;this.exchanges.matched+=1,xr(e)&&(this.exchanges.withBody+=1);let{operation:i,pathParams:o}=n,{entries:a}=s;j(a,{kind:"operation"});for(let c of i.requestParameters){let m=H(c,e.request,o,r);if(m!==void 0&&(j(a,{kind:"parameter",name:c.name,in:c.in}),c.formSchema&&d(m)))for(let v of Object.keys(m))j(a,{kind:"parameter",name:`${c.name}.${v}`,in:c.in})}if(e.request.bodyJson!==void 0){let c=x(i.requestBodyContent,e.request.contentType);B(e.request.bodyJson,c,{target:"request"},"",a,new Set)}let u=e.response;if(!u)return;let l=K(u.status,i.responseStatuses);if(l!==void 0&&(j(a,{kind:"response",status:l}),u.bodyJson!==void 0)){let c=x(i.responseBodyContent[l]??{},u.contentType);B(u.bodyJson,c,{target:"response",status:l},"",a,new Set)}}finalize(){let e=Array.from(this.states.values()).sort((n,r)=>n.operation.pathTemplate.localeCompare(r.operation.pathTemplate)||n.operation.method.localeCompare(r.operation.method));return{exchanges:this.exchanges,totals:{operations:W(e,"operation"),parameters:W(e,"parameter"),properties:W(e,"property"),responses:W(e,"response")},operations:e.map(Cr)}}};var $r=10,rt={info:0,warning:1,error:2};function Er(){return{totalExchanges:0,documentedExchanges:0,undocumentedExchanges:0,skippedExchanges:0,hostCompatibleExchanges:0,findingsBySeverity:{info:0,warning:0,error:0},findingsByRule:{}}}function qr(t,e){t.findingsBySeverity[e.severity]+=1,t.findingsByRule[e.ruleId]=(t.findingsByRule[e.ruleId]??0)+1}function Tr(t,e){return{...t,id:st(),method:e.request.method,url:e.request.url,path:e.request.path,status:e.response?.status}}function Fr(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 jr(t,e){if(!e)return;t.operationId||(t.operationId=e.operation.operationId),t.specSource||(t.specSource=e.operation.specSource);let n=t.details??{};if(!d(n)){t.details={operationPathTemplate:e.operation.pathTemplate};return}typeof n.operationPathTemplate!="string"&&(n.operationPathTemplate=e.operation.pathTemplate),t.details=n}function Mr(t){let e=new Set,n=!1;for(let r of t.operationsByMethod.values())for(let s of r)for(let i of s.servers)i.host?e.add(i.host):n=!0;return{specServerHosts:e,hasHostlessSpecServer:n}}async function Br(t,e){let n=[];for(let r of t)try{let s=await r.analyze(e);s.length>0&&n.push(...s)}catch(s){R.warn(`Rule "${r.id}" failed to execute: ${s.message}
|
|
18
|
+
`)}return n}var nt=class t{runId=st();previewLimit;rules;schemaValidator=new F;coercingSchemaValidator=new F({coerceTypes:!0});options;coverage;counters=Er();findings=[];previewFindings=[];problemGroupsByRule={};problemKeyStats=new Map;totalProblemGroups=0;server;ignoreHeaders;minSeverityRank;specServerHosts;hasHostlessSpecServer;constructor(e,n){this.options=e,this.rules=n,this.server=Ae(e.server),this.ignoreHeaders=e.ignoreHeaders?Pe(e.ignoreHeaders):void 0;let{specServerHosts:r,hasHostlessSpecServer:s}=Mr(e.openApiIndex);this.specServerHosts=r,this.hasHostlessSpecServer=s,this.minSeverityRank=rt[e.minSeverity??"info"],this.previewLimit=e.previewFindingsLimit&&e.previewFindingsLimit>0?e.previewFindingsLimit:$r,this.coverage=e.coverage?new Y({openApiIndex:e.openApiIndex,ignoreCookies:e.ignoreCookies??!1}):void 0}static create(e){if(e.openApiIndex.loadedOperations===0)throw new Error("No OpenAPI operations available to validate traffic against.");return new t(e,Je(e.activeRules))}async process(e){this.counters.totalExchanges+=1;let n=je(e.request.headers.cookie),r;if(this.server!==void 0&&(r=xe(e.request,this.server),r===void 0))return this.counters.skippedExchanges+=1,this.coverage?.record(e,null,n),[];let s=this.isHostCompatible(e.request.host);s&&(this.counters.hostCompatibleExchanges+=1);let i=Ee(this.options.openApiIndex,e,this.options.matchMode,r);i?this.counters.documentedExchanges+=1:this.counters.undocumentedExchanges+=1,this.coverage?.record(e,i,n);let o=await Br(this.rules,{exchange:e,matchedOperation:i,matchMode:this.options.matchMode,hostCompatibleWithSpecServers:r!==void 0||s,ignoreCookies:this.options.ignoreCookies??!1,ignoreHeaders:this.ignoreHeaders,cookies:n,validateSchema:(u,l,c)=>c?.coerce?this.coercingSchemaValidator.validate(u,l,c?.target):this.schemaValidator.validate(u,l,c?.target)}),a=[];for(let u of o){if(rt[u.severity]<this.minSeverityRank)continue;jr(u,i);let l=Tr(u,e);this.findings.push(l),a.push(l),qr(this.counters,u);let c=L({ruleId:u.ruleId,severity:u.severity,message:u.message,operationId:u.operationId,path:e.request.path,target:u.target,schemaPath:u.schemaPath}),m=this.problemKeyStats.get(c);if(m){m.occurrences+=1,m.previewIndex!==null&&(this.previewFindings[m.previewIndex].occurrences=m.occurrences);continue}if(this.totalProblemGroups+=1,this.problemGroupsByRule[u.ruleId]=(this.problemGroupsByRule[u.ruleId]??0)+1,this.previewFindings.length<this.previewLimit){let v=this.previewFindings.length;this.previewFindings.push(Fr(u,e)),this.problemKeyStats.set(c,{occurrences:1,previewIndex:v});continue}this.problemKeyStats.set(c,{occurrences:1,previewIndex:null})}return a}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,previewFindings:this.previewFindings,previewLimit:this.previewLimit,previewTruncated:this.totalProblemGroups>this.previewFindings.length};return{runId:this.runId,summary:e,findings:this.findings,coverage:this.coverage?.finalize()}}};import{stat as _r}from"node:fs/promises";var Lr=["get","put","post","delete","patch","head","options","trace"],Nr=new Set(["query","querystring","header","path","cookie"]),zr=/^(default|[1-5](\d{2}|xx))$/i;function Vr(t){return Lr.includes(t)}function Kr(t){return Nr.has(t)}function it(t,e){if(!Array.isArray(t))return[];let n=[];for(let r of t){if(!d(r))continue;let s=r.in;if(typeof s!="string"||!Kr(s))continue;let i=String(r.name??""),o=s==="querystring"?Object.entries(ie(r.content)):[],[a]=o,u=a?Ie(a[0]):void 0,l=s==="querystring"?a?.[1]:r.schema;s==="querystring"&&!a?R.warn(`Parameter "${i}" (querystring) of "${e}" has no content schema, so its value is not validated. Run \`redocly lint\` to check the description.
|
|
19
19
|
`):o.length>1&&R.warn(`Parameter "${i}" (querystring) of "${e}" has more than one media type, so only "${u}" is used. Run \`redocly lint\` to check the description.
|
|
20
|
-
`),n.push({name:i,in:s,required:!!r.required||s==="path",style:typeof r.style=="string"?r.style:void 0,schema:l,mediaType:u,formSchema:u===
|
|
20
|
+
`),n.push({name:i,in:s,required:!!r.required||s==="path",style:typeof r.style=="string"?r.style:void 0,schema:l,mediaType:u,formSchema:u===Me?Be(l):void 0})}return n}function ot(t){let e=t.in==="header";return`${t.in}:${e?t.name.toLowerCase():t.name}`}function Hr(t,e){let n=new Map;for(let r of t)n.set(ot(r),r);for(let r of e)n.set(ot(r),r);return Array.from(n.values())}function ie(t){let e={};if(!d(t))return e;for(let[n,r]of Object.entries(t))d(r)&&"schema"in r&&(e[n.toLowerCase()]=r.schema);return e}function Dr(t){return d(t)?ie(t.content):{}}function Ur(t){let e={};for(let[n,r]of Object.entries(t))!d(r)||!("content"in r)||(e[n]=ie(r.content));return e}function Jr(t,e,n){let r=t??e??n;return!Array.isArray(r)||r.length===0?[V("/")]:r.map(s=>{if(!d(s))return V("/");let i=typeof s.url=="string"?s.url:"/",o=d(s.variables)?s.variables:void 0;return V(i,o)})}function Gr(t,e,n){return n||`${t.toUpperCase()} ${e}`}function Wr(t){try{let e=ge(t.parsed);return he(e)==="oas3"?e:null}catch{return null}}function at(t){return Array.isArray(t)?t:void 0}function Qr(t,e){let n,r,s={},i="/",o=[],a;return{Root:{enter(u){n=u.servers,r=u.security;let l=d(u.components)?u.components.securitySchemes:void 0;s=d(l)?l:{}}},Paths:{PathItem:{enter(u,l){i=Fe(String(l.key)),o=it(u.parameters,i),a=u.servers},Operation:{enter(u,l){let c=String(l.key);if(!Vr(c))return;let m=Hr(o,it(u.parameters,`${c.toUpperCase()} ${i}`)),v=Oe(i),_=Jr(u.servers,a,n),P=u.requestBody,f=d(u.responses)?Object.fromEntries(Object.entries(u.responses).filter(([X])=>zr.test(X))):{},h={operationId:Gr(c,i,typeof u.operationId=="string"?u.operationId:void 0),method:c,pathTemplate:i,pathRegex:v.regex,pathParams:v.params,pathScore:v.score,servers:_,requestParameters:m,requestBodyContent:Dr(P),requestBodyRequired:d(P)&&!!P.required,responseStatuses:Object.keys(f),responseBodyContent:Ur(f),security:at(u.security)??at(r),securitySchemes:s,specSource:t},y=e.get(c)??[];y.push(h),e.set(c,y)}}}}}}function Yr(t,e,n,r,s){let i=pe(n.extendTypes(de(e),e),n),o=new Map,a={problems:[],specVersion:e,config:n,visitorsData:{}},u=ye([{severity:"warn",ruleId:"drift-index",visitor:Qr(r,s)}],i);Se({document:t,rootType:i.Root,normalizedVisitors:u,resolvedRefMap:o,ctx:a})}function Xr(t){return`${t.host??""}|${t.basePath}`}function Zr(t){for(let e of t.values()){let n=new Map;for(let r of e){let s=n.get(r.pathRegex.source)??[];s.push(r),n.set(r.pathRegex.source,s)}for(let r of n.values()){let s=new Map;for(let i of r)for(let o of i.servers){let a=Xr(o),u=s.get(a)??new Set;u.add(i.specSource),s.set(a,u)}for(let i of s.values())if(i.size>1){let[o]=r;R.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.
|
|
21
21
|
`);break}}}}function en(t,e){for(let r of t.values())r.sort((s,i)=>i.pathScore-s.pathScore);let n=Array.from(t.values()).reduce((r,s)=>r+s.length,0);return{operationsByMethod:t,loadedSpecs:e,loadedOperations:n}}async function tn(t){return(await _r(t)).isDirectory()?{specFiles:await we(t),fromDirectory:!0}:{specFiles:[t],fromDirectory:!1}}async function rs(t,e){let{specFiles:n,fromDirectory:r}=await tn(t),s=new Map,i=new le(e.resolve),o=0;for(let a of n){let u=await i.resolveDocument(null,a,!0);if(u instanceof Error){R.warn(`Failed to load OpenAPI description ${a}: ${u.message}
|
|
22
22
|
`);continue}let l=Wr(u);if(!l){r||R.warn(`Skipping ${a}: not an OpenAPI 3.x description.
|
|
23
23
|
`);continue}let c;try{let{bundle:m}=await ve({config:e,doc:u,externalRefResolver:i,dereference:!0});c=m}catch(m){R.warn(`Failed to bundle OpenAPI description ${a}: ${m.message}
|