@redocly/cli 2.47.0 → 2.48.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/chunks/{TEQA5OM7.js → 2GJPOM5H.js} +1 -1
- package/lib/chunks/{W2NJCZOS.js → 3CR6IHZV.js} +1 -1
- package/lib/chunks/3JJEI7CJ.js +456 -0
- package/lib/chunks/{QRD3XQNU.js → 3M6ARSHY.js} +1 -1
- package/lib/chunks/3X52NOC5.js +7 -0
- package/lib/chunks/46OWEERC.js +19 -0
- package/lib/chunks/4IA3ZTGK.js +20 -0
- package/lib/chunks/{TO2KJ36N.js → 5E3L4HJN.js} +1 -1
- package/lib/chunks/5EG7SNNU.js +177 -0
- package/lib/chunks/5L3FH5WQ.js +16 -0
- package/lib/chunks/5L5WOOWA.js +7 -0
- package/lib/chunks/5ZEWVWOC.js +14 -0
- package/lib/chunks/6O3ZHZZ2.js +7 -0
- package/lib/chunks/{KEUH3PST.js → AJZAID3R.js} +1 -1
- package/lib/chunks/BD5JG7YZ.js +7 -0
- package/lib/chunks/{B6HS7CVY.js → BEOYUN4L.js} +48 -48
- package/lib/chunks/CF5YCHNA.js +7 -0
- package/lib/chunks/D27SC2KR.js +90 -0
- package/lib/chunks/{SN2EC2ZR.js → DYAVWTVD.js} +1 -1
- package/lib/chunks/E35Q6YJN.js +7 -0
- package/lib/chunks/EB2V4VMP.js +7 -0
- package/lib/chunks/{QVV2EKMT.js → FL3CA53Z.js} +1 -1
- package/lib/chunks/FVBSRIWC.js +18 -0
- package/lib/chunks/G2XR6TRU.js +67 -0
- package/lib/chunks/G3YJARF7.js +57 -0
- package/lib/chunks/GA6WYGKY.js +7 -0
- package/lib/chunks/GBRES7WG.js +5400 -0
- package/lib/chunks/GHPAE4DZ.js +20 -0
- package/lib/chunks/{SL6AH3N2.js → GJRJZYC4.js} +1 -1
- package/lib/chunks/{REBHK2JR.js → GOJNDGZT.js} +1 -1
- package/lib/chunks/HJYFWIVE.js +9 -0
- package/lib/chunks/HLZCPNF7.js +16 -0
- package/lib/chunks/KIQI3UBS.js +177 -0
- package/lib/chunks/KNPQJVYA.js +14 -0
- package/lib/chunks/L3TZNNJJ.js +13 -0
- package/lib/chunks/{34J2ZJDK.js → LUC2DWUK.js} +1 -1
- package/lib/chunks/MBHFDTYI.js +78 -0
- package/lib/chunks/NB54XRRU.js +10 -0
- package/lib/chunks/NSIQWNYL.js +7 -0
- package/lib/chunks/NWMTC4AN.js +7 -0
- package/lib/chunks/PFYPTG4G.js +7 -0
- package/lib/chunks/{5NR4DJW4.js → PVM7EVWV.js} +1 -1
- package/lib/chunks/Q5FNL2RM.js +22 -0
- package/lib/chunks/QW5MTOU2.js +22 -0
- package/lib/chunks/REFX2EKS.js +13 -0
- package/lib/chunks/S4GQKQ5G.js +7 -0
- package/lib/chunks/SGBB4RNM.js +11 -0
- package/lib/chunks/{YQW463Z7.js → SPPRUUK3.js} +1 -1
- package/lib/chunks/SQVG3CEM.js +8 -0
- package/lib/chunks/TSB6PODJ.js +13 -0
- package/lib/chunks/U2A6GEAN.js +42 -0
- package/lib/chunks/UDBINQ2S.js +42 -0
- package/lib/chunks/UKSQ7B5H.js +2268 -0
- package/lib/chunks/{QL4V2A4A.js → V3JMSQFP.js} +1 -1
- package/lib/chunks/VWSPU27A.js +30 -0
- package/lib/chunks/W62VKXGM.js +26 -0
- package/lib/chunks/WIZYCYZG.js +7 -0
- package/lib/chunks/XDK4JK3V.js +9 -0
- package/lib/chunks/{5PXRDPHV.js → YJGI7CZ2.js} +1 -1
- package/lib/chunks/YQS3OX36.js +11 -0
- package/lib/chunks/{S4MX7JPH.js → Z2AXUXMK.js} +1 -1
- package/lib/chunks/ZBL4IVEW.js +11 -0
- package/lib/chunks/ZGMTMVBB.js +19 -0
- package/lib/chunks/{RIFZSMUA.js → ZVUMPMHU.js} +1 -1
- package/lib/eject-assets/AGENTS.md +137 -0
- package/lib/eject-assets/generators/cli/docs.ts +224 -0
- package/lib/eject-assets/generators/cli/engine-source.ts +21 -0
- package/lib/eject-assets/generators/cli/index.ts +90 -0
- package/lib/eject-assets/generators/cli/render.ts +348 -0
- package/lib/eject-assets/generators/go/client.ts +57 -0
- package/lib/eject-assets/generators/go/descriptor.ts +41 -0
- package/lib/eject-assets/generators/go/index.ts +336 -0
- package/lib/eject-assets/generators/go/models.ts +179 -0
- package/lib/eject-assets/generators/go/naming.ts +49 -0
- package/lib/eject-assets/generators/go/operations.ts +296 -0
- package/lib/eject-assets/generators/go/pagination.ts +194 -0
- package/lib/eject-assets/generators/go/types.ts +60 -0
- package/lib/eject-assets/generators/mock/faker.ts +214 -0
- package/lib/eject-assets/generators/mock/index.ts +35 -0
- package/lib/eject-assets/generators/mock/render.ts +282 -0
- package/lib/eject-assets/generators/mock/sample.ts +316 -0
- package/lib/eject-assets/generators/mock/values.ts +63 -0
- package/lib/eject-assets/generators/php/client.ts +63 -0
- package/lib/eject-assets/generators/php/descriptor.ts +58 -0
- package/lib/eject-assets/generators/php/index.ts +237 -0
- package/lib/eject-assets/generators/php/models.ts +275 -0
- package/lib/eject-assets/generators/php/naming.ts +51 -0
- package/lib/eject-assets/generators/php/operations.ts +232 -0
- package/lib/eject-assets/generators/php/pagination.ts +133 -0
- package/lib/eject-assets/generators/php/types.ts +148 -0
- package/lib/eject-assets/generators/python/client.ts +123 -0
- package/lib/eject-assets/generators/python/descriptor.ts +52 -0
- package/lib/eject-assets/generators/python/index.ts +251 -0
- package/lib/eject-assets/generators/python/models.ts +242 -0
- package/lib/eject-assets/generators/python/naming.ts +46 -0
- package/lib/eject-assets/generators/python/operations.ts +147 -0
- package/lib/eject-assets/generators/python/pagination.ts +128 -0
- package/lib/eject-assets/generators/python/types.ts +54 -0
- package/lib/eject-assets/generators/swr/index.ts +37 -0
- package/lib/eject-assets/generators/swr/render.ts +78 -0
- package/lib/eject-assets/generators/tanstack-query/index.ts +48 -0
- package/lib/eject-assets/generators/tanstack-query/render.ts +346 -0
- package/lib/eject-assets/generators/transformers/index.ts +46 -0
- package/lib/eject-assets/generators/transformers/render.ts +506 -0
- package/lib/eject-assets/generators/typescript/banner.ts +35 -0
- package/lib/eject-assets/generators/typescript/client.ts +254 -0
- package/lib/eject-assets/generators/typescript/descriptor.ts +137 -0
- package/lib/eject-assets/generators/typescript/index.ts +101 -0
- package/lib/eject-assets/generators/typescript/inline-runtime.ts +135 -0
- package/lib/eject-assets/generators/typescript/operation-signature.ts +62 -0
- package/lib/eject-assets/generators/typescript/operation-types.ts +17 -0
- package/lib/eject-assets/generators/typescript/operations.ts +524 -0
- package/lib/eject-assets/generators/typescript/response-headers.ts +74 -0
- package/lib/eject-assets/generators/typescript/type-guards.ts +159 -0
- package/lib/eject-assets/generators/typescript/types.ts +172 -0
- package/lib/eject-assets/generators/zod/index.ts +32 -0
- package/lib/eject-assets/generators/zod/schemas.ts +456 -0
- package/lib/eject-assets/skills/cli-generator/SKILL.md +121 -0
- package/lib/eject-assets/skills/client-generators/SKILL.md +142 -0
- package/lib/eject-assets/skills/go-generator/SKILL.md +96 -0
- package/lib/eject-assets/skills/mock-generator/SKILL.md +50 -0
- package/lib/eject-assets/skills/php-generator/SKILL.md +112 -0
- package/lib/eject-assets/skills/python-generator/SKILL.md +110 -0
- package/lib/eject-assets/skills/swr-generator/SKILL.md +50 -0
- package/lib/eject-assets/skills/tanstack-query-generator/SKILL.md +55 -0
- package/lib/eject-assets/skills/transformers-generator/SKILL.md +47 -0
- package/lib/eject-assets/skills/typescript-generator/SKILL.md +95 -0
- package/lib/eject-assets/skills/zod-generator/SKILL.md +54 -0
- package/lib/index.js +272 -193
- package/package.json +1 -1
- package/lib/chunks/PIJLRHNN.js +0 -8
- package/lib/chunks/Y5HLCNL5.js +0 -2542
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { createRequire as __createRequire } from 'node:module';
|
|
2
|
+
import { fileURLToPath as __fileURLToPath } from 'node:url';
|
|
3
|
+
import { dirname as __pathDirname } from 'node:path';
|
|
4
|
+
const require = __createRequire(import.meta.url);
|
|
5
|
+
var __filename = __fileURLToPath(import.meta.url);
|
|
6
|
+
var __dirname = __pathDirname(__filename);
|
|
7
|
+
import{a as j}from"./NSIQWNYL.js";import{b as O}from"./UKSQ7B5H.js";import{b as Q,c as _,d as I,e as M,f as X,g as Z,h as ee}from"./YQS3OX36.js";import{c as z,d as P,e as H,f as N,g as R,h as U,i as V,j as x,k as D,n as Y}from"./HJYFWIVE.js";var p=z.php,B=new j;function h(e){return B.typeName(e)}function g(e){return B.memberName(e)}function c(e){return B.string(e)}function ne(e){return P(e.name,{style:"camel",reserved:p})}function F(e){let n=e.services.flatMap(s=>s.operations),a=H(n.map(s=>s.name),{style:"camel",reserved:p});return new Map(n.map((s,r)=>[s.name,a[r]]))}function ue(e){return X(e).map(a=>a.kind==="literal"?c(a.value):`$${g(a.name)}`).join(" . ")}function te(e,n){let a=n.servers??[];if(a.length===0)return;let s=new Set;e.line("/** The declared servers; variables default to the values from the description. */"),e.line("final class Servers"),e.block("{",()=>{a.forEach((r,t)=>{let i=P(r.description??`server${t+1}`,{style:"camel",reserved:p});s.has(i)&&(i=`${i}${t+1}`),s.add(i);let o=r.variables.map(l=>`string $${g(l.name)} = ${c(l.default)}`);t>0&&e.blank(),e.line(`public static function ${i}(${o.join(", ")}): string`),e.block("{",()=>{e.line(`return ${ue(r)};`)},"}")})},"}"),e.blank()}function re(e,n){let a=Z(e,n).map(s=>`[${s.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(a.length!==0)return`[${a.join(", ")}]`}function se(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.limitParam!==void 0?[`'limitParam' => ${c(e.limitParam)}`]:[],...e.items!==void 0?[`'items' => ${c(e.items)}`]:[]].join(", ")}]`}function ae(e,n){let a=new Set;return`[${(e.successResponseHeaders??[]).map(r=>{let t=P(r.name,{style:"camel",reserved:p}),i=2;for(;a.has(t);)t=`${P(r.name,{style:"camel",reserved:p})}_${i++}`;a.add(t);let o=Y(r.schema,n);return`[${c(r.name)}, ${c(t)}, ${c(o)}]`}).join(", ")}]`}function E(e,n){let a=n.schemas.find(t=>t.name===e);if(a===void 0)return"other";let s=a.schema,r=D(s);return r!==void 0&&(r.scalar==="string"||r.scalar==="integer")?"enum":(s.kind==="object"||s.kind==="intersection")&&R(s,n)!==void 0?"class":"other"}function m(e,n,a="string"){if(V(e)){let s=m(x(e),n,a);return A(s)}switch(e.kind){case"scalar":return a==="Date"&&e.scalar==="string"&&G(e)?"\\DateTimeImmutable":{string:"string",integer:"int",number:"float",boolean:"bool"}[e.scalar];case"array":case"record":return"array";case"ref":{let s=E(e.name,n);if(s==="class"||s==="enum")return h(e.name);let r=N(e,n);return r===void 0?"mixed":m(r,n,a)}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 h(e.base);case"union":return $e(e.members,n,a);case"null":case"object":case"intersection":case"unknown":return"mixed"}}function G(e){let n=e.metadata?.format;return n==="date"||n==="date-time"}function A(e){return e==="mixed"||e.startsWith("?")||e.endsWith("|null")?e:e.includes("|")?`${e}|null`:`?${e}`}function $e(e,n,a){let s=[];for(let r of e){if(r.kind==="null")continue;let t=m(r,n,a);if(t==="mixed")return"mixed";let i=t.startsWith("?")?t.slice(1):t;s.includes(i)||s.push(i),t.startsWith("?")&&!s.includes("null")&&s.push("null")}return s.length===0?"mixed":s.join("|")}function K(e,n,a){if(e===void 0)return;let s=x(e);if(s.kind==="ref"){let t=N(s,n);return E(s.name,n)==="other"?K(t,n,a):void 0}if(s.kind!=="array")return;let r=m(s.items,n,a);return r==="mixed"?void 0:r}function ie(e,n){let a=n.schemas.find(s=>s.name===e);return a!==void 0&&U(a.schema,n)!==void 0}function v(e,n,a,s){let r=x(e);if(s==="Date"&&r.kind==="scalar"&&r.scalar==="string"&&G(r))return`new \\DateTimeImmutable(${n})`;if(r.kind==="omit")return v({kind:"ref",name:r.base},n,a,s);if(r.kind==="ref"){let t=E(r.name,a);if(t==="class")return`${h(r.name)}::fromArray(${n})`;if(t==="enum")return`${h(r.name)}::from(${n})`;if(ie(r.name,a))return`unmarshal${h(r.name)}(${n})`;let i=N(r,a);return i===void 0?void 0:v(i,n,a,s)}if(r.kind==="array"){let t=v(r.items,"$item",a,s);return t===void 0?void 0:`array_map(static fn ($item) => ${t}, ${n})`}if(r.kind==="record"){let t=v(r.value,"$item",a,s);return t===void 0?void 0:`array_map(static fn ($item) => ${t}, ${n})`}}function q(e,n,a,s="string"){let r=x(e);if(s==="Date"&&r.kind==="scalar"&&r.scalar==="string"){if(r.metadata?.format==="date")return`${n}->format('Y-m-d')`;if(r.metadata?.format==="date-time")return`${n}->format(\\DateTimeInterface::ATOM)`}if(r.kind==="omit")return q({kind:"ref",name:r.base},n,a,s);if(r.kind==="ref"){let t=E(r.name,a);if(t==="class")return`${n}->toArray()`;if(t==="enum")return`${n}->value`;if(ie(r.name,a))return`is_object(${n}) ? ${n}->toArray() : ${n}`;let i=N(r,a);return i===void 0?void 0:q(i,n,a,s)}if(r.kind==="array"||r.kind==="record"){let t=r.kind==="array"?r.items:r.value,i=q(t,"$item",a,s);return i===void 0?void 0:`array_map(static fn ($item) => ${i}, ${n})`}}function fe(e,n,a,s,r,t){let i=[...a.filter(o=>o.required),...a.filter(o=>!o.required)];e.doc(h(n),t),e.line(`final class ${h(n)}`),e.block("{",()=>{e.block("public function __construct(",()=>{for(let o of i){let l=m(o.schema,s,r);if(o.required)e.line(`public ${l} $${g(o.name)},`);else{let u=A(l);e.line(`public ${u} $${g(o.name)} = null,`)}}},") {"),e.line("}"),e.blank(),e.line("public static function fromArray(array $data): self"),e.block("{",()=>{e.block("return new self(",()=>{for(let o of i){let l=`$data[${c(o.name)}]`,u=v(o.schema,l,s,r),f=g(o.name);o.required?e.line(`${f}: ${u??l},`):u===void 0?e.line(`${f}: ${l} ?? null,`):e.line(`${f}: isset(${l}) ? ${u} : null,`)}},");")},"}"),e.blank(),e.line("public function toArray(): array"),e.block("{",()=>{e.line("$data = [];");for(let o of i){let l=`$this->${g(o.name)}`,u=q(o.schema,l,s,r)??l;o.required?e.line(`$data[${c(o.name)}] = ${u};`):e.block(`if (${l} !== null) {`,()=>{e.line(`$data[${c(o.name)}] = ${u};`)},"}")}e.line("return $data;")},"}")},"}"),e.blank()}function L(e,n="string"){let a=new j;for(let{name:s,schema:r}of e.schemas){let t=D(r);if(t!==void 0&&(t.scalar==="string"||t.scalar==="integer")){let o=t.scalar==="string"?"string":"int";a.doc(h(s),r.description),a.line(`enum ${h(s)}: ${o}`),a.block("{",()=>{let l=H(t.values.map(u=>String(u)),{style:"pascal",reserved:p});t.values.forEach((u,f)=>{let y=typeof u=="string"?c(u):String(u);a.line(`case ${l[f]} = ${y};`)})},"}"),a.blank();continue}if(r.kind==="object"||r.kind==="intersection"){let o=R(r,e);if(o!==void 0){fe(a,s,o.properties,e,n,o.description??r.description);continue}}let i=U(r,e);if(i!==void 0){let o=h(s),l=i.cases.map(u=>`${u.value} -> ${h(u.schemaName)}`).join(", ");a.line(`/** ${o} is a discriminated union (${c(i.property)}): ${l}. */`),a.line(`function unmarshal${o}(array $data): mixed`),a.block("{",()=>{a.block(`return match ($data[${c(i.property)}] ?? null) {`,()=>{for(let u of i.cases)a.line(`${c(u.value)} => ${h(u.schemaName)}::fromArray($data),`);a.line("default => $data,")},"};")},"}"),a.blank();continue}}return a.toString()}var oe=new Set(["post","put","patch"]),de=["body","headers","idempotencyKey"];function W(e,n,a,s){let r=H([...e.pathParams,...e.queryParams].map(l=>l.name),{style:"camel",reserved:p,taken:de}),t=e.pathParams.map((l,u)=>({php:r[u],wire:l.name,type:m(l.schema,n,s)})),i=e.queryParams.map((l,u)=>{let f=r[e.pathParams.length+u];return{php:f,wire:l.name,type:m(l.schema,n,s),value:q(l.schema,`$${f}`,n,s)??`$${f}`}}),o=[...t.map(({php:l,type:u})=>`${u} $${l}`),...a&&e.requestBody?[`${M(e)?"array":m(e.requestBody.schema,n,s)} $body`]:[],...i.map(({php:l,type:u})=>`${A(u)} $${l} = null`),"?array $headers = null",...a&&oe.has(e.method.toLowerCase())?["?string $idempotencyKey = null"]:[]];return{pathArgs:t,queryArgs:i,signature:o}}function me(e,n,a){e.line(`$op = OPERATIONS[${c(n.specName??n.name)}];`),e.line("[$authHeaders, $query, $cookies] = resolveAuth($op['security'] ?? [], $this->config->auth);");for(let{php:r,wire:t,value:i}of a.queryArgs)e.block(`if ($${r} !== null) {`,()=>{e.line(`$query[${c(t)}] = ${i};`)},"}");let s=a.pathArgs.map(({php:r,wire:t})=>`${c(t)} => $${r}`).join(", ");e.line(`$url = buildUrl($this->config->serverUrl, $op['path'], [${s}]);`),e.line("$requestHeaders = array_merge($authHeaders, $headers ?? []);"),e.block("if ($cookies !== []) {",()=>{e.line("$requestHeaders['Cookie'] = implode('; ', $cookies);")},"}")}function J(e,n,a,s,r,t=!1){let i=W(n,s,!0,r),o=I(n),l=_(n),u=o===void 0&&l===void 0&&n.successResponses.some(b=>b.contentType!==""),f=t?"Envelope":o!==void 0?"\\Generator":l!==void 0?m(l,s,r):u?"string":"void",y=t?`${a}WithHeaders`:a,S=t?void 0:K(l,s,r);e.doc(y,t?`Like ${a}(), returning an Envelope with the declared response headers.`:n.summary??`${n.method.toUpperCase()} ${n.path}`,S===void 0?[]:[`@return ${S}[]`]),e.line(`public function ${y}(${i.signature.join(", ")}): ${f}`),e.block("{",()=>{if(me(e,n,i),o!==void 0){let d=o.schema!==void 0&&o.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, ${d?"true":"false"});`);return}let b=["'operationId' => $op['id']","'method' => $op['method']","'url' => $url","'headers' => $requestHeaders","'query' => $query"];if(n.requestBody&&M(n))e.line("[$contentType, $encoded] = toMultipart($body);"),b.push("'body' => $encoded","'contentType' => $contentType");else if(n.requestBody){let d=q(n.requestBody.schema,"$body",s,r)??"$body";e.line(`$payload = json_encode(${d});`),b.push("'body' => $payload",`'contentType' => ${c(n.requestBody.contentType)}`)}oe.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 $=u?"$response['body']":(l===void 0?void 0:v(l,"decodeJson($response)",s,r))??"decodeJson($response)";if(t){e.line(`$data = ${$};`),e.line(`return new Envelope(data: $data, headers: readEnvelopeHeaders($response, ${ae(n,s)}), status: $response['status']);`);return}if(u){e.line("return $response['body'];");return}if(f==="void"){e.line("decodeJson($response);");return}e.line(`return ${$};`)},"}"),e.blank()}function ce(e,n,a,s,r,t,i,o,l){let u=W(n,s,!1,r),f=a,y=()=>{e.line(`$op = OPERATIONS[${c(n.specName??n.name)}];`),e.line("$base = [];");for(let{php:d,wire:k,value:w}of u.queryArgs)e.block(`if ($${d} !== null) {`,()=>{e.line(`$base[${c(k)}] = ${w};`)},"}");let $=u.pathArgs.map(({php:d,wire:k})=>`${c(k)} => $${d}`).join(", ");e.block("$call = function (array $params) use ($op, $headers): array {",()=>{e.line("[$authHeaders, $authQuery, $cookies] = resolveAuth($op['security'] ?? [], $this->config->auth);"),e.line(`$url = buildUrl($this->config->serverUrl, $op['path'], [${$}]);`),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];")},"};")},S=m(_(n)??{kind:"unknown"},s,r),b=S==="mixed"?"mixed":S;e.line("/**"),e.line(` * ${f} response pages, following the pagination rule automatically.`),e.line(" *"),e.line(` * @return \\Generator<int, ${b}>`),e.line(" */"),e.line(`public function ${f}Pages(${u.signature.join(", ")}): \\Generator`),e.block("{",()=>{y(),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 ${f} page.`),e.line(" *"),e.line(` * @return \\Generator<int, ${l}>`),e.line(" */"),e.line(`public function ${f}Items(${u.signature.join(", ")}): \\Generator`),e.block("{",()=>{y(),e.block("foreach (iterPages($call, $op['pagination'], $base) as $page) {",()=>{e.line(`$items = resolvePointer($page, ${c(o??"")});`),e.block("foreach (is_array($items) ? $items : [] as $item) {",()=>{e.line(`yield ${i??"$item"};`)},"}")},"}")},"}"),e.blank()}function pe(e){let n=e.split(`
|
|
8
|
+
`),a=0;for(let s=0;s<n.length;s++)if(n[s].trim().startsWith("namespace ")){a=s+1;break}return n.slice(a).join(`
|
|
9
|
+
`).trim()}var nn=({model:e,output:n,banner:a,emit:s,pagination:r})=>{let t=new j,i=s.dateType??"string",o=P(e.title,{style:"pascal",reserved:p});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 ${o};`),t.blank(),t.line(L(e,i)),te(t,e),s.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(pe(O)),t.blank());let l=e.services.flatMap($=>$.operations),u=F(e),f=new Map;for(let $ of l){let d=r?.get($.name)?.spec;d!==void 0&&f.set($.name,d)}t.block("const OPERATIONS = [",()=>{for(let $ of l){let d=$.specName??$.name,k=re($,e),w=f.get($.name),T=[`'id' => ${c(d)}`,`'method' => ${c($.method.toUpperCase())}`,`'path' => ${c($.path)}`,...k!==void 0?[`'security' => ${k}`]:[],...w!==void 0?[`'pagination' => ${se(w)}`]:[]];t.line(`${c(d)} => [${T.join(", ")}],`)}},"];"),t.blank(),t.doc("Client",`Client for ${e.title} (${e.version}).`),t.line("class Client"),t.block("{",()=>{t.line("public function __construct(private Config $config)"),t.block("{",()=>{t.block("if ($this->config->serverUrl === '') {",()=>{t.line(`$this->config->serverUrl = ${c(s.serverUrl??e.serverUrl??"")};`)},"}")},"}"),t.blank();for(let $ of l){let d=u.get($.name);J(t,$,d,e,i),I($)===void 0&&($.successResponseHeaders?.length??0)>0&&J(t,$,d,e,i,!0);let k=f.get($.name);if(k===void 0)continue;let w=_($),T=w===void 0?void 0:v(w,"$page",e,i),C=ee(w,k.items,e),le=C===void 0?void 0:v(C,"$item",e,i);ce(t,$,d,e,i,T,le,k.items,C===void 0?"mixed":m(C,e,i))}},"}");let y={path:n.path.replace(/\.[^.\\/]+$/,".php"),content:t.toString()};if(s.runtime!=="module")return[y];let S=a.map($=>`// ${$}`).join(`
|
|
10
|
+
`),b=O.replace(/^namespace .*$/m,`namespace ${o};`).replace(/^<\?php\n/,`<?php
|
|
11
|
+
|
|
12
|
+
${S}
|
|
13
|
+
`).trimEnd();return[y,{path:y.path.replace(/[^\\/]+$/,"runtime.php"),content:`${b}
|
|
14
|
+
`}]};function he(e,n){let a=[...e.pathParams.map(t=>`${c(`<${g(t.name)}>`)}`),...e.requestBody?["$body"]:[],...e.queryParams.length>0?[`${g(e.queryParams[0].name)}: ${c("<value>")}`]:[]],s=P(n.model.title,{style:"pascal",reserved:p});return{lang:"php",label:"PHP SDK",source:`require '${n.outputPath.replace(/^.*[\\/]/,"").replace(/\.[^.]+$/,".php")}';
|
|
15
|
+
|
|
16
|
+
use ${s}\\{Client, Config};
|
|
17
|
+
|
|
18
|
+
$client = new Client(new Config());
|
|
19
|
+
$result = $client->${F(n.model).get(e.name)??ne(e)}(${a.join(", ")});
|
|
20
|
+
`}}var tn=({model:e,output:n,emit:a,pagination:s})=>[{path:n.path.replace(/\.[^.\\/]+$/,".php.md"),content:Q(e,{title:`${e.title} PHP SDK reference`,frontmatter:a.docsFrontmatter===!0,language:{name:"php",label:"PHP",fence:"php",requires:"The SDK needs the curl extension."},sample:r=>he(r,{model:e,emit:a,outputPath:n.path}),paginated:new Set(s?.keys()??[])})}];export{m as a,L as b,nn as c,he as d,tn as e};
|
|
@@ -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 x}from"./
|
|
7
|
+
import{a as x}from"./5E3L4HJN.js";import{a as v,b as y,c as R,d as u}from"./YJGI7CZ2.js";import{c as f,d as w}from"./SPPRUUK3.js";import{a as g,b as m}from"./3M6ARSHY.js";import{O as a}from"./BEOYUN4L.js";import"./NEWT5A6S.js";import"./RFWIIJFG.js";import{mkdir as A,writeFile as C}from"node:fs/promises";import S from"node:path";async function F(e){let i=await w(e.trafficPath);if(i.length===0)throw new Error("No traffic files found in the provided traffic path.");let t=y.create({openApiIndex:e.openApiIndex,matchMode:e.matchMode,ignoreCookies:e.ignoreCookies,ignoreHeaders:e.ignoreHeaders,previewFindingsLimit:e.previewFindingsLimit,activeRules:e.activeRules,server:e.server,minSeverity:e.minSeverity}),r=0,o=0;for(let n of i){let s=await x(n,e.format);if(!s){a.warn(`Skipping traffic file with unrecognized format: ${n}
|
|
8
8
|
`);continue}r+=1;for await(let c of s.parse(n))await t.process({...c,index:o}),o+=1}if(r===0)throw new Error("No supported traffic files found. In auto mode, files must match built-in traffic parser signatures.");if(o===0)throw new Error("No HTTP exchanges were parsed from the provided traffic files.");return t.finalize()}var E=!!process.stdout.isTTY&&process.env.NO_COLOR===void 0;function T(e){let i=new Set;for(let t of e.operationsByMethod.values())for(let r of t)for(let o of r.servers)i.add(o.rawUrl);return Array.from(i).sort()}function I(e,i,t){let r=e.totalExchanges-e.skippedExchanges;if(r===0&&e.skippedExchanges>0){a.warn(`All ${e.skippedExchanges} exchange(s) were outside the --server "${t}" and were skipped. Check that the server matches the traffic URLs.
|
|
9
9
|
`);return}if(e.documentedExchanges>0||r===0)return;let o=T(i),n=t?`Check that the --server "${t}" matches the traffic URLs and that the description paths align with the remainder.`:e.hostCompatibleExchanges===r?`The traffic hosts are compatible with the description servers (${o.join(", ")}), so the endpoints are likely undocumented; if they should be documented, check that the description base paths and paths align with the traffic URLs, or use --server to declare the server the traffic was captured against.`:`Check that the traffic host and base path match the description servers (${o.join(", ")}), or use --server to declare the server the traffic was captured against.`;a.warn(`None of the ${r} validated exchange(s) matched a documented operation. ${n}
|
|
10
10
|
`)}async function $(e,i){let t=f(e);await A(S.dirname(t),{recursive:!0}),await C(t,i,"utf8")}async function q({argv:e,config:i}){let t=f(e.traffic),r=e["traffic-format"],o=e.rules?u(e.rules):void 0,n=e["ignore-headers"]?u(e["ignore-headers"]):void 0,s=e.server;if(s&&e["match-mode"])return m("The --server and --match-mode options are mutually exclusive: --match-mode controls how requests are located via the description servers, while --server replaces the description servers with the one the traffic was captured against.");let c=e["match-mode"]??"strict-host",d=f(e.api),p=await R(d,i);if(p.loadedOperations===0)return m(`No OpenAPI operations were loaded from: ${d}`);let{runId:k,summary:h,findings:O}=await F({trafficPath:t,format:r,matchMode:c,ignoreCookies:e["ignore-cookies"],ignoreHeaders:n,previewFindingsLimit:e["max-findings"],activeRules:o,openApiIndex:p,server:s,minSeverity:e["min-severity"]});I(h,p,s);let l=v({runId:k,summary:h,findings:O,meta:{specSource:d,trafficPath:t,format:r,matchMode:c,server:s}},{format:e["report-format"],color:E&&e["report-format"]==="pretty"&&!e.output,maxFindings:e["max-findings"]});if(e.output?(await $(e.output,l),a.info(`Drift report written to: ${f(e.output)}
|
|
@@ -4,4 +4,4 @@ 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,b,c,d,e,f,g}from"./
|
|
7
|
+
import{a,b,c,d,e,f,g}from"./LUC2DWUK.js";import"./O6PRCLSV.js";import"./32XCOMOR.js";import"./BEOYUN4L.js";import"./NEWT5A6S.js";import"./RFWIIJFG.js";export{d as RESET_ESCAPE_CODE,c as calculateTotals,f as conditionallyMaskSecrets,b as generate,e as maskSecrets,a as parseRuntimeExpression,g as run};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { createRequire as __createRequire } from 'node:module';
|
|
2
|
+
import { fileURLToPath as __fileURLToPath } from 'node:url';
|
|
3
|
+
import { dirname as __pathDirname } from 'node:path';
|
|
4
|
+
const require = __createRequire(import.meta.url);
|
|
5
|
+
var __filename = __fileURLToPath(import.meta.url);
|
|
6
|
+
var __dirname = __pathDirname(__filename);
|
|
7
|
+
var c=class{constructor(n=" "){this.indentUnit=n}indentUnit;lines=[];depth=0;line(n=""){return this.lines.push(n===""?"":this.indentUnit.repeat(this.depth)+n),this}blank(){return this.line()}indent(n){return this.depth++,n(),this.depth--,this}block(n,t,r){return this.line(n),this.indent(t),r===void 0?this:this.line(r)}toString(){return this.lines.join(`
|
|
8
|
+
`)+`
|
|
9
|
+
`}};function d(e){return e.replace(/^\+(?=\d)/,"plus ").replace(/^-(?=\d)/,"minus ").replace(/([A-Z]{2,})s(?![a-z])/g,"$1S").replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").split(/[^A-Za-z0-9]+/).filter(n=>n!=="").map(n=>n.toLowerCase())}var p=e=>e.charAt(0).toUpperCase()+e.slice(1),l={camel:e=>{let[n,...t]=d(e);return(n??"")+t.map(p).join("")},pascal:e=>d(e).map(p).join(""),snake:e=>d(e).join("_"),screaming:e=>d(e).join("_").toUpperCase()},S={typescript:new Set(["break","case","catch","class","const","continue","debugger","default","delete","do","else","enum","export","extends","false","finally","for","function","if","import","in","instanceof","new","null","return","super","switch","this","throw","true","try","typeof","var","void","while","with","implements","interface","let","package","private","protected","public","static","yield","await"]),python:new Set(["false","none","true","and","as","assert","async","await","break","class","continue","def","del","elif","else","except","finally","for","from","global","if","import","in","is","lambda","nonlocal","not","or","pass","raise","return","try","while","with","yield","match","case","type"]),go:new Set(["break","case","chan","const","continue","default","defer","else","fallthrough","for","func","go","goto","if","import","interface","map","package","range","return","select","struct","switch","type","var"]),php:new Set(["abstract","and","array","as","break","callable","case","catch","class","clone","const","continue","declare","default","die","do","echo","else","elseif","empty","enddeclare","endfor","endforeach","endif","endswitch","endwhile","enum","eval","exit","extends","final","finally","fn","for","foreach","function","global","goto","if","implements","include","instanceof","insteadof","interface","isset","list","match","namespace","new","or","print","private","protected","public","readonly","require","return","static","switch","throw","trait","try","unset","use","var","while","xor","yield","true","false","null","int","float","bool","string","void","iterable","object","mixed","never","self","parent"])};function h(e,n={}){let t=l[n.style??"camel"](e),r=t===""?"_":/^[0-9]/.test(t)?`_${t}`:t;return n.reserved?.has(r.toLowerCase())?`${r}_`:r}function m(e,n={}){let t=new Set(n.taken??[]),r=n.style==="snake"||n.style==="screaming"?"_":"";return e.map(s=>{let i=h(s,n),o=i;for(let f=2;t.has(o);f++)o=`${i}${r}${f}`;return t.add(o),o})}function a(e,n){let t=new Set,r=e;for(;r.kind==="ref";){let{name:s}=r;if(t.has(s))return;t.add(s);let i=n.schemas.find(o=>o.name===s);if(i===void 0)return;r=i.schema}return r}function b(e,n){let t=a(e,n);if(t===void 0)return;if(t.kind==="object")return{properties:t.properties,description:t.description};if(t.kind!=="intersection")return;let r=new Map;for(let s of t.members){let i=b(s,n);if(i===void 0)return;for(let o of i.properties)r.set(o.name,o)}return{properties:[...r.values()],description:t.description}}function M(e,n){let t=a(e,n);if(t?.kind!=="union"||t.discriminator===void 0)return;let r=[];for(let{value:s,schemaName:i}of t.discriminator.mapping){let o=a({kind:"ref",name:i},n);if(o===void 0)return;r.push({value:s,schemaName:i,schema:o})}return{property:t.discriminator.propertyName,cases:r}}function y(e){return e.kind==="union"&&e.members.some(n=>n.kind==="null")}function x(e){if(e.kind!=="union"||!y(e))return e;let n=e.members.filter(t=>t.kind!=="null");return n.length===1?n[0]:{...e,members:n}}function A(e){if(e.kind!=="enum")return;let n=m(e.values.map(t=>typeof t=="string"?l.screaming(t):`VALUE_${l.screaming(String(t))}`),{style:"screaming"});return{values:e.values,scalar:e.scalar,memberNames:n}}function $(e){if(!e)return[];let n=e.split(/\r\n|\n|\r/).map(t=>t.trim());for(;n.length>0&&n[0]==="";)n.shift();for(;n.length>0&&n[n.length-1]==="";)n.pop();return n}function g(e,n,t){if(e.kind==="object")return e.properties.find(r=>r.name===n)?.schema;if(e.kind==="record")return e.value;if(e.kind==="array"&&/^(0|[1-9]\d*)$/.test(n))return e.items;if(e.kind==="intersection"){let r;for(let s of e.members){let i=a(s,t);i!==void 0&&(r=g(i,n,t)??r)}return r}}function N(e,n,t){let r=a(e,t);if(!(r===void 0||n!==""&&!n.startsWith("/"))){if(n==="")return r;for(let s of n.slice(1).split("/")){let i=s.replaceAll("~1","/").replaceAll("~0","~"),o=g(r,i,t);if(o===void 0||(r=a(o,t),r===void 0))return}return r}}function u(e,n,t=new Set){if(e.kind==="ref"){if(t.has(e.name))return"string";t.add(e.name);let r=n.schemas.find(s=>s.name===e.name);return r===void 0?"string":u(r.schema,n,t)}if(e.kind==="intersection"){let r=e.members.filter(i=>i.kind!=="unknown");if(r.length===1)return u(r[0],n,t);let s=[...new Set(r.map(i=>u(i,n,new Set(t))))];return s.length===1?s[0]:s.every(i=>i==="integer"||i==="number")?"number":"string"}if(e.kind==="union"){let r=e.members.filter(s=>s.kind!=="null");return r.length===1?u(r[0],n,t):"string"}if(e.kind==="scalar"||e.kind==="enum"){if(e.scalar==="integer")return"integer";if(e.scalar==="number")return"number";if(e.scalar==="boolean")return"boolean"}if(e.kind==="literal"){if(typeof e.value=="number")return Number.isInteger(e.value)?"integer":"number";if(typeof e.value=="boolean")return"boolean"}return"string"}export{c as a,l as b,S as c,h as d,m as e,a as f,b as g,M as h,y as i,x as j,A as k,$ as l,N as m,u as n};
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { createRequire as __createRequire } from 'node:module';
|
|
2
|
+
import { fileURLToPath as __fileURLToPath } from 'node:url';
|
|
3
|
+
import { dirname as __pathDirname } from 'node:path';
|
|
4
|
+
const require = __createRequire(import.meta.url);
|
|
5
|
+
var __filename = __fileURLToPath(import.meta.url);
|
|
6
|
+
var __dirname = __pathDirname(__filename);
|
|
7
|
+
import{a as $,b as i,c,d as a,e as m,f as p}from"./XDK4JK3V.js";import"./VWSPU27A.js";import"./YQS3OX36.js";import"./GBRES7WG.js";import"./PFYPTG4G.js";import"./BEOYUN4L.js";import"./NEWT5A6S.js";import{k as u}from"./NB54XRRU.js";import"./HJYFWIVE.js";import"./RFWIIJFG.js";import{join as M}from"node:path";function d(t,e){let r=$(t,"swr");if(r.length===0)return"";let s=r.some(i),o=r.some(n=>!i(n));return[...s?['import useSWR from "swr";']:[],...o?['import useSWRMutation from "swr/mutation";']:[],p(r,e.sdkModule,s),...r.flatMap(n=>i(n)?y(n):[k(n)])].join(`
|
|
8
|
+
|
|
9
|
+
`)}function f(t,e,r){return`export function use${u(t.name)}(${e}) {
|
|
10
|
+
return ${r};
|
|
11
|
+
}`}function y(t){let e=c(t),r=e?`vars: ${a(t)}`:"",s=e?`[${JSON.stringify(t.name)}, vars]`:`[${JSON.stringify(t.name)}]`,o=`export const ${t.name}Key = (${r}) => ${s} as const;`,n=`useSWR(${`${t.name}Key(${e?"vars":""})`}, () => ${m(t,"vars",!0)})`,g=e?`vars: ${a(t)}, init?: Omit<RequestOptions, "envelope">`:'init?: Omit<RequestOptions, "envelope">';return[o,f(t,g,n)]}function k(t){let e=c(t)?`(_key: string, { arg }: {
|
|
12
|
+
arg: ${a(t)};
|
|
13
|
+
}) => ${m(t,"arg",!1)}`:`() => ${m(t,"arg",!1)}`,r=`useSWRMutation(${JSON.stringify(t.name)}, ${e})`;return f(t,"",r)}var h=({model:t,output:e,banner:r,emit:s})=>{let o=d(t,{sdkModule:`./${e.stem}.${s.importExt??"js"}`});if(o==="")return[];let l=r.map(n=>`// ${n}`).join(`
|
|
14
|
+
`);return[{path:M(e.dir,`${e.stem}.swr.ts`),content:`${l}
|
|
15
|
+
|
|
16
|
+
${o}`}]};export{h as swrGenerator};
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
import { createRequire as __createRequire } from 'node:module';
|
|
2
|
+
import { fileURLToPath as __fileURLToPath } from 'node:url';
|
|
3
|
+
import { dirname as __pathDirname } from 'node:path';
|
|
4
|
+
const require = __createRequire(import.meta.url);
|
|
5
|
+
var __filename = __fileURLToPath(import.meta.url);
|
|
6
|
+
var __dirname = __pathDirname(__filename);
|
|
7
|
+
import"./YQS3OX36.js";import{a as h}from"./GBRES7WG.js";import"./PFYPTG4G.js";import"./BEOYUN4L.js";import"./NEWT5A6S.js";import{e as g,h as p,k as y}from"./NB54XRRU.js";import"./HJYFWIVE.js";import"./RFWIIJFG.js";import{join as M}from"node:path";var a=" ";function f(e){return`${y(e)}Schema`}var x=new Map;function u(e,r=x,t=""){return k(w(e,r,t),e)}function w(e,r,t){switch(e.kind){case"scalar":return S(e.scalar,e.metadata);case"object":return b(e.properties,r,t);case"array":return`z.array(${u(e.items,r,t)})`;case"record":return`z.record(z.string(), ${u(e.value,r,t)})`;case"ref":return`z.lazy(() => ${f(e.name)})`;case"literal":return`z.literal(${p(e.value)})`;case"enum":return z(e.values);case"union":return E(e.members,r,t);case"intersection":return e.members.map(n=>u(n,r,t)).reduce((n,o)=>`${n}.and(${o})`);case"null":return"z.null()";case"unknown":return"z.unknown()";case"omit":return q(e.base,e.keys,r,t)}}function S(e,r){switch(e){case"string":return r?.format==="binary"?"z.instanceof(Blob)":"z.string()";case"integer":return"z.number().int()";case"number":return"z.number()";case"boolean":return"z.boolean()"}}function c(e){return g(e)===e?e:JSON.stringify(e)}function b(e,r,t){if(e.length===0)return"z.object({})";let n=t+a;return`z.object({
|
|
8
|
+
${e.map((s,i)=>{let d=u(s.schema,r,n),l=s.required?d:`${d}.optional()`,v=i===e.length-1?"":",";return`${n}${c(s.name)}: ${l}${v}`}).join(`
|
|
9
|
+
`)}
|
|
10
|
+
${t}})`}function z(e){return e.every(r=>typeof r=="string")?`z.enum([${e.map(r=>JSON.stringify(r)).join(", ")}])`:`z.union([${e.map(r=>`z.literal(${p(r)})`).join(", ")}])`}function E(e,r,t){let n=e.map(o=>u(o,r,t));return n.length===1?n[0]:`z.union([${n.join(", ")}])`}function q(e,r,t,n){let o=t.get(e);if(o&&o.kind!=="object")return u(m(o,r,t,new Set([e])),t,n);let s=r.map(i=>`${c(i)}: true`).join(", ");return`${f(e)}.omit({ ${s} })`}function m(e,r,t,n){switch(e.kind){case"object":return{...e,properties:e.properties.filter(o=>!r.includes(o.name))};case"union":case"intersection":return{...e,members:e.members.map(o=>m(o,r,t,n))};case"ref":{if(n.has(e.name))return e;let o=t.get(e.name);if(!o)return e;if(o.kind==="object"){let s=r.filter(i=>o.properties.some(d=>d.name===i));return s.length>0?{kind:"omit",base:e.name,keys:s}:e}return m(o,r,t,new Set([...n,e.name]))}default:return e}}function k(e,r){let t=r.metadata;if(!t)return e;let n=e;return r.kind==="scalar"&&r.scalar==="string"&&(t.minLength!==void 0&&(n=`${n}.min(${t.minLength})`),t.maxLength!==void 0&&(n=`${n}.max(${t.maxLength})`),t.pattern!==void 0&&(n=`${n}.regex(new RegExp(${JSON.stringify(t.pattern)}))`)),r.kind==="scalar"&&(r.scalar==="number"||r.scalar==="integer")&&(t.minimum!==void 0&&(n=`${n}.min(${t.minimum})`),t.maximum!==void 0&&(n=`${n}.max(${t.maximum})`),t.exclusiveMinimum!==void 0&&(n=`${n}.gt(${t.exclusiveMinimum})`),t.exclusiveMaximum!==void 0&&(n=`${n}.lt(${t.exclusiveMaximum})`)),r.kind==="array"&&(t.minItems!==void 0&&(n=`${n}.min(${t.minItems})`),t.maxItems!==void 0&&(n=`${n}.max(${t.maxItems})`)),n}function j(e,r){let t=[];for(let n of h(e.services)){if(n.sse!==void 0)continue;let o=n.requestBody,s=o&&o.contentType.toLowerCase().includes("json")?u(o.schema,r,a):void 0,i=n.successResponses.find(l=>l.contentType.toLowerCase().includes("json")),d=i?u(i.schema,r,a):void 0;!s&&!d||t.push({name:n.specName??n.name,request:s,response:d})}return t}function Z(e){let r=e.flatMap(n=>[`${a}${c(n.name)}: {`,...n.request?[`${a}${a}request: z.ZodType;`]:[],...n.response?[`${a}${a}response: z.ZodType;`]:[],`${a}};`]),t=e.map((n,o)=>{let s=[...n.request?[`request: ${n.request}`]:[],...n.response?[`response: ${n.response}`]:[]].join(", "),i=o===e.length-1?"":",";return`${a}${c(n.name)}: { ${s} }${i}`});return["/**"," * Request/response validators by operationId \u2014 powers `zodValidation`, or import one directly."," */","export const operationSchemas: {",...r,"} = {",...t,"};"].join(`
|
|
11
|
+
`)}var I=`/** \`request\`/\`response\` validators for one operation (an absent side is not validated). */
|
|
12
|
+
export type OperationSchemaSet = { request?: z.ZodType; response?: z.ZodType };
|
|
13
|
+
|
|
14
|
+
const schemaIndex: Partial<Record<string, OperationSchemaSet>> = operationSchemas;
|
|
15
|
+
|
|
16
|
+
/** One flattened validation problem: the full nested path and a short preview of the value. */
|
|
17
|
+
export type ZodViolation = { path: string; message: string; received: string };
|
|
18
|
+
|
|
19
|
+
/** A request or response payload failed validation. Requests throw it; response handling is configurable. */
|
|
20
|
+
export class ZodValidationError extends Error {
|
|
21
|
+
// Declared and assigned in the body, NOT as constructor parameter properties: those
|
|
22
|
+
// need a transform, so they break \`node --experimental-strip-types\` for anything
|
|
23
|
+
// importing this module (the generated CLI runs that way).
|
|
24
|
+
readonly operationId: string;
|
|
25
|
+
readonly direction: "request" | "response";
|
|
26
|
+
readonly issues: z.ZodError["issues"];
|
|
27
|
+
readonly violations: ZodViolation[];
|
|
28
|
+
|
|
29
|
+
constructor(
|
|
30
|
+
operationId: string,
|
|
31
|
+
direction: "request" | "response",
|
|
32
|
+
issues: z.ZodError["issues"],
|
|
33
|
+
violations: ZodViolation[]
|
|
34
|
+
) {
|
|
35
|
+
const detail = violations
|
|
36
|
+
.slice(0, 5)
|
|
37
|
+
.map((violation) => \`\${violation.path || "(root)"}: \${violation.message} (received \${violation.received})\`)
|
|
38
|
+
.join("; ");
|
|
39
|
+
const more = violations.length > 5 ? \`; \u2026and \${violations.length - 5} more\` : "";
|
|
40
|
+
super(\`\${direction === "request" ? "Request" : "Response"} validation failed for operation "\${operationId}": \${detail}\${more}\`);
|
|
41
|
+
this.operationId = operationId;
|
|
42
|
+
this.direction = direction;
|
|
43
|
+
this.issues = issues;
|
|
44
|
+
this.violations = violations;
|
|
45
|
+
this.name = "ZodValidationError";
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// Flatten zod issues into leaf violations. Union branches (zod 3 \`unionErrors\`, zod 4
|
|
50
|
+
// nested \`errors\`) are recursed into, so the message names the actual failing fields
|
|
51
|
+
// instead of just the union root ("Invalid input").
|
|
52
|
+
function flattenIssues(
|
|
53
|
+
issues: z.ZodError["issues"],
|
|
54
|
+
value: unknown,
|
|
55
|
+
base: PropertyKey[] = []
|
|
56
|
+
): ZodViolation[] {
|
|
57
|
+
const violations: ZodViolation[] = [];
|
|
58
|
+
for (const issue of issues) {
|
|
59
|
+
const path = [...base, ...issue.path];
|
|
60
|
+
const nested = nestedIssueLists(issue);
|
|
61
|
+
if (nested.length > 0) {
|
|
62
|
+
for (const sub of nested) violations.push(...flattenIssues(sub, value, path));
|
|
63
|
+
} else {
|
|
64
|
+
violations.push({
|
|
65
|
+
path: path.map(String).join("."),
|
|
66
|
+
message: issue.message,
|
|
67
|
+
received: preview(valueAt(value, path)),
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
return violations;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** The nested issue lists of a union-ish issue, across zod 3 (\`unionErrors\`) and zod 4 (\`errors\`). */
|
|
75
|
+
function nestedIssueLists(issue: unknown): Array<z.ZodError["issues"]> {
|
|
76
|
+
const candidate = issue as {
|
|
77
|
+
unionErrors?: Array<{ issues: z.ZodError["issues"] }>;
|
|
78
|
+
errors?: Array<z.ZodError["issues"]>;
|
|
79
|
+
};
|
|
80
|
+
if (Array.isArray(candidate.unionErrors)) return candidate.unionErrors.map((error) => error.issues);
|
|
81
|
+
if (Array.isArray(candidate.errors)) return candidate.errors;
|
|
82
|
+
return [];
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function valueAt(value: unknown, path: PropertyKey[]): unknown {
|
|
86
|
+
let current = value;
|
|
87
|
+
for (const key of path) {
|
|
88
|
+
if (current === null || typeof current !== "object") return undefined;
|
|
89
|
+
current = (current as Record<PropertyKey, unknown>)[key];
|
|
90
|
+
}
|
|
91
|
+
return current;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** A short single-line preview of the offending value. NOTE: validation output can surface
|
|
95
|
+
* payload data \u2014 route \`onViolation\` to a scrubbed logger when responses may carry secrets. */
|
|
96
|
+
function preview(value: unknown): string {
|
|
97
|
+
let text: string;
|
|
98
|
+
try {
|
|
99
|
+
text = JSON.stringify(value) ?? String(value);
|
|
100
|
+
} catch {
|
|
101
|
+
text = String(value);
|
|
102
|
+
}
|
|
103
|
+
return text.length > 80 ? \`\${text.slice(0, 77)}\u2026\` : text;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export type ZodValidationOptions = {
|
|
107
|
+
/** Validate request bodies before any network call; a failure THROWS (it is the caller's own bug). Default: true. */
|
|
108
|
+
request?: boolean;
|
|
109
|
+
/** Replace the outgoing body with the parsed result, dropping keys the schema does not declare
|
|
110
|
+
* (for strict-DTO servers that 400 on excess properties). Runs request validation. Default: false. */
|
|
111
|
+
stripRequestBodies?: boolean;
|
|
112
|
+
/** Response drift handling: \`"warn"\` (default) reports via \`onViolation\` and lets the call
|
|
113
|
+
* succeed \u2014 a server drifting from its description should not crash the consumer;
|
|
114
|
+
* \`"throw"\` fails the call (even on result-mode clients); \`false\` skips response validation. */
|
|
115
|
+
response?: "warn" | "throw" | false;
|
|
116
|
+
/** Sink for \`"warn"\` mode. Default: \`console.warn\` with the error message. */
|
|
117
|
+
onViolation?: (error: ZodValidationError) => void;
|
|
118
|
+
};
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Schema-validation middleware for the generated client: \`use(zodValidation())\`.
|
|
122
|
+
* Request bodies are validated before any network call and throw on failure; successful
|
|
123
|
+
* JSON responses are validated against the operation's response schema and WARN by
|
|
124
|
+
* default (see \`ZodValidationOptions.response\`). Operations without a schema pass
|
|
125
|
+
* through untouched. Payloads are never mutated unless \`stripRequestBodies\` is set.
|
|
126
|
+
*/
|
|
127
|
+
export function zodValidation(options: ZodValidationOptions = {}) {
|
|
128
|
+
const { request = true, stripRequestBodies = false, response = "warn", onViolation } = options;
|
|
129
|
+
const report = onViolation ?? ((error: ZodValidationError) => console.warn(error.message));
|
|
130
|
+
return {
|
|
131
|
+
onRequest(context: { body?: unknown; operation: { id: string } }): void {
|
|
132
|
+
if ((!request && !stripRequestBodies) || context.body === undefined) return;
|
|
133
|
+
const schema = schemaIndex[context.operation.id]?.request;
|
|
134
|
+
if (!schema) return;
|
|
135
|
+
const result = schema.safeParse(context.body);
|
|
136
|
+
if (!result.success) {
|
|
137
|
+
throw new ZodValidationError(
|
|
138
|
+
context.operation.id,
|
|
139
|
+
"request",
|
|
140
|
+
result.error.issues,
|
|
141
|
+
flattenIssues(result.error.issues, context.body)
|
|
142
|
+
);
|
|
143
|
+
}
|
|
144
|
+
// zod object schemas drop undeclared keys during parsing, so the parsed value
|
|
145
|
+
// IS the declared shape (intersections keep their own zod semantics).
|
|
146
|
+
if (stripRequestBodies) context.body = result.data;
|
|
147
|
+
},
|
|
148
|
+
async onResponse(incoming: Response, context: { operation: { id: string } }): Promise<void> {
|
|
149
|
+
if (response === false || !incoming.ok) return;
|
|
150
|
+
const schema = schemaIndex[context.operation.id]?.response;
|
|
151
|
+
if (!schema) return;
|
|
152
|
+
const contentType = (incoming.headers.get("content-type") ?? "").toLowerCase();
|
|
153
|
+
if (!contentType.includes("json")) return;
|
|
154
|
+
const payload: unknown = await incoming.clone().json();
|
|
155
|
+
const result = schema.safeParse(payload);
|
|
156
|
+
if (!result.success) {
|
|
157
|
+
const error = new ZodValidationError(
|
|
158
|
+
context.operation.id,
|
|
159
|
+
"response",
|
|
160
|
+
result.error.issues,
|
|
161
|
+
flattenIssues(result.error.issues, payload)
|
|
162
|
+
);
|
|
163
|
+
if (response === "throw") throw error;
|
|
164
|
+
report(error);
|
|
165
|
+
}
|
|
166
|
+
},
|
|
167
|
+
};
|
|
168
|
+
}`;function $(e){let r=new Map(e.schemas.map(o=>[o.name,o.schema])),t=j(e,r);if(e.schemas.length===0&&t.length===0)return"";let n=['import { z } from "zod";',...e.schemas.map(o=>`export const ${f(o.name)} = ${u(o.schema,r)};`)];return t.length===0?n.join(`
|
|
169
|
+
|
|
170
|
+
`):(n.push(Z(t)),`${n.join(`
|
|
171
|
+
|
|
172
|
+
`)}
|
|
173
|
+
${I}
|
|
174
|
+
`)}var T=({model:e,output:r,banner:t})=>{let n=$(e);if(n==="")return[];let o=t.map(s=>`// ${s}`).join(`
|
|
175
|
+
`);return[{path:M(r.dir,`${r.stem}.zod.ts`),content:`${o}
|
|
176
|
+
|
|
177
|
+
${n}`}]};export{T as zodGenerator};
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { createRequire as __createRequire } from 'node:module';
|
|
2
|
+
import { fileURLToPath as __fileURLToPath } from 'node:url';
|
|
3
|
+
import { dirname as __pathDirname } from 'node:path';
|
|
4
|
+
const require = __createRequire(import.meta.url);
|
|
5
|
+
var __filename = __fileURLToPath(import.meta.url);
|
|
6
|
+
var __dirname = __pathDirname(__filename);
|
|
7
|
+
import{a as S,b as f}from"./REFX2EKS.js";import{a as N}from"./UKSQ7B5H.js";import{b as E,c as U,d as j,e as K,f as J,g as z,h as Q}from"./YQS3OX36.js";import{a as M}from"./PFYPTG4G.js";import{b as O,c as H,d as w,e as B,g as F,h as G,i as T,j as W,k as _,n as A}from"./HJYFWIVE.js";var c=new S,y=H.go;function V(e){if(e===void 0)return"client";if(!/^[a-z_][a-z0-9_]*$/.test(e)||y.has(e))throw new M(`goPackage "${e}" is not a valid Go package name: use lowercase letters, digits, and underscores, don't start with a digit, and avoid Go keywords.`);return e}function R(e){let t=new Set,n=[];for(let r of e.services)for(let o of r.operations){let a=f(o.name),s=2;for(;t.has(a);)a=`${f(o.name)}${s++}`;t.add(a),n.push({op:o,ident:a})}return n}function oe(e){return J(e).map(n=>n.kind==="literal"?c.string(n.value):w(n.name,{style:"camel",reserved:y})).join(" + ")}function X(e,t){let n=t.servers??[];if(n.length===0)return;let r=new Set;n.forEach((o,a)=>{let s=`${f(o.description??`server${a+1}`)}URL`;r.has(s)&&(s=`${s}${a+1}`),r.add(s);let i=o.variables.map(l=>`${w(l.name,{style:"camel",reserved:y})} string`),u=o.variables.map(l=>`${w(l.name,{style:"camel",reserved:y})} default: ${c.string(l.default)}`).join(", ");e.line(`// ${s} returns the ${c.string(o.description??o.url)} base URL${u===""?".":` (${u}).`}`),e.block(`func ${s}(${i.join(", ")}) string {`,()=>{e.line(`return ${oe(o)}`)},"}"),e.blank()})}function Y(e,t){let n=z(e,t).map(r=>r.map(o=>o.kind==="apiKey"?`{Scheme: ${c.string(o.scheme)}, Kind: "apiKey", Name: ${c.string(o.name)}, In: ${c.string(o.in)}}`:`{Scheme: ${c.string(o.scheme)}, Kind: ${c.string(o.kind)}}`));if(n.length!==0)return`[][]SecuritySpec{${n.map(r=>`{${r.join(", ")}}`).join(", ")}}`}function Z(e){return`&PaginationSpec{${[`Style: ${c.string(e.style)}`,...e.param!==void 0?[`Param: ${c.string(e.param)}`]:[],...e.nextCursor!==void 0?[`NextCursor: ${c.string(e.nextCursor)}`]:[],...e.hasMore!==void 0?[`HasMore: ${c.string(e.hasMore)}`]:[],...e.limitParam!==void 0?[`LimitParam: ${c.string(e.limitParam)}`]:[],...e.items!==void 0?[`Items: ${c.string(e.items)}`]:[]].join(", ")}}`}function g(e,t="string"){if(T(e)){let n=g(W(e),t);return n.startsWith("*")||n==="any"?n:`*${n}`}switch(e.kind){case"scalar":if(t==="Date"&&e.scalar==="string"){if(e.metadata?.format==="date-time")return"time.Time";if(e.metadata?.format==="date")return"Date"}return{string:"string",integer:"int64",number:"float64",boolean:"bool"}[e.scalar];case"array":return`[]${g(e.items,t)}`;case"record":return`map[string]${g(e.value,t)}`;case"ref":return f(e.name);case"literal":return typeof e.value=="string"?"string":typeof e.value=="boolean"?"bool":"float64";case"enum":return{string:"string",integer:"int64",number:"float64",boolean:"bool"}[e.scalar];case"omit":return f(e.base);case"union":case"null":case"object":case"intersection":case"unknown":return"any"}}function ae(e,t,n,r,o){e.doc(f(t),o),e.block(`type ${f(t)} struct {`,()=>{for(let a of n){let s=f(a.name),i=g(a.schema,r),u=`\`json:"${a.name}"\``;a.required||(!i.startsWith("*")&&!i.startsWith("[]")&&!i.startsWith("map[")&&i!=="any"&&(i=`*${i}`),u=`\`json:"${a.name},omitempty"\``),e.line(`${s} ${i} ${u}`)}},"}"),e.blank()}function D(e,t="string"){let n=new S;n.line("package client"),n.blank(),e.schemas.some(({schema:a})=>G(a,e)!==void 0)&&(n.line('import "encoding/json"'),n.blank());let o=se(e,t);return t==="Date"&&o.includes("time.Time")&&(n.line('import "time"'),n.blank()),n.line(o),n.toString()}function se(e,t){let n=new S;for(let{name:r,schema:o}of e.schemas){let a=_(o);if(a!==void 0){let i=a.scalar==="string"?"string":"int64";n.doc(f(r),o.description),n.line(`type ${f(r)} ${i}`),n.blank(),n.block("const (",()=>{let u=new Set;a.values.forEach(l=>{let d=O.pascal(String(l))||"Value",m="";for(let k=2;u.has(d+m);k++)m=String(k);u.add(d+m);let p=f(r)+d+m;n.line(`${p} ${f(r)} = ${c.literal(l)}`)})},")"),n.blank();continue}if(o.kind==="object"||o.kind==="intersection"){let i=F(o,e);if(i!==void 0){ae(n,r,i.properties,t,i.description??o.description);continue}}let s=G(o,e);if(s!==void 0){let i=f(r),u=s.cases.map(l=>`${l.value} -> ${f(l.schemaName)}`).join(", ");n.line(`// ${i} is a discriminated union ("${s.property}"): ${u}.`),n.line(`type ${i} = any`),n.blank(),n.line(`// Unmarshal${i} decodes into the member selected by "${s.property}".`),n.block(`func Unmarshal${i}(data []byte) (${i}, error) {`,()=>{n.block("var probe struct {",()=>{n.line(`Discriminant string \`json:"${s.property}"\``)},"}"),n.block("if err := json.Unmarshal(data, &probe); err != nil {",()=>{n.line("return nil, err")},"}"),n.line("switch probe.Discriminant {");for(let l of s.cases)n.block(`case ${c.string(l.value)}:`,()=>{n.line(`var value ${f(l.schemaName)}`),n.line("err := json.Unmarshal(data, &value)"),n.line("return value, err")});n.line("}"),n.line("var fallback any"),n.line("err := json.Unmarshal(data, &fallback)"),n.line("return fallback, err")},"}"),n.blank();continue}n.doc(f(r),o.description),n.line(`type ${f(r)} = ${g(o,t)}`),n.blank()}return n.toString()}function q(e,t){if(t==="string")return e;let n=e.startsWith("*")?`(${e})`:e;return t==="time.Time"?`${n}.Format(time.RFC3339)`:t==="Date"?`${n}.Format("2006-01-02")`:t==="int64"?`strconv.FormatInt(${e}, 10)`:t==="float64"?`strconv.FormatFloat(${e}, 'f', -1, 64)`:t==="bool"?`strconv.FormatBool(${e})`:`fmt.Sprint(${e})`}var ie=["c","ctx","body","params","out","op"];function I(e,t){let n=B(e.pathParams.map(r=>r.name),{style:"camel",reserved:y,taken:ie});return e.pathParams.map((r,o)=>({param:r,go:n[o],type:g(r.schema,t)}))}function le(e,t){let n=new Set;return(e.successResponseHeaders??[]).map(r=>{let o=f(r.name),a=o,s=2;for(;n.has(a);)a=`${o}${s++}`;n.add(a);let i=A(r.schema,t),u={integer:{goType:"*int64",helper:"headerInt64"},number:{goType:"*float64",helper:"headerFloat64"},boolean:{goType:"*bool",helper:"headerBool"},string:{goType:"*string",helper:"headerString"}}[i];return{field:a,name:r.name,...u}})}function L(e,t,n,r,o,a=!1){let s=I(t,r),i=t.queryParams.length>0,u=U(t),l=u===void 0?void 0:g(u,r),d=a?le(t,o):[];a&&(e.line(`// ${n}Headers carries the declared response headers of ${n}WithHeaders (nil when absent or unparsable).`),e.block(`type ${n}Headers struct {`,()=>{for(let $ of d)e.line(`${$.field} ${$.goType}`)},"}"),e.blank());let m=["ctx context.Context",...s.map(({go:$,type:v})=>`${$} ${v}`),...t.requestBody?[`body ${g(t.requestBody.schema,r)}`]:[],...i?[`params *${n}Params`]:[]],p=j(t),k=a?l===void 0?`(${n}Headers, error)`:`(${l}, ${n}Headers, error)`:p!==void 0?"func(yield func(ServerSentEvent, error) bool)":l===void 0?"error":`(${l}, error)`,b=$=>a?l===void 0?`return headers, ${$}`:`return out, headers, ${$}`:l===void 0?`return ${$}`:`return out, ${$}`,P=a?`${n}WithHeaders`:n;e.doc(P,a?`Like ${n}, also returning the declared response headers.`:t.summary),e.block(`func (c *Client) ${P}(${m.join(", ")}) ${k} {`,()=>{p===void 0&&l!==void 0&&e.line(`var out ${l}`),a&&e.line(`var headers ${n}Headers`),e.line(`op := operations[${c.string(t.specName??t.name)}]`),e.line("authHeaders, query := resolveAuth(op.Security, c.config.Auth)"),i&&e.block("if params != nil {",()=>{for(let h of t.queryParams){let x=f(h.name);e.block(`if params.${x} != nil {`,()=>{if(h.schema.kind==="array"){let C=g(h.schema.items,r);e.block(`for _, item := range *params.${x} {`,()=>{e.line(`query.Add(${c.string(h.name)}, ${q("item",C)})`)},"}")}else e.line(`query.Set(${c.string(h.name)}, ${q(`*params.${x}`,g(h.schema,r))})`)},"}")}},"}");let $=s.map(({param:h,go:x,type:C})=>`${c.string(h.name)}: ${q(x,C)}`).join(", ");if(e.line(`requestURL := buildURL(c.config.ServerURL, op.Path, map[string]string{${$}})`),p!==void 0){e.block("open := func(extraHeaders map[string]string) (*http.Response, error) {",()=>{e.line("merged := map[string]string{}"),e.block("for key, value := range authHeaders {",()=>{e.line("merged[key] = value")},"}"),e.block("for key, value := range extraHeaders {",()=>{e.line("merged[key] = value")},"}"),e.line("return send(ctx, &c.config, requestSpec{OperationID: op.ID, Method: op.Method, URL: requestURL, Headers: merged, Query: query})")},"}"),e.line(`return iterSSE(open, ${p.schema!==void 0&&p.schema.kind!=="unknown"})`);return}let v=["OperationID: op.ID","Method: op.Method","URL: requestURL","Headers: authHeaders","Query: query"];if(t.requestBody&&K(t)?(e.line("contentType, reader, err := toMultipart(body)"),e.block("if err != nil {",()=>{e.line(b("err"))},"}"),v.push("Body: reader"),v.push("ContentType: contentType")):t.requestBody&&(e.line("payload, err := json.Marshal(body)"),e.block("if err != nil {",()=>{e.line(b("err"))},"}"),v.push("Body: bytes.NewReader(payload)"),v.push(`ContentType: ${c.string(t.requestBody.contentType)}`)),e.line(`resp, err := send(ctx, &c.config, requestSpec{${v.join(", ")}})`),e.block("if err != nil {",()=>{e.line(b("err"))},"}"),e.block("if resp.StatusCode >= 400 {",()=>{e.line(b("apiErrorFrom(resp, requestURL)"))},"}"),a){e.block(`if err := decodeJSON(resp, ${l===void 0?"nil":"&out"}); err != nil {`,()=>{e.line(b("err"))},"}");for(let h of d)e.line(`headers.${h.field} = ${h.helper}(resp.Header, ${c.string(h.name)})`);e.line(l===void 0?"return headers, nil":"return out, headers, nil")}else l===void 0?e.line("return decodeJSON(resp, nil)"):(e.block("if err := decodeJSON(resp, &out); err != nil {",()=>{e.line("return out, err")},"}"),e.line("return out, nil"))},"}"),e.blank()}function ee(e,t,n,r,o,a){let s=I(t,r),i=t.queryParams.length>0,u=["ctx context.Context",...s.map(({go:d,type:m})=>`${d} ${m}`),...i?[`params *${n}Params`]:[]].join(", "),l=()=>{e.line(`op := operations[${c.string(t.specName??t.name)}]`),e.line("base := url.Values{}"),i&&e.block("if params != nil {",()=>{for(let d of t.queryParams){let m=f(d.name);e.block(`if params.${m} != nil {`,()=>{e.line(`base.Set(${c.string(d.name)}, ${q(`*params.${m}`,g(d.schema,r))})`)},"}")}},"}"),e.block("call := func(pageParams url.Values) (any, *http.Response, error) {",()=>{e.line("authHeaders, query := resolveAuth(op.Security, c.config.Auth)"),e.block("for key, values := range pageParams {",()=>{e.block("for _, value := range values {",()=>{e.line("query.Set(key, value)")},"}")},"}");let d=s.map(({param:m,go:p,type:k})=>`${c.string(m.name)}: ${q(p,k)}`).join(", ");e.line(`requestURL := buildURL(c.config.ServerURL, op.Path, map[string]string{${d}})`),e.line("resp, err := send(ctx, &c.config, requestSpec{OperationID: op.ID, Method: op.Method, URL: requestURL, Headers: authHeaders, Query: query})"),e.block("if err != nil {",()=>{e.line("return nil, nil, err")},"}"),e.block("if resp.StatusCode >= 400 {",()=>{e.line("return nil, resp, apiErrorFrom(resp, requestURL)")},"}"),e.line("var raw any"),e.block("if err := decodeJSON(resp, &raw); err != nil {",()=>{e.line("return nil, resp, err")},"}"),e.line("return raw, resp, nil")},"}"),e.line("pages := iterPages(call, *op.Pagination, base)")};e.line(`// ${n}Pages iterates ${n} response pages; use with \`for page, err := range\`.`),e.block(`func (c *Client) ${n}Pages(${u}) func(yield func(${o}, error) bool) {`,()=>{l(),e.block(`return func(yield func(${o}, error) bool) {`,()=>{e.block("pages(func(raw any, err error) bool {",()=>{e.line(`var page ${o}`),e.block("if err == nil {",()=>{e.line("err = reencode(raw, &page)")},"}"),e.line("return yield(page, err)")},"})")},"}")},"}"),e.blank(),e.line(`// ${n}Items iterates the items of every ${n} page.`),e.block(`func (c *Client) ${n}Items(${u}) func(yield func(${a}, error) bool) {`,()=>{l(),e.block(`return func(yield func(${a}, error) bool) {`,()=>{e.block("pages(func(raw any, err error) bool {",()=>{e.block("if err != nil {",()=>{e.line(`var zero ${a}`),e.line("return yield(zero, err)")},"}"),e.line("pageItems, _ := resolvePointer(raw, op.Pagination.Items).([]any)"),e.block("for _, item := range pageItems {",()=>{e.line(`var typed ${a}`),e.block("if err := reencode(item, &typed); err != nil {",()=>{e.line("return yield(typed, err)")},"}"),e.block("if !yield(typed, nil) {",()=>{e.line("return false")},"}")},"}"),e.line("return true")},"})")},"}")},"}"),e.blank()}function ne(e){let t=e.split(`
|
|
8
|
+
`),n=[],r=!1;for(let o of t)if(!o.startsWith("package ")){if(o.startsWith("import (")){r=!0;continue}if(r){o.startsWith(")")&&(r=!1);continue}o.startsWith("import ")||n.push(o)}return n.join(`
|
|
9
|
+
`).trim()}var te=["bytes","context","encoding/base64","encoding/json","errors","fmt","io","math/rand","mime/multipart","net/http","net/url","strconv","strings","time"];function re(e,t,n,r,o,a){e.line(ne(D(t,r))),e.blank(),X(e,t),a&&(e.line("// \u2500\u2500\u2500 Embedded runtime (@redocly/client-generator go runtime) \u2500\u2500\u2500"),e.line(ne(N)),e.blank()),e.block("type operationMeta struct {",()=>{e.line("ID string"),e.line("Method string"),e.line("Path string"),e.line("Security [][]SecuritySpec"),e.line("Pagination *PaginationSpec")},"}"),e.blank(),e.block("var operations = map[string]operationMeta{",()=>{for(let{op:s,ident:i}of R(t)){let u=s.specName??s.name,l=Y(s,t),d=o.get(i),m=[`ID: ${c.string(u)}`,`Method: ${c.string(s.method.toUpperCase())}`,`Path: ${c.string(s.path)}`,...l!==void 0?[`Security: ${l}`]:[],...d!==void 0?[`Pagination: ${Z(d)}`]:[]];e.line(`${c.string(u)}: {${m.join(", ")}},`)}},"}"),e.blank();for(let{op:s,ident:i}of R(t))s.queryParams.length!==0&&(e.block(`type ${i}Params struct {`,()=>{for(let u of s.queryParams){let l=g(u.schema,r);e.line(`${f(u.name)} ${l.startsWith("*")?l:`*${l}`}`)}},"}"),e.blank());e.doc("Client",`Client for ${t.title} (${t.version}).`),e.block("type Client struct {",()=>{e.line("config Config")},"}"),e.blank(),e.block("func New(config Config) *Client {",()=>{e.block('if config.ServerURL == "" {',()=>{e.line(`config.ServerURL = ${c.string(n.serverUrl??t.serverUrl??"")}`)},"}"),e.line("return &Client{config: config}")},"}"),e.blank();for(let{op:s,ident:i}of R(t)){L(e,s,i,r),j(s)===void 0&&(s.successResponseHeaders?.length??0)>0&&L(e,s,i,r,t,!0);let u=o.get(i);if(u===void 0)continue;let l=U(s),d=l===void 0?"any":g(l,r),m=Q(l,u.items,t);ee(e,s,i,r,d,m===void 0?"any":g(m,r))}}var ze=({model:e,output:t,banner:n,emit:r,pagination:o})=>{let a=new S,s=r.dateType??"string",i=V(r.goPackage),u=new Map;for(let{op:b,ident:P}of R(e)){let $=o?.get(b.name)?.spec;$!==void 0&&u.set(P,$)}a.line(`// Code generated by @redocly/client-generator (go) from "${e.title}" ${e.version}. DO NOT EDIT.`),a.line("// Regenerate with `redocly generate-client`. Standard library only \u2014 zero dependencies."),a.line(`package ${i}`),a.blank();let l=r.runtime!=="module",d=l?te:(()=>{let b=new S;re(b,e,r,s,u,!1);let P=b.toString();return te.filter($=>new RegExp(`\\b${$.split("/").pop()}\\.`).test(P))})();a.block("import (",()=>{for(let b of d)a.line(c.string(b))},")"),a.blank(),re(a,e,r,s,u,l);let m={path:t.path.replace(/\.[^.\\/]+$/,".go"),content:a.toString()};if(l)return[m];let p=n.map(b=>`// ${b}`).join(`
|
|
10
|
+
`),k=N.replace(/^package .*$/m,`package ${i}`);return[m,{path:m.path.replace(/[^\\/]+$/,"runtime.go"),content:`${p}
|
|
11
|
+
${k.trimEnd()}
|
|
12
|
+
`}]};function ce(e,t){let n=t.emit.dateType??"string",r=t.emit.goPackage??"client",o=R(t.model).find(u=>u.op.name===e.name)?.ident??f(e.name),a=["ctx",...e.pathParams.map(u=>`"<${w(u.name,{style:"camel",reserved:y})}>"`),...e.requestBody?[`${g(e.requestBody.schema,n)}{ /* \u2026 */ }`]:[],...e.queryParams.length>0?["nil"]:[]],s=`client.${o}(${a.join(", ")})`,i=j(e)!==void 0?`stream := ${s}`:U(e)===void 0?`err := ${s}`:`result, err := ${s}`;return{lang:"go",label:"Go SDK",source:`client := ${r}.New(${r}.Config{})
|
|
13
|
+
${i}
|
|
14
|
+
`}}var Qe=({model:e,output:t,emit:n,pagination:r})=>[{path:t.path.replace(/\.[^.\\/]+$/,".go.md"),content:E(e,{title:`${e.title} Go SDK reference`,frontmatter:n.docsFrontmatter===!0,language:{name:"go",label:"Go",fence:"go",requires:"The SDK needs the standard library only."},sample:o=>ce(o,{model:e,emit:n,outputPath:t.path}),paginated:new Set(r?.keys()??[])})}];export{g as a,D as b,ze as c,ce as d,Qe as e};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { createRequire as __createRequire } from 'node:module';
|
|
2
|
+
import { fileURLToPath as __fileURLToPath } from 'node:url';
|
|
3
|
+
import { dirname as __pathDirname } from 'node:path';
|
|
4
|
+
const require = __createRequire(import.meta.url);
|
|
5
|
+
var __filename = __fileURLToPath(import.meta.url);
|
|
6
|
+
var __dirname = __pathDirname(__filename);
|
|
7
|
+
import{e as y,k as A}from"./NB54XRRU.js";import"./HJYFWIVE.js";import"./RFWIIJFG.js";import{join as R}from"node:path";var u=" ";function M(t){return`transform${A(t)}`}var I="type __Writable<T> = { -readonly [K in keyof T]: T[K] };",k=!1;function _(t){return{text:t,path:[t]}}function G(t,r){return{text:`${t.text}[${JSON.stringify(r)}]`,path:[...t.path,r]}}function d(t,r,n){if(x(t))return!0;switch(t.kind){case"array":return d(t.items,r,n);case"union":return t.members.some(e=>d(e,r,n));case"ref":{if(n.has(t.name))return!1;let e=r.get(t.name);return e!==void 0&&d(e,r,new Set(n).add(t.name))}default:return!1}}function x(t){return t.kind==="scalar"&&t.scalar==="string"&&(t.metadata?.format==="date-time"||t.metadata?.format==="date")}function l(t,r,n){if(x(t))return!0;switch(t.kind){case"array":return l(t.items,r,n);case"record":return l(t.value,r,n);case"object":return t.properties.some(e=>l(e.schema,r,n));case"union":case"intersection":return t.members.some(e=>l(e,r,n));case"ref":{let e=r.get(t.name);return e!==void 0&&!n.has(t.name)?l(e,r,new Set(n).add(t.name)):!1}default:return!1}}function $(t,r,n,e=!1){return e?[`${n}if (${t}) {`,...r(n+u),`${n}}`]:[`${n}if (${t})`,...r(n+u)]}function m(t,r,n=!1){let e=n?J(t):t.text;return s=>[`${s}${e} = ${r};`]}function T(t){return r=>[`${r}${t};`]}function J(t){if(t.path.length<2)return t.text;k=!0;let r={text:t.text.slice(0,t.text.lastIndexOf("[")),path:t.path.slice(0,-1)},n=t.path[t.path.length-1];return`(${r.text} as __Writable<${C(r)}>)[${JSON.stringify(n)}]`}function C(t){let r=`typeof ${t.path[0]}`;for(let n of t.path.slice(1))r=`NonNullable<${r}>[${JSON.stringify(n)}]`;return`NonNullable<${r}>`}function W(t){return t==="data"?"item":`item${Number(t.slice(4))+1}`}function g(t,r,n,e,s,o,a=!1){if(x(r))return $(`typeof ${t.text} === "string"`,m(t,`new Date(${t.text})`,a),o);switch(r.kind){case"ref":return w(t,r.name,n,e,o,a);case"object":{let i=[];for(let f of r.properties)i.push(...K(G(t,f.name),f.schema,n,e,s,o,f.readOnly===!0));return i}case"array":return U(t,r.items,n,e,s,o,a);case"record":return b(t,r.value,n,e,s,o,!0);case"intersection":{let i=[];for(let f of r.members)i.push(...g(t,f,n,e,s,o,a));return i}case"union":return B(t,r.members,n,e,s,o,a);default:return[]}}function B(t,r,n,e,s,o,a=!1){let i=[],f=o+u,p=[];for(let c of r)if(x(c))i.push(...g(t,c,n,e,s,o,a));else if(c.kind==="ref"){if(!l(c,n,e))continue;let S=`${M(c.name)}(${t.text} as ${c.name})`,h=d(c,n,e)?m(t,S,a):T(S);p.push(...h(f))}else p.push(...g(t,c,n,e,s,f,a));return p.length>0&&i.push(...$(`${t.text} && typeof ${t.text} === "object"`,()=>p,o,!0)),i}function w(t,r,n,e,s,o=!1){let a={kind:"ref",name:r};if(!l(a,n,e))return[];let i=`${M(r)}(${t.text})`;return $(t.text,d(a,n,e)?m(t,i,o):T(i),s)}function K(t,r,n,e,s,o,a=!1){if(r.kind==="ref")return w(t,r.name,n,e,o,a);if(r.kind==="object"){let i=g(t,r,n,e,s,o+u);return i.length===0?[]:$(t.text,()=>i,o,!0)}return g(t,r,n,e,s,o,a)}function j(t,r,n,e,s=0){if(x(r))return`new Date(${t})`;if(r.kind==="ref"&&d(r,n,e))return`${M(r.name)}(${t})`;if(r.kind==="array"){let o=r.items.kind==="array"?O(s+1):"v",a=j(o,r.items,n,e,s+1);return a===null?null:`${t}.map(${o} => ${a})`}return null}function O(t){return t<=1?"row":`row${t}`}function U(t,r,n,e,s,o,a=!1){let i=r.kind==="array"?O(1):"v",f=j(i,r,n,e,1);return f!==null?$(`Array.isArray(${t.text})`,m(t,`${t.text}.map(${i} => ${f})`,a),o):r.kind==="ref"?l(r,n,e)?$(`Array.isArray(${t.text})`,T(`${t.text}.forEach(${M(r.name)})`),o):[]:b(t,r,n,e,s,o,!1)}function b(t,r,n,e,s,o,a){if(a){let c={text:`${t.text}[__k]`,path:[...t.path,"__k"]},S=j(c.text,r,n,e);if(S!==null){let h=x(r)?`typeof ${c.text} === "string"`:`Array.isArray(${c.text})`;return $(t.text,v=>[`${v}for (const __k of Object.keys(${t.text}))`,...$(h,E=>[`${E}${c.text} = ${S};`],v+u)],o)}}let i=W(s),f=g(_(i),r,n,e,i,o+u+u);if(f.length===0)return[];let p=a?`Object.values(${t.text})`:t.text;return $(a?t.text:`Array.isArray(${t.text})`,c=>[`${c}${p}.forEach(${i} => {`,...f,`${c}});`],o)}function P(t,r){let n=t.name,e=_("data"),s=t.schema.kind==="ref"?w(e,t.schema.name,r,new Set,u):g(e,t.schema,r,new Set,"data",u);return[`export const ${M(t.name)} = (data: ${n}): ${n} => {`,...s,`${u}return data;`,"};"].join(`
|
|
8
|
+
`)}function D(t,r){let n=new Map(t.schemas.map(i=>[i.name,i.schema])),e=t.schemas.filter(i=>l(i.schema,n,new Set));if(e.length===0)return"";let s=e.map(i=>y(i.name)).join(", ");k=!1;let o=e.map(i=>P(i,n));return[`import type { ${s} } from ${JSON.stringify(r.sdkModule)};`,...k?[I]:[],...o].join(`
|
|
9
|
+
|
|
10
|
+
`)}var Q=({model:t,output:r,banner:n,emit:e})=>{let s=D(t,{sdkModule:`./${r.stem}.${e.importExt??"js"}`});if(s==="")return[];let o=n.map(a=>`// ${a}`).join(`
|
|
11
|
+
`);return[{path:R(r.dir,`${r.stem}.transformers.ts`),content:`${o}
|
|
12
|
+
|
|
13
|
+
${s}`}]};export{Q as transformersGenerator};
|
|
@@ -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 Br,b as _3}from"./O6PRCLSV.js";import{a as J3}from"./32XCOMOR.js";import{aa as La,c as _,ca as S1,ea as M1,fa as j1,ha as P1,l as br,m as E0,x as z1}from"./
|
|
7
|
+
import{a as Br,b as _3}from"./O6PRCLSV.js";import{a as J3}from"./32XCOMOR.js";import{aa as La,c as _,ca as S1,ea as M1,fa as j1,ha as P1,l as br,m as E0,x as z1}from"./BEOYUN4L.js";import{c as du,e as Cu}from"./RFWIIJFG.js";var Lr=du((Ue,Tr)=>{"use strict";Object.defineProperty(Ue,"__esModule",{value:!0});Ue.outdent=void 0;function Oa(){for(var u=[],a=0;a<arguments.length;a++)u[a]=arguments[a]}function ko(){return typeof WeakMap<"u"?new WeakMap:jE()}function jE(){return{add:Oa,delete:Oa,get:Oa,set:Oa,has:function(u){return!1}}}var PE=Object.prototype.hasOwnProperty,Kr=function(u,a){return PE.call(u,a)};function wr(u,a){for(var e in a)Kr(a,e)&&(u[e]=a[e]);return u}var wE=/^[ \t]*(?:\r\n|\r|\n)/,KE=/(?:\r\n|\r|\n)[ \t]*$/,TE=/^(?:[\r\n]|$)/,LE=/(?:\r\n|\r|\n)([ \t]*)(?:[^ \t\r\n]|$)/,NE=/^[ \t]*[\r\n][ \t\r\n]*$/;function ho(u,a,e){var i=0,r=u[0].match(LE);r&&(i=r[1].length);var n="(\\r\\n|\\r|\\n).{0,"+i+"}",o=new RegExp(n,"g");a&&(u=u.slice(1));var l=e.newline,x=e.trimLeadingNewline,d=e.trimTrailingNewline,F=typeof l=="string",h=u.length,v=u.map(function(y,T){return y=y.replace(o,"$1"),T===0&&x&&(y=y.replace(wE,"")),T===h-1&&d&&(y=y.replace(KE,"")),F&&(y=y.replace(/\r\n|\n|\r/g,function(K){return l})),y});return v}function RE(u,a){for(var e="",i=0,r=u.length;i<r;i++)e+=u[i],i<r-1&&(e+=a[i]);return e}function HE(u){return Kr(u,"raw")&&Kr(u,"length")}function po(u){var a=ko(),e=ko();function i(n){for(var o=[],l=1;l<arguments.length;l++)o[l-1]=arguments[l];if(HE(n)){var x=n,d=(o[0]===i||o[0]===Yu)&&NE.test(x[0])&&TE.test(x[1]),F=d?e:a,h=F.get(x);if(h||(h=ho(x,d,u),F.set(x,h)),o.length===0)return h[0];var v=RE(h,d?o.slice(1):o);return v}else return po(wr(wr({},u),n||{}))}var r=wr(i,{string:function(n){return ho([n],!1,u)[0]}});return r}var Yu=po({trimLeadingNewline:!0,trimTrailingNewline:!0});Ue.outdent=Yu;Ue.default=Yu;if(typeof Tr<"u")try{Tr.exports=Yu,Object.defineProperty(Yu,"__esModule",{value:!0}),Yu.default=Yu,Yu.outdent=Yu}catch{}});var vs=du(a0=>{"use strict";Object.defineProperty(a0,"__esModule",{value:!0});var $$="[",Y$="]",Q$="{",X$="}",uY=":",eY=",",Fs="true",ks="false",hs="null",xs='"',aY=new Map([["t",Fs],["f",ks],["n",hs]]),en=new Map([[xs,xs],["\\","\\"],["/","/"],["b","\b"],["n",`
|
|
8
8
|
`],["f","\f"],["r","\r"],["t"," "]]),un=new Map([[$$,"Punctuator"],[Y$,"Punctuator"],[Q$,"Punctuator"],[X$,"Punctuator"],[uY,"Punctuator"],[eY,"Punctuator"],[Fs,"Boolean"],[ks,"Boolean"],[hs,"Null"]]),K0=class extends Error{constructor(a,{line:e,column:i,index:r}){super(`${a} (${e}:${i})`),this.line=e,this.column=i,this.index=r}},an=class extends K0{constructor(a,e){super(`Unexpected character ${a} found.`,e)}},xe=class extends K0{constructor(a){super(`Unexpected token ${a.type}(${a.value}) found.`,a.loc.start)}},rn=class extends K0{constructor(a){super("Unexpected end of input found.",a)}},cs='"',ds="/",ms="*",iY={comments:!1,ranges:!1};function rY(u){return/[\s\n]/.test(u)}function h0(u){return u>="0"&&u<="9"}function nY(u){return h0(u)||/[a-f]/i.test(u)}function oY(u){return u>="1"&&u<="9"}function tY(u){return/[tfn]/.test(u)}function sY(u){return h0(u)||u==="."||u==="-"}function ps(u,a){a=Object.freeze({...iY,...a});let e=-1,i=1,r=0,n=!1,o=[];function l(b,B,z,S){let N=z.offset+B.length,au=a.ranges?{range:[z.offset,N]}:void 0;return{type:b,value:B,loc:{start:z,end:S||{line:z.line,column:z.column+B.length,offset:N}},...au}}function x(){let b=u.charAt(++e);return n?(i++,r=1,n=!1):r++,b==="\r"?(n=!0,u.charAt(e+1)===`
|
|
9
9
|
`&&e++):b===`
|
|
10
10
|
`&&(n=!0),b}function d(){return{line:i,column:r,offset:e}}function F(b){let B=aY.get(b);if(u.slice(e,e+B.length)===B)return e+=B.length-1,r+=B.length-1,{value:B,c:x()};for(let z=1;z<B.length;z++)B[z]!==u.charAt(e+z)&&T(x())}function h(b){let B=b;for(b=x();b&&b!==cs;){if(b==="\\")if(B+=b,b=x(),en.has(b))B+=b;else if(b==="u"){B+=b;for(let z=0;z<4;z++)b=x(),nY(b)?B+=b:T(b)}else T(b);else B+=b;b=x()}return b||K(),B+=b,{value:B,c:x()}}function v(b){let B="";if(b==="-"&&(B+=b,b=x(),h0(b)||T(b)),b==="0")B+=b,b=x(),h0(b)&&T(b);else{oY(b)||T(b);do B+=b,b=x();while(h0(b))}if(b===".")do B+=b,b=x();while(h0(b));if(b==="e"||b==="E")for(B+=b,b=x(),(b==="+"||b==="-")&&(B+=b,b=x()),h0(b)||T(b);h0(b);)B+=b,b=x();return{value:B,c:b}}function y(b){let B=b;if(b=x(),b==="/"){do B+=b,b=x();while(b&&b!=="\r"&&b!==`
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { createRequire as __createRequire } from 'node:module';
|
|
2
|
+
import { fileURLToPath as __fileURLToPath } from 'node:url';
|
|
3
|
+
import { dirname as __pathDirname } from 'node:path';
|
|
4
|
+
const require = __createRequire(import.meta.url);
|
|
5
|
+
var __filename = __fileURLToPath(import.meta.url);
|
|
6
|
+
var __dirname = __pathDirname(__filename);
|
|
7
|
+
import{g}from"./VWSPU27A.js";import{k as u,l as m}from"./YQS3OX36.js";import{c as C,d as j}from"./GBRES7WG.js";import{O as b}from"./BEOYUN4L.js";import{a as S,b as k}from"./HJYFWIVE.js";import{join as $}from"node:path";function h(r){return(r??"").replace(/\s+/g," ").trim().replace(/\\/g,"\\\\").replace(/\|/g,"\\|")}function v(r){return[r.group===void 0?void 0:u(r.group),r.name].filter(Boolean).join(" ")}function N(r,e){return[r,v(e),...e.positionals.map(o=>`<${o.name}>`),...e.flags.filter(o=>o.required).map(o=>`--${o.name} <${o.type}>`),...e.body?[e.body.required?"--json '<json>'":"[--json '<json>']"]:[]].filter(o=>o!=="").join(" ")}function T(r,e){r.line("| Flag | Type | Required | Description |"),r.line("| ---- | ---- | -------- | ----------- |");for(let n of e){let o=[h(n.description),n.enum===void 0?"":`One of ${n.enum.map(t=>`\`${t}\``).join(", ")}.`,n.type==="array"?"Repeat the flag for multiple values.":""].filter(t=>t!=="").join(" ");r.line(`| \`--${n.name}\` | ${n.type} | ${n.required?"yes":"no"} | ${o} |`)}r.blank()}function D(r,e,n){if(r.line(`### \`${v(e)}\``),r.blank(),e.summary!==void 0&&(r.line(h(e.summary)),r.blank()),r.line(`\`${e.method} ${e.path}\``),r.blank(),r.line("```sh"),r.line(N(n.name,e)),r.line("```"),r.blank(),e.positionals.length>0){r.line("| Argument | Description |"),r.line("| -------- | ----------- |");for(let t of e.positionals)r.line(`| \`<${t.name}>\` | ${h(t.description)} |`);r.blank()}e.flags.length>0&&T(r,e.flags);let o=[e.body===void 0?"":`Takes a JSON body${e.body.required?" (required)":""}: \`--json '<json>'\`, \`--json @file.json\`, or \`--json @-\` for stdin.`,e.unsupportedBody===void 0?"":`Takes a \`${e.unsupportedBody}\` body, which the CLI cannot build \u2014 call this operation through the generated client instead.`,e.paginated===!0?"Paginated: `--page-all` follows every page, printing one JSON page per line.":"",e.sse===!0?"Streams server-sent events as one JSON object per line.":"",e.blob===!0?"Returns binary content, so `--output <path>` is required.":""].filter(t=>t!=="");for(let t of o)r.line(t);o.length>0&&r.blank()}function w(r,e){let n=new S;e.frontmatter&&(n.line("---"),n.line(`title: ${e.title}`),n.line("---"),n.blank()),n.line(`# ${e.title}`),n.blank(),n.line(`Generated command-line reference for \`${e.name}\`, produced from the API description by \`redocly generate-client\`.`),n.line("Re-run generation to update it \u2014 this file is not hand-edited."),n.blank(),n.line("## Usage"),n.blank(),n.line("```sh"),n.line(`${e.name} <command> [flags]`),n.line(`${e.name} --help`),n.line(`${e.name} schema <command> # request/response schemas`),n.line("```"),n.blank(),n.line("Install the file under any `bin` name: the command takes that name, and the credential variables below do not change."),n.blank(),n.line("## Global flags"),n.blank(),n.line("| Flag | Description |"),n.line("| ---- | ----------- |");let o=e.schemes.some(i=>i.kind==="bearer");for(let[i,s]of[["--server-url <url>","Override the server URL included in the client."],["--format <json\\|ndjson>","Output format."],["--dry-run","Print the prepared request, credentials redacted, without sending it."],["--page-all","Follow pagination, printing one JSON page per line."],["--output <path>","Write the response body to a file. Required for binary responses."],...o?[["--token <token>","Bearer token, overriding the environment."]]:[],["--json <json\\|@file\\|@->","Request body, inline or from a file or stdin."]])n.line(`| \`${i}\` | ${s} |`);n.blank();let t=m(e.name);if(n.line("## Credentials"),n.blank(),e.schemes.length===0)n.line("The description declares no security schemes, so no credentials are read.");else{n.line("Credentials come from the environment:"),n.blank(),n.line("| Scheme | Variable |"),n.line("| ------ | -------- |");for(let i of e.schemes){let s=i.kind==="bearer"?`\`${t}_TOKEN\` (or \`--token\`)`:i.kind==="basic"?`\`${t}_USERNAME\` and \`${t}_PASSWORD\``:`\`${t}_API_KEY_${m(i.key)}\``;n.line(`| ${i.kind} (\`${i.key}\`) | ${s} |`)}}n.blank(),n.line("## Exit codes"),n.blank(),n.line("| Code | Meaning |"),n.line("| ---- | ------- |");for(let[i,s]of[[0,"success"],[1,"API error (status other than 401 or 403)"],[2,"auth error (401 or 403)"],[3,"validation error"],[4,"usage error (unknown command or flag, bad `--json`)"]])n.line(`| ${i} | ${s} |`);n.blank(),n.line("Errors print one JSON object to stderr, so stdout stays clean for piping."),n.blank();let a=[...new Set(r.map(i=>i.group))];for(let i of a){let s=r.filter(l=>l.group===i);i===void 0?(n.line("## Commands"),n.blank()):(n.line(`## ${i}`),n.blank(),n.line(`Addressed as \`${e.name} ${u(i)} <command>\`.`),n.blank());for(let l of s)D(n,l,e)}return n.toString().replace(/\n{3,}/g,`
|
|
8
|
+
|
|
9
|
+
`).trimEnd()+`
|
|
10
|
+
`}function R(){return j["cli.ts"]}function x(){return C["cli.ts"]}var O="// Generated by @redocly/client-generator \u2014 do not edit by hand.\n// Source: OpenAPI description. Re-run `redocly generate-client` to update.";function q(r){return k.snake(r).replace(/_/g,"-")}function E(r){let e=r.schema,n=e.kind==="array"?"array":e.kind==="scalar"&&(e.scalar==="integer"||e.scalar==="number")?"number":e.kind==="scalar"&&e.scalar==="boolean"?"boolean":"string";return{name:q(r.name),param:r.name,type:n,required:r.required,...e.kind==="enum"?{enum:e.values.map(String)}:{},...r.description!==void 0?{description:r.description}:{}}}function F(r){let e=r.successResponses;return e.some(n=>n.contentType.toLowerCase().includes("json"))?!1:e.some(n=>n.contentType.startsWith("image/")||n.contentType==="application/octet-stream")}function M(r){return r.successResponses.find(e=>e.contentType.toLowerCase().includes("json"))?.schema}function U(r,e,n){if(n!=="flat")return{};let o=g(r,e.schemas);return"mergeBody"in o&&o.mergeBody?{merged:!0}:{}}function _(r,e,n){return n!=="flat"?{}:"collisions"in g(r,e.schemas)?{argsStyle:"grouped"}:{}}function f(r,e){let n=[];for(let o of r.services)for(let t of o.operations){let a=t.requestBody?.contentType.toLowerCase().includes("json")?t.requestBody:void 0,i=M(t);n.push({...t.tags.length>0?{group:t.tags[0]}:{},name:t.name,...t.summary!==void 0?{summary:t.summary}:{},method:t.method.toUpperCase(),path:t.path,positionals:t.pathParams.map(s=>({name:s.name,type:E(s).type,...s.description!==void 0?{description:s.description}:{}})),flags:t.queryParams.map(E),...a?{body:{required:a.required,...U(t,r,e.argsStyle)}}:{},...a===void 0&&t.requestBody!==void 0?{unsupportedBody:t.requestBody.contentType}:{},...e.pagination?.has(t.name)===!0?{paginated:!0}:{},..._(t,r,e.argsStyle),...t.sse!==void 0?{sse:!0}:{},...F(t)?{blob:!0}:{},...a!==void 0||i!==void 0?{schemas:{...a?{request:a.schema}:{},...i!==void 0?{response:i}:{}}}:{}})}return n}var P=`function isProcessEntry(): boolean {
|
|
11
|
+
if (process.argv[1] === undefined) return false;
|
|
12
|
+
try {
|
|
13
|
+
return realpathSync(fileURLToPath(import.meta.url)) === realpathSync(process.argv[1]);
|
|
14
|
+
} catch {
|
|
15
|
+
return false;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
if (isProcessEntry()) {
|
|
19
|
+
process.exit(await run());
|
|
20
|
+
}`;function p(r,e){return JSON.stringify(r,null,e).replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}function y(r){return r.securitySchemes.map(e=>({key:e.key,kind:e.kind==="bearer"||e.kind==="basic"?e.kind:"apiKey"}))}function B(r){return r.group===void 0?`${r.name} (keeps the bare word, so the "${r.name}" group has no help page)`:`${r.name} (run it as "${u(r.group)} ${r.name}")`}function I(r){let e=new Set(r.filter(o=>o.group).map(o=>u(o.group))),n=r.filter(o=>e.has(o.name));n.length!==0&&b.warn(`generate-client: cli reads a leading group name as the group, so ${n.length} operation(s) named after a tag resolve unusually \u2014 rename the operation or the tag: ${n.map(B).join(", ")}.
|
|
21
|
+
`)}function A(r,e){let n=f(r,{pagination:e.pagination,argsStyle:e.argsStyle});I(n);let o=y(r),t=`./${e.stem}.${e.importExt}`,a=["client","configure",...e.zodSelected?["use"]:[]];return["#!/usr/bin/env node",O,`import { readFileSync, realpathSync, writeFileSync } from "node:fs";
|
|
22
|
+
import { fileURLToPath } from "node:url";`,[`import { ${a.join(", ")} } from "${t}";`,...e.zodSelected?[`import { zodValidation } from "./${e.stem}.zod.${e.importExt}";`]:[]].join(`
|
|
23
|
+
`),e.runtime==="module"?`import { invokedName, runCli, type CliCommand, type CliWiring } from "./runtime/cli.${e.importExt}";`:`// \u2500\u2500\u2500 Embedded cli engine (@redocly/client-generator) \u2500\u2500\u2500
|
|
24
|
+
`+R(),`export const COMMANDS: CliCommand[] = ${p(n,2)};`,...e.zodSelected?['use(zodValidation(process.argv.includes("--dry-run") ? { response: false } : {}));']:[],`export const wiring: CliWiring = {
|
|
25
|
+
name: invokedName(process.argv[1], ${p(e.stem)}),
|
|
26
|
+
envPrefix: ${p(m(e.stem))},
|
|
27
|
+
client,
|
|
28
|
+
${e.argsStyle==="flat"?` argsStyle: "flat",
|
|
29
|
+
`:""} configure,
|
|
30
|
+
schemes: ${p(o)},
|
|
31
|
+
env: process.env,
|
|
32
|
+
stdin: () => readFileSync(0, "utf-8"),
|
|
33
|
+
readFile: (path: string) => readFileSync(path, "utf-8"),
|
|
34
|
+
writeFile: (path: string, data: Uint8Array) => writeFileSync(path, data),
|
|
35
|
+
stdout: (line: string) => console.log(line),
|
|
36
|
+
stderr: (line: string) => console.error(line),
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
/** Run this CLI programmatically; defaults to the process argv. */
|
|
40
|
+
export const run = (argv: string[] = process.argv.slice(2)): Promise<number> =>
|
|
41
|
+
runCli(COMMANDS, wiring, argv);
|
|
42
|
+
|
|
43
|
+
// Re-exported so a composed entry can run these commands without its own runtime copy.
|
|
44
|
+
export { runCli };
|
|
45
|
+
|
|
46
|
+
// Self-execute only as the process entry, so importing this module is side-effect-safe:
|
|
47
|
+
// composed binaries and login-style wrappers import COMMANDS/wiring/run instead of
|
|
48
|
+
// editing this generated file.
|
|
49
|
+
${P}`].join(`
|
|
50
|
+
|
|
51
|
+
`)+`
|
|
52
|
+
`}function H(r,e){let n=m(e),o=new Map;r.forEach(({alias:s},l)=>{let c=s.replace(/[^A-Za-z0-9]/g,"_"),d=/^[A-Za-z_]/.test(c)?c:`_${c}`;o.set(s,[...o.values()].includes(d)?`${d}_${l}`:d)});let t=s=>o.get(s),a=r.map(({alias:s,modulePath:l},c)=>{let d=t(s);return`import { COMMANDS as ${d}Commands, wiring as ${d}Wiring${c===0?", runCli":""} } from ${JSON.stringify(l)};`}),i=r.map(({alias:s})=>{let l=t(s),c=q(s),d=`${n}_${m(s)}`;return` {
|
|
53
|
+
namespace: ${JSON.stringify(c)},
|
|
54
|
+
commands: ${l}Commands,
|
|
55
|
+
wiring: { ...${l}Wiring, envPrefix: ${JSON.stringify(d)} },
|
|
56
|
+
},`});return["#!/usr/bin/env node",O,['import { realpathSync } from "node:fs";','import { fileURLToPath } from "node:url";',...a].join(`
|
|
57
|
+
`),`/** The composed sources \u2014 import SOURCES to layer custom commands around this binary. */
|
|
58
|
+
export const SOURCES = [
|
|
59
|
+
${i.join(`
|
|
60
|
+
`)}
|
|
61
|
+
];
|
|
62
|
+
|
|
63
|
+
/** Run the composed CLI programmatically; defaults to the process argv. */
|
|
64
|
+
export const run = (argv: string[] = process.argv.slice(2)): Promise<number> =>
|
|
65
|
+
runCli(SOURCES, argv);
|
|
66
|
+
|
|
67
|
+
// Re-exported so a wrapper (a custom \`login\` command) can run these sources itself.
|
|
68
|
+
export { runCli };
|
|
69
|
+
|
|
70
|
+
${P}`].join(`
|
|
71
|
+
|
|
72
|
+
`)+`
|
|
73
|
+
`}var oe=({model:r,output:e,banner:n,emit:o,selected:t,pagination:a})=>{let i=A(r,{stem:e.stem,importExt:o.importExt??"js",zodSelected:t?.includes("zod")??!1,pagination:a,argsStyle:o.argsStyle??"grouped",runtime:o.runtime??"inline"}),s={path:$(e.dir,`${e.stem}.cli.ts`),content:i};if(o.runtime!=="module")return[s];let l=n.map(c=>`// ${c}`).join(`
|
|
74
|
+
`);return[s,{path:$(e.dir,"runtime","cli.ts"),content:`${l}
|
|
75
|
+
|
|
76
|
+
${x().trim()}
|
|
77
|
+
`}]},ie=({model:r,output:e,emit:n,pagination:o})=>{let t=w(f(r,{pagination:o}),{title:`${r.title} command-line reference`,frontmatter:n.docsFrontmatter===!0,name:e.stem,schemes:y(r)});return[{path:$(e.dir,`${e.stem}.cli.md`),content:t}]};function se(r,e){let n=f(e.model,{pagination:e.pagination}).find(t=>t.name===r.name);return n===void 0?void 0:{lang:"shell",label:"CLI",source:`npx tsx client.cli.ts ${["client",...n.group?[u(n.group)]:[],n.name,...n.positionals.map(t=>`<${t.name}>`),...n.flags.filter(t=>t.required).map(t=>`--${t.name} <${t.type}>`),...n.body?["--json '<json>'"]:[]].slice(1).join(" ")}
|
|
78
|
+
`}}export{H as a,oe as b,ie as c,se as d};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { createRequire as __createRequire } from 'node:module';
|
|
2
|
+
import { fileURLToPath as __fileURLToPath } from 'node:url';
|
|
3
|
+
import { dirname as __pathDirname } from 'node:path';
|
|
4
|
+
const require = __createRequire(import.meta.url);
|
|
5
|
+
var __filename = __fileURLToPath(import.meta.url);
|
|
6
|
+
var __dirname = __pathDirname(__filename);
|
|
7
|
+
import{c as f}from"./HJYFWIVE.js";var o=/^[A-Za-z_$][A-Za-z0-9_$]*$/,u=f.typescript;function m(n){return o.test(n)}function I(n){return o.test(n)&&!u.has(n)}function c(n){let e=n.replace(/[^A-Za-z0-9_$]/g,"_");return(e===""||/^[0-9]/.test(e)||u.has(e))&&(e=`_${e}`),e}var p={"<":"\\u003C",">":"\\u003E","\u2028":"\\u2028","\u2029":"\\u2029"};function s(n){return JSON.stringify(n).replace(/[<>\u2028\u2029]/g,e=>p[e])}function E(n){return o.test(n)&&!u.has(n)?n:s(n)}function b(n,e){let i=c(n),t=i,r=2;for(;e.has(t);)t=`${i}_${r++}`;return e.add(t),t}var L=s;function g(n){if(typeof n=="string")return s(n);if(typeof n=="boolean"||n===null||typeof n=="number")return String(n);if(Array.isArray(n))return`[${n.map(g).join(", ")}]`;let e=Object.entries(n).map(([i,t])=>`${m(i)?i:s(i)}: ${g(t)}`);return e.length===0?"{}":`{ ${e.join(", ")} }`}function d(n){return n.replace(/\*\//g,"*\\/")}function M(n,e){let i=l(n,e);return i.length===0?void 0:i.join(`
|
|
8
|
+
`)}function l(n,e){let i=[];return n&&n.trim()&&i.push(...x(S(n))),e&&i.push(...h(e)),i}function h(n){let e=[],i=(t,r)=>{r===void 0?e.push(`@${t}`):e.push(`@${t} ${r}`)};return n.minimum!==void 0&&i("minimum",n.minimum),n.maximum!==void 0&&i("maximum",n.maximum),n.exclusiveMinimum!==void 0&&i("exclusiveMinimum",n.exclusiveMinimum),n.exclusiveMaximum!==void 0&&i("exclusiveMaximum",n.exclusiveMaximum),n.minLength!==void 0&&i("minLength",n.minLength),n.maxLength!==void 0&&i("maxLength",n.maxLength),n.pattern!==void 0&&i("pattern",d(n.pattern)),n.minItems!==void 0&&i("minItems",n.minItems),n.maxItems!==void 0&&i("maxItems",n.maxItems),n.uniqueItems===!0&&i("uniqueItems"),n.format!==void 0&&i("format",n.format),n.deprecated===!0&&i("deprecated"),e}function x(n){let e=0,i=n.length;for(;e<i&&n[e]==="";)e++;for(;i>e&&n[i-1]==="";)i--;return n.slice(e,i)}function _(n){return n[0].toUpperCase()+n.slice(1)}function y(n){let e=n.split(/[-_]/).filter(i=>i.length>0).map((i,t)=>{let r=i.toLowerCase();return t===0?r:r.charAt(0).toUpperCase()+r.slice(1)}).join("");return c(e)}function S(n){return n.replace(/\r\n/g,`
|
|
9
|
+
`).split(`
|
|
10
|
+
`).map(e=>e.trimEnd())}export{m as a,I as b,c,s as d,E as e,b as f,L as g,g as h,d as i,M as j,_ as k,y as l,S as m};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { createRequire as __createRequire } from 'node:module';
|
|
2
|
+
import { fileURLToPath as __fileURLToPath } from 'node:url';
|
|
3
|
+
import { dirname as __pathDirname } from 'node:path';
|
|
4
|
+
const require = __createRequire(import.meta.url);
|
|
5
|
+
var __filename = __fileURLToPath(import.meta.url);
|
|
6
|
+
var __dirname = __pathDirname(__filename);
|
|
7
|
+
import{a as g,c as f,d as i,e as c,l as o}from"./HJYFWIVE.js";var s=f.php,h=class extends g{constructor(){super(" ")}typeName(r){return i(r,{style:"pascal",reserved:s})}memberName(r){return i(r,{style:"camel",reserved:s})}identifier(r){return i(r,{style:"camel",reserved:s})}identifiers(r,t){return c(r,{style:"camel",reserved:s,taken:t})}string(r){return`'${r.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}'`}literal(r){return r==null?"null":typeof r=="boolean"||typeof r=="number"?String(r):typeof r=="string"?this.string(r):Array.isArray(r)?`[${r.map(e=>this.literal(e)).join(", ")}]`:`[${Object.entries(r).map(([e,n])=>`${this.string(e)} => ${this.literal(n)}`).join(", ")}]`}comment(r){for(let t of o(r))this.line(t===""?"//":`// ${t}`);return this}doc(r,t,e=[]){let n=o(t);if(n.length===0&&e.length===0)return this;let l=n.length===0?r:`${r} \u2014 ${n.join(" ")}`;if(e.length===0)return this.line(`/** ${l} */`);this.line("/**"),this.line(` * ${l}`),this.line(" *");for(let m of e)this.line(` * ${m}`);return this.line(" */")}};export{h as a};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { createRequire as __createRequire } from 'node:module';
|
|
2
|
+
import { fileURLToPath as __fileURLToPath } from 'node:url';
|
|
3
|
+
import { dirname as __pathDirname } from 'node:path';
|
|
4
|
+
const require = __createRequire(import.meta.url);
|
|
5
|
+
var __filename = __fileURLToPath(import.meta.url);
|
|
6
|
+
var __dirname = __pathDirname(__filename);
|
|
7
|
+
import{a}from"./TSB6PODJ.js";import"./NB54XRRU.js";import"./HJYFWIVE.js";import"./RFWIIJFG.js";export{a as transformersGenerator};
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import { createRequire as __createRequire } from 'node:module';
|
|
2
|
+
import { fileURLToPath as __fileURLToPath } from 'node:url';
|
|
3
|
+
import { dirname as __pathDirname } from 'node:path';
|
|
4
|
+
const require = __createRequire(import.meta.url);
|
|
5
|
+
var __filename = __fileURLToPath(import.meta.url);
|
|
6
|
+
var __dirname = __pathDirname(__filename);
|
|
7
|
+
var r=class extends Error{constructor(s){super(s),this.name="NotSupportedError"}};export{r as a};
|
|
@@ -4,4 +4,4 @@ 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
|
-
var e={name:"@redocly/cli",version:"2.
|
|
7
|
+
var e={name:"@redocly/cli",version:"2.48.0",description:"",license:"MIT",bin:{redocly:"bin/cli.js",openapi:"bin/cli.js"},type:"module",engines:{node:">=22.12.0 || >=20.19.0 <21.0.0",npm:">=10"},engineStrict:!0,scripts:{build:"node ./scripts/build.mjs","prepare:publish-dir":"node ./scripts/prepare-publish-dir.mjs","clean:publish-dir":`node -e "require('fs').rmSync('.publish', {recursive:true, force:true})"`},publishConfig:{directory:".publish"},repository:{type:"git",url:"https://github.com/Redocly/redocly-cli.git"},homepage:"https://github.com/Redocly/redocly-cli",keywords:["linter","OpenAPI","Swagger","OpenAPI linter","Swagger linter","AsyncAPI linter","Arazzo linter","oas"],contributors:["Roman Hotsiy <roman@redocly.com> (https://redocly.com/)"],devDependencies:{"@opentelemetry/exporter-trace-otlp-http":"0.219.0","@opentelemetry/resources":"2.8.0","@opentelemetry/sdk-trace-node":"2.8.0","@opentelemetry/semantic-conventions":"1.41.1","@redocly/cli-otel":"0.3.5","@redocly/client-generator":"0.4.0","@redocly/openapi-core":"2.48.0","@redocly/respect-core":"2.48.0","@types/cookie":"0.6.0","@types/har-format":"^1.2.16","@types/react":"^17.0.0 || ^18.2.21 || ^19.2.16","@types/react-dom":"^17.0.0 || ^18.2.7 || ^19.2.3","@types/semver":"^7.5.0","@types/set-cookie-parser":"2.4.10","@types/yargs":"17.0.32",colorette:"^1.2.0",cookie:"^0.7.2",dotenv:"16.4.7",esbuild:"^0.28.0",glob:"^13.0.5",handlebars:"^4.7.9","https-proxy-agent":"^7.0.5",react:"^17.0.0 || ^18.2.0 || ^19.2.7","react-dom":"^17.0.0 || ^18.2.0 || ^19.2.7",redoc:"2.5.3",semver:"^7.5.2","set-cookie-parser":"^2.3.5","styled-components":"6.4.2",typescript:"6.0.2",ulid:"^3.0.1",undici:"^6.28.0",yargs:"17.0.1"}};var{version:s,name:i,engines:c}=e,n=e.devDependencies.redoc,p="sha384-xiEssMQFSpSfLbzRZCGfxxIM5QDb2DTrU6vyoZdp2sV1L6pmOMy6MpTtUoLbpC96";export{s as a,i as b,c,n as d,p as e};
|