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.js
CHANGED
|
@@ -1,84 +1,789 @@
|
|
|
1
|
-
'use strict';var
|
|
2
|
-
`+" ".repeat(
|
|
3
|
-
`).filter(
|
|
4
|
-
${" ".repeat(
|
|
5
|
-
${" ".repeat(
|
|
1
|
+
'use strict';var Te=require('js-yaml'),D=require('path'),oe=require('fs'),Ln=require('lodash.isequal'),De=require('lodash.get'),Bn=require('axios'),Qn=require('axios-retry'),zn=require('@apidevtools/swagger-parser'),curlGenerator=require('curl-generator'),Tn=require('prompts');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var Te__namespace=/*#__PURE__*/_interopNamespace(Te);var D__default=/*#__PURE__*/_interopDefault(D);var oe__default=/*#__PURE__*/_interopDefault(oe);var Ln__default=/*#__PURE__*/_interopDefault(Ln);var De__default=/*#__PURE__*/_interopDefault(De);var Bn__default=/*#__PURE__*/_interopDefault(Bn);var Qn__default=/*#__PURE__*/_interopDefault(Qn);var zn__default=/*#__PURE__*/_interopDefault(zn);var Tn__default=/*#__PURE__*/_interopDefault(Tn);var sn=Object.defineProperty,Rn=Object.defineProperties;var qn=Object.getOwnPropertyDescriptors;var nn=Object.getOwnPropertySymbols;var Un=Object.prototype.hasOwnProperty,Gn=Object.prototype.propertyIsEnumerable;var rn=(s,o,t)=>o in s?sn(s,o,{enumerable:true,configurable:true,writable:true,value:t}):s[o]=t,re=(s,o)=>{for(var t in o||(o={}))Un.call(o,t)&&rn(s,t,o[t]);if(nn)for(var t of nn(o))Gn.call(o,t)&&rn(s,t,o[t]);return s},Ie=(s,o)=>Rn(s,qn(o));var xe=(s=>typeof require!="undefined"?require:typeof Proxy!="undefined"?new Proxy(s,{get:(o,t)=>(typeof require!="undefined"?require:o)[t]}):s)(function(s){if(typeof require!="undefined")return require.apply(this,arguments);throw Error('Dynamic require of "'+s+'" is not supported')});var se=(s,o)=>()=>(s&&(o=s(s=0)),o);var an=(s,o)=>{for(var t in o)sn(s,t,{get:o[t],enumerable:true});};var X=(s,o,t)=>new Promise((e,r)=>{var n=c=>{try{a(t.next(c));}catch(p){r(p);}},i=c=>{try{a(t.throw(c));}catch(p){r(p);}},a=c=>c.done?e(c.value):Promise.resolve(c.value).then(n,i);a((t=t.apply(s,o)).next());});exports.variableName=void 0;exports.variableNameChar=void 0;var Ue=se(()=>{exports.variableName=/^[A-Za-z_$][A-Za-z0-9_$]*$/,exports.variableNameChar=/[A-Za-z0-9_$]/;});function Mn(s,o){return o.split(".").reduce((e,r)=>e&&e[r]!==void 0?e[r]:void 0,s)}exports.isJson=void 0;exports.isYamlString=void 0;exports.yamlStringToJson=void 0;exports.capitalize=void 0;exports.getEndpointDetails=void 0;exports.JSONStringify=void 0;exports.renderTypeRefMD=void 0;exports.extractCustomCode=void 0;exports.createCustomCodeMarker=void 0;exports.mergeCustomCode=void 0;var je=se(()=>{Ue();exports.isJson=s=>["object"].includes(typeof s)&&!(s instanceof Blob),exports.isYamlString=s=>{try{return Te__namespace.load(s),!0}catch(o){let t=o;if(t instanceof Te__namespace.YAMLException)return false;throw t}},exports.yamlStringToJson=s=>{if(exports.isYamlString(s)){let o=Te__namespace.load(s),t=JSON.stringify(o,null,2);return JSON.parse(t)}},exports.capitalize=s=>s.substring(0,1).toUpperCase()+s.substring(1),exports.getEndpointDetails=(s,o)=>{let t=s.split("/"),e=`${exports.capitalize(o)}`,r=[];return t.forEach(n=>{if(n[0]==="{"&&n[n.length-1]==="}"){let a=n.replace(/{/,"").replace(/}/,"");r.push(a),n=`$${a}`;}else if(n[0]==="<"&&n[n.length-1]===">"){let a=n.replace(/</,"").replace(/>/,"");r.push(a),n=`$${a}`;}else if(n[0]===":"){let a=n.replace(/:/,"");r.push(a),n=`$${a}`;}let i="";n.split("").forEach(a=>{let c=a;exports.variableNameChar.test(a)||(c="/"),i+=c;}),i.split("/").forEach(a=>{e+=exports.capitalize(a);});}),{name:e,variables:r,pathParts:t}},exports.JSONStringify=(s,o=1)=>{let t="{",e=Object.keys(s);for(let r=0;r<e.length;r++){let n=e[r],i=s[n];if(t+=`
|
|
2
|
+
`+" ".repeat(o)+n+": ",Array.isArray(i)){t+="[";for(let a=0;a<i.length;a++){let c=i[a];typeof c=="object"&&c!==null?t+=exports.JSONStringify(c,o+1):t+=typeof c=="string"?`"${c}"`:c,a<i.length-1&&(t+=", ");}t+="]";}else typeof i=="object"&&i!==null?t+=""+exports.JSONStringify(i,o+1):t+=i.split(`
|
|
3
|
+
`).filter(a=>a.trim()!=="").join(`
|
|
4
|
+
${" ".repeat(o)}`);r<e.length-1&&(t+=", ");}return t+=`
|
|
5
|
+
${" ".repeat(o-1)}}`,t},exports.renderTypeRefMD=(s,o=1)=>`
|
|
6
6
|
\`\`\`typescript
|
|
7
|
-
${" ".repeat(
|
|
8
|
-
`).filter(
|
|
9
|
-
${" ".repeat(
|
|
10
|
-
\`\`\``;
|
|
11
|
-
`,
|
|
12
|
-
`).filter(
|
|
7
|
+
${" ".repeat(o)} ${s.split(`
|
|
8
|
+
`).filter(t=>t.trim()!=="").join(`
|
|
9
|
+
${" ".repeat(o)} `)}
|
|
10
|
+
\`\`\``;exports.extractCustomCode=(s,o="CUSTOM CODE")=>{let t=`// \u{1F512} ${o} START`,e=`// \u{1F512} ${o} END`,r={beforeGenerated:"",afterGenerated:""},n=0,i=[];for(;n<s.length;){let a=s.indexOf(t,n);if(a===-1)break;let c=s.indexOf(e,a);if(c===-1)break;let p=c+e.length,E=s.substring(p,p+100),j=E.match(/^\s*\n\s*(\/\/ =+)/);if(j){let N=E.indexOf(`
|
|
11
|
+
`,j.index+1);N!==-1?p+=N+1:p+=j[0].length;}let R=a,x=s.substring(Math.max(0,a-200),a).lastIndexOf("// ==========");x!==-1&&(R=Math.max(0,a-200)+x);let v=s.substring(R,p);i.push({start:R,end:p,content:v}),n=p;}return i.length>0&&(s.substring(0,i[0].start).split(`
|
|
12
|
+
`).filter(p=>{let E=p.trim();return E.length>0&&!E.startsWith("//")}).join("").length===0?(r.beforeGenerated=i[0].content,i.length>1&&(r.afterGenerated=i[1].content)):(r.afterGenerated=i[0].content,i.length>1&&!r.beforeGenerated&&(r.beforeGenerated=i[1].content))),r},exports.createCustomCodeMarker=(s,o="CUSTOM CODE",t=true)=>{let e=t?`// ${s==="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} ${o} START
|
|
16
|
+
${e}// ${"=".repeat(60)}
|
|
17
|
+
|
|
18
|
+
// \u{1F512} ${o} END
|
|
19
|
+
// ${"=".repeat(60)}`},exports.mergeCustomCode=(s,o,t={})=>{let{position:e="bottom",markerText:r="CUSTOM CODE",includeInstructions:n=true}=t,i={beforeGenerated:"",afterGenerated:""};o&&(i=exports.extractCustomCode(o,r)),!i.beforeGenerated&&!i.afterGenerated&&((e==="top"||e==="both")&&(i.beforeGenerated=exports.createCustomCodeMarker("top",r,n)),(e==="bottom"||e==="both")&&(i.afterGenerated=exports.createCustomCodeMarker("bottom",r,n)));let a=[];return i.beforeGenerated&&(a.push(i.beforeGenerated),a.push("")),a.push(s),i.afterGenerated&&(a.push(""),a.push(i.afterGenerated)),a.join(`
|
|
20
|
+
`)};});var Pe,Be,ve,pn,un,mn,Qe,ze=se(()=>{Pe=D__default.default.join(__dirname,"../","../db.json");oe__default.default.existsSync(Pe)||oe__default.default.writeFileSync(Pe,"{}");Be={};try{Be=xe(Pe);}catch(s){Be={};}ve=Be||{},pn=s=>{oe__default.default.writeFileSync(Pe,JSON.stringify(s));},un=(s,o)=>{ve[s]=o,pn(ve);},mn=s=>ve[s],Qe=()=>{ve={},pn(ve);};});var dn,cn,yn,We=se(()=>{dn={},cn=(s,o)=>{dn[s]=o;},yn=s=>dn[s]||[];});var me,Je,fn,de,gn,Ke,hn=se(()=>{je();ze();We();me=process.cwd(),Je={},fn=Bn__default.default.create({timeout:6e4});Qn__default.default(fn,{retries:20,retryCondition:s=>s.code==="ECONNABORTED"||s.message.includes("Network Error"),retryDelay:s=>s*1e3});de=(s,o,t)=>X(null,null,function*(){var i,a,c,p;if(!(((i=t==null?void 0:t.customCode)==null?void 0:i.enabled)!==false)){yield oe__default.default.promises.writeFile(s,o);return}let r=null;try{r=yield oe__default.default.promises.readFile(s,"utf-8");}catch(E){}let n=exports.mergeCustomCode(o,r,{position:((a=t==null?void 0:t.customCode)==null?void 0:a.position)||"bottom",markerText:(c=t==null?void 0:t.customCode)==null?void 0:c.markerText,includeInstructions:(p=t==null?void 0:t.customCode)==null?void 0:p.includeInstructions});yield oe__default.default.promises.writeFile(s,n);}),gn=(s,o,t,e)=>X(null,null,function*(){var le,Oe,Ze,Xe,et,tt,nt,rt,st,at;let r=yield fn.get(s),n=exports.isJson(r.data)?r.data:exports.yamlStringToJson(r.data),i;try{i=yield zn__default.default.parse(n);}catch(l){let m=l instanceof Error?l.message:String(l);throw new Error(`Failed to parse OpenAPI spec for ${o}: ${m}`)}let a=D__default.default.join((t==null?void 0:t.folder)||"",o),c={},p=l=>{var m,T;if((m=t==null?void 0:t.folderSplit)!=null&&m.customFolder){let h=t.folderSplit.customFolder(l);if(h)return h}return (T=t==null?void 0:t.folderSplit)!=null&&T.byTags&&l.tags&&l.tags.length>0?l.tags[0].toLowerCase().replace(/\s+/g,"-"):"default"},E=typeof(t==null?void 0:t.server)=="string"?t==null?void 0:t.server:((Oe=(le=i==null?void 0:i.servers)==null?void 0:le[(t==null?void 0:t.server)||0])==null?void 0:Oe.url)||"",j=typeof((Xe=(Ze=t==null?void 0:t.types)==null?void 0:Ze.name)==null?void 0:Xe.prefix)=="string"?t==null?void 0:t.types.name.prefix:"I",R=typeof((tt=(et=t==null?void 0:t.endpoints)==null?void 0:et.name)==null?void 0:tt.prefix)=="string"?t==null?void 0:t.endpoints.name.prefix:"",A=(l,m)=>{var h,y;let T=exports.capitalize(l);if((y=(h=t==null?void 0:t.types)==null?void 0:h.name)!=null&&y.format){let f=t==null?void 0:t.types.name.format("shared",{name:l},T);if(f)return `${j}${f}`}return `${j}${T}`},x=(l,m,T,h,y,f=0)=>{let d="",$="",g="";if(m)if(m.$ref)if(m.$ref[0]==="#"){let w=(m.$ref||"").split("/");w.shift(),[...w].pop();let Q=De__default.default(l,w,null);if(Q){Q!=null&&Q.name&&(d=Q.name),$=w[w.length-1];let V=A($);V.includes(".")&&(V=V.split(".").map((ne,ue)=>ue===0?ne:`["${ne}"]`).join("")),g+=`${y!=null&&y.noSharedImport?"":"Shared."}${V}`;}}else g+="";else if(m.anyOf)g+=`(${m.anyOf.map(w=>x(l,w,"",h,y)).filter(w=>!!w).join("|")})`;else if(m.oneOf)g+=`(${m.oneOf.map(w=>x(l,w,"",h,y)).filter(w=>!!w).join("|")})`;else if(m.allOf)g+=`(${m.allOf.map(w=>x(l,w,"",h,y)).filter(w=>!!w).join("&")})`;else if(m.items)g+=`${x(l,m.items,"",false,y)}[]`;else if(m.properties){let w=Object.keys(m.properties),F=m.required||[],B="";w.forEach(Q=>{var ie,ne,ue,ke,be,Ce;let V="";!((ne=(ie=t==null?void 0:t.types)==null?void 0:ie.doc)!=null&&ne.disable)&&((ke=(ue=m.properties)==null?void 0:ue[Q])!=null&&ke.description)&&(V=" * "+((be=m.properties)==null?void 0:be[Q].description.split(`
|
|
21
|
+
`).filter(he=>he.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(l,(Ce=m.properties)==null?void 0:Ce[Q],Q,F.includes(Q),y,f+1)}`;}),B.length>0?g+=`{
|
|
26
|
+
${" ".repeat(f)}${B}${" ".repeat(f)}}`:g+="{[k: string]: any}";}else if(m.enum&&m.enum.length>0)m.enum.length>1&&(g+="("),m.enum.map(w=>JSON.stringify(w)).filter(w=>!!w).forEach((w,F)=>{g+=`${F===0?"":"|"}${w}`;}),m.enum.length>1&&(g+=")");else if(m.type){let w=F=>{let B="";if(typeof F=="string")["string","integer","number","array","boolean","null"].includes(F)?["integer","number"].includes(F)?B+="number":F==="array"?B+="any[]":B+=F:F==="object"&&(m.additionalProperties?B+=`{[k: string]: ${x(l,m.additionalProperties,"",true,y)||"any"}}`:B+="{[k: string]: any}");else if(Array.isArray(F)){let Q=F.map(V=>w(V));Q.filter(V=>V!==""),Q.length>1&&(B+="("+Q.join("|")+")");}else B+="any";return B};g=w(m.type);}else g+="any";else g="string";let k=d||T;y!=null&&y.useComponentName&&!k&&(k=$);let J=k?` "${k}"${h?"":"?"}: `:"",u=m!=null&&m.nullable?" | null":"";return g.length>0?`${J}${g}${u}${k?`;
|
|
27
|
+
`:""}`:""},v=(l,m)=>{let y="";if(m)if(m.$ref)if(m.$ref[0]==="#"){let f=(m.$ref||"").split("/");f.shift();let $=De__default.default(l,f,null);$&&($!=null&&$.name&&($.name),f[f.length-1],y+=v(l,$));}else y+="";else if(m.anyOf)y+=v(l,m.anyOf[0]);else if(m.oneOf)y+=v(l,m.oneOf[0]);else if(m.allOf)y+=`{${m.allOf.map(f=>`...(${v(l,f)})`).join(",")}}`;else if(m.items)y+=`[${v(l,m.items)}]`;else if(m.properties){let $=Object.keys(m.properties).map(g=>{var k;return ` "${g}": ${v(l,(k=m.properties)==null?void 0:k[g])}`}).join(`,
|
|
28
|
+
`);$.length>0?y+=`{
|
|
29
|
+
${$}
|
|
30
|
+
}`:y+="{}";}else if(m.enum&&m.enum.length>0)m.enum.length>1&&(y+=m.enum[0]);else if(m.type)if(m.example)y+=JSON.stringify(m.example);else {let f=d=>{let $="";if(typeof d=="string")["string","integer","number","array","boolean","null"].includes(d)?["integer","number"].includes(d)?$+="123":d==="array"?$+="[]":d==="boolean"?$+="true":d==="null"?$+="null":$+=`"${d}"`:d==="object"&&($+="{}");else if(Array.isArray(d)){let g=d.map(k=>f(k));g.filter(k=>k!==""),g.length>1&&($+=g.join("|"));}else $+="any";return $};y=f(m.type);}else y+="any";else y="string";return y};e&&!isNaN(e)&&e>0&&(process.env.NODE_ENV&&["production","prod","test","staging"].includes(process.env.NODE_ENV)||(Je[o]&&clearTimeout(Je[o]),Je[o]=setTimeout(()=>gn(s,o,t,e),e)));let N=mn(o);if(Ln__default.default(N,i))return;un(o,i);let G="",W="",O={},C=[];i.components&&Object.keys(i.components).forEach(l=>{if(["schemas","responses","parameters","examples","requestBodies","headers","links","callbacks"].includes(l)){let m=i.components[l],T={},h={};Object.keys(m).forEach(f=>{var g;let d=(g=m[f])!=null&&g.schema?m[f].schema:m[f],$=`${x(i,d,"",true,{noSharedImport:true,useComponentName:["parameters"].includes(l)})}`;if($){let k=f.split("."),J=T,u=h;for(let w=0;w<k.length;w++){let F=k[w];w<k.length-1?(F in J||(J[F]={},u[F]={}),J=J[F],u=u[F]):(J[F]=$,u[F]=d);}}}),Object.keys(T).forEach(f=>{var k,J,u,w;let d=A(f),$=T[f],g="";!((J=(k=t==null?void 0:t.types)==null?void 0:k.doc)!=null&&J.disable)&&f in m&&((u=m[f])!=null&&u.description)&&(g=" * "+m[f].description.split(`
|
|
31
|
+
`).filter(F=>F.trim()!=="").join(`
|
|
32
|
+
*${" ".repeat(1)}`)),O[f]=((w=O[f])!=null?w:"")+(g?`/**
|
|
33
|
+
${g}
|
|
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 $=="string"?$:exports.JSONStringify($))+`;
|
|
36
|
+
`;});}});let L=l=>{let m="";if(l.content){let T=Object.keys(l.content);T[0]&&l.content[T[0]].schema&&(m+=`${x(i,l.content[T[0]].schema,"")}`);}return m},P=(l,m,T=0)=>{if(!l)return m==="joi"?"Joi.any()":m==="yup"?"yup.mixed()":"z.any()";if(l.$ref){if(l.$ref[0]==="#"){let h=l.$ref.split("/");h.shift();let y=h.join("."),f=De__default.default(i,y);if(f)return P(f,m,T)}return m==="joi"?"Joi.any()":m==="yup"?"yup.mixed()":"z.any()"}if(l.anyOf||l.oneOf){let h=l.anyOf||l.oneOf;if(h.every(f=>f.enum!==void 0&&Array.isArray(f.enum))){let f=[],d=false;if(h.forEach($=>{$.enum&&$.enum.forEach(g=>{g===null?d=true:f.includes(g)||f.push(g);});}),f.length>0){let $=f.map(g=>JSON.stringify(g)).join(", ");if(m==="zod"){let g=`z.enum([${$}])`;return d&&(g+=".nullable()"),g}else if(m==="yup"){let g=`yup.mixed().oneOf([${$}])`;return d&&(g+=".nullable()"),g}else return d?`Joi.valid(${$}, null)`:`Joi.valid(${$})`}else if(d)return m==="zod"?"z.null()":m==="yup"?"yup.mixed().nullable()":"Joi.valid(null)"}return m==="zod"?`z.union([${h.map($=>P($,m,T+1)).join(", ")}])`:m==="yup"?`yup.mixed().oneOf([${h.map($=>P($,m,T+1)).join(", ")}])`:`Joi.alternatives().try(${h.map(d=>P(d,m,T+1)).join(", ")})`}if(l.allOf)if(m==="zod"){let h=l.allOf.map(f=>P(f,m,T+1)),y=h[0];for(let f=1;f<h.length;f++)y=`${y}.merge(${h[f]})`;return y}else return P(l.allOf[0],m,T+1);if(l.items){let h=P(l.items,m,T+1);if(m==="zod"){let y=`z.array(${h})`;return l.minItems!==void 0&&(y+=`.min(${l.minItems})`),l.maxItems!==void 0&&(y+=`.max(${l.maxItems})`),y}else if(m==="yup"){let y=`yup.array().of(${h})`;return l.minItems!==void 0&&(y+=`.min(${l.minItems})`),l.maxItems!==void 0&&(y+=`.max(${l.maxItems})`),y}else {let y=`Joi.array().items(${h})`;return l.minItems!==void 0&&(y+=`.min(${l.minItems})`),l.maxItems!==void 0&&(y+=`.max(${l.maxItems})`),y}}if(l.properties){let h=l.required||[],y=" ".repeat(T+1),f=Object.entries(l.properties).map(([d,$])=>{let g=h.includes(d),k=P($,m,T+1);return g||(k+=".optional()"),`${y}${d}: ${k}`}).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(l.enum&&l.enum.length>0){let h=[],y=false;l.enum.forEach(d=>{d===null?y=true:h.includes(d)||h.push(d);});let f=h.map(d=>JSON.stringify(d)).join(", ");if(m==="zod"){let d=`z.enum([${f}])`;return y&&(d+=".nullable()"),d}else if(m==="yup"){let d=`yup.mixed().oneOf([${f}])`;return y&&(d+=".nullable()"),d}else {let d=`Joi.valid(${f})`;return y&&(d+=".allow(null)"),d}}if(l.type){let y=(f=>{switch(f){case "string":if(m==="zod"){let d="z.string()";return l.format==="email"?d+=".email()":l.format==="uuid"?d+=".uuid()":l.format==="url"||l.format==="uri"?d+=".url()":l.format==="date-time"?d+=".datetime()":l.format==="date"&&(d+=".date()"),l.minLength&&(d+=`.min(${l.minLength})`),l.maxLength&&(d+=`.max(${l.maxLength})`),l.pattern&&(d+=`.regex(/${l.pattern}/)`),d}else if(m==="yup"){let d="yup.string()";return l.format==="email"?d+=".email()":(l.format==="url"||l.format==="uri")&&(d+=".url()"),l.minLength&&(d+=`.min(${l.minLength})`),l.maxLength&&(d+=`.max(${l.maxLength})`),l.pattern&&(d+=`.matches(/${l.pattern}/)`),d}else {let d="Joi.string()";return l.format==="email"?d+=".email()":l.format==="url"||l.format==="uri"?d+=".uri()":l.format==="uuid"?d+=".guid({ version: 'uuidv4' })":l.format==="date-time"&&(d+=".isoDate()"),l.minLength&&(d+=`.min(${l.minLength})`),l.maxLength&&(d+=`.max(${l.maxLength})`),l.pattern&&(d+=`.pattern(/${l.pattern}/)`),d}case "integer":case "number":if(m==="zod"){let d="z.number()";return f==="integer"&&(d+=".int()"),l.minimum!==void 0&&(l.exclusiveMinimum?d+=`.gt(${l.minimum})`:d+=`.min(${l.minimum})`),l.maximum!==void 0&&(l.exclusiveMaximum?d+=`.lt(${l.maximum})`:d+=`.max(${l.maximum})`),d}else if(m==="yup"){let d="yup.number()";return f==="integer"&&(d+=".integer()"),l.minimum!==void 0&&(d+=`.min(${l.minimum})`),l.maximum!==void 0&&(d+=`.max(${l.maximum})`),d}else {let d="Joi.number()";return f==="integer"&&(d+=".integer()"),l.minimum!==void 0&&(l.exclusiveMinimum?d+=`.greater(${l.minimum})`:d+=`.min(${l.minimum})`),l.maximum!==void 0&&(l.exclusiveMaximum?d+=`.less(${l.maximum})`:d+=`.max(${l.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 l.type=="string"?l.type:l.type[0]);return l.nullable&&m!=="joi"?y+=".nullable()":l.nullable&&m==="joi"&&(y+=".allow(null)"),y}return m==="joi"?"Joi.any()":m==="yup"?"yup.mixed()":"z.any()"},ee=l=>{var m,T,h,y,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=l;return (f=(y=(h=t==null?void 0:t.endpoints)==null?void 0:h.value)==null?void 0:y.replaceWords)==null||f.forEach(($,g)=>{let k=new RegExp($.replace,"g");d=d.replace(k,$.with||"");}),d}else return l},ge=(l,m,T=[])=>{var f,d;let h=(f=t==null?void 0:t.endpoints)==null?void 0:f.exclude,y=(d=t==null?void 0:t.endpoints)==null?void 0:d.include;if(y){let $=y.tags&&y.tags.length>0?T.some(k=>y.tags.includes(k)):true,g=y.endpoints&&y.endpoints.length>0?y.endpoints.some(k=>{let J=!k.method||k.method.toLowerCase()===m.toLowerCase();return k.path?l===k.path&&J:k.regex?new RegExp(k.regex).test(l)&&J:false}):true;if(!$||!g)return true}return !!(h&&(h.tags&&h.tags.length>0&&T.some(g=>h.tags.includes(g))||h.endpoints&&h.endpoints.length>0&&h.endpoints.some(g=>{let k=!g.method||g.method.toLowerCase()===m.toLowerCase();return g.path?l===g.path&&k:g.regex?new RegExp(g.regex).test(l)&&k:false})))};if(Object.keys(i.paths||{}).forEach(l=>{let m=i.paths[l];Object.keys(m).forEach(h=>{var it,lt,pt,ut,mt,dt,ct,yt,ft,gt,ht,$t,bt,Ct,It,xt,Tt,wt,Et,vt,At,Ot,kt,jt,Pt,St,Rt,qt,Ut,Gt,Ft,Mt,Nt,Lt,Bt,Qt,zt,Wt,Dt,Jt,Kt,Ht,_t,Vt,Yt,Zt,Xt,en,tn;let y=h,f=exports.getEndpointDetails(l,y),d=((it=m[y])==null?void 0:it.tags)||[];if(ge(l,y,d))return;let $=m[y],g=p({method:y,path:l,summary:$==null?void 0:$.summary,operationId:$==null?void 0:$.operationId,tags:d,parameters:$==null?void 0:$.parameters,requestBody:$==null?void 0:$.requestBody,responses:$==null?void 0:$.responses});c[g]||(c[g]={endpoints:"",types:"",validation:""});let k=((pt=(lt=t==null?void 0:t.endpoints)==null?void 0:lt.value)!=null&&pt.includeServer?E:"")+f.pathParts.map(b=>(b[0]==="{"&&b[b.length-1]==="}"?b=`\${${b.replace(/{/,"").replace(/}/,"")}}`:b[0]==="<"&&b[b.length-1]===">"?b=`\${${b.replace(/</,"").replace(/>/,"")}}`:b[0]===":"&&(b=`\${${b.replace(/:/,"")}}`),b)).join("/"),J=`"${k}"`;f.variables.length>0&&(J=`(${f.variables.map(I=>`${I}:string`).join(",")})=> \`${k}\``),J=ee(J);let u=m[y],w="",F;if(u!=null&&u.parameters&&((u==null?void 0:u.parameters).forEach((I,S)=>{(I.$ref||I.in==="query"&&I.name)&&(w+=`${x(i,I.$ref?I:I.schema,I.name||"",I.required)}`);}),w)){w=`{
|
|
44
|
+
${w}}`;let I=`${f.name}Query`;if((mt=(ut=t==null?void 0:t.types)==null?void 0:ut.name)!=null&&mt.useOperationId&&(u!=null&&u.operationId)&&(I=`${u.operationId}Query`),I=exports.capitalize(`${j}${I}`),(ct=(dt=t==null?void 0:t.types)==null?void 0:dt.name)!=null&&ct.format){let M=t==null?void 0:t.types.name.format("endpoint",{code:"",type:"query",method:y,path:l,summary:u==null?void 0:u.summary,operationId:u==null?void 0:u.operationId},I);M&&(I=`${j}${M}`);}F=I;let S=`export type ${I} = ${w};
|
|
45
|
+
`;t!=null&&t.folderSplit?c[g].types+=S:W+=S;}if(((yt=t==null?void 0:t.validations)==null?void 0:yt.disable)!==true&&((gt=(ft=t==null?void 0:t.validations)==null?void 0:ft.generate)==null?void 0:gt.query)!==false&&(u!=null&&u.parameters)){let b=((ht=t.validations)==null?void 0:ht.library)||"zod",S=u.parameters.filter(M=>!M.$ref&&M.in==="query"&&M.name);if(S.length>0){let M=(($t=t==null?void 0:t.validations)==null?void 0:$t.name)||((bt=t==null?void 0:t.types)==null?void 0:bt.name),K=typeof(M==null?void 0:M.prefix)=="string"?M.prefix:"I",U=typeof((It=(Ct=t==null?void 0:t.validations)==null?void 0:Ct.name)==null?void 0:It.suffix)=="string"?t.validations.name.suffix:"Schema",z=`${f.name}Query`;if(M!=null&&M.useOperationId&&(u!=null&&u.operationId)&&(z=`${u.operationId}Query`),z=exports.capitalize(`${K}${z}${U}`),(Tt=(xt=t==null?void 0:t.validations)==null?void 0:xt.name)!=null&&Tt.format){let Z=t.validations.name.format({code:"",type:"query",method:y,path:l,summary:u==null?void 0:u.summary,operationId:u==null?void 0:u.operationId},z);Z&&(z=`${K}${Z}${U}`);}else if((Et=(wt=t==null?void 0:t.types)==null?void 0:wt.name)!=null&&Et.format){let Z=t.types.name.format("endpoint",{code:"",type:"query",method:y,path:l,summary:u==null?void 0:u.summary,operationId:u==null?void 0:u.operationId},z);Z&&(z=`${K}${Z}${U}`);}let q=S.map(Z=>{let Pn=Z!=null&&Z.schema?P(Z.schema,b):b==="joi"?"Joi.string()":b==="yup"?"yup.string()":"z.string()",Sn=Z.required?"":".optional()";return ` ${Z.name}: ${Pn}${Sn}`}).join(`,
|
|
46
|
+
`),pe=`export const ${z} = ${b==="joi"?"Joi.object":b==="yup"?"yup.object":"z.object"}({
|
|
47
|
+
${q}
|
|
48
48
|
});
|
|
49
49
|
|
|
50
|
-
`;
|
|
51
|
-
`;
|
|
50
|
+
`;t!=null&&t.folderSplit||c[g]||(c[g]={endpoints:"",types:"",validation:""}),c[g].validation+=pe;}}let B=u==null?void 0:u.requestBody,Q="",V;if(B&&(Q=L(B),Q)){let b=`${f.name}DTO`;if((At=(vt=t==null?void 0:t.types)==null?void 0:vt.name)!=null&&At.useOperationId&&(u!=null&&u.operationId)&&(b=`${u.operationId}DTO`),b=exports.capitalize(`${j}${b}`),(kt=(Ot=t==null?void 0:t.types)==null?void 0:Ot.name)!=null&&kt.format){let S=t==null?void 0:t.types.name.format("endpoint",{code:"",type:"dto",method:y,path:l,summary:u==null?void 0:u.summary,operationId:u==null?void 0:u.operationId},b);S&&(b=`${j}${S}`);}V=b;let I=`export type ${b} = ${Q};
|
|
51
|
+
`;t!=null&&t.folderSplit?c[g].types+=I:W+=I;}if(((jt=t==null?void 0:t.validations)==null?void 0:jt.disable)!==true&&((St=(Pt=t==null?void 0:t.validations)==null?void 0:Pt.generate)==null?void 0:St.dto)!==false&&B){let b=((Rt=t.validations)==null?void 0:Rt.library)||"zod";if(B.content){let I=Object.keys(B.content);if(I[0]&&B.content[I[0]].schema){let S=((qt=t==null?void 0:t.validations)==null?void 0:qt.name)||((Ut=t==null?void 0:t.types)==null?void 0:Ut.name),M=typeof(S==null?void 0:S.prefix)=="string"?S.prefix:"I",K=typeof((Ft=(Gt=t==null?void 0:t.validations)==null?void 0:Gt.name)==null?void 0:Ft.suffix)=="string"?t.validations.name.suffix:"Schema",U=`${f.name}DTO`;if(S!=null&&S.useOperationId&&(u!=null&&u.operationId)&&(U=`${u.operationId}DTO`),U=exports.capitalize(`${M}${U}${K}`),(Nt=(Mt=t==null?void 0:t.validations)==null?void 0:Mt.name)!=null&&Nt.format){let Y=t.validations.name.format({code:"",type:"dto",method:y,path:l,summary:u==null?void 0:u.summary,operationId:u==null?void 0:u.operationId},U);Y&&(U=`${M}${Y}${K}`);}else if((Bt=(Lt=t==null?void 0:t.types)==null?void 0:Lt.name)!=null&&Bt.format){let Y=t.types.name.format("endpoint",{code:"",type:"dto",method:y,path:l,summary:u==null?void 0:u.summary,operationId:u==null?void 0:u.operationId},U);Y&&(U=`${M}${Y}${K}`);}let z=P(B.content[I[0]].schema,b),q=`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||c[g]||(c[g]={endpoints:"",types:"",validation:""}),c[g].validation+=q;}}}let ie={},ne="",ue="";if(u!=null&&u.responses){let b=u==null?void 0:u.responses;Object.keys(b).forEach(S=>{var M,K,U,z;if(ne=L(b[S]),ie[S]=ne,ne){let q=`${f.name}${S}Response`;if((K=(M=t==null?void 0:t.types)==null?void 0:M.name)!=null&&K.useOperationId&&(u!=null&&u.operationId)&&(q=`${u.operationId}${S}Response`),q=exports.capitalize(`${j}${q}`),(z=(U=t==null?void 0:t.types)==null?void 0:U.name)!=null&&z.format){let Z=t==null?void 0:t.types.name.format("endpoint",{code:S,type:"response",method:y,path:l,summary:u==null?void 0:u.summary,operationId:u==null?void 0:u.operationId},q);Z&&(q=`${j}${Z}`);}let Y=`export type ${q} = ${ne};
|
|
54
|
+
`;t!=null&&t.folderSplit?c[g].types+=Y:W+=Y,ie[S]=q;let pe=parseInt(S);pe>=200&&pe<300&&(ue=q);}});}let ke=b=>!b||!b.length?"":b.map(I=>Object.entries(I).map(([M,K])=>{let U=M,z="";return Array.isArray(K)&&K.length&&(z=`
|
|
55
|
+
- Scopes: [\`${K.join("`, `")}\`]`,U=`**${U}**`),`
|
|
56
|
+
- ${U}${z}`}).join("")).join(`
|
|
57
|
+
`),be=u!=null&&u.security?ke(u.security):"",Ce="";if(!((zt=(Qt=t==null?void 0:t.endpoints)==null?void 0:Qt.doc)!=null&&zt.disable)){let b="";if((Dt=(Wt=t==null?void 0:t.endpoints)==null?void 0:Wt.doc)!=null&&Dt.showCurl){let I={},S="",M="";(Jt=u.requestBody)!=null&&Jt.content&&Object.keys(u.requestBody.content).forEach(z=>{let q=u.requestBody.content[z].schema;if(q){Array.isArray(I["Content-type"])?I["Content-type"].push(z):I["Content-type"]=[z];let Y=v(i,q);Y&&(S=Y);}}),u!=null&&u.security&&u.security.forEach(U=>{Object.keys(U).forEach(z=>{var Y,pe;let q=(pe=(Y=i.components)==null?void 0:Y.securitySchemes)==null?void 0:pe[z];q&&(q.type==="mutualTLS"?M+=`
|
|
58
|
+
--cert client-certificate.crt --key client-private-key.key --cacert ca-certificate.crt`:q.type==="apiKey"?I[(q==null?void 0:q.name)||"X-API-KEY"]="{API_KEY_VALUE}":I.Authorization=`${(q==null?void 0:q.scheme)==="basic"?"Basic":"Bearer"} {${(q==null?void 0:q.scheme)==="basic"?"VALUE":"TOKEN"}}`);});});let K={};Object.keys(I).forEach(U=>{Array.isArray(I[U])?K[U]=I[U].join("; "):K[U]=I[U];}),b=`
|
|
59
59
|
\`\`\`bash
|
|
60
|
-
${curlGenerator.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.CurlGenerator({url:E+l,method:y.toUpperCase(),headers:K,body:S})}${M}
|
|
61
|
+
\`\`\``;}Ce=`/**${u!=null&&u.description?`
|
|
62
|
+
* ${u==null?void 0:u.description} `:""}
|
|
63
|
+
* **Method**: \`${y.toUpperCase()}\`
|
|
64
|
+
* **Summary**: ${(u==null?void 0:u.summary)||""}
|
|
65
|
+
* **Tags**: [${((Kt=u==null?void 0:u.tags)==null?void 0:Kt.join(", "))||""}]
|
|
66
|
+
* **OperationId**: ${(u==null?void 0:u.operationId)||""} ${w?`
|
|
67
|
+
* **Query**: ${exports.renderTypeRefMD(w)} `:""}${Q?`
|
|
68
|
+
* **DTO**: ${exports.renderTypeRefMD(Q)} `:""}${ne?`
|
|
69
|
+
* **Response**: ${Object.entries(ie).map(([I,S])=>`
|
|
70
|
+
- **${I}**: ${exports.renderTypeRefMD(S,2)} `).join("")}`:""}${be?`
|
|
71
|
+
* **Security**: ${be}
|
|
72
|
+
`:""}${b}
|
|
73
73
|
*/
|
|
74
|
-
`;}let
|
|
75
|
-
`;
|
|
74
|
+
`;}let he=(_t=(Ht=t==null?void 0:t.endpoints)==null?void 0:Ht.name)!=null&&_t.useOperationId&&((Vt=u==null?void 0:u.operationId)==null?void 0:Vt.length)>0?u.operationId:`${f.name}`;if((Zt=(Yt=t==null?void 0:t.endpoints)==null?void 0:Yt.name)!=null&&Zt.format){let b=t==null?void 0:t.endpoints.name.format({method:y,path:l,summary:u==null?void 0:u.summary,operationId:u==null?void 0:u.operationId},he);b&&(he=b);}let kn={method:`"${y}"`,operationId:`"${u==null?void 0:u.operationId}"`,url:J,tags:(u==null?void 0:u.tags)||[]},ot=`${Ce}export const ${R}${he} = ${((en=(Xt=t==null?void 0:t.endpoints)==null?void 0:Xt.value)==null?void 0:en.type)==="object"?exports.JSONStringify(kn):J};
|
|
75
|
+
`;t!=null&&t.folderSplit?c[g].endpoints+=ot:G+=ot;let jn={name:`${R}${he}`,method:y,path:l,summary:u==null?void 0:u.summary,operationId:u==null?void 0:u.operationId,tags:d,parameters:(tn=u==null?void 0:u.parameters)==null?void 0:tn.filter(b=>!b.$ref&&b.in&&b.name).map(b=>{var I;return {name:b.name,in:b.in,required:b.required,type:((I=b.schema)==null?void 0:I.type)||"string"}}),requestBody:B?{type:Q,required:B.required}:void 0,responses:ie?Object.entries(ie).reduce((b,[I,S])=>(b[I]={type:S},b),{}):void 0,queryType:F,dtoType:V,responseType:ue||void 0};C.push(jn);});}),t!=null&&t.folderSplit){for(let[l,m]of Object.entries(c))if(m.endpoints||m.types){let T=D__default.default.join(a,l);if(m.endpoints){let h=D__default.default.join(me,T,"endpoints.ts");yield oe__default.default.promises.mkdir(D__default.default.dirname(h),{recursive:true}),yield de(h,m.endpoints,t);}if(m.types){let h=D__default.default.join(me,T,"types.ts");yield oe__default.default.promises.mkdir(D__default.default.dirname(h),{recursive:true});let y=Object.values(O).length>0?`import * as Shared from "../shared";
|
|
76
|
+
|
|
77
|
+
${m.types}`:m.types;yield de(h,y,t);}if(((nt=t==null?void 0:t.validations)==null?void 0:nt.disable)!==true&&m.validation){let h=((rt=t.validations)==null?void 0:rt.library)||"zod",y=h==="joi"?'import Joi from "joi";':h==="yup"?'import * as yup from "yup";':'import { z } from "zod";',f=D__default.default.join(me,T,"validations.ts");yield oe__default.default.promises.mkdir(D__default.default.dirname(f),{recursive:true}),yield de(f,`${y}
|
|
78
|
+
|
|
79
|
+
${m.validation}`,t);}}}if(G.length>0){let l=D__default.default.join(me,a,"endpoints.ts");yield oe__default.default.promises.mkdir(D__default.default.dirname(l),{recursive:true}),yield de(l,G,t);}if(Object.values(O).length>0){let l=D__default.default.join(me,a,t!=null&&t.folderSplit?"":"types","shared.ts");yield oe__default.default.promises.mkdir(D__default.default.dirname(l),{recursive:true}),yield de(l,Object.values(O).join(`
|
|
80
|
+
`),t);}if(W.length>0){let l=D__default.default.join(me,a,"types","index.ts");yield oe__default.default.promises.mkdir(D__default.default.dirname(l),{recursive:true}),yield de(l,`${Object.values(O).length>0?`import * as Shared from "./shared";
|
|
81
|
+
|
|
82
|
+
`:""}${W}`,t);}if(((st=t==null?void 0:t.validations)==null?void 0:st.disable)!==true&&!(t!=null&&t.folderSplit)){let l=((at=t.validations)==null?void 0:at.library)||"zod",m=l==="joi"?'import Joi from "joi";':l==="yup"?'import * as yup from "yup";':'import { z } from "zod";',T=Object.values(c).map(h=>h.validation).filter(h=>h.length>0).join("");if(T){let h=D__default.default.join(me,a,"validations.ts");yield oe__default.default.promises.mkdir(D__default.default.dirname(h),{recursive:true}),yield de(h,`${m}
|
|
83
|
+
|
|
84
|
+
${T}`,t);}}cn(o,C);}),Ke=gn;});var $n,He,ce,_e,Ve,Ye,bn=se(()=>{$n=(s,o)=>{let t=s;return o.tags&&o.tags.length>0&&(t=t.filter(e=>!e.tags||e.tags.length===0?false:e.tags.some(r=>o.tags.includes(r)))),o.endpoints&&o.endpoints.length>0&&(t=t.filter(e=>o.endpoints.includes(e.name))),t},He=(s,o,t=false)=>{var a,c;let e=o.baseURL||"",r=o.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 i=new Set;return s.forEach(p=>{p.queryType&&i.add(p.queryType),p.dtoType&&i.add(p.dtoType),p.responseType&&i.add(p.responseType);}),i.forEach(p=>{n+=` ${p},
|
|
89
|
+
`;}),n+=`} from '../types';
|
|
90
|
+
|
|
91
|
+
`,n+=`import {
|
|
92
|
+
`,s.forEach(p=>{n+=` ${p.name} as ${p.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
|
+
`,(a=o.errorHandling)!=null&&a.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
|
+
`,(c=o.errorHandling)!=null&&c.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
|
+
`,s.forEach(p=>{var W,O;let E=p.name,j=((W=p.parameters)==null?void 0:W.filter(C=>C.in==="path"))||[],R=((O=p.parameters)==null?void 0:O.filter(C=>C.in==="query"))||[],A=j.length>0,x=R.length>0,v=!!p.requestBody,N=p.responseType||"any";if(n+=`/**
|
|
156
|
+
`,p.summary&&(n+=` * ${p.summary}
|
|
157
|
+
`),n+=` * @method ${p.method.toUpperCase()}
|
|
158
|
+
`,n+=` * @path ${p.path}
|
|
159
|
+
`,p.tags&&p.tags.length>0&&(n+=` * @tags ${p.tags.join(", ")}
|
|
160
|
+
`),n+=` */
|
|
161
|
+
`,n+=`export async function ${E}(`,(A||x||v)&&(n+=`params: {
|
|
162
|
+
`,A&&(n+=` url: {
|
|
163
|
+
`,j.forEach(C=>{let P={string:"string",number:"number",integer:"number",boolean:"boolean",array:"any[]",object:"any"}[C.type||"string"]||"any",ee=C.required?"":"?";n+=` ${C.name}${ee}: ${P};
|
|
164
|
+
`;}),n+=` };
|
|
165
|
+
`),x&&(n+=` query: ${p.queryType||"Record<string, any>"};
|
|
166
|
+
`),v&&(n+=` data: ${p.dtoType||"any"};
|
|
167
|
+
`),n+=`}
|
|
168
|
+
`),n+=`): Promise<${N}> {
|
|
169
|
+
`,A||x||v){let C=[];A&&C.push("url"),x&&C.push("query"),v&&C.push("data"),n+=` const { ${C.join(", ")} } = params;
|
|
170
|
+
`;}let G;if(A){let C=j.map(L=>`url.${L.name}`).join(", ");G=`${p.name}_endpoint(${C})`;}else G=`${p.name}_endpoint`;x?(n+=` const queryParams = new URLSearchParams();
|
|
171
|
+
`,R.forEach(C=>{C.required?n+=` queryParams.append('${C.name}', String(query.${C.name}));
|
|
172
|
+
`:(n+=` if (query.${C.name} !== undefined) {
|
|
173
|
+
`,n+=` queryParams.append('${C.name}', String(query.${C.name}));
|
|
174
|
+
`,n+=` }
|
|
175
|
+
`);}),n+=` const _url = \`\${${G}}?\${queryParams.toString()}\`;
|
|
176
|
+
`):n+=` const _url = ${G};
|
|
177
|
+
`,n+=` return fetchAPI<${N}>(_url, {
|
|
178
|
+
`,n+=` method: '${p.method.toUpperCase()}',
|
|
179
|
+
`,v&&(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
|
+
`,s.forEach(p=>{n+=` ${p.name},
|
|
187
|
+
`;}),n+=`};
|
|
188
|
+
|
|
189
|
+
`,n+=`export default apiClient;
|
|
190
|
+
`),n},ce=(s,o,t=false)=>{var a,c;let e=o.baseURL||"",r=o.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 i=new Set;return s.forEach(p=>{p.queryType&&i.add(p.queryType),p.dtoType&&i.add(p.dtoType),p.responseType&&i.add(p.responseType);}),i.forEach(p=>{n+=` ${p},
|
|
197
|
+
`;}),n+=`} from '../types';
|
|
198
|
+
|
|
199
|
+
`,n+=`import {
|
|
200
|
+
`,s.forEach(p=>{n+=` ${p.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
|
+
`,(a=o.errorHandling)!=null&&a.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
|
+
`,(c=o.errorHandling)!=null&&c.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
|
+
`,s.forEach(p=>{var G,W;let E=p.name,j=((G=p.parameters)==null?void 0:G.filter(O=>O.in==="path"))||[],R=((W=p.parameters)==null?void 0:W.filter(O=>O.in==="query"))||[],A=j.length>0,x=R.length>0,v=!!p.requestBody,N=p.responseType||"any";if(n+=` /**
|
|
275
|
+
`,p.summary&&(n+=` * ${p.summary}
|
|
276
|
+
`),n+=` * @method ${p.method.toUpperCase()}
|
|
277
|
+
`,n+=` * @path ${p.path}
|
|
278
|
+
`,p.tags&&p.tags.length>0&&(n+=` * @tags ${p.tags.join(", ")}
|
|
279
|
+
`),n+=` */
|
|
280
|
+
`,n+=` async ${E}(`,(A||x||v)&&(n+=`params: {
|
|
281
|
+
`,A&&(n+=` url: {
|
|
282
|
+
`,j.forEach(O=>{let L={string:"string",number:"number",integer:"number",boolean:"boolean",array:"any[]",object:"any"}[O.type||"string"]||"any",P=O.required?"":"?";n+=` ${O.name}${P}: ${L};
|
|
283
|
+
`;}),n+=` };
|
|
284
|
+
`),x&&(n+=` query: ${p.queryType||"Record<string, any>"};
|
|
285
|
+
`),v&&(n+=` data: ${p.dtoType||"any"};
|
|
286
|
+
`),n+=" }"),n+=`): Promise<${N}> {
|
|
287
|
+
`,A||x||v){let O=[];A&&O.push("url"),x&&O.push("query"),v&&O.push("data"),n+=` const { ${O.join(", ")} } = params;
|
|
288
|
+
`;}if(A){let O=j.map(C=>`url.${C.name}`).join(", ");n+=` const _url = ${p.name}(${O});
|
|
289
|
+
`;}else n+=` const _url = ${p.name};
|
|
290
|
+
`;n+=` const config: AxiosRequestConfig = {};
|
|
291
|
+
`,x&&(n+=` config.params = { ...query };
|
|
292
|
+
`),n+=` const response = await this.client.${p.method.toLowerCase()}<${N}>(
|
|
293
|
+
`,n+=` _url,
|
|
294
|
+
`,v?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},_e=(s,o)=>{var a,c;let t=((a=o.reactQuery)==null?void 0:a.version)||5,e=((c=o.reactQuery)==null?void 0:c.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&&s.some(p=>["POST","PUT","PATCH","DELETE"].includes(p.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 i=new Set;return s.forEach(p=>{p.queryType&&i.add(p.queryType),p.dtoType&&i.add(p.dtoType),p.responseType&&i.add(p.responseType);}),i.forEach(p=>{r+=` ${p},
|
|
317
|
+
`;}),r+=`} from '../types';
|
|
318
|
+
|
|
319
|
+
`,s.forEach(p=>{var O,C;let E=p.method.toUpperCase(),j=E==="GET",R=["POST","PUT","PATCH","DELETE"].includes(E),A=((O=p.parameters)==null?void 0:O.filter(L=>L.in==="path"))||[],x=((C=p.parameters)==null?void 0:C.filter(L=>L.in==="query"))||[],v=A.length>0,N=x.length>0,G=!!p.requestBody,W=p.responseType||"any";if(j){let L=`use${p.name.charAt(0).toUpperCase()+p.name.slice(1)}`;r+=`/**
|
|
320
|
+
`,p.summary&&(r+=` * ${p.summary}
|
|
321
|
+
`),r+=` * @method ${E}
|
|
322
|
+
`,r+=` * @path ${p.path}
|
|
323
|
+
`,p.tags&&p.tags.length>0&&(r+=` * @tags ${p.tags.join(", ")}
|
|
324
|
+
`),r+=` */
|
|
325
|
+
`,v||N?(r+=`export function ${L}(
|
|
326
|
+
`,r+=` params: {
|
|
327
|
+
`,v&&(r+=` url: {
|
|
328
|
+
`,A.forEach(P=>{let ge={string:"string",number:"number",integer:"number",boolean:"boolean",array:"any[]",object:"any"}[P.type||"string"]||"any",le=P.required?"":"?";r+=` ${P.name}${le}: ${ge};
|
|
329
|
+
`;}),r+=` };
|
|
330
|
+
`),N&&(r+=` query: ${p.queryType||"Record<string, any>"};
|
|
331
|
+
`),r+=` },
|
|
332
|
+
`,r+=` options?: Omit<UseQueryOptions<${W}>, 'queryKey' | 'queryFn'>
|
|
333
|
+
`,r+=`) {
|
|
334
|
+
`,r+=` return useQuery({
|
|
335
|
+
`,r+=` queryKey: ['${p.name}', params],
|
|
336
|
+
`,r+=` queryFn: () => apiClient.${p.name}(params),
|
|
337
|
+
`,r+=` ...options,
|
|
338
|
+
`,r+=` });
|
|
339
|
+
`):(r+=`export function ${L}(
|
|
340
|
+
`,r+=` options?: Omit<UseQueryOptions<${W}>, 'queryKey' | 'queryFn'>
|
|
341
|
+
`,r+=`) {
|
|
342
|
+
`,r+=` return useQuery({
|
|
343
|
+
`,r+=` queryKey: ['${p.name}'],
|
|
344
|
+
`,r+=` queryFn: () => apiClient.${p.name}(),
|
|
345
|
+
`,r+=` ...options,
|
|
346
|
+
`,r+=` });
|
|
347
|
+
`),r+=`}
|
|
348
|
+
|
|
349
|
+
`;}else if(R&&e){let L=`use${p.name.charAt(0).toUpperCase()+p.name.slice(1)}`;r+=`/**
|
|
350
|
+
`,p.summary&&(r+=` * ${p.summary}
|
|
351
|
+
`),r+=` * @method ${E}
|
|
352
|
+
`,r+=` * @path ${p.path}
|
|
353
|
+
`,p.tags&&p.tags.length>0&&(r+=` * @tags ${p.tags.join(", ")}
|
|
354
|
+
`),r+=` */
|
|
355
|
+
`;let P="void";(v||N||G)&&(P=`{
|
|
356
|
+
`,v&&(P+=` url: {
|
|
357
|
+
`,A.forEach(ee=>{let le={string:"string",number:"number",integer:"number",boolean:"boolean",array:"any[]",object:"any"}[ee.type||"string"]||"any",Oe=ee.required?"":"?";P+=` ${ee.name}${Oe}: ${le};
|
|
358
|
+
`;}),P+=` };
|
|
359
|
+
`),N&&(P+=` query: ${p.queryType||"Record<string, any>"};
|
|
360
|
+
`),G&&(P+=` data: ${p.dtoType||"any"};
|
|
361
|
+
`),P+=" }"),r+=`export function ${L}(
|
|
362
|
+
`,r+=` options?: Omit<UseMutationOptions<${W}, Error, ${P}>, 'mutationFn'>
|
|
363
|
+
`,r+=`) {
|
|
364
|
+
`,r+=` return useMutation({
|
|
365
|
+
`,r+=" mutationFn: (",P!=="void"&&(r+=`variables: ${P}`),r+=`) => {
|
|
366
|
+
`,r+=` return apiClient.${p.name}(${P!=="void"?"variables":""});
|
|
367
|
+
`,r+=` },
|
|
368
|
+
`,r+=` ...options,
|
|
369
|
+
`,r+=` });
|
|
370
|
+
`,r+=`}
|
|
371
|
+
|
|
372
|
+
`;}}),r},Ve=(s,o)=>{var i;let t=((i=o.swr)==null?void 0:i.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&&s.some(a=>["POST","PUT","PATCH","DELETE"].includes(a.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 s.forEach(a=>{a.queryType&&n.add(a.queryType),a.dtoType&&n.add(a.dtoType),a.responseType&&n.add(a.responseType);}),n.forEach(a=>{e+=` ${a},
|
|
572
|
+
`;}),e+=`} from '../types';
|
|
573
|
+
|
|
574
|
+
`,s.forEach(a=>{var G,W;let c=a.method.toUpperCase(),p=c==="GET",E=["POST","PUT","PATCH","DELETE"].includes(c),j=((G=a.parameters)==null?void 0:G.filter(O=>O.in==="path"))||[],R=((W=a.parameters)==null?void 0:W.filter(O=>O.in==="query"))||[],A=j.length>0,x=R.length>0,v=!!a.requestBody,N=a.responseType||"any";if(p){let O=`use${a.name.charAt(0).toUpperCase()+a.name.slice(1)}`;e+=`/**
|
|
575
|
+
`,a.summary&&(e+=` * ${a.summary}
|
|
576
|
+
`),e+=` * @method ${c}
|
|
577
|
+
`,e+=` * @path ${a.path}
|
|
578
|
+
`,a.tags&&a.tags.length>0&&(e+=` * @tags ${a.tags.join(", ")}
|
|
579
|
+
`),e+=` */
|
|
580
|
+
`,A||x?(e+=`export function ${O}(
|
|
581
|
+
`,e+=` params: {
|
|
582
|
+
`,A&&(e+=` url: {
|
|
583
|
+
`,j.forEach(C=>{let P={string:"string",number:"number",integer:"number",boolean:"boolean",array:"any[]",object:"any"}[C.type||"string"]||"any",ee=C.required?"":"?";e+=` ${C.name}${ee}: ${P};
|
|
584
|
+
`;}),e+=` };
|
|
585
|
+
`),x&&(e+=` query: ${a.queryType||"Record<string, any>"};
|
|
586
|
+
`),e+=` },
|
|
587
|
+
`,e+=` config?: SWRConfiguration<${N}>
|
|
588
|
+
`,e+=`) {
|
|
589
|
+
`,e+=` return useSWR(
|
|
590
|
+
`,e+=` ['${a.name}', params],
|
|
591
|
+
`,e+=` () => apiClient.${a.name}(params),
|
|
592
|
+
`,e+=` config
|
|
593
|
+
`,e+=` );
|
|
594
|
+
`):(e+=`export function ${O}(
|
|
595
|
+
`,e+=` config?: SWRConfiguration<${N}>
|
|
596
|
+
`,e+=`) {
|
|
597
|
+
`,e+=` return useSWR(
|
|
598
|
+
`,e+=` '${a.name}',
|
|
599
|
+
`,e+=` () => apiClient.${a.name}(),
|
|
600
|
+
`,e+=` config
|
|
601
|
+
`,e+=` );
|
|
602
|
+
`),e+=`}
|
|
603
|
+
|
|
604
|
+
`;}else if(E&&t){let O=`use${a.name.charAt(0).toUpperCase()+a.name.slice(1)}`;e+=`/**
|
|
605
|
+
`,a.summary&&(e+=` * ${a.summary}
|
|
606
|
+
`),e+=` * @method ${c}
|
|
607
|
+
`,e+=` * @path ${a.path}
|
|
608
|
+
`,a.tags&&a.tags.length>0&&(e+=` * @tags ${a.tags.join(", ")}
|
|
609
|
+
`),e+=` */
|
|
610
|
+
`;let C="void",L="void";(A||x||v)&&(C=`{
|
|
611
|
+
`,A&&(C+=` url: {
|
|
612
|
+
`,j.forEach(P=>{let ge={string:"string",number:"number",integer:"number",boolean:"boolean",array:"any[]",object:"any"}[P.type||"string"]||"any",le=P.required?"":"?";C+=` ${P.name}${le}: ${ge};
|
|
613
|
+
`;}),C+=` };
|
|
614
|
+
`),x&&(C+=` query: ${a.queryType||"Record<string, any>"};
|
|
615
|
+
`),v&&(C+=` data: ${a.dtoType||"any"};
|
|
616
|
+
`),C+=" }",L=`{ arg: ${C} }`),e+=`export function ${O}(
|
|
617
|
+
`,e+=` config?: SWRMutationConfiguration<${N}, Error, string, ${C}>
|
|
618
|
+
`,e+=`) {
|
|
619
|
+
`,e+=` return useSWRMutation(
|
|
620
|
+
`,e+=` '${a.name}',
|
|
621
|
+
`,e+=" async (_, ",C!=="void"&&(e+=`{ arg }: ${L}`),e+=`) => {
|
|
622
|
+
`,e+=` return apiClient.${a.name}(${C!=="void"?"arg":""});
|
|
623
|
+
`,e+=` },
|
|
624
|
+
`,e+=` config
|
|
625
|
+
`,e+=` );
|
|
626
|
+
`,e+=`}
|
|
627
|
+
|
|
628
|
+
`;}}),e},Ye=(s,o)=>{var i;let t=((i=o.rtkQuery)==null?void 0:i.apiName)||"api",e=o.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 s.forEach(a=>{a.queryType&&n.add(a.queryType),a.dtoType&&n.add(a.dtoType),a.responseType&&n.add(a.responseType);}),n.forEach(a=>{r+=` ${a},
|
|
635
|
+
`;}),r+=`} from '../types';
|
|
636
|
+
|
|
637
|
+
`,r+=`import {
|
|
638
|
+
`,s.forEach(a=>{r+=` ${a.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
|
+
`,o.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
|
+
`,o.auth.type==="bearer"?r+=" // headers.set('Authorization', `Bearer ${token}`);\n":o.auth.type==="apiKey"&&o.auth.in==="header"&&(r+=` // headers.set('${o.auth.name||"X-API-Key"}', token);
|
|
650
|
+
`),r+=` // }
|
|
651
|
+
`,r+=` return headers;
|
|
652
|
+
`,r+=` },
|
|
653
|
+
`),r+=` }),
|
|
654
|
+
`,r+=` tagTypes: [${[...new Set(s.flatMap(a=>a.tags||[]))].map(a=>`'${a}'`).join(", ")}],
|
|
655
|
+
`,r+=` endpoints: (builder) => ({
|
|
656
|
+
`,s.forEach((a,c)=>{var W,O;let p=a.method.toUpperCase(),E=p==="GET",j=((W=a.parameters)==null?void 0:W.filter(C=>C.in==="path"))||[],R=((O=a.parameters)==null?void 0:O.filter(C=>C.in==="query"))||[],A=j.length>0,x=R.length>0,v=!!a.requestBody,N=a.responseType||"any";r+=` ${a.name}: builder.${E?"query":"mutation"}<
|
|
657
|
+
`,r+=` ${N},
|
|
658
|
+
`;let G="void";if((A||x||v)&&(G=`{
|
|
659
|
+
`,A&&(G+=` url: {
|
|
660
|
+
`,j.forEach(C=>{let P={string:"string",number:"number",integer:"number",boolean:"boolean",array:"any[]",object:"any"}[C.type||"string"]||"any",ee=C.required?"":"?";G+=` ${C.name}${ee}: ${P};
|
|
661
|
+
`;}),G+=` };
|
|
662
|
+
`),x&&(G+=` query: ${a.queryType||"Record<string, any>"};
|
|
663
|
+
`),v&&(G+=` data: ${a.dtoType||"any"};
|
|
664
|
+
`),G+=" }"),r+=` ${G}
|
|
665
|
+
`,r+=` >({
|
|
666
|
+
`,r+=" query: (",G!=="void"&&(r+="arg"),r+=`) => {
|
|
667
|
+
`,A){let C=j.map(L=>`arg.url.${L.name}`).join(", ");r+=` const url = ${a.name}(${C});
|
|
668
|
+
`;}else r+=` const url = ${a.name};
|
|
669
|
+
`;r+=` return {
|
|
670
|
+
`,r+=` url,
|
|
671
|
+
`,r+=` method: '${p}',
|
|
672
|
+
`,x&&(r+=` params: arg.query,
|
|
673
|
+
`),v&&(r+=` body: arg.data,
|
|
674
|
+
`),r+=` };
|
|
675
|
+
`,r+=` },
|
|
676
|
+
`,a.tags&&a.tags.length>0&&(E?r+=` providesTags: ['${a.tags[0]}'],
|
|
677
|
+
`:r+=` invalidatesTags: ['${a.tags[0]}'],
|
|
678
|
+
`),r+=` })${c<s.length-1?",":""}
|
|
679
|
+
`;}),r+=` }),
|
|
680
|
+
`,r+=`});
|
|
681
|
+
|
|
682
|
+
`,r+=`export default ${t}Api;
|
|
683
|
+
|
|
684
|
+
`,r};});var Dn,Cn,H,Jn,Kn,In=se(()=>{bn();je();Dn=(s,o)=>{var t,e;if((t=o==null?void 0:o.folderSplit)!=null&&t.customFolder){let r=o.folderSplit.customFolder({method:s.method,path:s.path,tags:s.tags,operationId:s.operationId,summary:s.summary});if(r)return r}return (e=o==null?void 0:o.folderSplit)!=null&&e.byTags&&s.tags&&s.tags.length>0?s.tags[0].toLowerCase().replace(/\s+/g,"-"):"default"},Cn=(s,o,t,e,r)=>X(null,null,function*(){let n=$n(s,t);if(n.length===0)return;let i=t.type||"fetch";t.outputDir||D__default.default.join(r,e,"client");let c=!!(o!=null&&o.folderSplit&&(o.folderSplit.byTags||o.folderSplit.customFolder));if(`${i}${n.length}`,c){let E={};n.forEach(A=>{let x=Dn(A,o);E[x]||(E[x]=[]),E[x].push(A);});let j=Object.keys(E);for(let[A,x]of Object.entries(E)){let v=D__default.default.join(r,e,A);yield oe__default.default.promises.mkdir(v,{recursive:true}),`${i}${A}${x.length}`,yield Jn(x,o,t,v,i,A,true);}let R=D__default.default.join(r,e);yield Kn(R,j,i,o);return}let p=D__default.default.join(r,e);switch(yield oe__default.default.promises.mkdir(p,{recursive:true}),i){case "fetch":let E=He(n,t);E=E.replace("} from '../types';","} from './types';").replace("} from '../endpoints';","} from './endpoints';"),yield H(D__default.default.join(p,"clients.ts"),E,o);break;case "axios":let j=ce(n,t,false);j=j.replace("} from '../types';","} from './types';").replace("} from '../endpoints';","} from './endpoints';"),yield H(D__default.default.join(p,"clients.ts"),j,o);break;case "react-query":let R=ce(n,t,false);R=R.replace("} from '../types';","} from './types';").replace("} from '../endpoints';","} from './endpoints';"),yield H(D__default.default.join(p,"clients.ts"),R,o);let A=_e(n,t);A=A.replace("} from '../types';","} from './types';").replace("} from '../endpoints';","} from './endpoints';").replace("import apiClient from './client';","import apiClient from './clients';"),yield H(D__default.default.join(p,"hooks.ts"),A,o);break;case "swr":let x=ce(n,t,false);x=x.replace("} from '../types';","} from './types';").replace("} from '../endpoints';","} from './endpoints';"),yield H(D__default.default.join(p,"clients.ts"),x,o);let v=Ve(n,t);v=v.replace("} from '../types';","} from './types';").replace("} from '../endpoints';","} from './endpoints';").replace("import apiClient from './client';","import apiClient from './clients';"),yield H(D__default.default.join(p,"hooks.ts"),v,o);break;case "rtk-query":let N=Ye(n,t);N=N.replace("} from '../types';","} from './types';").replace("} from '../endpoints';","} from './endpoints';"),yield H(D__default.default.join(p,"api.ts"),N,o);break;default:throw new Error(`Unknown client type: ${i}`)}}),H=(s,o,t)=>X(null,null,function*(){var i,a,c,p;if(!(((i=t==null?void 0:t.customCode)==null?void 0:i.enabled)!==false)){yield oe__default.default.promises.writeFile(s,o);return}let r=null;try{r=yield oe__default.default.promises.readFile(s,"utf-8");}catch(E){}let n=exports.mergeCustomCode(o,r,{position:((a=t==null?void 0:t.customCode)==null?void 0:a.position)||"bottom",markerText:(c=t==null?void 0:t.customCode)==null?void 0:c.markerText,includeInstructions:(p=t==null?void 0:t.customCode)==null?void 0:p.includeInstructions});yield oe__default.default.promises.writeFile(s,n);}),Jn=(s,o,t,e,r,n,i=false)=>X(null,null,function*(){let a="",c="",p=i?"./types":"../types",E=i?"./endpoints":"../endpoints";switch(r){case "fetch":a=He(s,t,i),a=a.replace("} from '../types';",`} from '${p}';`).replace("} from '../endpoints';",`} from '${E}';`),yield H(D__default.default.join(e,"client.ts"),a,o);break;case "axios":a=ce(s,t,i),a=a.replace("} from '../types';",`} from '${p}';`).replace("} from '../endpoints';",`} from '${E}';`),yield H(D__default.default.join(e,"client.ts"),a,o);break;case "react-query":if(a=ce(s,t,i),a=a.replace("} from '../types';",`} from '${p}';`).replace("} from '../endpoints';",`} from '${E}';`),yield H(D__default.default.join(e,"client.ts"),a,o),c=_e(s,t),c=c.replace("} from '../types';",`} from '${p}';`).replace("} from '../endpoints';",`} from '${E}';`),i){let R=n.replace(/-/g,"_");c=c.replace("import apiClient from './client';",`import { ${R}Client as apiClient } from '../clients';`);}yield H(D__default.default.join(e,"hooks.ts"),c,o);break;case "swr":if(a=ce(s,t,i),a=a.replace("} from '../types';",`} from '${p}';`).replace("} from '../endpoints';",`} from '${E}';`),yield H(D__default.default.join(e,"client.ts"),a,o),c=Ve(s,t),c=c.replace("} from '../types';",`} from '${p}';`).replace("} from '../endpoints';",`} from '${E}';`),i){let R=n.replace(/-/g,"_");c=c.replace("import apiClient from './client';",`import { ${R}Client as apiClient } from '../clients';`);}yield H(D__default.default.join(e,"hooks.ts"),c,o);break;case "rtk-query":let j=i?Ie(re({},t),{rtkQuery:Ie(re({},t.rtkQuery),{apiName:n.replace(/-/g,"_")})}):t;c=Ye(s,j),c=c.replace("} from '../types';",`} from '${p}';`).replace("} from '../endpoints';",`} from '${E}';`),yield H(D__default.default.join(e,"api.ts"),c,o);break;default:throw new Error(`Unknown client type: ${r}`)}}),Kn=(s,o,t,e)=>X(null,null,function*(){var n;if(t==="rtk-query"){let i=`// Generated RTK Query APIs
|
|
685
|
+
`;i+=`// This file was auto-generated.
|
|
686
|
+
`,i+=`// Aggregates all API slices for easy Redux store setup
|
|
687
|
+
|
|
688
|
+
`,o.forEach(a=>{let c=a.replace(/-/g,"_");i+=`import ${c}Api from './${a}/api';
|
|
689
|
+
`;}),i+=`
|
|
690
|
+
// Export all API slices
|
|
691
|
+
`,o.forEach(a=>{let c=a.replace(/-/g,"_");i+=`export { default as ${c}Api } from './${a}/api';
|
|
692
|
+
`;}),i+=`
|
|
693
|
+
/**
|
|
694
|
+
`,i+=` * Configure Redux store with all API slices
|
|
695
|
+
`,i+=` *
|
|
696
|
+
`,i+=` * @example
|
|
697
|
+
`,i+=` * import { configureStore } from '@reduxjs/toolkit';
|
|
698
|
+
`,i+=` * import { setupApiStore } from './apis';
|
|
699
|
+
`,i+=` *
|
|
700
|
+
`,i+=` * export const store = configureStore({
|
|
701
|
+
`,i+=` * reducer: setupApiStore.reducer,
|
|
702
|
+
`,i+=` * middleware: (getDefaultMiddleware) =>
|
|
703
|
+
`,i+=` * getDefaultMiddleware().concat(setupApiStore.middleware),
|
|
704
|
+
`,i+=` * });
|
|
705
|
+
`,i+=` */
|
|
706
|
+
`,i+=`export const setupApiStore = {
|
|
707
|
+
`,i+=` reducer: {
|
|
708
|
+
`,o.forEach(a=>{let c=a.replace(/-/g,"_");i+=` [${c}Api.reducerPath]: ${c}Api.reducer,
|
|
709
|
+
`;}),i+=` },
|
|
710
|
+
`,i+=` middleware: [
|
|
711
|
+
`,o.forEach(a=>{let c=a.replace(/-/g,"_");i+=` ${c}Api.middleware,
|
|
712
|
+
`;}),i+=` ],
|
|
713
|
+
`,i+=`};
|
|
714
|
+
`,yield H(D__default.default.join(s,"apis.ts"),i,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"?o.forEach(i=>{let a=i.replace(/-/g,"_");r+=`export { default as ${a}Client } from './${i}/client';
|
|
719
|
+
`;}):(o.forEach(i=>{let a=i.replace(/-/g,"_"),c=`${a.charAt(0).toUpperCase()+a.slice(1)}ApiClient`;r+=`import ${c} from './${i}/client';
|
|
720
|
+
`;}),r+=`
|
|
721
|
+
// Create client instances
|
|
722
|
+
`,o.forEach(i=>{let a=i.replace(/-/g,"_"),c=`${a.charAt(0).toUpperCase()+a.slice(1)}ApiClient`;r+=`export const ${a}Client = new ${c}();
|
|
723
|
+
`;})),t==="fetch"&&(r+=`
|
|
724
|
+
// Import clients for aggregation
|
|
725
|
+
`,o.forEach(i=>{let a=i.replace(/-/g,"_");r+=`import ${a}_client from './${i}/client';
|
|
726
|
+
`;})),r+=`
|
|
727
|
+
// Aggregate all client instances
|
|
728
|
+
`,r+=`export const clients = {
|
|
729
|
+
`,o.forEach(i=>{let a=i.replace(/-/g,"_");t==="fetch"?r+=` ${a}: ${a}_client,
|
|
730
|
+
`:r+=` ${a}: ${a}Client,
|
|
731
|
+
`;}),r+=`};
|
|
732
|
+
|
|
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
|
+
`,o.forEach(i=>{let a=i.replace(/-/g,"_");r+=` ${a}Client.updateConfig(config);
|
|
744
|
+
`;}),r+=`};
|
|
745
|
+
|
|
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
|
+
`,o.forEach(i=>{let a=i.replace(/-/g,"_");r+=` ${a}_client.setApiConfig(config);
|
|
757
|
+
`;}),r+=`};
|
|
76
758
|
|
|
77
|
-
|
|
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=o[0])==null?void 0:n.replace(/-/g,"_")}.someMethod(...);
|
|
770
|
+
`,yield H(D__default.default.join(s,"clients.ts"),r,e),t==="react-query"||t==="swr"){let i=`// Generated Hooks Aggregator
|
|
771
|
+
`;i+=`// This file was auto-generated.
|
|
772
|
+
`,i+=`// Aggregates all folder-split hooks
|
|
78
773
|
|
|
79
|
-
|
|
80
|
-
|
|
774
|
+
`,o.forEach(a=>{i+=`export * from './${a}/hooks';
|
|
775
|
+
`;}),i+=`
|
|
776
|
+
// Example usage:
|
|
777
|
+
`,i+=`// import { useGetSomething } from './hooks';
|
|
778
|
+
`,yield H(D__default.default.join(s,"hooks.ts"),i,e);}});});var xn=se(()=>{});var wn={};an(wn,{interactiveInit:()=>Hn});function Hn(){return X(this,null,function*(){try{let s=yield Tn__default.default([{type:"select",name:"configFormat",message:"What configuration format would you like to use?",choices:[{title:"TypeScript (openapi.sync.ts)",value:"typescript"},{title:"JSON (openapi.sync.json)",value:"json"},{title:"JavaScript (openapi.sync.js)",value:"javascript"}],initial:0},{type:"select",name:"apiSource",message:"Where is your OpenAPI specification?",choices:[{title:"URL (e.g., https://api.example.com/openapi.json)",value:"url"},{title:"Local file",value:"file"}],initial:0},{type:a=>a==="url"?"text":null,name:"apiUrl",message:"Enter the OpenAPI specification URL:",validate:a=>a.startsWith("http://")||a.startsWith("https://")?!0:"Please enter a valid URL starting with http:// or https://"},{type:(a,c)=>c.apiSource==="file"?"text":null,name:"apiFile",message:"Enter the path to your OpenAPI file:",validate:a=>a.trim()!==""?!0:"Please enter a valid file path"},{type:"text",name:"apiName",message:"What would you like to name this API?",initial:"myapi",validate:a=>/^[a-zA-Z0-9_-]+$/.test(a)?!0:"API name must contain only letters, numbers, hyphens, and underscores"},{type:"text",name:"outputFolder",message:"Where should generated files be saved?",initial:"./src/api",validate:a=>{if(!a||a.trim()==="")return "Output folder cannot be empty";let c=D__default.default.normalize(a);if(c==="/"||c==="C:\\"||c==="\\")return "Cannot use filesystem root directory. Please use a project subfolder like './src/api'";if(D__default.default.isAbsolute(a)){let p=process.cwd();if(!a.startsWith(p))return "\u26A0\uFE0F Warning: Using absolute path outside project directory. Recommended: use relative path like './src/api'"}return !0}},{type:"confirm",name:"enableFolderSplit",message:"Organize generated code into folders by OpenAPI tags?",initial:!1},{type:"confirm",name:"generateClient",message:"Generate API client code?",initial:!0},{type:a=>a?"select":null,name:"clientType",message:"Which client type would you like?",choices:[{title:"React Query (Recommended for React)",value:"react-query"},{title:"RTK Query (Redux Toolkit)",value:"rtk-query"},{title:"SWR",value:"swr"},{title:"Fetch API",value:"fetch"},{title:"Axios",value:"axios"}],initial:0},{type:"confirm",name:"enableValidation",message:"Enable runtime validation schemas?",initial:!0},{type:a=>a?"select":null,name:"validationLibrary",message:"Which validation library?",choices:[{title:"Zod (Recommended)",value:"zod"},{title:"Yup",value:"yup"},{title:"Joi",value:"joi"}],initial:0},{type:"confirm",name:"enableCustomCode",message:"Enable custom code preservation?",initial:!0},{type:"confirm",name:"typesUseOperationId",message:"Use operationId from OpenAPI spec for type names?",initial:!0},{type:"text",name:"typesPrefix",message:"Prefix for TypeScript interface names (leave empty for none):",initial:"I"},{type:"confirm",name:"excludeEndpointsByTags",message:"Exclude endpoints by tags (e.g., deprecated, internal)?",initial:!1},{type:a=>a?"text":null,name:"excludeTags",message:"Enter tags to exclude (comma-separated):",initial:"deprecated,internal"},{type:"confirm",name:"showCurlInDocs",message:"Include cURL examples in generated documentation?",initial:!0},{type:"number",name:"refetchInterval",message:"Refetch interval in milliseconds (0 to disable auto-refresh):",initial:5e3,min:0},{type:"confirm",name:"runSync",message:"Run initial sync after setup?",initial:!0}],{onCancel:()=>{throw te||process.exit(0),new Error("Setup cancelled")}}),o={refetchInterval:s.refetchInterval||void 0,folder:s.outputFolder,api:{[s.apiName]:s.apiUrl||s.apiFile}};s.enableFolderSplit&&(o.folderSplit={byTags:!0}),o.types={name:{prefix:s.typesPrefix||"",useOperationId:s.typesUseOperationId}},o.endpoints={name:{useOperationId:s.typesUseOperationId},doc:{showCurl:s.showCurlInDocs}},s.excludeEndpointsByTags&&s.excludeTags&&(o.endpoints.exclude={tags:s.excludeTags.split(",").map(a=>a.trim())}),s.generateClient&&s.clientType&&(o.clientGeneration={enabled:!0,type:s.clientType,outputDir:D__default.default.join(s.outputFolder,s.apiName,"client")},s.clientType==="react-query"?o.clientGeneration.reactQuery={version:5,mutations:!0}:s.clientType==="swr"&&(o.clientGeneration.swr={mutations:!0})),s.enableValidation&&s.validationLibrary&&(o.validations={library:s.validationLibrary}),s.enableCustomCode&&(o.customCode={enabled:!0,position:"bottom"});let t,e;s.configFormat==="json"?(e="openapi.sync.json",t=JSON.stringify(o,null,2)):s.configFormat==="typescript"?(e="openapi.sync.ts",t=`import { IConfig } from "openapi-sync";
|
|
81
779
|
|
|
82
|
-
|
|
780
|
+
const config: IConfig = ${JSON.stringify(o,null,2)};
|
|
83
781
|
|
|
84
|
-
|
|
782
|
+
export default config;
|
|
783
|
+
`):(e="openapi.sync.js",t=`module.exports = ${JSON.stringify(o,null,2)};
|
|
784
|
+
`);let r=D__default.default.join(process.cwd(),e);if(oe__default.default.existsSync(r)&&!(yield Tn__default.default({type:"confirm",name:"value",message:`${e} already exists. Overwrite?`,initial:!1})).value)throw te||process.exit(0),new Error("Configuration file not created");oe__default.default.writeFileSync(r,t,"utf-8"),te||`${e}`;let n=D__default.default.isAbsolute(s.outputFolder)?s.outputFolder:D__default.default.join(process.cwd(),s.outputFolder);if(!oe__default.default.existsSync(n))try{oe__default.default.mkdirSync(n,{recursive:!0}),te||`${s.outputFolder}`;}catch(a){te||`${a.message}`;}let i=D__default.default.join(process.cwd(),".gitignore");if(oe__default.default.existsSync(i)&&(oe__default.default.readFileSync(i,"utf-8").includes(s.outputFolder)||oe__default.default.appendFileSync(i,`
|
|
785
|
+
# OpenAPI Sync generated files
|
|
786
|
+
${s.outputFolder}
|
|
787
|
+
`)),te||(`${e}`,s.generateClient&&s.clientType&&(s.clientType==="axios"||s.clientType==="react-query"||s.clientType==="swr"||s.clientType),s.enableValidation&&s.validationLibrary&&(s.generateClient,`${s.validationLibrary}`)),s.runSync&&!te)try{let{Init:a,GenerateClient:c}=yield Promise.resolve().then(()=>(An(),vn));yield a({refetchInterval:s.refetchInterval}),s.generateClient&&s.clientType&&(yield c({type:s.clientType,apiName:s.apiName}));}catch(a){console.error(`
|
|
788
|
+
\u274C Error during sync:`,a.message),a.stack&&process.env.DEBUG&&console.error(a.stack);}else te||(s.generateClient||s.enableValidation,s.generateClient&&s.clientType&&(s.generateClient||s.enableValidation,`${s.clientType}`));te||(`${s.outputFolder}${s.apiName}`,s.generateClient&&`${s.outputFolder}${s.apiName}`,s.generateClient&&s.clientType&&`${s.clientType}`);}catch(s){throw te||(console.error(`
|
|
789
|
+
\u274C Error during setup:`,s.message),process.exit(1)),s}})}var te,En=se(()=>{te=process.env.NODE_ENV==="test"||process.env.JEST_WORKER_ID!==void 0;});var vn={};an(vn,{GenerateClient:()=>exports.GenerateClient,Init:()=>exports.Init,InteractiveInit:()=>exports.InteractiveInit,JSONStringify:()=>exports.JSONStringify,capitalize:()=>exports.capitalize,createCustomCodeMarker:()=>exports.createCustomCodeMarker,extractCustomCode:()=>exports.extractCustomCode,getEndpointDetails:()=>exports.getEndpointDetails,getNestedValue:()=>Mn,isJson:()=>exports.isJson,isYamlString:()=>exports.isYamlString,mergeCustomCode:()=>exports.mergeCustomCode,renderTypeRefMD:()=>exports.renderTypeRefMD,variableName:()=>exports.variableName,variableNameChar:()=>exports.variableNameChar,yamlStringToJson:()=>exports.yamlStringToJson});var Re,On;exports.Init=void 0;exports.GenerateClient=void 0;exports.InteractiveInit=void 0;var An=se(()=>{hn();ze();We();In();xn();je();Ue();Re=process.cwd(),On=()=>{let s;try{xe("esbuild-register");}catch(i){throw i}let o=D__default.default.join(Re,"openapi.sync.js"),t=D__default.default.join(Re,"openapi.sync.ts"),e=D__default.default.join(Re,"openapi.sync.json"),r=[o,t,e];try{for(let i of r)oe__default.default.existsSync(i)&&(s=xe(i),Object.keys(s).length===1&&s.default&&(s=s.default));}catch(i){}typeof s=="function"&&(s=s());let n=s;if(!n)throw new Error("No config found");return n},exports.Init=s=>X(null,null,function*(){let o=On(),t=Object.keys(o.api),e=s&&"refetchInterval"in s&&!isNaN(s==null?void 0:s.refetchInterval)?s.refetchInterval:o.refetchInterval;Qe();for(let r=0;r<t.length;r+=1){let n=t[r],i=o.api[n];yield Ke(i,n,o,e);}}),exports.GenerateClient=s=>X(null,null,function*(){let o=On(),t=s.apiName?[s.apiName]:Object.keys(o.api);for(let r of t)if(!o.api[r])throw new Error(`API "${r}" not found in configuration. Available APIs: ${Object.keys(o.api).join(", ")}`);Qe();for(let r of t){let n=o.api[r];yield Ke(n,r,o);}let e=(o==null?void 0:o.folder)||"api";for(let r of t){let n=yn(r);if(n.length===0){continue}`${n.length}${r}`;let i=re(re(re(re(Ie(re({enabled:true},o.clientGeneration||{}),{type:s.type}),s.outputDir&&{outputDir:s.outputDir}),s.baseURL&&{baseURL:s.baseURL}),s.tags&&{tags:s.tags}),s.endpoints&&{endpoints:s.endpoints});yield Cn(n,o,i,r,D__default.default.join(Re,e));}}),exports.InteractiveInit=()=>X(null,null,function*(){let{interactiveInit:s}=yield Promise.resolve().then(()=>(En(),wn));yield s();});});An();exports.getNestedValue=Mn;
|