openapi-sync 4.0.1 → 5.0.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/README.md +225 -8
- package/bin/cli.js +105 -12
- package/dist/chunk-PUWCZVB7.mjs +1 -0
- package/dist/index.d.mts +409 -12
- package/dist/index.d.ts +409 -12
- package/dist/index.js +775 -70
- package/dist/index.mjs +764 -70
- package/dist/interactive-init-4LMPMPGI.mjs +12 -0
- package/package.json +16 -3
package/dist/index.mjs
CHANGED
|
@@ -1,84 +1,778 @@
|
|
|
1
|
-
import
|
|
2
|
-
`+" ".repeat(
|
|
3
|
-
`).filter(
|
|
4
|
-
${" ".repeat(
|
|
5
|
-
${" ".repeat(
|
|
1
|
+
import {c,d,a,b}from'./chunk-PUWCZVB7.mjs';import re from'fs';import J from'path';import*as Ce from'js-yaml';import cn from'lodash.isequal';import qe from'lodash.get';import yn from'axios';import fn from'axios-retry';import hn from'@apidevtools/swagger-parser';import {CurlGenerator}from'curl-generator';var xn=/^[A-Za-z_$][A-Za-z0-9_$]*$/,zt=/[A-Za-z0-9_$]/;var Jt=p=>["object"].includes(typeof p)&&!(p instanceof Blob),pn=p=>{try{return Ce.load(p),!0}catch(u){let t=u;if(t instanceof Ce.YAMLException)return false;throw t}},Wt=p=>{if(pn(p)){let u=Ce.load(p),t=JSON.stringify(u,null,2);return JSON.parse(t)}},ae=p=>p.substring(0,1).toUpperCase()+p.substring(1),Ht=(p,u)=>{let t=p.split("/"),e=`${ae(u)}`,r=[];return t.forEach(n=>{if(n[0]==="{"&&n[n.length-1]==="}"){let s=n.replace(/{/,"").replace(/}/,"");r.push(s),n=`$${s}`;}else if(n[0]==="<"&&n[n.length-1]===">"){let s=n.replace(/</,"").replace(/>/,"");r.push(s),n=`$${s}`;}else if(n[0]===":"){let s=n.replace(/:/,"");r.push(s),n=`$${s}`;}let o="";n.split("").forEach(s=>{let y=s;zt.test(s)||(y="/"),o+=y;}),o.split("/").forEach(s=>{e+=ae(s);});}),{name:e,variables:r,pathParts:t}},ge=(p,u=1)=>{let t="{",e=Object.keys(p);for(let r=0;r<e.length;r++){let n=e[r],o=p[n];if(t+=`
|
|
2
|
+
`+" ".repeat(u)+n+": ",Array.isArray(o)){t+="[";for(let s=0;s<o.length;s++){let y=o[s];typeof y=="object"&&y!==null?t+=ge(y,u+1):t+=typeof y=="string"?`"${y}"`:y,s<o.length-1&&(t+=", ");}t+="]";}else typeof o=="object"&&o!==null?t+=""+ge(o,u+1):t+=o.split(`
|
|
3
|
+
`).filter(s=>s.trim()!=="").join(`
|
|
4
|
+
${" ".repeat(u)}`);r<e.length-1&&(t+=", ");}return t+=`
|
|
5
|
+
${" ".repeat(u-1)}}`,t},Ee=(p,u=1)=>`
|
|
6
6
|
\`\`\`typescript
|
|
7
|
-
${" ".repeat(
|
|
8
|
-
`).filter(
|
|
9
|
-
${" ".repeat(
|
|
10
|
-
\`\`\``;function
|
|
11
|
-
`,
|
|
12
|
-
`).filter(
|
|
7
|
+
${" ".repeat(u)} ${p.split(`
|
|
8
|
+
`).filter(t=>t.trim()!=="").join(`
|
|
9
|
+
${" ".repeat(u)} `)}
|
|
10
|
+
\`\`\``;function wn(p,u){return u.split(".").reduce((e,r)=>e&&e[r]!==void 0?e[r]:void 0,p)}var mn=(p,u="CUSTOM CODE")=>{let t=`// \u{1F512} ${u} START`,e=`// \u{1F512} ${u} END`,r={beforeGenerated:"",afterGenerated:""},n=0,o=[];for(;n<p.length;){let s=p.indexOf(t,n);if(s===-1)break;let y=p.indexOf(e,s);if(y===-1)break;let i=y+e.length,w=p.substring(i,i+100),P=w.match(/^\s*\n\s*(\/\/ =+)/);if(P){let N=w.indexOf(`
|
|
11
|
+
`,P.index+1);N!==-1?i+=N+1:i+=P[0].length;}let R=s,x=p.substring(Math.max(0,s-200),s).lastIndexOf("// ==========");x!==-1&&(R=Math.max(0,s-200)+x);let A=p.substring(R,i);o.push({start:R,end:i,content:A}),n=i;}return o.length>0&&(p.substring(0,o[0].start).split(`
|
|
12
|
+
`).filter(i=>{let w=i.trim();return w.length>0&&!w.startsWith("//")}).join("").length===0?(r.beforeGenerated=o[0].content,o.length>1&&(r.afterGenerated=o[1].content)):(r.afterGenerated=o[0].content,o.length>1&&!r.beforeGenerated&&(r.beforeGenerated=o[1].content))),r},Dt=(p,u="CUSTOM CODE",t=true)=>{let e=t?`// ${p==="top"?"Add your custom code below this line":"Add your custom code above this line"}
|
|
13
13
|
// This section will be preserved during regeneration
|
|
14
14
|
`:"";return `// ${"=".repeat(60)}
|
|
15
|
-
// \u{1F512} ${
|
|
16
|
-
${
|
|
17
|
-
|
|
18
|
-
// \u{1F512} ${
|
|
19
|
-
// ${"=".repeat(60)}`},
|
|
20
|
-
`)};var
|
|
21
|
-
`).filter(
|
|
22
|
-
*${" ".repeat(1)}`))),
|
|
23
|
-
${
|
|
15
|
+
// \u{1F512} ${u} START
|
|
16
|
+
${e}// ${"=".repeat(60)}
|
|
17
|
+
|
|
18
|
+
// \u{1F512} ${u} END
|
|
19
|
+
// ${"=".repeat(60)}`},we=(p,u,t={})=>{let{position:e="bottom",markerText:r="CUSTOM CODE",includeInstructions:n=true}=t,o={beforeGenerated:"",afterGenerated:""};u&&(o=mn(u,r)),!o.beforeGenerated&&!o.afterGenerated&&((e==="top"||e==="both")&&(o.beforeGenerated=Dt("top",r,n)),(e==="bottom"||e==="both")&&(o.afterGenerated=Dt("bottom",r,n)));let s=[];return o.beforeGenerated&&(s.push(o.beforeGenerated),s.push("")),s.push(p),o.afterGenerated&&(s.push(""),s.push(o.afterGenerated)),s.join(`
|
|
20
|
+
`)};var Ae=J.join(__dirname,"../","../db.json");re.existsSync(Ae)||re.writeFileSync(Ae,"{}");var Pe={};try{Pe=c(Ae);}catch(p){Pe={};}var be=Pe||{},Kt=p=>{re.writeFileSync(Ae,JSON.stringify(p));},_t=(p,u)=>{be[p]=u,Kt(be);},Vt=p=>be[p],Oe=()=>{be={},Kt(be);};var Yt={},Xt=(p,u)=>{Yt[p]=u;},Zt=p=>Yt[p]||[];var ue=process.cwd(),Re={},en=yn.create({timeout:6e4});fn(en,{retries:20,retryCondition:p=>p.code==="ECONNABORTED"||p.message.includes("Network Error"),retryDelay:p=>p*1e3});var pe=(p,u,t)=>d(null,null,function*(){var o,s,y,i;if(!(((o=t==null?void 0:t.customCode)==null?void 0:o.enabled)!==false)){yield re.promises.writeFile(p,u);return}let r=null;try{r=yield re.promises.readFile(p,"utf-8");}catch(w){}let n=we(u,r,{position:((s=t==null?void 0:t.customCode)==null?void 0:s.position)||"bottom",markerText:(y=t==null?void 0:t.customCode)==null?void 0:y.markerText,includeInstructions:(i=t==null?void 0:t.customCode)==null?void 0:i.includeInstructions});yield re.promises.writeFile(p,n);}),tn=(p,u,t,e)=>d(null,null,function*(){var oe,xe,Ne,Fe,Be,Qe,ze,De,Je,We;let r=yield en.get(p),n=Jt(r.data)?r.data:Wt(r.data),o;try{o=yield hn.parse(n);}catch(a){let m=a instanceof Error?a.message:String(a);throw new Error(`Failed to parse OpenAPI spec for ${u}: ${m}`)}let s=J.join((t==null?void 0:t.folder)||"",u),y={},i=a=>{var m,T;if((m=t==null?void 0:t.folderSplit)!=null&&m.customFolder){let $=t.folderSplit.customFolder(a);if($)return $}return (T=t==null?void 0:t.folderSplit)!=null&&T.byTags&&a.tags&&a.tags.length>0?a.tags[0].toLowerCase().replace(/\s+/g,"-"):"default"},w=typeof(t==null?void 0:t.server)=="string"?t==null?void 0:t.server:((xe=(oe=o==null?void 0:o.servers)==null?void 0:oe[(t==null?void 0:t.server)||0])==null?void 0:xe.url)||"",P=typeof((Fe=(Ne=t==null?void 0:t.types)==null?void 0:Ne.name)==null?void 0:Fe.prefix)=="string"?t==null?void 0:t.types.name.prefix:"I",R=typeof((Qe=(Be=t==null?void 0:t.endpoints)==null?void 0:Be.name)==null?void 0:Qe.prefix)=="string"?t==null?void 0:t.endpoints.name.prefix:"",k=(a,m)=>{var $,c;let T=ae(a);if((c=($=t==null?void 0:t.types)==null?void 0:$.name)!=null&&c.format){let f=t==null?void 0:t.types.name.format("shared",{name:a},T);if(f)return `${P}${f}`}return `${P}${T}`},x=(a,m,T,$,c,f=0)=>{let d="",g="",h="";if(m)if(m.$ref)if(m.$ref[0]==="#"){let E=(m.$ref||"").split("/");E.shift(),[...E].pop();let Q=qe(a,E,null);if(Q){Q!=null&&Q.name&&(d=Q.name),g=E[E.length-1];let V=k(g);V.includes(".")&&(V=V.split(".").map((te,le)=>le===0?te:`["${te}"]`).join("")),h+=`${c!=null&&c.noSharedImport?"":"Shared."}${V}`;}}else h+="";else if(m.anyOf)h+=`(${m.anyOf.map(E=>x(a,E,"",$,c)).filter(E=>!!E).join("|")})`;else if(m.oneOf)h+=`(${m.oneOf.map(E=>x(a,E,"",$,c)).filter(E=>!!E).join("|")})`;else if(m.allOf)h+=`(${m.allOf.map(E=>x(a,E,"",$,c)).filter(E=>!!E).join("&")})`;else if(m.items)h+=`${x(a,m.items,"",false,c)}[]`;else if(m.properties){let E=Object.keys(m.properties),G=m.required||[],B="";E.forEach(Q=>{var se,te,le,Te,ye,fe;let V="";!((te=(se=t==null?void 0:t.types)==null?void 0:se.doc)!=null&&te.disable)&&((Te=(le=m.properties)==null?void 0:le[Q])!=null&&Te.description)&&(V=" * "+((ye=m.properties)==null?void 0:ye[Q].description.split(`
|
|
21
|
+
`).filter(ce=>ce.trim()!=="").join(`
|
|
22
|
+
*${" ".repeat(1)}`))),B+=(V?`/**
|
|
23
|
+
${V}
|
|
24
24
|
*/
|
|
25
|
-
`:"")+`${
|
|
26
|
-
${" ".repeat(
|
|
27
|
-
`:""}`:""},
|
|
28
|
-
`);
|
|
29
|
-
${
|
|
30
|
-
}`:
|
|
31
|
-
`).filter(
|
|
32
|
-
*${" ".repeat(1)}`)),
|
|
33
|
-
${
|
|
25
|
+
`:"")+`${x(a,(fe=m.properties)==null?void 0:fe[Q],Q,G.includes(Q),c,f+1)}`;}),B.length>0?h+=`{
|
|
26
|
+
${" ".repeat(f)}${B}${" ".repeat(f)}}`:h+="{[k: string]: any}";}else if(m.enum&&m.enum.length>0)m.enum.length>1&&(h+="("),m.enum.map(E=>JSON.stringify(E)).filter(E=>!!E).forEach((E,G)=>{h+=`${G===0?"":"|"}${E}`;}),m.enum.length>1&&(h+=")");else if(m.type){let E=G=>{let B="";if(typeof G=="string")["string","integer","number","array","boolean","null"].includes(G)?["integer","number"].includes(G)?B+="number":G==="array"?B+="any[]":B+=G:G==="object"&&(m.additionalProperties?B+=`{[k: string]: ${x(a,m.additionalProperties,"",true,c)||"any"}}`:B+="{[k: string]: any}");else if(Array.isArray(G)){let Q=G.map(V=>E(V));Q.filter(V=>V!==""),Q.length>1&&(B+="("+Q.join("|")+")");}else B+="any";return B};h=E(m.type);}else h+="any";else h="string";let j=d||T;c!=null&&c.useComponentName&&!j&&(j=g);let W=j?` "${j}"${$?"":"?"}: `:"",l=m!=null&&m.nullable?" | null":"";return h.length>0?`${W}${h}${l}${j?`;
|
|
27
|
+
`:""}`:""},A=(a,m)=>{let c="";if(m)if(m.$ref)if(m.$ref[0]==="#"){let f=(m.$ref||"").split("/");f.shift();let g=qe(a,f,null);g&&(g!=null&&g.name&&(g.name),f[f.length-1],c+=A(a,g));}else c+="";else if(m.anyOf)c+=A(a,m.anyOf[0]);else if(m.oneOf)c+=A(a,m.oneOf[0]);else if(m.allOf)c+=`{${m.allOf.map(f=>`...(${A(a,f)})`).join(",")}}`;else if(m.items)c+=`[${A(a,m.items)}]`;else if(m.properties){let g=Object.keys(m.properties).map(h=>{var j;return ` "${h}": ${A(a,(j=m.properties)==null?void 0:j[h])}`}).join(`,
|
|
28
|
+
`);g.length>0?c+=`{
|
|
29
|
+
${g}
|
|
30
|
+
}`:c+="{}";}else if(m.enum&&m.enum.length>0)m.enum.length>1&&(c+=m.enum[0]);else if(m.type)if(m.example)c+=JSON.stringify(m.example);else {let f=d=>{let g="";if(typeof d=="string")["string","integer","number","array","boolean","null"].includes(d)?["integer","number"].includes(d)?g+="123":d==="array"?g+="[]":d==="boolean"?g+="true":d==="null"?g+="null":g+=`"${d}"`:d==="object"&&(g+="{}");else if(Array.isArray(d)){let h=d.map(j=>f(j));h.filter(j=>j!==""),h.length>1&&(g+=h.join("|"));}else g+="any";return g};c=f(m.type);}else c+="any";else c="string";return c};e&&!isNaN(e)&&e>0&&(process.env.NODE_ENV&&["production","prod","test","staging"].includes(process.env.NODE_ENV)||(Re[u]&&clearTimeout(Re[u]),Re[u]=setTimeout(()=>tn(p,u,t,e),e)));let N=Vt(u);if(cn(N,o))return;_t(u,o);let M="",D="",v={},b=[];o.components&&Object.keys(o.components).forEach(a=>{if(["schemas","responses","parameters","examples","requestBodies","headers","links","callbacks"].includes(a)){let m=o.components[a],T={},$={};Object.keys(m).forEach(f=>{var h;let d=(h=m[f])!=null&&h.schema?m[f].schema:m[f],g=`${x(o,d,"",true,{noSharedImport:true,useComponentName:["parameters"].includes(a)})}`;if(g){let j=f.split("."),W=T,l=$;for(let E=0;E<j.length;E++){let G=j[E];E<j.length-1?(G in W||(W[G]={},l[G]={}),W=W[G],l=l[G]):(W[G]=g,l[G]=d);}}}),Object.keys(T).forEach(f=>{var j,W,l,E;let d=k(f),g=T[f],h="";!((W=(j=t==null?void 0:t.types)==null?void 0:j.doc)!=null&&W.disable)&&f in m&&((l=m[f])!=null&&l.description)&&(h=" * "+m[f].description.split(`
|
|
31
|
+
`).filter(G=>G.trim()!=="").join(`
|
|
32
|
+
*${" ".repeat(1)}`)),v[f]=((E=v[f])!=null?E:"")+(h?`/**
|
|
33
|
+
${h}
|
|
34
34
|
*/
|
|
35
|
-
`:"")+"export type "+
|
|
36
|
-
`;});}});let
|
|
37
|
-
`);return
|
|
38
|
-
${
|
|
39
|
-
${" ".repeat(
|
|
40
|
-
${
|
|
41
|
-
${" ".repeat(
|
|
42
|
-
${
|
|
43
|
-
${" ".repeat(
|
|
44
|
-
${
|
|
45
|
-
`;
|
|
46
|
-
`),
|
|
47
|
-
${
|
|
35
|
+
`:"")+"export type "+d+" = "+(typeof g=="string"?g:ge(g))+`;
|
|
36
|
+
`;});}});let F=a=>{let m="";if(a.content){let T=Object.keys(a.content);T[0]&&a.content[T[0]].schema&&(m+=`${x(o,a.content[T[0]].schema,"")}`);}return m},O=(a,m,T=0)=>{if(!a)return m==="joi"?"Joi.any()":m==="yup"?"yup.mixed()":"z.any()";if(a.$ref){if(a.$ref[0]==="#"){let $=a.$ref.split("/");$.shift();let c=$.join("."),f=qe(o,c);if(f)return O(f,m,T)}return m==="joi"?"Joi.any()":m==="yup"?"yup.mixed()":"z.any()"}if(a.anyOf||a.oneOf){let $=a.anyOf||a.oneOf;if($.every(f=>f.enum!==void 0&&Array.isArray(f.enum))){let f=[],d=false;if($.forEach(g=>{g.enum&&g.enum.forEach(h=>{h===null?d=true:f.includes(h)||f.push(h);});}),f.length>0){let g=f.map(h=>JSON.stringify(h)).join(", ");if(m==="zod"){let h=`z.enum([${g}])`;return d&&(h+=".nullable()"),h}else if(m==="yup"){let h=`yup.mixed().oneOf([${g}])`;return d&&(h+=".nullable()"),h}else return d?`Joi.valid(${g}, null)`:`Joi.valid(${g})`}else if(d)return m==="zod"?"z.null()":m==="yup"?"yup.mixed().nullable()":"Joi.valid(null)"}return m==="zod"?`z.union([${$.map(g=>O(g,m,T+1)).join(", ")}])`:m==="yup"?`yup.mixed().oneOf([${$.map(g=>O(g,m,T+1)).join(", ")}])`:`Joi.alternatives().try(${$.map(d=>O(d,m,T+1)).join(", ")})`}if(a.allOf)if(m==="zod"){let $=a.allOf.map(f=>O(f,m,T+1)),c=$[0];for(let f=1;f<$.length;f++)c=`${c}.merge(${$[f]})`;return c}else return O(a.allOf[0],m,T+1);if(a.items){let $=O(a.items,m,T+1);if(m==="zod"){let c=`z.array(${$})`;return a.minItems!==void 0&&(c+=`.min(${a.minItems})`),a.maxItems!==void 0&&(c+=`.max(${a.maxItems})`),c}else if(m==="yup"){let c=`yup.array().of(${$})`;return a.minItems!==void 0&&(c+=`.min(${a.minItems})`),a.maxItems!==void 0&&(c+=`.max(${a.maxItems})`),c}else {let c=`Joi.array().items(${$})`;return a.minItems!==void 0&&(c+=`.min(${a.minItems})`),a.maxItems!==void 0&&(c+=`.max(${a.maxItems})`),c}}if(a.properties){let $=a.required||[],c=" ".repeat(T+1),f=Object.entries(a.properties).map(([d,g])=>{let h=$.includes(d),j=O(g,m,T+1);return h||(j+=".optional()"),`${c}${d}: ${j}`}).join(`,
|
|
37
|
+
`);return m==="zod"?`z.object({
|
|
38
|
+
${f}
|
|
39
|
+
${" ".repeat(T)}})`:m==="yup"?`yup.object({
|
|
40
|
+
${f}
|
|
41
|
+
${" ".repeat(T)}})`:`Joi.object({
|
|
42
|
+
${f}
|
|
43
|
+
${" ".repeat(T)}})`}if(a.enum&&a.enum.length>0){let $=[],c=false;a.enum.forEach(d=>{d===null?c=true:$.includes(d)||$.push(d);});let f=$.map(d=>JSON.stringify(d)).join(", ");if(m==="zod"){let d=`z.enum([${f}])`;return c&&(d+=".nullable()"),d}else if(m==="yup"){let d=`yup.mixed().oneOf([${f}])`;return c&&(d+=".nullable()"),d}else {let d=`Joi.valid(${f})`;return c&&(d+=".allow(null)"),d}}if(a.type){let c=(f=>{switch(f){case "string":if(m==="zod"){let d="z.string()";return a.format==="email"?d+=".email()":a.format==="uuid"?d+=".uuid()":a.format==="url"||a.format==="uri"?d+=".url()":a.format==="date-time"?d+=".datetime()":a.format==="date"&&(d+=".date()"),a.minLength&&(d+=`.min(${a.minLength})`),a.maxLength&&(d+=`.max(${a.maxLength})`),a.pattern&&(d+=`.regex(/${a.pattern}/)`),d}else if(m==="yup"){let d="yup.string()";return a.format==="email"?d+=".email()":(a.format==="url"||a.format==="uri")&&(d+=".url()"),a.minLength&&(d+=`.min(${a.minLength})`),a.maxLength&&(d+=`.max(${a.maxLength})`),a.pattern&&(d+=`.matches(/${a.pattern}/)`),d}else {let d="Joi.string()";return a.format==="email"?d+=".email()":a.format==="url"||a.format==="uri"?d+=".uri()":a.format==="uuid"?d+=".guid({ version: 'uuidv4' })":a.format==="date-time"&&(d+=".isoDate()"),a.minLength&&(d+=`.min(${a.minLength})`),a.maxLength&&(d+=`.max(${a.maxLength})`),a.pattern&&(d+=`.pattern(/${a.pattern}/)`),d}case "integer":case "number":if(m==="zod"){let d="z.number()";return f==="integer"&&(d+=".int()"),a.minimum!==void 0&&(a.exclusiveMinimum?d+=`.gt(${a.minimum})`:d+=`.min(${a.minimum})`),a.maximum!==void 0&&(a.exclusiveMaximum?d+=`.lt(${a.maximum})`:d+=`.max(${a.maximum})`),d}else if(m==="yup"){let d="yup.number()";return f==="integer"&&(d+=".integer()"),a.minimum!==void 0&&(d+=`.min(${a.minimum})`),a.maximum!==void 0&&(d+=`.max(${a.maximum})`),d}else {let d="Joi.number()";return f==="integer"&&(d+=".integer()"),a.minimum!==void 0&&(a.exclusiveMinimum?d+=`.greater(${a.minimum})`:d+=`.min(${a.minimum})`),a.maximum!==void 0&&(a.exclusiveMaximum?d+=`.less(${a.maximum})`:d+=`.max(${a.maximum})`),d}case "boolean":return m==="joi"?"Joi.boolean()":m==="yup"?"yup.boolean()":"z.boolean()";case "null":return m==="joi"?"Joi.any().allow(null)":m==="yup"?"yup.mixed().nullable()":"z.null()";default:return m==="joi"?"Joi.any()":m==="yup"?"yup.mixed()":"z.any()"}})(typeof a.type=="string"?a.type:a.type[0]);return a.nullable&&m!=="joi"?c+=".nullable()":a.nullable&&m==="joi"&&(c+=".allow(null)"),c}return m==="joi"?"Joi.any()":m==="yup"?"yup.mixed()":"z.any()"},Z=a=>{var m,T,$,c,f;if((T=(m=t==null?void 0:t.endpoints)==null?void 0:m.value)!=null&&T.replaceWords&&Array.isArray(t==null?void 0:t.endpoints.value.replaceWords)){let d=a;return (f=(c=($=t==null?void 0:t.endpoints)==null?void 0:$.value)==null?void 0:c.replaceWords)==null||f.forEach((g,h)=>{let j=new RegExp(g.replace,"g");d=d.replace(j,g.with||"");}),d}else return a},de=(a,m,T=[])=>{var f,d;let $=(f=t==null?void 0:t.endpoints)==null?void 0:f.exclude,c=(d=t==null?void 0:t.endpoints)==null?void 0:d.include;if(c){let g=c.tags&&c.tags.length>0?T.some(j=>c.tags.includes(j)):true,h=c.endpoints&&c.endpoints.length>0?c.endpoints.some(j=>{let W=!j.method||j.method.toLowerCase()===m.toLowerCase();return j.path?a===j.path&&W:j.regex?new RegExp(j.regex).test(a)&&W:false}):true;if(!g||!h)return true}return !!($&&($.tags&&$.tags.length>0&&T.some(h=>$.tags.includes(h))||$.endpoints&&$.endpoints.length>0&&$.endpoints.some(h=>{let j=!h.method||h.method.toLowerCase()===m.toLowerCase();return h.path?a===h.path&&j:h.regex?new RegExp(h.regex).test(a)&&j:false})))};if(Object.keys(o.paths||{}).forEach(a=>{let m=o.paths[a];Object.keys(m).forEach($=>{var Ke,_e,Ve,Ye,Xe,Ze,et,tt,nt,rt,st,at,ot,it,lt,ut,pt,mt,dt,ct,yt,ft,ht,$t,gt,Ct,bt,It,xt,Tt,Et,wt,At,kt,vt,jt,Pt,Ot,qt,Rt,St,Ut,Mt,Gt,Lt,Nt,Ft,Bt,Qt;let c=$,f=Ht(a,c),d=((Ke=m[c])==null?void 0:Ke.tags)||[];if(de(a,c,d))return;let g=m[c],h=i({method:c,path:a,summary:g==null?void 0:g.summary,operationId:g==null?void 0:g.operationId,tags:d,parameters:g==null?void 0:g.parameters,requestBody:g==null?void 0:g.requestBody,responses:g==null?void 0:g.responses});y[h]||(y[h]={endpoints:"",types:"",validation:""});let j=((Ve=(_e=t==null?void 0:t.endpoints)==null?void 0:_e.value)!=null&&Ve.includeServer?w:"")+f.pathParts.map(C=>(C[0]==="{"&&C[C.length-1]==="}"?C=`\${${C.replace(/{/,"").replace(/}/,"")}}`:C[0]==="<"&&C[C.length-1]===">"?C=`\${${C.replace(/</,"").replace(/>/,"")}}`:C[0]===":"&&(C=`\${${C.replace(/:/,"")}}`),C)).join("/"),W=`"${j}"`;f.variables.length>0&&(W=`(${f.variables.map(I=>`${I}:string`).join(",")})=> \`${j}\``),W=Z(W);let l=m[c],E="",G;if(l!=null&&l.parameters&&((l==null?void 0:l.parameters).forEach((I,q)=>{(I.$ref||I.in==="query"&&I.name)&&(E+=`${x(o,I.$ref?I:I.schema,I.name||"",I.required)}`);}),E)){E=`{
|
|
44
|
+
${E}}`;let I=`${f.name}Query`;if((Xe=(Ye=t==null?void 0:t.types)==null?void 0:Ye.name)!=null&&Xe.useOperationId&&(l!=null&&l.operationId)&&(I=`${l.operationId}Query`),I=ae(`${P}${I}`),(et=(Ze=t==null?void 0:t.types)==null?void 0:Ze.name)!=null&&et.format){let L=t==null?void 0:t.types.name.format("endpoint",{code:"",type:"query",method:c,path:a,summary:l==null?void 0:l.summary,operationId:l==null?void 0:l.operationId},I);L&&(I=`${P}${L}`);}G=I;let q=`export type ${I} = ${E};
|
|
45
|
+
`;t!=null&&t.folderSplit?y[h].types+=q:D+=q;}if(((tt=t==null?void 0:t.validations)==null?void 0:tt.disable)!==true&&((rt=(nt=t==null?void 0:t.validations)==null?void 0:nt.generate)==null?void 0:rt.query)!==false&&(l!=null&&l.parameters)){let C=((st=t.validations)==null?void 0:st.library)||"zod",q=l.parameters.filter(L=>!L.$ref&&L.in==="query"&&L.name);if(q.length>0){let L=((at=t==null?void 0:t.validations)==null?void 0:at.name)||((ot=t==null?void 0:t.types)==null?void 0:ot.name),H=typeof(L==null?void 0:L.prefix)=="string"?L.prefix:"I",U=typeof((lt=(it=t==null?void 0:t.validations)==null?void 0:it.name)==null?void 0:lt.suffix)=="string"?t.validations.name.suffix:"Schema",z=`${f.name}Query`;if(L!=null&&L.useOperationId&&(l!=null&&l.operationId)&&(z=`${l.operationId}Query`),z=ae(`${H}${z}${U}`),(pt=(ut=t==null?void 0:t.validations)==null?void 0:ut.name)!=null&&pt.format){let X=t.validations.name.format({code:"",type:"query",method:c,path:a,summary:l==null?void 0:l.summary,operationId:l==null?void 0:l.operationId},z);X&&(z=`${H}${X}${U}`);}else if((dt=(mt=t==null?void 0:t.types)==null?void 0:mt.name)!=null&&dt.format){let X=t.types.name.format("endpoint",{code:"",type:"query",method:c,path:a,summary:l==null?void 0:l.summary,operationId:l==null?void 0:l.operationId},z);X&&(z=`${H}${X}${U}`);}let S=q.map(X=>{let ln=X!=null&&X.schema?O(X.schema,C):C==="joi"?"Joi.string()":C==="yup"?"yup.string()":"z.string()",un=X.required?"":".optional()";return ` ${X.name}: ${ln}${un}`}).join(`,
|
|
46
|
+
`),ie=`export const ${z} = ${C==="joi"?"Joi.object":C==="yup"?"yup.object":"z.object"}({
|
|
47
|
+
${S}
|
|
48
48
|
});
|
|
49
49
|
|
|
50
|
-
`;
|
|
51
|
-
`;
|
|
50
|
+
`;t!=null&&t.folderSplit||y[h]||(y[h]={endpoints:"",types:"",validation:""}),y[h].validation+=ie;}}let B=l==null?void 0:l.requestBody,Q="",V;if(B&&(Q=F(B),Q)){let C=`${f.name}DTO`;if((yt=(ct=t==null?void 0:t.types)==null?void 0:ct.name)!=null&&yt.useOperationId&&(l!=null&&l.operationId)&&(C=`${l.operationId}DTO`),C=ae(`${P}${C}`),(ht=(ft=t==null?void 0:t.types)==null?void 0:ft.name)!=null&&ht.format){let q=t==null?void 0:t.types.name.format("endpoint",{code:"",type:"dto",method:c,path:a,summary:l==null?void 0:l.summary,operationId:l==null?void 0:l.operationId},C);q&&(C=`${P}${q}`);}V=C;let I=`export type ${C} = ${Q};
|
|
51
|
+
`;t!=null&&t.folderSplit?y[h].types+=I:D+=I;}if((($t=t==null?void 0:t.validations)==null?void 0:$t.disable)!==true&&((Ct=(gt=t==null?void 0:t.validations)==null?void 0:gt.generate)==null?void 0:Ct.dto)!==false&&B){let C=((bt=t.validations)==null?void 0:bt.library)||"zod";if(B.content){let I=Object.keys(B.content);if(I[0]&&B.content[I[0]].schema){let q=((It=t==null?void 0:t.validations)==null?void 0:It.name)||((xt=t==null?void 0:t.types)==null?void 0:xt.name),L=typeof(q==null?void 0:q.prefix)=="string"?q.prefix:"I",H=typeof((Et=(Tt=t==null?void 0:t.validations)==null?void 0:Tt.name)==null?void 0:Et.suffix)=="string"?t.validations.name.suffix:"Schema",U=`${f.name}DTO`;if(q!=null&&q.useOperationId&&(l!=null&&l.operationId)&&(U=`${l.operationId}DTO`),U=ae(`${L}${U}${H}`),(At=(wt=t==null?void 0:t.validations)==null?void 0:wt.name)!=null&&At.format){let Y=t.validations.name.format({code:"",type:"dto",method:c,path:a,summary:l==null?void 0:l.summary,operationId:l==null?void 0:l.operationId},U);Y&&(U=`${L}${Y}${H}`);}else if((vt=(kt=t==null?void 0:t.types)==null?void 0:kt.name)!=null&&vt.format){let Y=t.types.name.format("endpoint",{code:"",type:"dto",method:c,path:a,summary:l==null?void 0:l.summary,operationId:l==null?void 0:l.operationId},U);Y&&(U=`${L}${Y}${H}`);}let z=O(B.content[I[0]].schema,C),S=`export const ${U} = ${z};
|
|
52
52
|
|
|
53
|
-
`;
|
|
54
|
-
`;
|
|
55
|
-
- Scopes: [\`${
|
|
56
|
-
- ${
|
|
57
|
-
`),
|
|
58
|
-
--cert client-certificate.crt --key client-private-key.key --cacert ca-certificate.crt`:
|
|
53
|
+
`;t!=null&&t.folderSplit||y[h]||(y[h]={endpoints:"",types:"",validation:""}),y[h].validation+=S;}}}let se={},te="",le="";if(l!=null&&l.responses){let C=l==null?void 0:l.responses;Object.keys(C).forEach(q=>{var L,H,U,z;if(te=F(C[q]),se[q]=te,te){let S=`${f.name}${q}Response`;if((H=(L=t==null?void 0:t.types)==null?void 0:L.name)!=null&&H.useOperationId&&(l!=null&&l.operationId)&&(S=`${l.operationId}${q}Response`),S=ae(`${P}${S}`),(z=(U=t==null?void 0:t.types)==null?void 0:U.name)!=null&&z.format){let X=t==null?void 0:t.types.name.format("endpoint",{code:q,type:"response",method:c,path:a,summary:l==null?void 0:l.summary,operationId:l==null?void 0:l.operationId},S);X&&(S=`${P}${X}`);}let Y=`export type ${S} = ${te};
|
|
54
|
+
`;t!=null&&t.folderSplit?y[h].types+=Y:D+=Y,se[q]=S;let ie=parseInt(q);ie>=200&&ie<300&&(le=S);}});}let Te=C=>!C||!C.length?"":C.map(I=>Object.entries(I).map(([L,H])=>{let U=L,z="";return Array.isArray(H)&&H.length&&(z=`
|
|
55
|
+
- Scopes: [\`${H.join("`, `")}\`]`,U=`**${U}**`),`
|
|
56
|
+
- ${U}${z}`}).join("")).join(`
|
|
57
|
+
`),ye=l!=null&&l.security?Te(l.security):"",fe="";if(!((Pt=(jt=t==null?void 0:t.endpoints)==null?void 0:jt.doc)!=null&&Pt.disable)){let C="";if((qt=(Ot=t==null?void 0:t.endpoints)==null?void 0:Ot.doc)!=null&&qt.showCurl){let I={},q="",L="";(Rt=l.requestBody)!=null&&Rt.content&&Object.keys(l.requestBody.content).forEach(z=>{let S=l.requestBody.content[z].schema;if(S){Array.isArray(I["Content-type"])?I["Content-type"].push(z):I["Content-type"]=[z];let Y=A(o,S);Y&&(q=Y);}}),l!=null&&l.security&&l.security.forEach(U=>{Object.keys(U).forEach(z=>{var Y,ie;let S=(ie=(Y=o.components)==null?void 0:Y.securitySchemes)==null?void 0:ie[z];S&&(S.type==="mutualTLS"?L+=`
|
|
58
|
+
--cert client-certificate.crt --key client-private-key.key --cacert ca-certificate.crt`:S.type==="apiKey"?I[(S==null?void 0:S.name)||"X-API-KEY"]="{API_KEY_VALUE}":I.Authorization=`${(S==null?void 0:S.scheme)==="basic"?"Basic":"Bearer"} {${(S==null?void 0:S.scheme)==="basic"?"VALUE":"TOKEN"}}`);});});let H={};Object.keys(I).forEach(U=>{Array.isArray(I[U])?H[U]=I[U].join("; "):H[U]=I[U];}),C=`
|
|
59
59
|
\`\`\`bash
|
|
60
|
-
${CurlGenerator({url:
|
|
61
|
-
\`\`\``;}
|
|
62
|
-
* ${
|
|
63
|
-
* **Method**: \`${
|
|
64
|
-
* **Summary**: ${(
|
|
65
|
-
* **Tags**: [${((
|
|
66
|
-
* **OperationId**: ${(
|
|
67
|
-
* **Query**: ${
|
|
68
|
-
* **DTO**: ${
|
|
69
|
-
* **Response**: ${Object.entries(
|
|
70
|
-
- **${I}**: ${
|
|
71
|
-
* **Security**: ${
|
|
72
|
-
`:""}${
|
|
60
|
+
${CurlGenerator({url:w+a,method:c.toUpperCase(),headers:H,body:q})}${L}
|
|
61
|
+
\`\`\``;}fe=`/**${l!=null&&l.description?`
|
|
62
|
+
* ${l==null?void 0:l.description} `:""}
|
|
63
|
+
* **Method**: \`${c.toUpperCase()}\`
|
|
64
|
+
* **Summary**: ${(l==null?void 0:l.summary)||""}
|
|
65
|
+
* **Tags**: [${((St=l==null?void 0:l.tags)==null?void 0:St.join(", "))||""}]
|
|
66
|
+
* **OperationId**: ${(l==null?void 0:l.operationId)||""} ${E?`
|
|
67
|
+
* **Query**: ${Ee(E)} `:""}${Q?`
|
|
68
|
+
* **DTO**: ${Ee(Q)} `:""}${te?`
|
|
69
|
+
* **Response**: ${Object.entries(se).map(([I,q])=>`
|
|
70
|
+
- **${I}**: ${Ee(q,2)} `).join("")}`:""}${ye?`
|
|
71
|
+
* **Security**: ${ye}
|
|
72
|
+
`:""}${C}
|
|
73
73
|
*/
|
|
74
|
-
`;}let
|
|
75
|
-
`;
|
|
74
|
+
`;}let ce=(Mt=(Ut=t==null?void 0:t.endpoints)==null?void 0:Ut.name)!=null&&Mt.useOperationId&&((Gt=l==null?void 0:l.operationId)==null?void 0:Gt.length)>0?l.operationId:`${f.name}`;if((Nt=(Lt=t==null?void 0:t.endpoints)==null?void 0:Lt.name)!=null&&Nt.format){let C=t==null?void 0:t.endpoints.name.format({method:c,path:a,summary:l==null?void 0:l.summary,operationId:l==null?void 0:l.operationId},ce);C&&(ce=C);}let an={method:`"${c}"`,operationId:`"${l==null?void 0:l.operationId}"`,url:W,tags:(l==null?void 0:l.tags)||[]},He=`${fe}export const ${R}${ce} = ${((Bt=(Ft=t==null?void 0:t.endpoints)==null?void 0:Ft.value)==null?void 0:Bt.type)==="object"?ge(an):W};
|
|
75
|
+
`;t!=null&&t.folderSplit?y[h].endpoints+=He:M+=He;let on={name:`${R}${ce}`,method:c,path:a,summary:l==null?void 0:l.summary,operationId:l==null?void 0:l.operationId,tags:d,parameters:(Qt=l==null?void 0:l.parameters)==null?void 0:Qt.filter(C=>!C.$ref&&C.in&&C.name).map(C=>{var I;return {name:C.name,in:C.in,required:C.required,type:((I=C.schema)==null?void 0:I.type)||"string"}}),requestBody:B?{type:Q,required:B.required}:void 0,responses:se?Object.entries(se).reduce((C,[I,q])=>(C[I]={type:q},C),{}):void 0,queryType:G,dtoType:V,responseType:le||void 0};b.push(on);});}),t!=null&&t.folderSplit){for(let[a,m]of Object.entries(y))if(m.endpoints||m.types){let T=J.join(s,a);if(m.endpoints){let $=J.join(ue,T,"endpoints.ts");yield re.promises.mkdir(J.dirname($),{recursive:true}),yield pe($,m.endpoints,t);}if(m.types){let $=J.join(ue,T,"types.ts");yield re.promises.mkdir(J.dirname($),{recursive:true});let c=Object.values(v).length>0?`import * as Shared from "../shared";
|
|
76
|
+
|
|
77
|
+
${m.types}`:m.types;yield pe($,c,t);}if(((ze=t==null?void 0:t.validations)==null?void 0:ze.disable)!==true&&m.validation){let $=((De=t.validations)==null?void 0:De.library)||"zod",c=$==="joi"?'import Joi from "joi";':$==="yup"?'import * as yup from "yup";':'import { z } from "zod";',f=J.join(ue,T,"validations.ts");yield re.promises.mkdir(J.dirname(f),{recursive:true}),yield pe(f,`${c}
|
|
78
|
+
|
|
79
|
+
${m.validation}`,t);}}}if(M.length>0){let a=J.join(ue,s,"endpoints.ts");yield re.promises.mkdir(J.dirname(a),{recursive:true}),yield pe(a,M,t);}if(Object.values(v).length>0){let a=J.join(ue,s,t!=null&&t.folderSplit?"":"types","shared.ts");yield re.promises.mkdir(J.dirname(a),{recursive:true}),yield pe(a,Object.values(v).join(`
|
|
80
|
+
`),t);}if(D.length>0){let a=J.join(ue,s,"types","index.ts");yield re.promises.mkdir(J.dirname(a),{recursive:true}),yield pe(a,`${Object.values(v).length>0?`import * as Shared from "./shared";
|
|
81
|
+
|
|
82
|
+
`:""}${D}`,t);}if(((Je=t==null?void 0:t.validations)==null?void 0:Je.disable)!==true&&!(t!=null&&t.folderSplit)){let a=((We=t.validations)==null?void 0:We.library)||"zod",m=a==="joi"?'import Joi from "joi";':a==="yup"?'import * as yup from "yup";':'import { z } from "zod";',T=Object.values(y).map($=>$.validation).filter($=>$.length>0).join("");if(T){let $=J.join(ue,s,"validations.ts");yield re.promises.mkdir(J.dirname($),{recursive:true}),yield pe($,`${m}
|
|
83
|
+
|
|
84
|
+
${T}`,t);}}Xt(u,b);}),Se=tn;var nn=(p,u)=>{let t=p;return u.tags&&u.tags.length>0&&(t=t.filter(e=>!e.tags||e.tags.length===0?false:e.tags.some(r=>u.tags.includes(r)))),u.endpoints&&u.endpoints.length>0&&(t=t.filter(e=>u.endpoints.includes(e.name))),t};var Ue=(p,u,t=false)=>{var s,y;let e=u.baseURL||"",r=u.auth,n=`// Generated Fetch API Client
|
|
85
|
+
`;n+=`// This file was auto-generated. Add custom code in the marked sections.
|
|
86
|
+
|
|
87
|
+
`,n+=`import type {
|
|
88
|
+
`;let o=new Set;return p.forEach(i=>{i.queryType&&o.add(i.queryType),i.dtoType&&o.add(i.dtoType),i.responseType&&o.add(i.responseType);}),o.forEach(i=>{n+=` ${i},
|
|
89
|
+
`;}),n+=`} from '../types';
|
|
90
|
+
|
|
91
|
+
`,n+=`import {
|
|
92
|
+
`,p.forEach(i=>{n+=` ${i.name} as ${i.name}_endpoint,
|
|
93
|
+
`;}),n+=`} from '../endpoints';
|
|
94
|
+
|
|
95
|
+
`,n+=`export interface ApiConfig {
|
|
96
|
+
`,n+=` baseURL?: string;
|
|
97
|
+
`,r&&(n+=` auth?: {
|
|
98
|
+
`,n+=` token?: string;
|
|
99
|
+
`,n+=` };
|
|
100
|
+
`),n+=` headers?: Record<string, string>;
|
|
101
|
+
`,n+=`}
|
|
102
|
+
|
|
103
|
+
`,n+=`let globalConfig: ApiConfig = {
|
|
104
|
+
`,n+=` baseURL: "${e}",
|
|
105
|
+
`,n+=`};
|
|
106
|
+
|
|
107
|
+
`,n+=`export const setApiConfig = (config: Partial<ApiConfig>) => {
|
|
108
|
+
`,n+=` globalConfig = { ...globalConfig, ...config };
|
|
109
|
+
`,n+=`};
|
|
110
|
+
|
|
111
|
+
`,(s=u.errorHandling)!=null&&s.generateErrorClasses&&(n+=`export class ApiError extends Error {
|
|
112
|
+
`,n+=` constructor(
|
|
113
|
+
`,n+=` message: string,
|
|
114
|
+
`,n+=` public statusCode: number,
|
|
115
|
+
`,n+=` public response?: any
|
|
116
|
+
`,n+=` ) {
|
|
117
|
+
`,n+=` super(message);
|
|
118
|
+
`,n+=` this.name = 'ApiError';
|
|
119
|
+
`,n+=` }
|
|
120
|
+
`,n+=`}
|
|
121
|
+
|
|
122
|
+
`),n+=`async function fetchAPI<T>(
|
|
123
|
+
`,n+=` url: string,
|
|
124
|
+
`,n+=` options: RequestInit = {}
|
|
125
|
+
`,n+=`): Promise<T> {
|
|
126
|
+
`,n+=` const headers: Record<string, string> = {
|
|
127
|
+
`,n+=` 'Content-Type': 'application/json',
|
|
128
|
+
`,n+=` ...globalConfig.headers,
|
|
129
|
+
`,n+=` ...(options.headers as Record<string, string>),
|
|
130
|
+
`,n+=` };
|
|
131
|
+
|
|
132
|
+
`,(r==null?void 0:r.type)==="bearer"?(n+=` if (globalConfig.auth?.token) {
|
|
133
|
+
`,n+=" headers['Authorization'] = `Bearer ${globalConfig.auth.token}`;\n",n+=` }
|
|
134
|
+
|
|
135
|
+
`):(r==null?void 0:r.type)==="apiKey"&&r.in==="header"&&(n+=` if (globalConfig.auth?.token) {
|
|
136
|
+
`,n+=` headers['${r.name||"X-API-Key"}'] = globalConfig.auth.token;
|
|
137
|
+
`,n+=` }
|
|
138
|
+
|
|
139
|
+
`),n+=" const response = await fetch(`${globalConfig.baseURL}${url}`, {\n",n+=` ...options,
|
|
140
|
+
`,n+=` headers,
|
|
141
|
+
`,n+=` });
|
|
142
|
+
|
|
143
|
+
`,n+=` if (!response.ok) {
|
|
144
|
+
`,(y=u.errorHandling)!=null&&y.generateErrorClasses?(n+=` const errorData = await response.json().catch(() => ({}));
|
|
145
|
+
`,n+=` throw new ApiError(
|
|
146
|
+
`,n+=` errorData.message || response.statusText,
|
|
147
|
+
`,n+=` response.status,
|
|
148
|
+
`,n+=` errorData
|
|
149
|
+
`,n+=` );
|
|
150
|
+
`):n+=" throw new Error(`HTTP error! status: ${response.status}`);\n",n+=` }
|
|
151
|
+
|
|
152
|
+
`,n+=` return response.json();
|
|
153
|
+
`,n+=`}
|
|
154
|
+
|
|
155
|
+
`,p.forEach(i=>{var D,v;let w=i.name,P=((D=i.parameters)==null?void 0:D.filter(b=>b.in==="path"))||[],R=((v=i.parameters)==null?void 0:v.filter(b=>b.in==="query"))||[],k=P.length>0,x=R.length>0,A=!!i.requestBody,N=i.responseType||"any";if(n+=`/**
|
|
156
|
+
`,i.summary&&(n+=` * ${i.summary}
|
|
157
|
+
`),n+=` * @method ${i.method.toUpperCase()}
|
|
158
|
+
`,n+=` * @path ${i.path}
|
|
159
|
+
`,i.tags&&i.tags.length>0&&(n+=` * @tags ${i.tags.join(", ")}
|
|
160
|
+
`),n+=` */
|
|
161
|
+
`,n+=`export async function ${w}(`,(k||x||A)&&(n+=`params: {
|
|
162
|
+
`,k&&(n+=` url: {
|
|
163
|
+
`,P.forEach(b=>{let O={string:"string",number:"number",integer:"number",boolean:"boolean",array:"any[]",object:"any"}[b.type||"string"]||"any",Z=b.required?"":"?";n+=` ${b.name}${Z}: ${O};
|
|
164
|
+
`;}),n+=` };
|
|
165
|
+
`),x&&(n+=` query: ${i.queryType||"Record<string, any>"};
|
|
166
|
+
`),A&&(n+=` data: ${i.dtoType||"any"};
|
|
167
|
+
`),n+=`}
|
|
168
|
+
`),n+=`): Promise<${N}> {
|
|
169
|
+
`,k||x||A){let b=[];k&&b.push("url"),x&&b.push("query"),A&&b.push("data"),n+=` const { ${b.join(", ")} } = params;
|
|
170
|
+
`;}let M;if(k){let b=P.map(F=>`url.${F.name}`).join(", ");M=`${i.name}_endpoint(${b})`;}else M=`${i.name}_endpoint`;x?(n+=` const queryParams = new URLSearchParams();
|
|
171
|
+
`,R.forEach(b=>{b.required?n+=` queryParams.append('${b.name}', String(query.${b.name}));
|
|
172
|
+
`:(n+=` if (query.${b.name} !== undefined) {
|
|
173
|
+
`,n+=` queryParams.append('${b.name}', String(query.${b.name}));
|
|
174
|
+
`,n+=` }
|
|
175
|
+
`);}),n+=` const _url = \`\${${M}}?\${queryParams.toString()}\`;
|
|
176
|
+
`):n+=` const _url = ${M};
|
|
177
|
+
`,n+=` return fetchAPI<${N}>(_url, {
|
|
178
|
+
`,n+=` method: '${i.method.toUpperCase()}',
|
|
179
|
+
`,A&&(n+=` body: JSON.stringify(data),
|
|
180
|
+
`),n+=` });
|
|
181
|
+
`,n+=`}
|
|
182
|
+
|
|
183
|
+
`;}),t&&(n+=`// Export all functions as a default object
|
|
184
|
+
`,n+=`const apiClient = {
|
|
185
|
+
`,n+=` setApiConfig,
|
|
186
|
+
`,p.forEach(i=>{n+=` ${i.name},
|
|
187
|
+
`;}),n+=`};
|
|
188
|
+
|
|
189
|
+
`,n+=`export default apiClient;
|
|
190
|
+
`),n},me=(p,u,t=false)=>{var s,y;let e=u.baseURL||"",r=u.auth,n=`// Generated Axios API Client
|
|
191
|
+
`;n+=`// This file was auto-generated. Add custom code in the marked sections.
|
|
192
|
+
|
|
193
|
+
`,n+=`import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from 'axios';
|
|
194
|
+
|
|
195
|
+
`,n+=`import type {
|
|
196
|
+
`;let o=new Set;return p.forEach(i=>{i.queryType&&o.add(i.queryType),i.dtoType&&o.add(i.dtoType),i.responseType&&o.add(i.responseType);}),o.forEach(i=>{n+=` ${i},
|
|
197
|
+
`;}),n+=`} from '../types';
|
|
198
|
+
|
|
199
|
+
`,n+=`import {
|
|
200
|
+
`,p.forEach(i=>{n+=` ${i.name},
|
|
201
|
+
`;}),n+=`} from '../endpoints';
|
|
202
|
+
|
|
203
|
+
`,n+=`export interface ApiConfig {
|
|
204
|
+
`,n+=` baseURL?: string;
|
|
205
|
+
`,r&&(n+=` auth?: {
|
|
206
|
+
`,n+=` token?: string;
|
|
207
|
+
`,n+=` };
|
|
208
|
+
`),n+=` headers?: Record<string, string>;
|
|
209
|
+
`,n+=` timeout?: number;
|
|
210
|
+
`,n+=`}
|
|
211
|
+
|
|
212
|
+
`,(s=u.errorHandling)!=null&&s.generateErrorClasses&&(n+=`export class ApiError extends Error {
|
|
213
|
+
`,n+=` constructor(
|
|
214
|
+
`,n+=` message: string,
|
|
215
|
+
`,n+=` public statusCode: number,
|
|
216
|
+
`,n+=` public response?: any
|
|
217
|
+
`,n+=` ) {
|
|
218
|
+
`,n+=` super(message);
|
|
219
|
+
`,n+=` this.name = 'ApiError';
|
|
220
|
+
`,n+=` }
|
|
221
|
+
`,n+=`}
|
|
222
|
+
|
|
223
|
+
`),n+=`class ApiClient {
|
|
224
|
+
`,n+=` private client: AxiosInstance;
|
|
225
|
+
|
|
226
|
+
`,n+=` constructor(config: ApiConfig = {}) {
|
|
227
|
+
`,n+=` this.client = axios.create({
|
|
228
|
+
`,n+=` baseURL: config.baseURL || "${e}",
|
|
229
|
+
`,n+=` timeout: config.timeout || 30000,
|
|
230
|
+
`,n+=` headers: {
|
|
231
|
+
`,n+=` 'Content-Type': 'application/json',
|
|
232
|
+
`,n+=` ...config.headers,
|
|
233
|
+
`,n+=` },
|
|
234
|
+
`,n+=` });
|
|
235
|
+
|
|
236
|
+
`,r&&(n+=` // Request interceptor for auth
|
|
237
|
+
`,n+=` this.client.interceptors.request.use((config) => {
|
|
238
|
+
`,r.type==="bearer"?(n+=` const token = this.getAuthToken();
|
|
239
|
+
`,n+=` if (token) {
|
|
240
|
+
`,n+=" config.headers.Authorization = `Bearer ${token}`;\n",n+=` }
|
|
241
|
+
`):r.type==="apiKey"&&r.in==="header"&&(n+=` const token = this.getAuthToken();
|
|
242
|
+
`,n+=` if (token) {
|
|
243
|
+
`,n+=` config.headers['${r.name||"X-API-Key"}'] = token;
|
|
244
|
+
`,n+=` }
|
|
245
|
+
`),n+=` return config;
|
|
246
|
+
`,n+=` });
|
|
247
|
+
|
|
248
|
+
`),n+=` // Response interceptor for error handling
|
|
249
|
+
`,n+=` this.client.interceptors.response.use(
|
|
250
|
+
`,n+=` (response) => response,
|
|
251
|
+
`,n+=` (error) => {
|
|
252
|
+
`,(y=u.errorHandling)!=null&&y.generateErrorClasses?(n+=` const message = error.response?.data?.message || error.message;
|
|
253
|
+
`,n+=` const statusCode = error.response?.status || 500;
|
|
254
|
+
`,n+=` throw new ApiError(message, statusCode, error.response?.data);
|
|
255
|
+
`):n+=` return Promise.reject(error);
|
|
256
|
+
`,n+=` }
|
|
257
|
+
`,n+=` );
|
|
258
|
+
`,n+=` }
|
|
259
|
+
|
|
260
|
+
`,r&&(n+=` private authToken?: string;
|
|
261
|
+
|
|
262
|
+
`,n+=` setAuthToken(token: string) {
|
|
263
|
+
`,n+=` this.authToken = token;
|
|
264
|
+
`,n+=` }
|
|
265
|
+
|
|
266
|
+
`,n+=` getAuthToken(): string | undefined {
|
|
267
|
+
`,n+=` return this.authToken;
|
|
268
|
+
`,n+=` }
|
|
269
|
+
|
|
270
|
+
`),n+=` updateConfig(config: Partial<ApiConfig>) {
|
|
271
|
+
`,n+=` Object.assign(this.client.defaults, config);
|
|
272
|
+
`,n+=` }
|
|
273
|
+
|
|
274
|
+
`,p.forEach(i=>{var M,D;let w=i.name,P=((M=i.parameters)==null?void 0:M.filter(v=>v.in==="path"))||[],R=((D=i.parameters)==null?void 0:D.filter(v=>v.in==="query"))||[],k=P.length>0,x=R.length>0,A=!!i.requestBody,N=i.responseType||"any";if(n+=` /**
|
|
275
|
+
`,i.summary&&(n+=` * ${i.summary}
|
|
276
|
+
`),n+=` * @method ${i.method.toUpperCase()}
|
|
277
|
+
`,n+=` * @path ${i.path}
|
|
278
|
+
`,i.tags&&i.tags.length>0&&(n+=` * @tags ${i.tags.join(", ")}
|
|
279
|
+
`),n+=` */
|
|
280
|
+
`,n+=` async ${w}(`,(k||x||A)&&(n+=`params: {
|
|
281
|
+
`,k&&(n+=` url: {
|
|
282
|
+
`,P.forEach(v=>{let F={string:"string",number:"number",integer:"number",boolean:"boolean",array:"any[]",object:"any"}[v.type||"string"]||"any",O=v.required?"":"?";n+=` ${v.name}${O}: ${F};
|
|
283
|
+
`;}),n+=` };
|
|
284
|
+
`),x&&(n+=` query: ${i.queryType||"Record<string, any>"};
|
|
285
|
+
`),A&&(n+=` data: ${i.dtoType||"any"};
|
|
286
|
+
`),n+=" }"),n+=`): Promise<${N}> {
|
|
287
|
+
`,k||x||A){let v=[];k&&v.push("url"),x&&v.push("query"),A&&v.push("data"),n+=` const { ${v.join(", ")} } = params;
|
|
288
|
+
`;}if(k){let v=P.map(b=>`url.${b.name}`).join(", ");n+=` const _url = ${i.name}(${v});
|
|
289
|
+
`;}else n+=` const _url = ${i.name};
|
|
290
|
+
`;n+=` const config: AxiosRequestConfig = {};
|
|
291
|
+
`,x&&(n+=` config.params = { ...query };
|
|
292
|
+
`),n+=` const response = await this.client.${i.method.toLowerCase()}<${N}>(
|
|
293
|
+
`,n+=` _url,
|
|
294
|
+
`,A?n+=` data,
|
|
295
|
+
config
|
|
296
|
+
`:n+=` config
|
|
297
|
+
`,n+=` );
|
|
298
|
+
`,n+=` return response.data;
|
|
299
|
+
`,n+=` }
|
|
300
|
+
|
|
301
|
+
`;}),n+=`}
|
|
302
|
+
|
|
303
|
+
`,t?n+=`export default ApiClient;
|
|
304
|
+
`:(n+=`export const apiClient = new ApiClient();
|
|
305
|
+
`,n+=`export default apiClient;
|
|
306
|
+
`),n},Me=(p,u)=>{var s,y;let t=((s=u.reactQuery)==null?void 0:s.version)||5,e=((y=u.reactQuery)==null?void 0:y.mutations)!==false,r=`// Generated React Query Hooks
|
|
307
|
+
`;r+=`// This file was auto-generated. Add custom code in the marked sections.
|
|
308
|
+
|
|
309
|
+
`;let n=e&&p.some(i=>["POST","PUT","PATCH","DELETE"].includes(i.method.toUpperCase()));t===5?r+=n?`import { useQuery, useMutation, UseQueryOptions, UseMutationOptions } from '@tanstack/react-query';
|
|
310
|
+
`:`import { useQuery, UseQueryOptions } from '@tanstack/react-query';
|
|
311
|
+
`:r+=n?`import { useQuery, useMutation, UseQueryOptions, UseMutationOptions } from 'react-query';
|
|
312
|
+
`:`import { useQuery, UseQueryOptions } from 'react-query';
|
|
313
|
+
`,r+=`
|
|
314
|
+
`,r+=`import apiClient from './client';
|
|
315
|
+
`,r+=`import type {
|
|
316
|
+
`;let o=new Set;return p.forEach(i=>{i.queryType&&o.add(i.queryType),i.dtoType&&o.add(i.dtoType),i.responseType&&o.add(i.responseType);}),o.forEach(i=>{r+=` ${i},
|
|
317
|
+
`;}),r+=`} from '../types';
|
|
318
|
+
|
|
319
|
+
`,p.forEach(i=>{var v,b;let w=i.method.toUpperCase(),P=w==="GET",R=["POST","PUT","PATCH","DELETE"].includes(w),k=((v=i.parameters)==null?void 0:v.filter(F=>F.in==="path"))||[],x=((b=i.parameters)==null?void 0:b.filter(F=>F.in==="query"))||[],A=k.length>0,N=x.length>0,M=!!i.requestBody,D=i.responseType||"any";if(P){let F=`use${i.name.charAt(0).toUpperCase()+i.name.slice(1)}`;r+=`/**
|
|
320
|
+
`,i.summary&&(r+=` * ${i.summary}
|
|
321
|
+
`),r+=` * @method ${w}
|
|
322
|
+
`,r+=` * @path ${i.path}
|
|
323
|
+
`,i.tags&&i.tags.length>0&&(r+=` * @tags ${i.tags.join(", ")}
|
|
324
|
+
`),r+=` */
|
|
325
|
+
`,A||N?(r+=`export function ${F}(
|
|
326
|
+
`,r+=` params: {
|
|
327
|
+
`,A&&(r+=` url: {
|
|
328
|
+
`,k.forEach(O=>{let de={string:"string",number:"number",integer:"number",boolean:"boolean",array:"any[]",object:"any"}[O.type||"string"]||"any",oe=O.required?"":"?";r+=` ${O.name}${oe}: ${de};
|
|
329
|
+
`;}),r+=` };
|
|
330
|
+
`),N&&(r+=` query: ${i.queryType||"Record<string, any>"};
|
|
331
|
+
`),r+=` },
|
|
332
|
+
`,r+=` options?: Omit<UseQueryOptions<${D}>, 'queryKey' | 'queryFn'>
|
|
333
|
+
`,r+=`) {
|
|
334
|
+
`,r+=` return useQuery({
|
|
335
|
+
`,r+=` queryKey: ['${i.name}', params],
|
|
336
|
+
`,r+=` queryFn: () => apiClient.${i.name}(params),
|
|
337
|
+
`,r+=` ...options,
|
|
338
|
+
`,r+=` });
|
|
339
|
+
`):(r+=`export function ${F}(
|
|
340
|
+
`,r+=` options?: Omit<UseQueryOptions<${D}>, 'queryKey' | 'queryFn'>
|
|
341
|
+
`,r+=`) {
|
|
342
|
+
`,r+=` return useQuery({
|
|
343
|
+
`,r+=` queryKey: ['${i.name}'],
|
|
344
|
+
`,r+=` queryFn: () => apiClient.${i.name}(),
|
|
345
|
+
`,r+=` ...options,
|
|
346
|
+
`,r+=` });
|
|
347
|
+
`),r+=`}
|
|
348
|
+
|
|
349
|
+
`;}else if(R&&e){let F=`use${i.name.charAt(0).toUpperCase()+i.name.slice(1)}`;r+=`/**
|
|
350
|
+
`,i.summary&&(r+=` * ${i.summary}
|
|
351
|
+
`),r+=` * @method ${w}
|
|
352
|
+
`,r+=` * @path ${i.path}
|
|
353
|
+
`,i.tags&&i.tags.length>0&&(r+=` * @tags ${i.tags.join(", ")}
|
|
354
|
+
`),r+=` */
|
|
355
|
+
`;let O="void";(A||N||M)&&(O=`{
|
|
356
|
+
`,A&&(O+=` url: {
|
|
357
|
+
`,k.forEach(Z=>{let oe={string:"string",number:"number",integer:"number",boolean:"boolean",array:"any[]",object:"any"}[Z.type||"string"]||"any",xe=Z.required?"":"?";O+=` ${Z.name}${xe}: ${oe};
|
|
358
|
+
`;}),O+=` };
|
|
359
|
+
`),N&&(O+=` query: ${i.queryType||"Record<string, any>"};
|
|
360
|
+
`),M&&(O+=` data: ${i.dtoType||"any"};
|
|
361
|
+
`),O+=" }"),r+=`export function ${F}(
|
|
362
|
+
`,r+=` options?: Omit<UseMutationOptions<${D}, Error, ${O}>, 'mutationFn'>
|
|
363
|
+
`,r+=`) {
|
|
364
|
+
`,r+=` return useMutation({
|
|
365
|
+
`,r+=" mutationFn: (",O!=="void"&&(r+=`variables: ${O}`),r+=`) => {
|
|
366
|
+
`,r+=` return apiClient.${i.name}(${O!=="void"?"variables":""});
|
|
367
|
+
`,r+=` },
|
|
368
|
+
`,r+=` ...options,
|
|
369
|
+
`,r+=` });
|
|
370
|
+
`,r+=`}
|
|
371
|
+
|
|
372
|
+
`;}}),r},Ge=(p,u)=>{var o;let t=((o=u.swr)==null?void 0:o.mutations)!==false,e=`// Generated SWR Hooks
|
|
373
|
+
`;e+=`// This file was auto-generated. Add custom code in the marked sections.
|
|
374
|
+
|
|
375
|
+
`,e+=`/**
|
|
376
|
+
`,e+=` * SWR Hooks - Complete Usage Guide
|
|
377
|
+
`,e+=` *
|
|
378
|
+
`,e+=` * This file contains type-safe SWR hooks generated from your OpenAPI specification.
|
|
379
|
+
`,e+=` *
|
|
380
|
+
`,e+=` * ## Quick Start
|
|
381
|
+
`,e+=` *
|
|
382
|
+
`,e+=` * 1. Configure SWR globally:
|
|
383
|
+
`,e+=` *
|
|
384
|
+
`,e+=" * ```typescript\n",e+=` * // app/providers.tsx
|
|
385
|
+
`,e+=` * import { SWRConfig } from 'swr';
|
|
386
|
+
`,e+=` *
|
|
387
|
+
`,e+=` * export function Providers({ children }) {
|
|
388
|
+
`,e+=` * return (
|
|
389
|
+
`,e+=` * <SWRConfig value={{
|
|
390
|
+
`,e+=` * revalidateOnFocus: false,
|
|
391
|
+
`,e+=` * shouldRetryOnError: true,
|
|
392
|
+
`,e+=` * errorRetryCount: 3,
|
|
393
|
+
`,e+=` * }}>
|
|
394
|
+
`,e+=` * {children}
|
|
395
|
+
`,e+=` * </SWRConfig>
|
|
396
|
+
`,e+=` * );
|
|
397
|
+
`,e+=` * }
|
|
398
|
+
`,e+=" * ```\n",e+=` *
|
|
399
|
+
`,e+=` * 2. Use the hooks in your components:
|
|
400
|
+
`,e+=` *
|
|
401
|
+
`,e+=` * ### Reading Data (GET)
|
|
402
|
+
`,e+=` *
|
|
403
|
+
`,e+=" * ```typescript\n",e+=` * import { useGetItems } from './hooks';
|
|
404
|
+
`,e+=` *
|
|
405
|
+
`,e+=` * function ItemList() {
|
|
406
|
+
`,e+=` * const { data, error, isLoading, mutate } = useGetItems();
|
|
407
|
+
`,e+=` *
|
|
408
|
+
`,e+=` * if (isLoading) return <div>Loading...</div>;
|
|
409
|
+
`,e+=` * if (error) return <div>Error: {error.message}</div>;
|
|
410
|
+
`,e+=` *
|
|
411
|
+
`,e+=` * return (
|
|
412
|
+
`,e+=` * <div>
|
|
413
|
+
`,e+=` * {data?.map(item => <div key={item.id}>{item.name}</div>)}
|
|
414
|
+
`,e+=` * <button onClick={() => mutate()}>Refresh</button>
|
|
415
|
+
`,e+=` * </div>
|
|
416
|
+
`,e+=` * );
|
|
417
|
+
`,e+=` * }
|
|
418
|
+
`,e+=" * ```\n",e+=` *
|
|
419
|
+
`,e+=` * ### With Path Parameters
|
|
420
|
+
`,e+=` *
|
|
421
|
+
`,e+=" * ```typescript\n",e+=` * function ItemDetail({ id }: { id: string }) {
|
|
422
|
+
`,e+=` * const { data } = useGetItemById({ url: { id } });
|
|
423
|
+
`,e+=` * return <div>{data?.name}</div>;
|
|
424
|
+
`,e+=` * }
|
|
425
|
+
`,e+=" * ```\n",e+=` *
|
|
426
|
+
`,e+=` * ### Creating Data (POST)
|
|
427
|
+
`,e+=` *
|
|
428
|
+
`,e+=" * ```typescript\n",e+=` * import { useCreateItem, useGetItems } from './hooks';
|
|
429
|
+
`,e+=` *
|
|
430
|
+
`,e+=` * function CreateItem() {
|
|
431
|
+
`,e+=` * const { trigger, isMutating, error } = useCreateItem();
|
|
432
|
+
`,e+=` * const { mutate: revalidateList } = useGetItems();
|
|
433
|
+
`,e+=` *
|
|
434
|
+
`,e+=` * const handleSubmit = async (name: string) => {
|
|
435
|
+
`,e+=` * try {
|
|
436
|
+
`,e+=` * const result = await trigger({
|
|
437
|
+
`,e+=` * arg: { data: { name } }
|
|
438
|
+
`,e+=` * });
|
|
439
|
+
`,e+=` * await revalidateList(); // Refresh the list
|
|
440
|
+
`,e+=` * alert('Created!');
|
|
441
|
+
`,e+=` * } catch (err) {
|
|
442
|
+
`,e+=` * console.error('Failed:', err);
|
|
443
|
+
`,e+=` * }
|
|
444
|
+
`,e+=` * };
|
|
445
|
+
`,e+=` *
|
|
446
|
+
`,e+=` * return (
|
|
447
|
+
`,e+=` * <button onClick={() => handleSubmit('New Item')} disabled={isMutating}>
|
|
448
|
+
`,e+=` * {isMutating ? 'Creating...' : 'Create'}
|
|
449
|
+
`,e+=` * </button>
|
|
450
|
+
`,e+=` * );
|
|
451
|
+
`,e+=` * }
|
|
452
|
+
`,e+=" * ```\n",e+=` *
|
|
453
|
+
`,e+=` * ### Updating Data (PUT/PATCH)
|
|
454
|
+
`,e+=` *
|
|
455
|
+
`,e+=" * ```typescript\n",e+=` * function UpdateItem({ id }: { id: string }) {
|
|
456
|
+
`,e+=` * const { data, mutate: revalidate } = useGetItemById({ url: { id } });
|
|
457
|
+
`,e+=` * const { trigger } = useUpdateItem();
|
|
458
|
+
`,e+=` *
|
|
459
|
+
`,e+=` * const handleUpdate = async (newName: string) => {
|
|
460
|
+
`,e+=` * await trigger({
|
|
461
|
+
`,e+=` * arg: {
|
|
462
|
+
`,e+=` * url: { id },
|
|
463
|
+
`,e+=` * data: { name: newName }
|
|
464
|
+
`,e+=` * }
|
|
465
|
+
`,e+=` * });
|
|
466
|
+
`,e+=` * await revalidate(); // Refresh the detail view
|
|
467
|
+
`,e+=` * };
|
|
468
|
+
`,e+=` *
|
|
469
|
+
`,e+=` * return <button onClick={() => handleUpdate('Updated')}>Update</button>;
|
|
470
|
+
`,e+=` * }
|
|
471
|
+
`,e+=" * ```\n",e+=` *
|
|
472
|
+
`,e+=` * ### Deleting Data (DELETE)
|
|
473
|
+
`,e+=` *
|
|
474
|
+
`,e+=" * ```typescript\n",e+=` * function DeleteItem({ id }: { id: string }) {
|
|
475
|
+
`,e+=` * const { trigger, isMutating } = useDeleteItem();
|
|
476
|
+
`,e+=` * const { mutate: revalidateList } = useGetItems();
|
|
477
|
+
`,e+=` *
|
|
478
|
+
`,e+=` * const handleDelete = async () => {
|
|
479
|
+
`,e+=` * if (confirm('Delete?')) {
|
|
480
|
+
`,e+=` * await trigger({ arg: { url: { id } } });
|
|
481
|
+
`,e+=` * await revalidateList();
|
|
482
|
+
`,e+=` * }
|
|
483
|
+
`,e+=` * };
|
|
484
|
+
`,e+=` *
|
|
485
|
+
`,e+=` * return (
|
|
486
|
+
`,e+=` * <button onClick={handleDelete} disabled={isMutating}>
|
|
487
|
+
`,e+=` * {isMutating ? 'Deleting...' : 'Delete'}
|
|
488
|
+
`,e+=` * </button>
|
|
489
|
+
`,e+=` * );
|
|
490
|
+
`,e+=` * }
|
|
491
|
+
`,e+=" * ```\n",e+=` *
|
|
492
|
+
`,e+=` * ## Advanced Patterns
|
|
493
|
+
`,e+=` *
|
|
494
|
+
`,e+=` * ### Optimistic Updates
|
|
495
|
+
`,e+=` *
|
|
496
|
+
`,e+=" * ```typescript\n",e+=` * function OptimisticUpdate({ id }: { id: string }) {
|
|
497
|
+
`,e+=` * const { data, mutate: revalidate } = useGetItemById({ url: { id } });
|
|
498
|
+
`,e+=` * const { trigger } = useUpdateItem();
|
|
499
|
+
`,e+=` *
|
|
500
|
+
`,e+=` * const handleUpdate = async (newName: string) => {
|
|
501
|
+
`,e+=` * // Update UI immediately
|
|
502
|
+
`,e+=` * revalidate({ ...data!, name: newName }, false);
|
|
503
|
+
`,e+=` *
|
|
504
|
+
`,e+=` * try {
|
|
505
|
+
`,e+=` * await trigger({ arg: { url: { id }, data: { name: newName } } });
|
|
506
|
+
`,e+=` * await revalidate(); // Sync with server
|
|
507
|
+
`,e+=` * } catch (err) {
|
|
508
|
+
`,e+=` * await revalidate(); // Rollback on error
|
|
509
|
+
`,e+=` * }
|
|
510
|
+
`,e+=` * };
|
|
511
|
+
`,e+=` *
|
|
512
|
+
`,e+=` * return <button onClick={() => handleUpdate('New')}>Update</button>;
|
|
513
|
+
`,e+=` * }
|
|
514
|
+
`,e+=" * ```\n",e+=` *
|
|
515
|
+
`,e+=` * ### Conditional Fetching
|
|
516
|
+
`,e+=` *
|
|
517
|
+
`,e+=" * ```typescript\n",e+=` * function ConditionalFetch({ id, enabled }: { id: string; enabled: boolean }) {
|
|
518
|
+
`,e+=` * // Only fetch when enabled is true
|
|
519
|
+
`,e+=` * const { data } = useGetItemById(enabled ? { url: { id } } : null);
|
|
520
|
+
`,e+=` * return <div>{data?.name || 'Not loaded'}</div>;
|
|
521
|
+
`,e+=` * }
|
|
522
|
+
`,e+=" * ```\n",e+=` *
|
|
523
|
+
`,e+=` * ### Pagination
|
|
524
|
+
`,e+=` *
|
|
525
|
+
`,e+=" * ```typescript\n",e+=` * function PaginatedList() {
|
|
526
|
+
`,e+=` * const [page, setPage] = useState(1);
|
|
527
|
+
`,e+=` * const { data, isLoading } = useGetItems({ query: { page, limit: 10 } });
|
|
528
|
+
`,e+=` *
|
|
529
|
+
`,e+=` * return (
|
|
530
|
+
`,e+=` * <div>
|
|
531
|
+
`,e+=` * {data?.items.map(item => <div key={item.id}>{item.name}</div>)}
|
|
532
|
+
`,e+=` * <button onClick={() => setPage(p => p - 1)} disabled={page === 1}>
|
|
533
|
+
`,e+=` * Previous
|
|
534
|
+
`,e+=` * </button>
|
|
535
|
+
`,e+=` * <button onClick={() => setPage(p => p + 1)}>Next</button>
|
|
536
|
+
`,e+=` * </div>
|
|
537
|
+
`,e+=` * );
|
|
538
|
+
`,e+=` * }
|
|
539
|
+
`,e+=" * ```\n",e+=` *
|
|
540
|
+
`,e+=` * ### Custom Configuration
|
|
541
|
+
`,e+=` *
|
|
542
|
+
`,e+=" * ```typescript\n",e+=` * function CustomConfig({ id }: { id: string }) {
|
|
543
|
+
`,e+=` * const { data } = useGetItemById(
|
|
544
|
+
`,e+=` * { url: { id } },
|
|
545
|
+
`,e+=` * {
|
|
546
|
+
`,e+=` * refreshInterval: 5000, // Refresh every 5s
|
|
547
|
+
`,e+=` * revalidateOnFocus: true, // Refresh on window focus
|
|
548
|
+
`,e+=` * dedupingInterval: 2000, // Dedupe within 2s
|
|
549
|
+
`,e+=` * onError: (err) => console.error(err),
|
|
550
|
+
`,e+=` * onSuccess: (data) => console.log('Loaded:', data),
|
|
551
|
+
`,e+=` * }
|
|
552
|
+
`,e+=` * );
|
|
553
|
+
`,e+=` * return <div>{data?.name}</div>;
|
|
554
|
+
`,e+=` * }
|
|
555
|
+
`,e+=" * ```\n",e+=` *
|
|
556
|
+
`,e+=` * ## Hook Return Values
|
|
557
|
+
`,e+=` *
|
|
558
|
+
`,e+=` * ### Query Hooks (GET)
|
|
559
|
+
`,e+=" * - `data`: The response data (undefined while loading)\n",e+=" * - `error`: Error object if request failed\n",e+=" * - `isLoading`: True during initial load\n",e+=" * - `isValidating`: True during revalidation\n",e+=" * - `mutate()`: Manually trigger revalidation\n",e+=` *
|
|
560
|
+
`,e+=` * ### Mutation Hooks (POST/PUT/DELETE)
|
|
561
|
+
`,e+=" * - `trigger()`: Execute the mutation\n",e+=" * - `data`: The response data from the mutation\n",e+=" * - `error`: Error object if mutation failed\n",e+=" * - `isMutating`: True while mutation is in progress\n",e+=" * - `reset()`: Reset the mutation state\n",e+=` *
|
|
562
|
+
`,e+=` * @see https://swr.vercel.app/docs/getting-started
|
|
563
|
+
`,e+=` * @see https://swr.vercel.app/docs/mutation
|
|
564
|
+
`,e+=` */
|
|
565
|
+
|
|
566
|
+
`,e+=`import useSWR, { SWRConfiguration } from 'swr';
|
|
567
|
+
`,t&&p.some(s=>["POST","PUT","PATCH","DELETE"].includes(s.method.toUpperCase()))&&(e+=`import useSWRMutation, { SWRMutationConfiguration } from 'swr/mutation';
|
|
568
|
+
`),e+=`
|
|
569
|
+
`,e+=`import apiClient from './client';
|
|
570
|
+
`,e+=`import type {
|
|
571
|
+
`;let n=new Set;return p.forEach(s=>{s.queryType&&n.add(s.queryType),s.dtoType&&n.add(s.dtoType),s.responseType&&n.add(s.responseType);}),n.forEach(s=>{e+=` ${s},
|
|
572
|
+
`;}),e+=`} from '../types';
|
|
573
|
+
|
|
574
|
+
`,p.forEach(s=>{var M,D;let y=s.method.toUpperCase(),i=y==="GET",w=["POST","PUT","PATCH","DELETE"].includes(y),P=((M=s.parameters)==null?void 0:M.filter(v=>v.in==="path"))||[],R=((D=s.parameters)==null?void 0:D.filter(v=>v.in==="query"))||[],k=P.length>0,x=R.length>0,A=!!s.requestBody,N=s.responseType||"any";if(i){let v=`use${s.name.charAt(0).toUpperCase()+s.name.slice(1)}`;e+=`/**
|
|
575
|
+
`,s.summary&&(e+=` * ${s.summary}
|
|
576
|
+
`),e+=` * @method ${y}
|
|
577
|
+
`,e+=` * @path ${s.path}
|
|
578
|
+
`,s.tags&&s.tags.length>0&&(e+=` * @tags ${s.tags.join(", ")}
|
|
579
|
+
`),e+=` */
|
|
580
|
+
`,k||x?(e+=`export function ${v}(
|
|
581
|
+
`,e+=` params: {
|
|
582
|
+
`,k&&(e+=` url: {
|
|
583
|
+
`,P.forEach(b=>{let O={string:"string",number:"number",integer:"number",boolean:"boolean",array:"any[]",object:"any"}[b.type||"string"]||"any",Z=b.required?"":"?";e+=` ${b.name}${Z}: ${O};
|
|
584
|
+
`;}),e+=` };
|
|
585
|
+
`),x&&(e+=` query: ${s.queryType||"Record<string, any>"};
|
|
586
|
+
`),e+=` },
|
|
587
|
+
`,e+=` config?: SWRConfiguration<${N}>
|
|
588
|
+
`,e+=`) {
|
|
589
|
+
`,e+=` return useSWR(
|
|
590
|
+
`,e+=` ['${s.name}', params],
|
|
591
|
+
`,e+=` () => apiClient.${s.name}(params),
|
|
592
|
+
`,e+=` config
|
|
593
|
+
`,e+=` );
|
|
594
|
+
`):(e+=`export function ${v}(
|
|
595
|
+
`,e+=` config?: SWRConfiguration<${N}>
|
|
596
|
+
`,e+=`) {
|
|
597
|
+
`,e+=` return useSWR(
|
|
598
|
+
`,e+=` '${s.name}',
|
|
599
|
+
`,e+=` () => apiClient.${s.name}(),
|
|
600
|
+
`,e+=` config
|
|
601
|
+
`,e+=` );
|
|
602
|
+
`),e+=`}
|
|
603
|
+
|
|
604
|
+
`;}else if(w&&t){let v=`use${s.name.charAt(0).toUpperCase()+s.name.slice(1)}`;e+=`/**
|
|
605
|
+
`,s.summary&&(e+=` * ${s.summary}
|
|
606
|
+
`),e+=` * @method ${y}
|
|
607
|
+
`,e+=` * @path ${s.path}
|
|
608
|
+
`,s.tags&&s.tags.length>0&&(e+=` * @tags ${s.tags.join(", ")}
|
|
609
|
+
`),e+=` */
|
|
610
|
+
`;let b="void",F="void";(k||x||A)&&(b=`{
|
|
611
|
+
`,k&&(b+=` url: {
|
|
612
|
+
`,P.forEach(O=>{let de={string:"string",number:"number",integer:"number",boolean:"boolean",array:"any[]",object:"any"}[O.type||"string"]||"any",oe=O.required?"":"?";b+=` ${O.name}${oe}: ${de};
|
|
613
|
+
`;}),b+=` };
|
|
614
|
+
`),x&&(b+=` query: ${s.queryType||"Record<string, any>"};
|
|
615
|
+
`),A&&(b+=` data: ${s.dtoType||"any"};
|
|
616
|
+
`),b+=" }",F=`{ arg: ${b} }`),e+=`export function ${v}(
|
|
617
|
+
`,e+=` config?: SWRMutationConfiguration<${N}, Error, string, ${b}>
|
|
618
|
+
`,e+=`) {
|
|
619
|
+
`,e+=` return useSWRMutation(
|
|
620
|
+
`,e+=` '${s.name}',
|
|
621
|
+
`,e+=" async (_, ",b!=="void"&&(e+=`{ arg }: ${F}`),e+=`) => {
|
|
622
|
+
`,e+=` return apiClient.${s.name}(${b!=="void"?"arg":""});
|
|
623
|
+
`,e+=` },
|
|
624
|
+
`,e+=` config
|
|
625
|
+
`,e+=` );
|
|
626
|
+
`,e+=`}
|
|
627
|
+
|
|
628
|
+
`;}}),e},Le=(p,u)=>{var o;let t=((o=u.rtkQuery)==null?void 0:o.apiName)||"api",e=u.baseURL||"",r=`// Generated RTK Query API Slice
|
|
629
|
+
`;r+=`// This file was auto-generated. Add custom code in the marked sections.
|
|
630
|
+
|
|
631
|
+
`,r+=`import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';
|
|
632
|
+
|
|
633
|
+
`,r+=`import type {
|
|
634
|
+
`;let n=new Set;return p.forEach(s=>{s.queryType&&n.add(s.queryType),s.dtoType&&n.add(s.dtoType),s.responseType&&n.add(s.responseType);}),n.forEach(s=>{r+=` ${s},
|
|
635
|
+
`;}),r+=`} from '../types';
|
|
636
|
+
|
|
637
|
+
`,r+=`import {
|
|
638
|
+
`,p.forEach(s=>{r+=` ${s.name},
|
|
639
|
+
`;}),r+=`} from '../endpoints';
|
|
640
|
+
|
|
641
|
+
`,r+=`const ${t}Api = createApi({
|
|
642
|
+
`,r+=` reducerPath: '${t}Api',
|
|
643
|
+
`,r+=` baseQuery: fetchBaseQuery({
|
|
644
|
+
`,r+=` baseUrl: '${e}',
|
|
645
|
+
`,u.auth&&(r+=` prepareHeaders: (headers, { getState }) => {
|
|
646
|
+
`,r+=` // Get token from your auth state
|
|
647
|
+
`,r+=` // const token = (getState() as RootState).auth.token;
|
|
648
|
+
`,r+=` // if (token) {
|
|
649
|
+
`,u.auth.type==="bearer"?r+=" // headers.set('Authorization', `Bearer ${token}`);\n":u.auth.type==="apiKey"&&u.auth.in==="header"&&(r+=` // headers.set('${u.auth.name||"X-API-Key"}', token);
|
|
650
|
+
`),r+=` // }
|
|
651
|
+
`,r+=` return headers;
|
|
652
|
+
`,r+=` },
|
|
653
|
+
`),r+=` }),
|
|
654
|
+
`,r+=` tagTypes: [${[...new Set(p.flatMap(s=>s.tags||[]))].map(s=>`'${s}'`).join(", ")}],
|
|
655
|
+
`,r+=` endpoints: (builder) => ({
|
|
656
|
+
`,p.forEach((s,y)=>{var D,v;let i=s.method.toUpperCase(),w=i==="GET",P=((D=s.parameters)==null?void 0:D.filter(b=>b.in==="path"))||[],R=((v=s.parameters)==null?void 0:v.filter(b=>b.in==="query"))||[],k=P.length>0,x=R.length>0,A=!!s.requestBody,N=s.responseType||"any";r+=` ${s.name}: builder.${w?"query":"mutation"}<
|
|
657
|
+
`,r+=` ${N},
|
|
658
|
+
`;let M="void";if((k||x||A)&&(M=`{
|
|
659
|
+
`,k&&(M+=` url: {
|
|
660
|
+
`,P.forEach(b=>{let O={string:"string",number:"number",integer:"number",boolean:"boolean",array:"any[]",object:"any"}[b.type||"string"]||"any",Z=b.required?"":"?";M+=` ${b.name}${Z}: ${O};
|
|
661
|
+
`;}),M+=` };
|
|
662
|
+
`),x&&(M+=` query: ${s.queryType||"Record<string, any>"};
|
|
663
|
+
`),A&&(M+=` data: ${s.dtoType||"any"};
|
|
664
|
+
`),M+=" }"),r+=` ${M}
|
|
665
|
+
`,r+=` >({
|
|
666
|
+
`,r+=" query: (",M!=="void"&&(r+="arg"),r+=`) => {
|
|
667
|
+
`,k){let b=P.map(F=>`arg.url.${F.name}`).join(", ");r+=` const url = ${s.name}(${b});
|
|
668
|
+
`;}else r+=` const url = ${s.name};
|
|
669
|
+
`;r+=` return {
|
|
670
|
+
`,r+=` url,
|
|
671
|
+
`,r+=` method: '${i}',
|
|
672
|
+
`,x&&(r+=` params: arg.query,
|
|
673
|
+
`),A&&(r+=` body: arg.data,
|
|
674
|
+
`),r+=` };
|
|
675
|
+
`,r+=` },
|
|
676
|
+
`,s.tags&&s.tags.length>0&&(w?r+=` providesTags: ['${s.tags[0]}'],
|
|
677
|
+
`:r+=` invalidatesTags: ['${s.tags[0]}'],
|
|
678
|
+
`),r+=` })${y<p.length-1?",":""}
|
|
679
|
+
`;}),r+=` }),
|
|
680
|
+
`,r+=`});
|
|
681
|
+
|
|
682
|
+
`,r+=`export default ${t}Api;
|
|
683
|
+
|
|
684
|
+
`,r};var gn=(p,u)=>{var t,e;if((t=u==null?void 0:u.folderSplit)!=null&&t.customFolder){let r=u.folderSplit.customFolder({method:p.method,path:p.path,tags:p.tags,operationId:p.operationId,summary:p.summary});if(r)return r}return (e=u==null?void 0:u.folderSplit)!=null&&e.byTags&&p.tags&&p.tags.length>0?p.tags[0].toLowerCase().replace(/\s+/g,"-"):"default"},rn=(p,u,t,e,r)=>d(null,null,function*(){let n=nn(p,t);if(n.length===0)return;let o=t.type||"fetch";t.outputDir||J.join(r,e,"client");let y=!!(u!=null&&u.folderSplit&&(u.folderSplit.byTags||u.folderSplit.customFolder));if(`${o}${n.length}`,y){let w={};n.forEach(k=>{let x=gn(k,u);w[x]||(w[x]=[]),w[x].push(k);});let P=Object.keys(w);for(let[k,x]of Object.entries(w)){let A=J.join(r,e,k);yield re.promises.mkdir(A,{recursive:true}),`${o}${k}${x.length}`,yield Cn(x,u,t,A,o,k,true);}let R=J.join(r,e);yield bn(R,P,o,u);return}let i=J.join(r,e);switch(yield re.promises.mkdir(i,{recursive:true}),o){case "fetch":let w=Ue(n,t);w=w.replace("} from '../types';","} from './types';").replace("} from '../endpoints';","} from './endpoints';"),yield K(J.join(i,"clients.ts"),w,u);break;case "axios":let P=me(n,t,false);P=P.replace("} from '../types';","} from './types';").replace("} from '../endpoints';","} from './endpoints';"),yield K(J.join(i,"clients.ts"),P,u);break;case "react-query":let R=me(n,t,false);R=R.replace("} from '../types';","} from './types';").replace("} from '../endpoints';","} from './endpoints';"),yield K(J.join(i,"clients.ts"),R,u);let k=Me(n,t);k=k.replace("} from '../types';","} from './types';").replace("} from '../endpoints';","} from './endpoints';").replace("import apiClient from './client';","import apiClient from './clients';"),yield K(J.join(i,"hooks.ts"),k,u);break;case "swr":let x=me(n,t,false);x=x.replace("} from '../types';","} from './types';").replace("} from '../endpoints';","} from './endpoints';"),yield K(J.join(i,"clients.ts"),x,u);let A=Ge(n,t);A=A.replace("} from '../types';","} from './types';").replace("} from '../endpoints';","} from './endpoints';").replace("import apiClient from './client';","import apiClient from './clients';"),yield K(J.join(i,"hooks.ts"),A,u);break;case "rtk-query":let N=Le(n,t);N=N.replace("} from '../types';","} from './types';").replace("} from '../endpoints';","} from './endpoints';"),yield K(J.join(i,"api.ts"),N,u);break;default:throw new Error(`Unknown client type: ${o}`)}}),K=(p,u,t)=>d(null,null,function*(){var o,s,y,i;if(!(((o=t==null?void 0:t.customCode)==null?void 0:o.enabled)!==false)){yield re.promises.writeFile(p,u);return}let r=null;try{r=yield re.promises.readFile(p,"utf-8");}catch(w){}let n=we(u,r,{position:((s=t==null?void 0:t.customCode)==null?void 0:s.position)||"bottom",markerText:(y=t==null?void 0:t.customCode)==null?void 0:y.markerText,includeInstructions:(i=t==null?void 0:t.customCode)==null?void 0:i.includeInstructions});yield re.promises.writeFile(p,n);});var Cn=(p,u,t,e,r,n,o=false)=>d(null,null,function*(){let s="",y="",i=o?"./types":"../types",w=o?"./endpoints":"../endpoints";switch(r){case "fetch":s=Ue(p,t,o),s=s.replace("} from '../types';",`} from '${i}';`).replace("} from '../endpoints';",`} from '${w}';`),yield K(J.join(e,"client.ts"),s,u);break;case "axios":s=me(p,t,o),s=s.replace("} from '../types';",`} from '${i}';`).replace("} from '../endpoints';",`} from '${w}';`),yield K(J.join(e,"client.ts"),s,u);break;case "react-query":if(s=me(p,t,o),s=s.replace("} from '../types';",`} from '${i}';`).replace("} from '../endpoints';",`} from '${w}';`),yield K(J.join(e,"client.ts"),s,u),y=Me(p,t),y=y.replace("} from '../types';",`} from '${i}';`).replace("} from '../endpoints';",`} from '${w}';`),o){let R=n.replace(/-/g,"_");y=y.replace("import apiClient from './client';",`import { ${R}Client as apiClient } from '../clients';`);}yield K(J.join(e,"hooks.ts"),y,u);break;case "swr":if(s=me(p,t,o),s=s.replace("} from '../types';",`} from '${i}';`).replace("} from '../endpoints';",`} from '${w}';`),yield K(J.join(e,"client.ts"),s,u),y=Ge(p,t),y=y.replace("} from '../types';",`} from '${i}';`).replace("} from '../endpoints';",`} from '${w}';`),o){let R=n.replace(/-/g,"_");y=y.replace("import apiClient from './client';",`import { ${R}Client as apiClient } from '../clients';`);}yield K(J.join(e,"hooks.ts"),y,u);break;case "rtk-query":let P=o?b(a({},t),{rtkQuery:b(a({},t.rtkQuery),{apiName:n.replace(/-/g,"_")})}):t;y=Le(p,P),y=y.replace("} from '../types';",`} from '${i}';`).replace("} from '../endpoints';",`} from '${w}';`),yield K(J.join(e,"api.ts"),y,u);break;default:throw new Error(`Unknown client type: ${r}`)}}),bn=(p,u,t,e)=>d(null,null,function*(){var n;if(t==="rtk-query"){let o=`// Generated RTK Query APIs
|
|
685
|
+
`;o+=`// This file was auto-generated.
|
|
686
|
+
`,o+=`// Aggregates all API slices for easy Redux store setup
|
|
687
|
+
|
|
688
|
+
`,u.forEach(s=>{let y=s.replace(/-/g,"_");o+=`import ${y}Api from './${s}/api';
|
|
689
|
+
`;}),o+=`
|
|
690
|
+
// Export all API slices
|
|
691
|
+
`,u.forEach(s=>{let y=s.replace(/-/g,"_");o+=`export { default as ${y}Api } from './${s}/api';
|
|
692
|
+
`;}),o+=`
|
|
693
|
+
/**
|
|
694
|
+
`,o+=` * Configure Redux store with all API slices
|
|
695
|
+
`,o+=` *
|
|
696
|
+
`,o+=` * @example
|
|
697
|
+
`,o+=` * import { configureStore } from '@reduxjs/toolkit';
|
|
698
|
+
`,o+=` * import { setupApiStore } from './apis';
|
|
699
|
+
`,o+=` *
|
|
700
|
+
`,o+=` * export const store = configureStore({
|
|
701
|
+
`,o+=` * reducer: setupApiStore.reducer,
|
|
702
|
+
`,o+=` * middleware: (getDefaultMiddleware) =>
|
|
703
|
+
`,o+=` * getDefaultMiddleware().concat(setupApiStore.middleware),
|
|
704
|
+
`,o+=` * });
|
|
705
|
+
`,o+=` */
|
|
706
|
+
`,o+=`export const setupApiStore = {
|
|
707
|
+
`,o+=` reducer: {
|
|
708
|
+
`,u.forEach(s=>{let y=s.replace(/-/g,"_");o+=` [${y}Api.reducerPath]: ${y}Api.reducer,
|
|
709
|
+
`;}),o+=` },
|
|
710
|
+
`,o+=` middleware: [
|
|
711
|
+
`,u.forEach(s=>{let y=s.replace(/-/g,"_");o+=` ${y}Api.middleware,
|
|
712
|
+
`;}),o+=` ],
|
|
713
|
+
`,o+=`};
|
|
714
|
+
`,yield K(J.join(p,"apis.ts"),o,e);return}let r=`// Generated API Clients
|
|
715
|
+
`;if(r+=`// This file was auto-generated.
|
|
716
|
+
`,r+=`// Centralized client instances and configuration
|
|
717
|
+
|
|
718
|
+
`,t==="fetch"?u.forEach(o=>{let s=o.replace(/-/g,"_");r+=`export { default as ${s}Client } from './${o}/client';
|
|
719
|
+
`;}):(u.forEach(o=>{let s=o.replace(/-/g,"_"),y=`${s.charAt(0).toUpperCase()+s.slice(1)}ApiClient`;r+=`import ${y} from './${o}/client';
|
|
720
|
+
`;}),r+=`
|
|
721
|
+
// Create client instances
|
|
722
|
+
`,u.forEach(o=>{let s=o.replace(/-/g,"_"),y=`${s.charAt(0).toUpperCase()+s.slice(1)}ApiClient`;r+=`export const ${s}Client = new ${y}();
|
|
723
|
+
`;})),t==="fetch"&&(r+=`
|
|
724
|
+
// Import clients for aggregation
|
|
725
|
+
`,u.forEach(o=>{let s=o.replace(/-/g,"_");r+=`import ${s}_client from './${o}/client';
|
|
726
|
+
`;})),r+=`
|
|
727
|
+
// Aggregate all client instances
|
|
728
|
+
`,r+=`export const clients = {
|
|
729
|
+
`,u.forEach(o=>{let s=o.replace(/-/g,"_");t==="fetch"?r+=` ${s}: ${s}_client,
|
|
730
|
+
`:r+=` ${s}: ${s}Client,
|
|
731
|
+
`;}),r+=`};
|
|
76
732
|
|
|
77
|
-
|
|
733
|
+
`,t==="axios"?(r+=`
|
|
734
|
+
/**
|
|
735
|
+
`,r+=` * Configure all API clients at once
|
|
736
|
+
`,r+=` * @param config - Configuration to apply to all clients
|
|
737
|
+
`,r+=` */
|
|
738
|
+
`,r+=`export const configureAllClients = (config: {
|
|
739
|
+
`,r+=` baseURL?: string;
|
|
740
|
+
`,r+=` headers?: Record<string, string>;
|
|
741
|
+
`,r+=` timeout?: number;
|
|
742
|
+
`,r+=`}) => {
|
|
743
|
+
`,u.forEach(o=>{let s=o.replace(/-/g,"_");r+=` ${s}Client.updateConfig(config);
|
|
744
|
+
`;}),r+=`};
|
|
78
745
|
|
|
79
|
-
|
|
80
|
-
|
|
746
|
+
`):t==="fetch"&&(r+=`
|
|
747
|
+
/**
|
|
748
|
+
`,r+=` * Configure all API clients at once
|
|
749
|
+
`,r+=` * @param config - Configuration to apply to all clients
|
|
750
|
+
`,r+=` */
|
|
751
|
+
`,r+=`export const configureAllClients = (config: {
|
|
752
|
+
`,r+=` baseURL?: string;
|
|
753
|
+
`,r+=` headers?: Record<string, string>;
|
|
754
|
+
`,r+=` auth?: { token?: string };
|
|
755
|
+
`,r+=`}) => {
|
|
756
|
+
`,u.forEach(o=>{let s=o.replace(/-/g,"_");r+=` ${s}_client.setApiConfig(config);
|
|
757
|
+
`;}),r+=`};
|
|
81
758
|
|
|
82
|
-
|
|
759
|
+
`),r+=`// Example usage:
|
|
760
|
+
`,r+=`// import { configureAllClients, clients } from './clients';
|
|
761
|
+
`,r+=`//
|
|
762
|
+
`,r+=`// // Configure all clients at once
|
|
763
|
+
`,r+=`// configureAllClients({
|
|
764
|
+
`,r+=`// baseURL: 'https://api.example.com',
|
|
765
|
+
`,r+=`// timeout: 10000,
|
|
766
|
+
`,r+=`// });
|
|
767
|
+
`,r+=`//
|
|
768
|
+
`,r+=`// // Use specific client
|
|
769
|
+
`,r+=`// const data = await clients.${(n=u[0])==null?void 0:n.replace(/-/g,"_")}.someMethod(...);
|
|
770
|
+
`,yield K(J.join(p,"clients.ts"),r,e),t==="react-query"||t==="swr"){let o=`// Generated Hooks Aggregator
|
|
771
|
+
`;o+=`// This file was auto-generated.
|
|
772
|
+
`,o+=`// Aggregates all folder-split hooks
|
|
83
773
|
|
|
84
|
-
|
|
774
|
+
`,u.forEach(s=>{o+=`export * from './${s}/hooks';
|
|
775
|
+
`;}),o+=`
|
|
776
|
+
// Example usage:
|
|
777
|
+
`,o+=`// import { useGetSomething } from './hooks';
|
|
778
|
+
`,yield K(J.join(p,"hooks.ts"),o,e);}});var ve=process.cwd(),sn=()=>{let p;try{c("esbuild-register");}catch(o){throw o}let u=J.join(ve,"openapi.sync.js"),t=J.join(ve,"openapi.sync.ts"),e=J.join(ve,"openapi.sync.json"),r=[u,t,e];try{for(let o of r)re.existsSync(o)&&(p=c(o),Object.keys(p).length===1&&p.default&&(p=p.default));}catch(o){}typeof p=="function"&&(p=p());let n=p;if(!n)throw new Error("No config found");return n},lr=p=>d(null,null,function*(){let u=sn(),t=Object.keys(u.api),e=p&&"refetchInterval"in p&&!isNaN(p==null?void 0:p.refetchInterval)?p.refetchInterval:u.refetchInterval;Oe();for(let r=0;r<t.length;r+=1){let n=t[r],o=u.api[n];yield Se(o,n,u,e);}}),ur=p=>d(null,null,function*(){let u=sn(),t=p.apiName?[p.apiName]:Object.keys(u.api);for(let r of t)if(!u.api[r])throw new Error(`API "${r}" not found in configuration. Available APIs: ${Object.keys(u.api).join(", ")}`);Oe();for(let r of t){let n=u.api[r];yield Se(n,r,u);}let e=(u==null?void 0:u.folder)||"api";for(let r of t){let n=Zt(r);if(n.length===0){continue}`${n.length}${r}`;let o=a(a(a(a(b(a({enabled:true},u.clientGeneration||{}),{type:p.type}),p.outputDir&&{outputDir:p.outputDir}),p.baseURL&&{baseURL:p.baseURL}),p.tags&&{tags:p.tags}),p.endpoints&&{endpoints:p.endpoints});yield rn(n,u,o,r,J.join(ve,e));}}),pr=()=>d(null,null,function*(){let{interactiveInit:p}=yield import('./interactive-init-4LMPMPGI.mjs');yield p();});export{ur as GenerateClient,lr as Init,pr as InteractiveInit,ge as JSONStringify,ae as capitalize,Dt as createCustomCodeMarker,mn as extractCustomCode,Ht as getEndpointDetails,wn as getNestedValue,Jt as isJson,pn as isYamlString,we as mergeCustomCode,Ee as renderTypeRefMD,xn as variableName,zt as variableNameChar,Wt as yamlStringToJson};
|