@fxri/swagger2api 1.3.0 → 1.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,3 +1,20 @@
1
- var M=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});import it from"axios";import{execSync as ct}from"child_process";import pt from"os";import O from"fs";import S from"path";import Se from"prompts";import{generateApi as ut}from"swagger-typescript-api";var q=e=>/^(https?:\/\/|:?\/\/)/.test(e);import k from"fs";import be from"url";import F from"path";var L={param:process.argv.filter((e,t)=>t>1)};function J(e,t="value",r={}){Array.isArray(e)||(e=[e]);let n;return L.param.forEach((s,o)=>{if(e.includes(s))["value"].includes(t)?n=L.param[o+1]:["array"].includes(t)?n=Array.from({length:r.length??1}).map((a,i)=>L.param[o+i+1]):n=!["false"].includes(L.param[o+1]);else return}),n}function d(e){return J(e,"key")}function w(e){return J(e,"value")}function te(e,t={}){return J(e,"array",t)??[]}function H(e,t){let r=F.dirname(e);k.existsSync(r)||k.mkdirSync(r,{recursive:!0}),k.writeFileSync(e,t)}function Ae(){return typeof M<"u"&&typeof module<"u"?__filename:be.fileURLToPath(import.meta.url)}function re(){return typeof M<"u"&&typeof module<"u"?__dirname:F.dirname(Ae())}function ne(e=process.cwd()){let t=[],r=n=>{for(let s of k.readdirSync(n,{withFileTypes:!0})){if(s.name.startsWith("."))continue;let o=F.join(n,s.name);if(s.isDirectory()){if(s.name==="node_modules")continue;r(o)}else s.isFile()&&s.name.startsWith("saconfig")&&s.name.endsWith(".json")&&t.push(F.relative(e,o))}};return r(e),t.sort()}function G(e){return JSON.stringify(e).slice(1,-1)}function se(e){return e.replace(/\\/g,"\\\\").replace(/`/g,"\\`").replace(/\$\{/g,"\\${")}import*as ie from"dns/promises";import*as B from"net";var je=5,E=async e=>{try{return(await ie.lookup(e,{all:!0,verbatim:!0})).map(r=>r.address)}catch{return[]}};function W(e){let t=e.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);if(!t)return!1;let r=t.slice(1).map(Number);if(r.some(o=>o>255))return!1;let[n,s]=r;return n===0||n===10||n===127||n===169&&s===254||n===172&&s>=16&&s<=31||n===192&&s===168}function Ce(e){let t=e.toLowerCase();if(t==="::"||t==="::1"||t.startsWith("fe80:"))return!0;let r=t.split(":")[0]??"";if(r>="fc00"&&r<="fdff")return!0;let n=t.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/);if(n?.[1])return W(n[1]);let s=t.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/);if(s?.[1]&&s?.[2]){let o=parseInt(s[1],16),a=parseInt(s[2],16);return W(`${o>>8&255}.${o&255}.${a>>8&255}.${a&255}`)}return!1}function oe(e){let t=B.isIP(e);return t===4?W(e):t===6?Ce(e):!1}function Ee(e){let t=e.toLowerCase();return t==="localhost"||t.endsWith(".localhost")}async function Ie(e,t=E){let r;try{r=new URL(e)}catch{return!1}if(r.protocol!=="http:"&&r.protocol!=="https:")return!1;let n=r.hostname.startsWith("[")&&r.hostname.endsWith("]")?r.hostname.slice(1,-1):r.hostname;if(Ee(n))return!1;if(B.isIP(n))return!oe(n);let s=await t(n);return s.length===0?!1:s.every(o=>!oe(o))}function Oe(e,t){if(typeof t!="string")return!1;try{let r=new URL(e),n=new URL(t);return r.protocol===n.protocol&&r.host===n.host}catch{return!1}}function ae(e){return e.split("#")[0]||e}async function z(e,t,r=E){let{specSourceUrl:n,allowExplicitSpecUrl:s=!1}=t;return s&&typeof n=="string"&&ae(e)===ae(n)||typeof n=="string"&&Oe(e,n)?!0:Ie(e,r)}function Le(e,t){try{return new URL(e,t).toString()}catch{return null}}async function ce(e,t,r,n=E,s=fetch){let o=e,a=0;for(;;){if(!await z(o,{specSourceUrl:r.specSourceUrl,allowExplicitSpecUrl:r.allowExplicitSpecUrl&&a===0},n))return null;let u=await s(o,{...t,redirect:"manual"});if(u.status>=300&&u.status<400){let c=u.headers.get("location");if(!c||a>=je)return null;let m=Le(c,o);if(!m)return null;o=m,a+=1;continue}return u}}var P=/["\\\u0000-\u001f]/;function ke(e){if(e.paths&&typeof e.paths=="object"){let t={};for(let[r,n]of Object.entries(e.paths))t[se(r)]=n;e.paths=t}if(Array.isArray(e.servers))for(let t of e.servers)t&&typeof t.url=="string"&&(t.url=G(t.url));V(e)}function V(e){if(Array.isArray(e)){e.forEach(t=>V(t));return}if(!(!e||typeof e!="object"))for(let t of Object.keys(e)){let r=e[t];t==="enum"&&Array.isArray(r)?e[t]=r.map(n=>typeof n=="string"?G(n):n):t==="default"&&typeof r=="string"?e[t]=G(r):V(r)}}function Fe(e){let t=[],r=(n,s)=>{if(Array.isArray(n)){n.forEach((o,a)=>r(o,`${s}[${a}]`));return}if(!(!n||typeof n!="object")){if(n.properties&&typeof n.properties=="object")for(let o of Object.keys(n.properties))P.test(o)&&t.push(`${s}.properties\uFF1A\u5C5E\u6027\u540D\u542B\u975E\u6CD5\u5B57\u7B26\uFF1A${JSON.stringify(o)}`);if(Array.isArray(n.required))for(let o of n.required)typeof o=="string"&&P.test(o)&&t.push(`${s}.required\uFF1A\u5FC5\u586B\u5B57\u6BB5\u540D\u542B\u975E\u6CD5\u5B57\u7B26\uFF1A${JSON.stringify(o)}`);if(n.discriminator&&typeof n.discriminator=="object"&&(typeof n.discriminator.propertyName=="string"&&P.test(n.discriminator.propertyName)&&t.push(`${s}.discriminator.propertyName\uFF1A\u542B\u975E\u6CD5\u5B57\u7B26\uFF1A${JSON.stringify(n.discriminator.propertyName)}`),n.discriminator.mapping&&typeof n.discriminator.mapping=="object"))for(let o of Object.keys(n.discriminator.mapping))P.test(o)&&t.push(`${s}.discriminator.mapping\uFF1A\u952E\u542B\u975E\u6CD5\u5B57\u7B26\uFF1A${JSON.stringify(o)}`);for(let o of Object.keys(n))r(n[o],`${s}.${o}`)}};return r(e,"#"),t}async function Ge(e,t={}){let r=[],n={baseUrl:t.baseUrl,resolve:t.resolve??E,fetchImpl:t.fetchImpl??fetch,docs:new Map,errors:r},s=async(a,i,u)=>{if(Array.isArray(a)){let m=[];for(let l=0;l<a.length;l+=1)m.push(await s(a[l],`${i}[${l}]`,u));return m}if(!a||typeof a!="object")return a;let c=a.$ref;if(typeof c=="string"&&!c.startsWith("#")){let m=await o(c,i,u);return m===null?a:s(m,i,u)}for(let m of Object.keys(a))a[m]=await s(a[m],`${i}.${m}`,u);return a},o=async(a,i,u)=>{if(!/^https?:\/\//i.test(a))return r.push(`${i}\uFF1A\u4E0D\u652F\u6301\u7684\u5916\u90E8\u5F15\u7528\uFF08\u4EC5\u5141\u8BB8\u6587\u6863\u5185 #/ \u6216 http(s)\uFF09\uFF1A${a}`),null;let c=a.indexOf("#"),m=c===-1?a:a.slice(0,c),l=c===-1?"":a.slice(c+1),g;try{g=n.baseUrl?new URL(m,n.baseUrl).toString():m}catch{return r.push(`${i}\uFF1A\u65E0\u6CD5\u89E3\u6790\u7684\u5F15\u7528\u5730\u5740\uFF1A${a}`),null}let y=`${g}#${l}`;if(u.includes(y))return r.push(`${i}\uFF1A\u68C0\u6D4B\u5230\u5F15\u7528\u73AF\uFF1A${[...u,y].join(" -> ")}`),null;if(!await z(g,{specSourceUrl:n.baseUrl},n.resolve))return r.push(`${i}\uFF1A\u62D2\u7EDD\u62C9\u53D6\u975E\u516C\u7F51\u6216\u975E\u4FE1\u4EFB\u6765\u6E90\u7684\u5916\u90E8\u5F15\u7528\uFF1A${a}`),null;let x=await Pe(g,n);if(!x)return null;let $=Ue(x,l);if($===void 0)return r.push(`${i}\uFF1A\u5F15\u7528\u7247\u6BB5\u4E0D\u5B58\u5728\uFF1A${a}`),null;let v=await s(structuredClone($),i,[...u,y]),b=_e(e,l,v,g);return b?{$ref:`#/components/schemas/${b}`}:v};return await s(e,"#",[]),r}async function Pe(e,t){if(t.docs.has(e))return t.docs.get(e);let r=await ce(e,{},{specSourceUrl:t.baseUrl},t.resolve,t.fetchImpl);if(!r?.ok)return t.errors.push(`\u5916\u90E8\u5F15\u7528\u62C9\u53D6\u5931\u8D25\uFF1A${e}`),null;let n=await r.text();try{let s=JSON.parse(n);return t.docs.set(e,s),s}catch{return t.errors.push(`\u5916\u90E8\u5F15\u7528\u6587\u6863\u4EC5\u652F\u6301 JSON \u683C\u5F0F\uFF1A${e}`),null}}function Ue(e,t){if(!t||t==="/")return e;let r=e;for(let n of t.replace(/^\//,"").split("/")){if(r===null||typeof r!="object")return;let s=decodeURIComponent(n).replace(/~1/g,"/").replace(/~0/g,"~");r=r[s]}return r}function _e(e,t,r,n){let s=t.match(/^\/components\/schemas\/([^/]+)$/);if(!s)return null;let o=decodeURIComponent(s[1]).replace(/~1/g,"/").replace(/~0/g,"~");e.components=e.components??{},e.components.schemas=e.components.schemas??{};let a=e.components.schemas;if(a[o]===void 0)return a[o]=r,o;if(JSON.stringify(a[o])===JSON.stringify(r))return o;let i=(n.split("/").pop()??"ref").replace(/\.[^.]+$/,"").replace(/[^A-Za-z0-9_$]/g,"_")||"ref",u=`${o}_${i}`,c=2;for(;a[u]!==void 0&&JSON.stringify(a[u])!==JSON.stringify(r);)u=`${o}_${i}_${c}`,c+=1;return a[u]=r,u}async function pe(e,t={}){let r=await Ge(e,t);return ke(e),{errors:[...r,...Fe(e)]}}import X from"fs";import De from"os";import I from"path";var Te=".swagger2apirc.json",Me=".swagger2apirc.local.json",qe=".swagger2apirc.json";function K(e,t,r){let n={layer:t,file:e,hit:!1,sections:[],config:null};if(!e||!X.existsSync(e))return n;try{let s=JSON.parse(X.readFileSync(e,"utf8"));return!s||typeof s!="object"||Array.isArray(s)?(r.push(`${e}\uFF1A\u6839\u8282\u70B9\u5FC5\u987B\u662F\u5BF9\u8C61\uFF0C\u5DF2\u5FFD\u7565\u8BE5\u5C42`),{...n,hit:!1}):{layer:t,file:e,hit:!0,sections:Object.keys(s),config:s}}catch(s){return r.push(`${e}\uFF1A\u89E3\u6790\u5931\u8D25\uFF08${s.message}\uFF09\uFF0C\u5DF2\u5FFD\u7565\u8BE5\u5C42`),n}}function ue(e,t){let r=I.resolve(t);for(;;){let n=I.join(r,e);if(X.existsSync(n))return n;let s=I.dirname(r);if(s===r)return null;r=s}}function Je(e,t){if(!e)return t?{...t}:null;if(!t)return{...e};let r={...e};for(let[n,s]of Object.entries(t))r[n]=s;return r}function He(e,t){if(!e)return t?{...t}:null;if(!t)return{...e};let r={...e};for(let[n,s]of Object.entries(t)){let o=r[n];r[n]=o&&typeof o=="object"&&!Array.isArray(o)&&s&&typeof s=="object"&&!Array.isArray(s)?{...o,...s}:s}return r}function le(e=process.cwd(),t={}){let r=[],n=K(I.join(t.homeDir??De.homedir(),qe),"\u5168\u5C40\u5C42",r),s=t.projectFile?I.resolve(t.projectFile):ue(Te,e),o=K(s,"\u9879\u76EE\u5C42",r),a=K(ue(Me,e),"\u672C\u5730\u5C42",r),i=He(Je(n.config,o.config),a.config);return{global:n,project:o,local:a,merged:i,warnings:r}}var We=[{env:"FX_S2A_INPUT",key:"input.url",type:"string"},{env:"FX_S2A_OUTPUT",key:"output.dir",type:"string"},{env:"FX_S2A_NAME",key:"output.name",type:"string"},{env:"FX_S2A_CLIENT",key:"client.type",type:"string"},{env:"FX_S2A_LANGUAGE",key:"language.target",type:"string"},{env:"FX_S2A_CLEAN",key:"output.clean",type:"boolean"}];function Be(e,t,r){let n=t.split("."),s=e;n.forEach((o,a)=>{if(a===n.length-1){s[o]=r;return}(!s[o]||typeof s[o]!="object")&&(s[o]={}),s=s[o]})}function fe(e,t=process.env){let r=e?structuredClone(e):{};for(let n of We){let s=t[n.env];s===void 0||s===""||Be(r,n.key,n.type==="boolean"?!["0","false"].includes(s.toLowerCase()):s)}return r}function ge(e,t){let r=e?structuredClone(e):{};if(!t)return r;let n=r.profiles?.[t];if(!n||typeof n!="object")return r;for(let[s,o]of Object.entries(n)){if(s==="profiles")continue;let a=r[s];r[s]=a&&typeof a=="object"&&!Array.isArray(a)&&o&&typeof o=="object"&&!Array.isArray(o)?{...a,...o}:o}return r}function me(e=process.argv.slice(2)){let t=r=>r.reduce((n,s)=>n??(e.includes(s)?e[e.indexOf(s)+1]:void 0),void 0);return{configFile:t(["--config","-c"]),profile:t(["--profile"])}}import N from"fs";import _ from"path";var ze=new Set(["index","datacontracts","httpclient"]),Ve=new Set(["HttpClient","RequestParams","ContentType","AxiosRequestConfig","AxiosResponse"]),Ke=new Set(["con","prn","aux","nul",...Array.from({length:9},(e,t)=>`com${t+1}`),...Array.from({length:9},(e,t)=>`lpt${t+1}`)]),de=64;function A(e){return String(e).normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N}]+/gu,"")}function Xe(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").split(" ").filter(Boolean)}function Ze(e){let t=e.normalize("NFKC"),r=[];for(let n of t.matchAll(/[A-Za-z0-9]+|[\p{L}\p{N}]+/gu)){let s=n[0];/^[A-Za-z0-9]+$/.test(s)?r.push(...Xe(s)):r.push(s)}return r}function Qe(e){return e.map((t,r)=>{if(/^[A-Za-z0-9]+$/.test(t)){let n=t.toLowerCase();return r===0?n:n.charAt(0).toUpperCase()+n.slice(1)}return t}).join("")}function Ye(e){let t=2166136261;for(let r of e)t^=r.codePointAt(0)??0,t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0").slice(0,6)}function ye(e){let t=[],r=Ze(e),n=Qe(r);return n?(/^[0-9]/.test(n)&&(n=`g${n}`,t.push("\u6570\u5B57\u5F00\u5934")),[...n].length>de&&(n=[...n].slice(0,de-6).join("")+Ye(e),t.push("\u8D85\u957F\u622A\u65AD")),{slug:n,reason:t.join("\u3001")}):{slug:"",reason:"\u540D\u79F0\u4E0D\u542B\u53EF\u7528\u5B57\u7B26"}}function Z(e){return e.charAt(0).toUpperCase()+e.slice(1)}function he(e,t={}){let r=[],n=[],s=[...new Set(e)].sort((g,y)=>g<y?-1:g>y?1:0),o=new Map,a=new Set;for(let[g,y]of Object.entries(t))o.set(g,y),o.set(A(g),y);let i=new Set,u=[],c=(g,y=2)=>{let h=g,x=y;for(;i.has(h.toLowerCase());)h=`${g}${x}`,x+=1;return i.add(h.toLowerCase()),h},m=new Map;for(let g of s){let y=o.get(g)??o.get(A(g));if(y===void 0)continue;a.add(g),a.add(A(g));let{slug:h}=ye(y);if(!h){r.push(`\u624B\u5DE5\u540D\u4E0D\u53EF\u7528\uFF1A${g} \u2192 ${y}`);continue}let x=m.get(h.toLowerCase());x?r.push(`\u624B\u5DE5\u540D\u51B2\u7A81\uFF1A${x} \u4E0E ${g} \u90FD\u6307\u5411 ${h}`):m.set(h.toLowerCase(),g);let $=c(h),v=Z($);u.push({raw:g,key:A(g),fileName:v,className:v,property:$,reason:$===h?"\u624B\u5DE5\u6307\u5B9A":"\u624B\u5DE5\u6307\u5B9A\u3001\u4E0E\u5DF2\u6709\u7EC4\u91CD\u540D",source:"manual"})}let l=1;for(let g of s){if(u.some(ve=>ve.raw===g))continue;let{slug:y,reason:h}=ye(g),x=!y,$=y;if(x){for(;i.has(`group${l}`.toLowerCase());)l+=1;$=`group${l}`,l+=1}let v=ze.has($.toLowerCase())||Ke.has($.toLowerCase())||Ve.has(Z($)),b=v?c(`${$}2`,3):c($),ee=Z(b),T=[h];v?T.push("\u4E0E\u4FDD\u7559\u540D\u51B2\u7A81"):b!==$&&T.push("\u4E0E\u5DF2\u6709\u7EC4\u91CD\u540D"),u.push({raw:g,key:A(g),fileName:ee,className:ee,property:b,reason:T.filter(Boolean).join("\u3001"),source:x?"fallback":"auto"})}for(let g of Object.keys(t))!a.has(g)&&!a.has(A(g))&&n.push(`grouping.names \u4E2D\u7684\u952E\u672A\u51FA\u73B0\u5728\u672C\u6B21\u5206\u7EC4\u7ED3\u679C\uFF1A${g}`);return{entries:u,errors:r,warnings:n}}function xe(e){let t={};for(let r of e)t[r.fileName]=r.className,t[r.fileName.charAt(0).toLowerCase()+r.fileName.slice(1)]=r.className;return t}function U(e,t,r){let n=new Set(t.map(o=>`${o.fileName}${r}`)),s=new Set([`index${r}`,"index.d.ts",`data-contracts${r}`,`http-client${r}`,`route-types${r}`]);return e.filter(o=>o.endsWith(r)&&!o.endsWith(`.d${r}`)&&!n.has(o)&&!s.has(o)&&!o.endsWith(`_Route${r}`))}var et=new Set(["index","data-contracts","http-client"]);function tt(e){return String(e).split(/[^A-Za-z0-9]+/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join("")}function rt(e,t){if(!N.existsSync(e))return[];let r=[];for(let n of N.readdirSync(e)){if(!n.endsWith(t)||n.endsWith(`.d${t}`))continue;let s=n.slice(0,-t.length);if(et.has(s)||s.endsWith("Route"))continue;let o=tt(s);r.push({base:s,className:o,property:o.charAt(0).toLowerCase()+o.slice(1)})}return r.sort((n,s)=>n.base.localeCompare(s.base))}function $e(e){return e.map(t=>({base:t.fileName,className:t.className,property:t.property}))}function nt(e,t,r,n){let s=t||"Api",o=e.map(c=>{let m=c.className===s?`${c.className}Module`:c.className,l=`${r?`${r.replace(/\\/g,"/")}/`:""}${c.base}`;return`import { ${c.className}${m===c.className?"":` as ${m}`} } from "./${l}"`}),a=e.map(c=>`${c.property} = new ${c.className===s?`${c.className}Module`:c.className}()`),i=e.map(c=>` this.${c.property}.instance = this.instance`);return['import { HttpClient } from "./http-client"',...o,'export * from "./data-contracts"',"","/** \u805A\u5408\u5165\u53E3\uFF1A\u5404\u6A21\u5757\u5171\u4EAB\u540C\u4E00\u4E2A\u8BF7\u6C42\u5B9E\u4F8B */",`export class ${s}<SecurityDataType = unknown> extends HttpClient<SecurityDataType> {`,...a.map(c=>` ${c}`),""," constructor(config?: any) {"," super(config)",...i," }","}",""].join(`
2
- `)}function Q(e,t,r,n){let s=r?".js":".ts",o=n??rt(e,s);if(o.length===0)return[];let a=nt(o,t,"",r),i=[],u=_.join(e,`index${s}`);if(N.writeFileSync(u,a),i.push(u),r){let c=st(o,t),m=_.join(e,"index.d.ts");N.writeFileSync(m,c),i.push(m)}return i}function Y(e,t,r,n={}){let s=r?".js":".ts",o=[];for(let i of t){let u=_.join(e,`${i.fileName}${s}`);if(!N.existsSync(u)){o.push(`\u7F3A\u5C11\u6A21\u5757\u6587\u4EF6\uFF1A\u671F\u671B ${i.fileName}${s}\uFF08\u539F\u59CB\u7EC4\u540D ${i.raw}\uFF09`);continue}N.readFileSync(u,"utf8").includes(`class ${i.className}`)||o.push(`\u7C7B\u540D\u4E0E\u547D\u540D\u8868\u4E0D\u4E00\u81F4\uFF1A${i.fileName}${s} \u671F\u671B ${i.className}`)}if(n.aggregate!==!1){let i=_.join(e,`index${s}`);if(!N.existsSync(i))o.push(`\u7F3A\u5C11\u805A\u5408\u5165\u53E3\uFF1Aindex${s}`);else{let u=N.readFileSync(i,"utf8");for(let c of t)u.includes(`this.${c.property}.instance = this.instance`)||o.push(`\u805A\u5408\u5165\u53E3\u7F3A\u5C11\u6A21\u5757\u6302\u8F7D\uFF1A${c.property}`)}}let a=N.existsSync(e)?U(N.readdirSync(e),t,s):[];return{errors:o,orphans:a}}function st(e,t){let r=t||"Api",n=e.map(o=>{let a=o.className===r?`${o.className}Module`:o.className;return`import { ${o.className}${a===o.className?"":` as ${a}`} } from "./${o.base}"`}),s=e.map(o=>{let a=o.className===r?`${o.className}Module`:o.className;return` ${o.property}: ${a}`});return['import { HttpClient } from "./http-client"',...n,'export * from "./data-contracts"',"",`export declare class ${r}<SecurityDataType = unknown> extends HttpClient<SecurityDataType> {`,...s," constructor(config?: any)","}",""].join(`
3
- `)}var ot=["get","post","put","delete","patch","head","options"];function at(e,t,r){let n=r.strategy?.length?r.strategy:["rules","tag","path"],s=r.fallback??"misc";for(let o of n)if(o==="rules")for(let[a,i]of(r.rules??[]).entries()){let u=i.match??{};if(u.prefix&&e.startsWith(u.prefix))return{group:i.group,source:"rules",ruleIndex:a};if(u.regex&&new RegExp(u.regex).test(e))return{group:i.group,source:"rules",ruleIndex:a};if(u.tag&&(t.tags??[]).includes(u.tag))return{group:i.group,source:"rules",ruleIndex:a};if(u.operationId&&t.operationId===u.operationId)return{group:i.group,source:"rules",ruleIndex:a}}else if(o==="tag"){let a=(t.tags??[])[0];if(a)return{group:String(a),source:"tag"}}else if(o==="path"){let a=e.split("/").filter(Boolean),i=r.pathDepth??0;if(a[i])return{group:a[i],source:"path"}}return{group:s,source:"fallback"}}function Re(e,t){let r=t.fallback??"misc",n=[],s=new Set;for(let[l,g]of Object.entries(e.paths??{}))for(let y of ot){let h=g[y];if(!h||typeof h!="object")continue;let x=at(l,h,t);x.ruleIndex!==void 0&&s.add(x.ruleIndex),n.push({path:l,method:y,operation:h,group:x.group,ruleIndex:x.ruleIndex})}let o=new Map;n.forEach(({group:l})=>o.set(l,(o.get(l)??0)+1));for(let l of n){let g=o.get(l.group)??0;if(t.minRoutes&&g<t.minRoutes&&l.group!==r)l.group=r;else if(t.maxRoutes&&g>t.maxRoutes){let h=l.path.split("/").filter(Boolean)[(t.pathDepth??0)+1];h&&(l.group=`${l.group}_${h}`)}}let a=he(n.map(l=>l.group),t.names),i=new Map(a.entries.map(l=>[l.raw,l])),u={},c={};for(let l of n){let g=Array.isArray(l.operation.tags)?l.operation.tags.join(", "):"";g&&(u[`${l.method.toUpperCase()}:${l.path}`]=g);let y=i.get(l.group);y&&(l.operation.tags=[y.fileName]),c[l.group]=(c[l.group]??0)+1}let m=Array.from({length:t.rules?.length??0},(l,g)=>g).filter(l=>!s.has(l));return{counts:c,originalTags:u,entries:a.entries,unmatchedRules:m,errors:a.errors,warnings:a.warnings}}var f={files:[],param:{}},p={home:pt.homedir(),enum:{}},C=0,j=[],lt=()=>process.argv.includes("--dry-run"),ft=()=>process.argv.includes("--json");function D(e,t=0){e&&console.log(e),process.exit(t)}async function gt(){p.param={config:w(["--config","-c"]),configScan:d(["--config-scan","-cs"])??!0,configAll:d(["--config-all","-ca"]),quick:d(["--quick","-q"]),replaceTags:te(["--replace-tags","-rt"],{length:2}),convertGet:d(["--convert-get","-cg"]),removeParam:d(["--remove-param","-rp"]),removePrefixIndex:w(["--remove-prefix-index","-rpi"]),removeDts:d(["--remove-dts","-rd"]),removeEmptyComponents:d(["--remove-empty-components","-rec"])??!0,extractRequestQuery:w(["--extract-request-query","-erq"]),extractResponseRaw:d(["--extract-response-raw","-err"]),template:S.resolve(re(),"./templates")},p.config={templates:w(["--templates","-t"])??p.param.template,defaultResponseAsSuccess:d(["--default-as-success","-d"]),generateResponses:d(["--responses","-r"]),generateUnionEnums:d("--union-enums"),addReadonly:d("--add-readonly"),generateRouteTypes:d("--route-types"),generateClient:!d("--no-client"),enumNamesAsValues:d("--enum-names-as-values"),extractRequestParams:d("--extract-request-params"),extractRequestBody:d("--extract-request-body"),extractResponseBody:d("--extract-response-body"),extractResponseError:d("--extract-response-error"),modular:d("--modular"),toJS:d("--js"),moduleNameIndex:Number(w("--module-name-index")??0),moduleNameFirstTag:d("--module-name-first-tag"),httpClientType:d("--axios")?"axios":"fetch",unwrapResponseData:d("--unwrap-response-data"),disableThrowOnError:d("--disable-throw-on-error"),singleHttpClient:d("--single-http-client"),silent:d("--silent")??!0,defaultResponseType:w("--default-response")??"void",typePrefix:w("--type-prefix")??"",typeSuffix:w("--type-suffix")??"",cleanOutput:d("--clean-output"),...w("--api-class-name")?{apiClassName:w("--api-class-name")}:{},patch:d("--patch"),debug:d("--debug"),anotherArrayType:d("--another-array-type"),sortTypes:d("--sort-types"),extractEnums:d("--extract-enums")},mt()}function R(e){let t=process.argv.slice(2);return e.some(r=>t.includes(r))}function mt(){let e=me(),t=le(process.cwd(),{projectFile:e.configFile});t.warnings.forEach(l=>console.error("\u26A0\uFE0F",l));let r=fe(ge(t.merged,e.profile)),n=r.input??{},s=r.output??{},o=r.types??{},a=r.naming??{},i=r.grouping??{},u=n.url??n.file;if(!u)return;p.rcDriven=!0,p.rcUrl=u,p.rcOutput=s.dir??"./src/api",p.rcName=s.name??"index";let c=p.param;c.quick=!0,!R(["--remove-prefix-index","-rpi"])&&a.pathPrefixIndex!==void 0&&(c.removePrefixIndex=String(a.pathPrefixIndex)),!R(["--convert-get","-cg"])&&a.convertGetToQuery!==void 0&&(c.convertGet=a.convertGetToQuery),!R(["--remove-param","-rp"])&&a.dropPathParams!==void 0&&(c.removeParam=a.dropPathParams),!R(["--extract-request-query","-erq"])&&o.extractQuery!==void 0&&(c.extractRequestQuery=o.extractQuery),!R(["--remove-dts","-rd"])&&o.removeDts!==void 0&&(c.removeDts=o.removeDts),!R(["--replace-tags","-rt"])&&a.tagRewrite&&(c.replaceTags=a.tagRewrite);let m=p.config;!R(["--axios"])&&r.client?.type&&(m.httpClientType=r.client.type==="axios"?"axios":"fetch"),!R(["--js"])&&r.language?.target&&(m.toJS=r.language.target==="js"),!R(["--responses","-r"])&&o.responses!==void 0&&(m.generateResponses=!!o.responses),!R(["--unwrap-response-data"])&&o.unwrapData!==void 0&&(m.unwrapResponseData=!!o.unwrapData),!R(["--extract-request-params"])&&o.extractParams!==void 0&&(m.extractRequestParams=!!o.extractParams),!R(["--clean-output"])&&s.clean!==void 0&&(m.cleanOutput=!!s.clean),!R(["--modular"])&&s.mode==="grouped"&&(m.modular=!0),!R(["--module-name-index"])&&i.pathDepth!==void 0&&(m.moduleNameIndex=Number(i.pathDepth)),Object.keys(i).length&&(m.grouping=i)}async function dt(){if(p.rcDriven){f.files=["(swagger2apirc)"];return}p.param.config?f.files=p.param.config.split(","):p.param.configScan&&(f.files=ne()),f.files.length==0&&(f.files=["saconfig.json"]),!p.param.configAll&&f.files.length>1&&(f.files=(await Se({type:"multiselect",name:"files",message:"\u9009\u62E9\u914D\u7F6E\u6587\u4EF6",hint:"\u53EF\u591A\u9009\uFF0C\u7A7A\u683C\u952E\u52FE\u9009\uFF0C\u56DE\u8F66\u5B8C\u6210",choices:f.files.map(e=>({title:e.replace(/\\/g,"/"),value:e}))}).then(e=>e.files?.length!=0?e:D("\u7ED3\u675F\uFF1A\u81F3\u5C11\u9009\u62E9\u4E00\u4E2A\u914D\u7F6E\u6587\u4EF6"))).files),f.files?.length>0||D("\u7ED3\u675F\uFF1A\u624B\u52A8\u9000\u51FA")}async function yt(){if(p.rcDriven){f.param={url:p.rcUrl,output:p.rcOutput,name:p.rcName},p.docFile=S.resolve(`${p.rcOutput}/${p.rcName}-${new Date().getTime()}.json`);return}try{f.param={},f.param=JSON.parse(O.readFileSync(f.file,"utf-8"))}catch{}(!p.param.quick||[f.param.url,f.param.output,f.param.name].includes(void 0))&&(f.param=await Se([{name:"url",type:"text",message:"Swagger docs \u5730\u5740:",initial:f.param.url??"https://example.com/v3/api-docs"},{name:"output",type:"text",message:"\u8F93\u51FA\u5730\u5740:",initial:f.param.output??"./src/api"},{name:"name",type:"text",message:"\u6587\u4EF6\u540D:",initial:f.param.name??"index"}])),[f.param.url,f.param.output,f.param.name].includes(void 0)&&D("\u7ED3\u675F\uFF1A\u624B\u52A8\u9000\u51FA"),p.docFile=S.resolve(`${f.param.output}/${f.param.name}-${new Date().getTime()}.json`)}async function Ne(e=0){if(f.file=f.files[e],await yt(),q(f.param.url))await it.get(f.param.url).then(t=>we(t.data)).catch(t=>console.log("\u5931\u8D25\uFF1A",t));else try{await we(JSON.parse(O.readFileSync(S.resolve(f.param.url),"utf8")))}catch(t){console.log("\u5931\u8D25\uFF1A",t)}f.files[e+1]?await Ne(e+1):C>0&&D(`\u7ED3\u675F\uFF1A${C} \u4E2A\u6587\u6863\u672A\u751F\u6210\uFF0C\u5931\u8D25\u539F\u56E0\u89C1\u4E0A\u65B9\u8F93\u51FA`,1)}function ht(e){let t=p.param.replaceTags;t?.length&&Object.values(e.paths??{}).forEach(r=>{Object.values(r).forEach(n=>{Array.isArray(n?.tags)&&(n.tags=n.tags.map(s=>s.replace(new RegExp(`^${t[0]}$`,"g"),t[1]??"")))})})}function xt(e,t){let r=p.config.toJS?".js":".ts",n=S.resolve(f.param.output??"./src/api"),s=O.existsSync(n)?O.readdirSync(n):[],o=e.map(i=>`${i.fileName}${r}`).filter(i=>!s.includes(i)),a=U(s,e,r);if(ft()){console.log(JSON.stringify({groups:e.map(({raw:i,fileName:u,className:c,property:m,reason:l,source:g})=>({raw:i,fileName:u,className:c,property:m,reason:l,source:g})),unmatchedRules:t,add:o,orphans:a},null,2));return}e.forEach(i=>console.log(`\u547D\u540D\uFF1A${i.raw} \u2192 ${i.fileName}\uFF08\u7C7B ${i.className}${i.reason?`\uFF0C${i.reason}`:""}\uFF09`)),t.length&&console.error(`\u26A0\uFE0F \u672A\u547D\u4E2D\u89C4\u5219\uFF1A${t.map(i=>i+1).join("\u3001")}`),o.length&&console.log(`\u9884\u8BA1\u65B0\u589E\uFF1A${o.join("\u3001")}`),a.length&&console.error(`\u26A0\uFE0F \u8868\u5916\u4EA7\u7269\uFF08\u5EFA\u8BAE\u5F00\u542F output.clean\uFF09\uFF1A${a.join("\u3001")}`)}async function we(e){if(typeof e?.paths!="object")return console.log("\u5931\u8D25\uFF1A\u7F3A\u5C11paths\u5B57\u6BB5");let t=await pe(e,{baseUrl:q(f.param.url)?f.param.url:void 0});if(t.errors.length>0){t.errors.forEach(n=>console.error("\u5931\u8D25\uFF1A",n)),C+=1;return}j=[],p.param.moduleClassNames=void 0,ht(e);let r=p.config.grouping;if(p.config.modular&&r&&(r.strategy?.length||r.rules?.length)){let n=Re(e,r);if(n.warnings.forEach(s=>console.error("\u26A0\uFE0F",s)),n.errors.length>0){n.errors.forEach(s=>console.error("\u5931\u8D25\uFF1A",s)),C+=1;return}if(j=n.entries,p.config.moduleNameFirstTag=!0,p.param.moduleClassNames=xe(n.entries),r.preserveTags!==!1&&(p.param.groupOriginalTags=n.originalTags),console.log("\u5206\u7EC4\uFF1A",...Object.entries(n.counts).map(([s,o])=>`${s}-${o}`)),lt()){xt(n.entries,n.unmatchedRules);return}}if(Object.entries(e.paths).forEach(n=>{Object.keys(n[1]).forEach(s=>{let o=`${n[0]}/${s}`;if(p.param.convertGet&&(o=o.replace(/([^\}]\/)get$/g,"$1query")),p.param.removeParam&&(o=o.replace(/\/\{.+?\}/g,"")),p.param.removePrefixIndex){let i=o.split("/");i=i.slice(0,1).concat(i.slice(Number(p.param.removePrefixIndex)+2)),o=i.join("/")}o=o.replace(/["\\`\r\n]/g,"_").replace(/\$\{/g,"_"),e.paths[n[0]][s].operationId=o;let a=o.split("/").slice(-1)[0];typeof p.enum[a]=="number"?p.enum[a]++:p.enum[a]=1})}),Object.entries(e.components).forEach(n=>{Object.keys(n[1]).forEach(s=>{p.param.removeEmptyComponents&&!Object.keys(e.components[n[0]][s]).length&&delete e.components[n[0]][s]})}),console.log("\u5C31\u7EEA\uFF1A",...Object.entries(p.enum).map(n=>n.join("-"))),H(p.docFile,JSON.stringify(e)),console.log("\u6267\u884C\uFF1A",f.file),await ut({fileName:`${f.param.name}.ts`,output:S.resolve(f.param.output),input:p.docFile,...p.config,param:p.param}),console.log("\u5B8C\u6210\uFF1A",S.resolve(f.param.output,`${f.param.name}${p.config.toJS?".js":".ts"}`)),p.config.modular){let n=S.resolve(f.param.output),s=String(p.config.apiClassName??"Api"),o=!!p.config.toJS;if(j.length){let a=Y(n,j,o,{aggregate:!1});if(a.errors.length>0){a.errors.forEach(c=>console.error("\u5931\u8D25\uFF1A",c)),C+=1;return}Q(n,s,o,$e(j));let{errors:i,orphans:u}=Y(n,j,o);if(i.length>0){i.forEach(c=>console.error("\u5931\u8D25\uFF1A",c)),C+=1;return}u.forEach(c=>console.error("\u26A0\uFE0F \u8868\u5916\u4EA7\u7269\uFF08\u5EFA\u8BAE\u5F00\u542F output.clean\uFF09\uFF1A",c))}else Q(n,s,o)}p.config.toJS&&console.log("\u5B8C\u6210\uFF1A",S.resolve(f.param.output,`${f.param.name}.d.ts`)),O.unlinkSync(p.docFile),p.param.removeDts&&(console.log("\u6E05\u7406\uFF1A",S.resolve(f.param.output,`${f.param.name}.d.ts`)),ct(`npx rimraf ${S.resolve(f.param.output,`${f.param.name}.d.ts`)}`,{cwd:p.home}).toString()),p.rcDriven||H(f.file,JSON.stringify(f.param,null,2))}async function cr(){await gt(),await dt(),Ne()}export{cr as generateApi};
1
+ var le=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')});import yr from"axios";import{execSync as hr}from"child_process";import tt from"os";import L from"fs";import R from"path";import rt from"prompts";import{generateApi as xr}from"swagger-typescript-api";var Y=e=>/^(https?:\/\/|:?\/\/)/.test(e);import X from"fs";import it from"url";import Z from"path";var Q={param:process.argv.filter((e,t)=>t>1)};function ue(e,t="value",r={}){Array.isArray(e)||(e=[e]);let n;return Q.param.forEach((s,o)=>{if(e.includes(s))["value"].includes(t)?n=Q.param[o+1]:["array"].includes(t)?n=Array.from({length:r.length??1}).map((i,a)=>Q.param[o+a+1]):n=!["false"].includes(Q.param[o+1]);else return}),n}function S(e){return ue(e,"key")}function D(e){return ue(e,"value")}function Fe(e,t={}){return ue(e,"array",t)??[]}function pe(e,t){let r=Z.dirname(e);X.existsSync(r)||X.mkdirSync(r,{recursive:!0}),X.writeFileSync(e,t)}function at(){return typeof le<"u"&&typeof module<"u"?__filename:it.fileURLToPath(import.meta.url)}function Ae(){return typeof le<"u"&&typeof module<"u"?__dirname:Z.dirname(at())}function Oe(e=process.cwd()){let t=[],r=n=>{for(let s of X.readdirSync(n,{withFileTypes:!0})){if(s.name.startsWith("."))continue;let o=Z.join(n,s.name);if(s.isDirectory()){if(s.name==="node_modules")continue;r(o)}else s.isFile()&&s.name.startsWith("saconfig")&&s.name.endsWith(".json")&&t.push(Z.relative(e,o))}};return r(e),t.sort()}function ee(e){return JSON.stringify(e).slice(1,-1)}function Le(e){return e.replace(/\\/g,"\\\\").replace(/`/g,"\\`").replace(/\$\{/g,"\\${")}import*as De from"dns/promises";import*as me from"net";var ct=5,z=async e=>{try{return(await De.lookup(e,{all:!0,verbatim:!0})).map(r=>r.address)}catch{return[]}};function fe(e){let t=e.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/);if(!t)return!1;let r=t.slice(1).map(Number);if(r.some(o=>o>255))return!1;let[n,s]=r;return n===0||n===10||n===127||n===169&&s===254||n===172&&s>=16&&s<=31||n===192&&s===168}function lt(e){let t=e.toLowerCase();if(t==="::"||t==="::1"||t.startsWith("fe80:"))return!0;let r=t.split(":")[0]??"";if(r>="fc00"&&r<="fdff")return!0;let n=t.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/);if(n?.[1])return fe(n[1]);let s=t.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/);if(s?.[1]&&s?.[2]){let o=parseInt(s[1],16),i=parseInt(s[2],16);return fe(`${o>>8&255}.${o&255}.${i>>8&255}.${i&255}`)}return!1}function Pe(e){let t=me.isIP(e);return t===4?fe(e):t===6?lt(e):!1}function ut(e){let t=e.toLowerCase();return t==="localhost"||t.endsWith(".localhost")}async function pt(e,t=z){let r;try{r=new URL(e)}catch{return!1}if(r.protocol!=="http:"&&r.protocol!=="https:")return!1;let n=r.hostname.startsWith("[")&&r.hostname.endsWith("]")?r.hostname.slice(1,-1):r.hostname;if(ut(n))return!1;if(me.isIP(n))return!Pe(n);let s=await t(n);return s.length===0?!1:s.every(o=>!Pe(o))}function ft(e,t){if(typeof t!="string")return!1;try{let r=new URL(e),n=new URL(t);return r.protocol===n.protocol&&r.host===n.host}catch{return!1}}function Ie(e){return e.split("#")[0]||e}async function ge(e,t,r=z){let{specSourceUrl:n,allowExplicitSpecUrl:s=!1}=t;return s&&typeof n=="string"&&Ie(e)===Ie(n)||typeof n=="string"&&ft(e,n)?!0:pt(e,r)}function mt(e,t){try{return new URL(e,t).toString()}catch{return null}}async function Me(e,t,r,n=z,s=fetch){let o=e,i=0;for(;;){if(!await ge(o,{specSourceUrl:r.specSourceUrl,allowExplicitSpecUrl:r.allowExplicitSpecUrl&&i===0},n))return null;let l=await s(o,{...t,redirect:"manual"});if(l.status>=300&&l.status<400){let u=l.headers.get("location");if(!u||i>=ct)return null;let p=mt(u,o);if(!p)return null;o=p,i+=1;continue}return l}}var te=/["\\\u0000-\u001f]/;function gt(e){if(e.paths&&typeof e.paths=="object"){let t={};for(let[r,n]of Object.entries(e.paths))t[Le(r)]=n;e.paths=t}if(Array.isArray(e.servers))for(let t of e.servers)t&&typeof t.url=="string"&&(t.url=ee(t.url));de(e)}function de(e){if(Array.isArray(e)){e.forEach(t=>de(t));return}if(!(!e||typeof e!="object"))for(let t of Object.keys(e)){let r=e[t];t==="enum"&&Array.isArray(r)?e[t]=r.map(n=>typeof n=="string"?ee(n):n):t==="default"&&typeof r=="string"?e[t]=ee(r):de(r)}}function dt(e){let t=[],r=(n,s)=>{if(Array.isArray(n)){n.forEach((o,i)=>r(o,`${s}[${i}]`));return}if(!(!n||typeof n!="object")){if(n.properties&&typeof n.properties=="object")for(let o of Object.keys(n.properties))te.test(o)&&t.push(`${s}.properties\uFF1A\u5C5E\u6027\u540D\u542B\u975E\u6CD5\u5B57\u7B26\uFF1A${JSON.stringify(o)}`);if(Array.isArray(n.required))for(let o of n.required)typeof o=="string"&&te.test(o)&&t.push(`${s}.required\uFF1A\u5FC5\u586B\u5B57\u6BB5\u540D\u542B\u975E\u6CD5\u5B57\u7B26\uFF1A${JSON.stringify(o)}`);if(n.discriminator&&typeof n.discriminator=="object"&&(typeof n.discriminator.propertyName=="string"&&te.test(n.discriminator.propertyName)&&t.push(`${s}.discriminator.propertyName\uFF1A\u542B\u975E\u6CD5\u5B57\u7B26\uFF1A${JSON.stringify(n.discriminator.propertyName)}`),n.discriminator.mapping&&typeof n.discriminator.mapping=="object"))for(let o of Object.keys(n.discriminator.mapping))te.test(o)&&t.push(`${s}.discriminator.mapping\uFF1A\u952E\u542B\u975E\u6CD5\u5B57\u7B26\uFF1A${JSON.stringify(o)}`);for(let o of Object.keys(n))r(n[o],`${s}.${o}`)}};return r(e,"#"),t}async function yt(e,t={}){let r=[],n={baseUrl:t.baseUrl,resolve:t.resolve??z,fetchImpl:t.fetchImpl??fetch,docs:new Map,errors:r},s=async(i,a,l)=>{if(Array.isArray(i)){let p=[];for(let c=0;c<i.length;c+=1)p.push(await s(i[c],`${a}[${c}]`,l));return p}if(!i||typeof i!="object")return i;let u=i.$ref;if(typeof u=="string"&&!u.startsWith("#")){let p=await o(u,a,l);return p===null?i:s(p,a,l)}for(let p of Object.keys(i))i[p]=await s(i[p],`${a}.${p}`,l);return i},o=async(i,a,l)=>{if(!/^https?:\/\//i.test(i))return r.push(`${a}\uFF1A\u4E0D\u652F\u6301\u7684\u5916\u90E8\u5F15\u7528\uFF08\u4EC5\u5141\u8BB8\u6587\u6863\u5185 #/ \u6216 http(s)\uFF09\uFF1A${i}`),null;let u=i.indexOf("#"),p=u===-1?i:i.slice(0,u),c=u===-1?"":i.slice(u+1),m;try{m=n.baseUrl?new URL(p,n.baseUrl).toString():p}catch{return r.push(`${a}\uFF1A\u65E0\u6CD5\u89E3\u6790\u7684\u5F15\u7528\u5730\u5740\uFF1A${i}`),null}let f=`${m}#${c}`;if(l.includes(f))return r.push(`${a}\uFF1A\u68C0\u6D4B\u5230\u5F15\u7528\u73AF\uFF1A${[...l,f].join(" -> ")}`),null;if(!await ge(m,{specSourceUrl:n.baseUrl},n.resolve))return r.push(`${a}\uFF1A\u62D2\u7EDD\u62C9\u53D6\u975E\u516C\u7F51\u6216\u975E\u4FE1\u4EFB\u6765\u6E90\u7684\u5916\u90E8\u5F15\u7528\uFF1A${i}`),null;let h=await ht(m,n);if(!h)return null;let w=xt(h,c);if(w===void 0)return r.push(`${a}\uFF1A\u5F15\u7528\u7247\u6BB5\u4E0D\u5B58\u5728\uFF1A${i}`),null;let k=await s(structuredClone(w),a,[...l,f]),b=St(e,c,k,m);return b?{$ref:`#/components/schemas/${b}`}:k};return await s(e,"#",[]),r}async function ht(e,t){if(t.docs.has(e))return t.docs.get(e);let r=await Me(e,{},{specSourceUrl:t.baseUrl},t.resolve,t.fetchImpl);if(!r?.ok)return t.errors.push(`\u5916\u90E8\u5F15\u7528\u62C9\u53D6\u5931\u8D25\uFF1A${e}`),null;let n=await r.text();try{let s=JSON.parse(n);return t.docs.set(e,s),s}catch{return t.errors.push(`\u5916\u90E8\u5F15\u7528\u6587\u6863\u4EC5\u652F\u6301 JSON \u683C\u5F0F\uFF1A${e}`),null}}function xt(e,t){if(!t||t==="/")return e;let r=e;for(let n of t.replace(/^\//,"").split("/")){if(r===null||typeof r!="object")return;let s=decodeURIComponent(n).replace(/~1/g,"/").replace(/~0/g,"~");r=r[s]}return r}function St(e,t,r,n){let s=t.match(/^\/components\/schemas\/([^/]+)$/);if(!s)return null;let o=decodeURIComponent(s[1]).replace(/~1/g,"/").replace(/~0/g,"~");e.components=e.components??{},e.components.schemas=e.components.schemas??{};let i=e.components.schemas;if(i[o]===void 0)return i[o]=r,o;if(JSON.stringify(i[o])===JSON.stringify(r))return o;let a=(n.split("/").pop()??"ref").replace(/\.[^.]+$/,"").replace(/[^A-Za-z0-9_$]/g,"_")||"ref",l=`${o}_${a}`,u=2;for(;i[l]!==void 0&&JSON.stringify(i[l])!==JSON.stringify(r);)l=`${o}_${a}_${u}`,u+=1;return i[l]=r,l}async function Te(e,t={}){let r=await yt(e,t);return gt(e),{errors:[...r,...dt(e)]}}import H from"fs";import $t from"os";import U from"path";var wt="swagger2api.json",Nt=".swagger2apirc.json",Rt="swagger2api.local.json",bt=".swagger2apirc.local.json",Ct=".swagger2api.json",kt=".swagger2apirc.json";function ye(e,t,r){let n={layer:t,file:e,hit:!1,sections:[],config:null};if(!e||!H.existsSync(e))return n;try{let s=JSON.parse(H.readFileSync(e,"utf8"));return!s||typeof s!="object"||Array.isArray(s)?(r.push(`${e}\uFF1A\u6839\u8282\u70B9\u5FC5\u987B\u662F\u5BF9\u8C61\uFF0C\u5DF2\u5FFD\u7565\u8BE5\u5C42`),{...n,hit:!1}):{layer:t,file:e,hit:!0,sections:Object.keys(s),config:s}}catch(s){return r.push(`${e}\uFF1A\u89E3\u6790\u5931\u8D25\uFF08${s.message}\uFF09\uFF0C\u5DF2\u5FFD\u7565\u8BE5\u5C42`),n}}function Et(e,t){if(!e)return t?{...t}:null;if(!t)return{...e};let r={...e};for(let[n,s]of Object.entries(t))r[n]=s;return r}function vt(e,t){if(!e)return t?{...t}:null;if(!t)return{...e};let r={...e};for(let[n,s]of Object.entries(t)){let o=r[n];r[n]=o&&typeof o=="object"&&!Array.isArray(o)&&s&&typeof s=="object"&&!Array.isArray(s)?{...o,...s}:s}return r}function Ge(e,t){let[r,...n]=e,s=U.resolve(t);for(;;){let o=U.join(s,r);if(H.existsSync(o)){let l=n.map(u=>U.join(s,u)).find(u=>H.existsSync(u))??null;return{file:o,ignored:l}}let i=n.map(l=>U.join(s,l)).find(l=>H.existsSync(l));if(i)return{file:i,ignored:null};let a=U.dirname(s);if(a===s)return null;s=a}}function _e(e=process.cwd(),t={}){let r=[],n=t.homeDir??$t.homedir(),s=U.join(n,Ct),o=U.join(n,kt),i=H.existsSync(s)?{file:s,ignored:H.existsSync(o)?o:null}:H.existsSync(o)?{file:o,ignored:null}:null,a=t.projectFile?{file:U.resolve(t.projectFile),ignored:null}:Ge([wt,Nt],e),l=Ge([Rt,bt],e);for(let f of[i,a,l])f?.ignored&&r.push(`${f.file}\uFF1A\u540C\u65F6\u5B58\u5728\u65E7\u914D\u7F6E ${f.ignored}\uFF0C\u5DF2\u6309\u65B0\u6587\u4EF6\u540D\u751F\u6548\uFF0C\u5EFA\u8BAE\u5220\u9664\u65E7\u6587\u4EF6`);let u=ye(i?.file??null,"\u5168\u5C40\u5C42",r),p=ye(a?.file??null,"\u9879\u76EE\u5C42",r),c=ye(l?.file??null,"\u672C\u5730\u5C42",r),m=vt(Et(u.config,p.config),c.config);return{global:u,project:p,local:c,merged:m,warnings:r}}var jt=[{env:"FX_S2A_INPUT",key:"input.url",type:"string"},{env:"FX_S2A_OUTPUT",key:"output.dir",type:"string"},{env:"FX_S2A_NAME",key:"output.name",type:"string"},{env:"FX_S2A_CLIENT",key:"client.type",type:"string"},{env:"FX_S2A_LANGUAGE",key:"language.target",type:"string"},{env:"FX_S2A_CLEAN",key:"output.clean",type:"boolean"}];function Ft(e,t,r){let n=t.split("."),s=e;n.forEach((o,i)=>{if(i===n.length-1){s[o]=r;return}(!s[o]||typeof s[o]!="object")&&(s[o]={}),s=s[o]})}function Be(e,t=process.env){let r=e?structuredClone(e):{};for(let n of jt){let s=t[n.env];s===void 0||s===""||Ft(r,n.key,n.type==="boolean"?!["0","false"].includes(s.toLowerCase()):s)}return r}var At=["url","file","name","mode","responses","query","extractResponseRaw","pathPrefixIndex","convertGetToQuery","dropPathParams","tagRewrite"];function he(e){if(!e||typeof e!="object"||Array.isArray(e))return{};if(typeof e.url!="string"&&typeof e.file!="string")return e;let t={...e};t.input={...e.input&&typeof e.input=="object"?e.input:{},...typeof e.url=="string"?{url:e.url}:{},...typeof e.file=="string"?{file:e.file}:{}};let r={...e.output&&typeof e.output=="object"?e.output:{},...typeof e.output=="string"?{dir:e.output}:{}};r.name=e.name??r.name??"index",r.mode=e.mode??r.mode??"single",r.prune=r.prune??r.mode==="grouped",t.output=r,t.client=typeof e.client=="string"?{type:e.client}:{...e.client??{}},t.language=typeof e.language=="string"?{target:e.language}:{...e.language??{}},t.types={...e.types??{}},e.responses!==void 0&&(t.types.responses=e.responses),e.extractResponseRaw!==void 0&&(t.types.extractResponseRaw=e.extractResponseRaw),e.query!==void 0&&(t.types.extractQuery=Array.isArray(e.query)?e.query.join(","):e.query),t.naming={...e.naming??{}};for(let n of["pathPrefixIndex","convertGetToQuery","dropPathParams","tagRewrite"])e[n]!==void 0&&(t.naming[n]=e[n]);if(r.mode==="grouped"){let n={...e.grouping??{}};n.strategy=n.strategy??["path"],n.pathDepth=n.pathDepth??t.naming.pathPrefixIndex??0,n.split=n.split??!0,t.grouping=n}for(let n of At)delete t[n];return t}function Ue(e,t){let r=e?structuredClone(e):{};if(!t)return r;let n=r.profiles?.[t];if(!n||typeof n!="object")return r;for(let[s,o]of Object.entries(n)){if(s==="profiles")continue;let i=r[s];r[s]=i&&typeof i=="object"&&!Array.isArray(i)&&o&&typeof o=="object"&&!Array.isArray(o)?{...i,...o}:o}return r}function He(e=process.argv.slice(2)){let t=r=>r.reduce((n,s)=>n??(e.includes(s)?e[e.indexOf(s)+1]:void 0),void 0);return{configFile:t(["--config","-c"]),profile:t(["--profile"])}}import{createHash as Gt}from"crypto";import C from"fs";import _t from"os";import F from"path";var j="client",E="types",q="shared",ne=["data-contracts","http-client"],Ot=new Set(["index",j,E,q]),Lt=new Set(["HttpClient","RequestParams","ContentType","AxiosRequestConfig","AxiosResponse","Array","ArrayBuffer","Blob","Boolean","Date","Document","Element","Error","Event","File","FileList","FormData","Headers","Image","Map","Node","Number","Object","Promise","ReadableStream","RegExp","Request","Response","Set","String","URL","Window"]),Je=new Set(["instance","request","setSecurityData","mergeRequestParams","stringifyFormItem","createFormData","securityData","securityWorker","secure","format","constructor","prototype"]),Pt=new Set(["con","prn","aux","nul",...Array.from({length:9},(e,t)=>`com${t+1}`),...Array.from({length:9},(e,t)=>`lpt${t+1}`)]),qe=64;function _(e){return String(e).normalize("NFKC").toLowerCase().replace(/[^\p{L}\p{N}]+/gu,"")}function It(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g,"$1 $2").split(" ").filter(Boolean)}function Dt(e){let t=e.normalize("NFKC"),r=[];for(let n of t.matchAll(/[A-Za-z0-9]+|[\p{L}\p{N}]+/gu)){let s=n[0];/^[A-Za-z0-9]+$/.test(s)?r.push(...It(s)):r.push(s)}return r}function Mt(e){return e.map((t,r)=>{if(/^[A-Za-z0-9]+$/.test(t)){let n=t.toLowerCase();return r===0?n:n.charAt(0).toUpperCase()+n.slice(1)}return t}).join("")}function Tt(e){let t=2166136261;for(let r of e)t^=r.codePointAt(0)??0,t=Math.imul(t,16777619);return(t>>>0).toString(16).padStart(8,"0").slice(0,6)}function re(e){let t=[],r=Dt(e),n=Mt(r);return n?(/^[0-9]/.test(n)&&(n=`g${n}`,t.push("\u6570\u5B57\u5F00\u5934")),[...n].length>qe&&(n=[...n].slice(0,qe-6).join("")+Tt(e),t.push("\u8D85\u957F\u622A\u65AD")),{slug:n,reason:t.join("\u3001")}):{slug:"",reason:"\u540D\u79F0\u4E0D\u542B\u53EF\u7528\u5B57\u7B26"}}function K(e){return e.charAt(0).toUpperCase()+e.slice(1)}function xe(e,t={}){let r=[],n=[],s=[...new Set(e)].sort((d,h)=>d<h?-1:d>h?1:0),o=new Map,i=new Set;for(let[d,h]of Object.entries(t))o.set(d,h),o.set(_(d),h);let a=new Set,l=new Set,u=[],p=(d,h=2)=>{let w=d,k=h;for(;a.has(w.toLowerCase());)w=`${d}${k}`,k+=1;return a.add(w.toLowerCase()),w},c=d=>{let h=d,w=2;for(;l.has(h)||Je.has(h.toLowerCase());)h=`${d}${w}`,w+=1;return l.add(h),h},m=new Map;for(let d of s){let h=o.get(d)??o.get(_(d));if(h===void 0)continue;i.add(d),i.add(_(d));let{slug:w}=re(h);if(!w){r.push(`\u624B\u5DE5\u540D\u4E0D\u53EF\u7528\uFF1A${d} \u2192 ${h}`);continue}let k=m.get(w.toLowerCase());k?r.push(`\u624B\u5DE5\u540D\u51B2\u7A81\uFF1A${k} \u4E0E ${d} \u90FD\u6307\u5411 ${w}`):m.set(w.toLowerCase(),d);let b=p(w);l.add(b);let I=K(b);u.push({raw:d,key:_(d),fileName:I,className:I,property:b,reason:b===w?"\u624B\u5DE5\u6307\u5B9A":"\u624B\u5DE5\u6307\u5B9A\u3001\u4E0E\u5DF2\u6709\u7EC4\u91CD\u540D",source:"manual"})}let f=1;for(let d of s){if(u.some(ot=>ot.raw===d))continue;let{slug:h,reason:w}=re(d),k=!h,b=h;if(k){for(;a.has(`group${f}`.toLowerCase());)f+=1;b=`group${f}`,f+=1}let I=Ot.has(b.toLowerCase())||Pt.has(b.toLowerCase()),g=Lt.has(K(b)),N=Je.has(b.toLowerCase()),A=[w],v,J;N||I?(v=p(`${b}2`,3),J=c(v),A.push(N?"\u4E0E\u805A\u5408\u6210\u5458\u540C\u540D":"\u4E0E\u4FDD\u7559\u540D\u51B2\u7A81")):g?(v=p(`${b}2`,3),J=c(b),A.push("\u4E0E\u5168\u5C40\u7C7B\u578B\u540C\u540D")):(v=p(b),J=c(v),v!==b&&A.push("\u4E0E\u5DF2\u6709\u7EC4\u91CD\u540D"));let je=K(v);u.push({raw:d,key:_(d),fileName:je,className:je,property:J,reason:A.filter(Boolean).join("\u3001"),source:k?"fallback":"auto"})}for(let d of Object.keys(t))!i.has(d)&&!i.has(_(d))&&n.push(`grouping.names \u4E2D\u7684\u952E\u672A\u51FA\u73B0\u5728\u672C\u6B21\u5206\u7EC4\u7ED3\u679C\uFF1A${d}`);return{entries:u,errors:r,warnings:n}}function We(e){let t={};for(let r of e)t[r.fileName]=r.className,t[r.fileName.charAt(0).toLowerCase()+r.fileName.slice(1)]=r.className;return t}function se(e,t,r,n=[]){let s=new Set([...t.flatMap(i=>[`${i.fileName}${r}`,`${i.importFrom??i.fileName}${r}`]),...n.map(i=>`${i}${r}`)]),o=new Set([`index${r}`,"index.d.ts",`${j}${r}`,`route-types${r}`,`${E}/index${r}`,...ne.flatMap(i=>[`${i}${r}`,`${i}.d.ts`])]);return e.filter(i=>i.endsWith(r)&&!i.endsWith(`.d${r}`)&&!s.has(i)&&!o.has(i)&&!i.endsWith(`_Route${r}`))}var Bt=new Set(["index","shared","types",j,...ne]);function W(e){let t=Gt("sha1").update(F.resolve(e)).digest("hex").slice(0,12);return F.join(_t.tmpdir(),"swagger2api",`${t}.json`)}function Ut(e){return String(e).split(/[^A-Za-z0-9]+/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join("")}function Ht(e,t){if(!C.existsSync(e))return[];let r=[];for(let n of C.readdirSync(e)){if(!n.endsWith(t)||n.endsWith(`.d${t}`))continue;let s=n.slice(0,-t.length);if(Bt.has(s.toLowerCase())||s.endsWith("Route"))continue;let o=Ut(s);r.push({base:s,className:o,property:o.charAt(0).toLowerCase()+o.slice(1)})}return r.sort((n,s)=>n.base.localeCompare(s.base))}function ze(e){return e.map(t=>({base:t.fileName,className:t.className,property:t.property,importFrom:t.importFrom}))}function oe(e){if(!C.existsSync(e))return null;try{let t=JSON.parse(C.readFileSync(e,"utf8"));return{files:Array.isArray(t.files)?t.files.map(String):[]}}catch{return null}}function ie(e,t,r,n=[]){let s=r?".js":".ts",i=["index",`${E}/index`,j,"route-types",...t.flatMap(u=>[u.fileName,u.importFrom??u.fileName]),...n].flatMap(u=>r?[`${u}${s}`,`${u}.d.ts`]:[`${u}${s}`]),a=F.join(e,E),l=C.existsSync(a)?C.readdirSync(a).filter(u=>u.endsWith(".ts")||u.endsWith(".js")).map(u=>`${E}/${u}`):[];return[...new Set([...i,...l])].filter(u=>C.existsSync(F.join(e,u))).sort()}function Ke(e,t){let r=t?[".js",".d.ts"]:[".ts"],n=[];for(let s of ne)for(let o of r){let i=`${s}${o}`;C.existsSync(F.join(e,i))&&(C.rmSync(F.join(e,i)),n.push(i))}return n}function Se(e,t){C.mkdirSync(F.dirname(e),{recursive:!0}),C.writeFileSync(e,`${JSON.stringify({files:t},null,2)}
2
+ `)}function $e(e,t,r){if(!t)return[];let n=new Set(r),s=[];for(let o of t.files){if(n.has(o))continue;let i=F.join(e,o);C.existsSync(i)&&(C.rmSync(i),s.push(o))}return s}function Ve(e,t,r,n,s=[]){let o=r?".js":".ts",i=new Set(n?.files??[]);return[...new Set([j,`${E}/index`,...t.flatMap(l=>[l.fileName,l.importFrom??l.fileName]),...s])].flatMap(l=>r?[`${l}${o}`,`${l}.d.ts`]:[`${l}${o}`]).filter(l=>C.existsSync(F.join(e,l))&&!i.has(l))}function Jt(e,t,r,n){let s=t||"Api",o=p=>p.className===s?`${p.className}Module`:p.className,i=new Map;for(let p of e){let c=p.importFrom??p.base,m=i.get(c);m?m.push(p):i.set(c,[p])}let a=[...i.entries()].map(([p,c])=>{let m=`${r?`${r.replace(/\\/g,"/")}/`:""}${p}`;return`import { ${c.map(d=>{let h=o(d);return h===d.className?d.className:`${d.className} as ${h}`}).join(", ")} } from "./${m}"`}),l=e.map(p=>`${p.property} = new ${o(p)}(this)`);return["/* eslint-disable */","/* tslint:disable */",`import { HttpClient } from "./${j}"`,...a,`export * from "./${E}"`,`export * from "./${j}"`,"","/** \u805A\u5408\u5165\u53E3\uFF1A\u5404\u6A21\u5757\u5171\u4EAB\u540C\u4E00\u4E2A\u8BF7\u6C42\u5B9E\u4F8B */",n?`export class ${s} extends HttpClient {`:`export class ${s}<SecurityDataType = unknown> extends HttpClient<SecurityDataType> {`,...l.map(p=>` ${p}`),"",n?" constructor(config) {":" constructor(config?: any) {"," super(config)"," }","}",""].join(`
3
+ `)}function we(e,t,r,n){let s=r?".js":".ts",o=n??Ht(e,s);if(o.length===0)return[];let i=Jt(o,t,"",r),a=[],l=F.join(e,`index${s}`);if(C.writeFileSync(l,i),a.push(l),r){let u=qt(o,t),p=F.join(e,"index.d.ts");C.writeFileSync(p,u),a.push(p)}return a}function Ne(e,t,r,n={}){let s=r?".js":".ts",o=[],i=new Map;for(let u of t){let p=u.importFrom??u.fileName,c=i.get(p);c?c.push(u):i.set(p,[u])}for(let[u,p]of i){let c=F.join(e,`${u}${s}`);if(!C.existsSync(c)){p.forEach(f=>o.push(`\u7F3A\u5C11\u6A21\u5757\u6587\u4EF6\uFF1A\u671F\u671B ${u}${s}\uFF08\u539F\u59CB\u7EC4\u540D ${f.raw}\uFF09`));continue}let m=C.readFileSync(c,"utf8");for(let f of p)m.includes(`class ${f.className}`)||o.push(`\u7C7B\u540D\u4E0E\u547D\u540D\u8868\u4E0D\u4E00\u81F4\uFF1A${u}${s} \u671F\u671B ${f.className}`)}let a=[`${j}${s}`,`${E}/index${s}`,...r?[`${j}.d.ts`,`${E}/index.d.ts`]:[]];for(let u of a)C.existsSync(F.join(e,u))||o.push(`\u7F3A\u5C11\u56FA\u5B9A\u4EA7\u7269\uFF1A${u}`);if(n.aggregate!==!1){let u=F.join(e,`index${s}`);if(!C.existsSync(u))o.push(`\u7F3A\u5C11\u805A\u5408\u5165\u53E3\uFF1Aindex${s}`);else{let p=C.readFileSync(u,"utf8");for(let c of t)p.includes(`${c.property} = new `)||o.push(`\u805A\u5408\u5165\u53E3\u7F3A\u5C11\u6A21\u5757\u6302\u8F7D\uFF1A${c.property}`)}}let l=C.existsSync(e)?se(C.readdirSync(e),t,s,n.extraFiles??[]):[];return{errors:o,orphans:l}}function qt(e,t){let r=t||"Api",n=a=>a.className===r?`${a.className}Module`:a.className,s=new Map;for(let a of e){let l=a.importFrom??a.base,u=s.get(l);u?u.push(a):s.set(l,[a])}let o=[...s.entries()].map(([a,l])=>`import { ${l.map(p=>{let c=n(p);return c===p.className?p.className:`${p.className} as ${c}`}).join(", ")} } from "./${a}"`),i=e.map(a=>` ${a.property}: ${n(a)}`);return["/* eslint-disable */","/* tslint:disable */",`import { HttpClient } from "./${j}"`,...o,`export * from "./${E}"`,`export * from "./${j}"`,"",`export declare class ${r}<SecurityDataType = unknown> extends HttpClient<SecurityDataType> {`,...i," constructor(config?: any)","}",""].join(`
4
+ `)}function Wt(e){return e.filter(t=>t.chunks.length>0).map(t=>({fileName:t.fileName,className:t.className,title:t.raw,chunks:t.chunks.map(r=>({fileName:r.fileName,className:r.className}))}))}function zt(e){let t=e.chunks.map(s=>`import { ${s.className} } from "./${s.fileName}"`),r=e.chunks.map(s=>`new ${s.className}(http)`).join(", "),n=e.chunks.map(s=>`${s.className}<SecurityDataType>`).join(", ");return["/* eslint-disable */","/* tslint:disable */",`import { HttpClient } from "./${j}"`,...t,"",`/** ${e.title} \u6A21\u5757\uFF1A\u7531\u5206\u7247\u5408\u5E76\uFF0C\u5BF9\u5916\u4E0E\u5355\u6587\u4EF6\u4EA7\u7269\u4E00\u81F4 */`,`export class ${e.className}<SecurityDataType = unknown> {`," /** \u5171\u4EAB\u8BF7\u6C42\u5668\uFF1A\u7531\u805A\u5408\u5165\u53E3\u6CE8\u5165\uFF1B\u4EC5\u4F9B\u6A21\u5757\u5185\u90E8\u8C03\u7528\uFF0C\u52FF\u5728\u4E1A\u52A1\u4FA7\u76F4\u63A5\u4F7F\u7528 */"," http: HttpClient<SecurityDataType>",""," constructor(http: HttpClient<SecurityDataType>) {"," this.http = http",` Object.assign(this, ${r})`," }",""," /** \u5E95\u5C42\u8BF7\u6C42\u5B9E\u4F8B\uFF1A\u4E0E\u805A\u5408\u5165\u53E3\u4FDD\u6301\u540C\u4E00\u4E2A */",' get instance(): HttpClient<SecurityDataType>["instance"] {'," return this.http.instance"," }","}","","/** \u7C7B\u578B\u5408\u5E76\uFF1A\u5206\u7247\u6210\u5458\u4E0E\u5355\u6587\u4EF6\u4EA7\u7269\u4FDD\u6301\u540C\u4E00\u547D\u540D\u7A7A\u95F4 */",`export interface ${e.className}<SecurityDataType = unknown> extends ${n} {}`,""].join(`
5
+ `)}function Kt(e){let t=e.chunks.map(n=>`import { ${n.className} } from "./${n.fileName}"`),r=e.chunks.map(n=>`new ${n.className}(http)`).join(", ");return["/* eslint-disable */","/* tslint:disable */",...t,"",`/** ${e.title} \u6A21\u5757\uFF1A\u7531\u5206\u7247\u5408\u5E76\uFF0C\u5BF9\u5916\u4E0E\u5355\u6587\u4EF6\u4EA7\u7269\u4E00\u81F4 */`,`export class ${e.className} {`," constructor(http) {"," this.http = http",` Object.assign(this, ${r})`," }",""," get instance() {"," return this.http.instance"," }","}",""].join(`
6
+ `)}function Vt(e){let t=e.chunks.map(n=>`import { ${n.className} } from "./${n.fileName}"`),r=e.chunks.map(n=>`${n.className}<SecurityDataType>`).join(", ");return["/* eslint-disable */","/* tslint:disable */",`import { HttpClient } from "./${j}"`,...t,"",`export interface ${e.className}<SecurityDataType = unknown> extends ${r} {}`,`export declare class ${e.className}<SecurityDataType = unknown> {`," constructor(http: HttpClient<SecurityDataType>)","}",""].join(`
7
+ `)}function Ye(e,t,r){let n=[];for(let s of Wt(t))if(r){let o=`${s.fileName}.js`;C.writeFileSync(F.join(e,o),Kt(s)),n.push(o);let i=`${s.fileName}.d.ts`;C.writeFileSync(F.join(e,i),Vt(s)),n.push(i)}else{let o=`${s.fileName}.ts`;C.writeFileSync(F.join(e,o),zt(s)),n.push(o)}return n}var Yt=["get","post","put","delete","patch","head","options"],Qt=["index","data-contracts","http-client","route-types"];function Xt(e,t,r){let n=r.strategy?.length?r.strategy:["rules","tag","path"],s=r.fallback??"misc";for(let o of n)if(o==="rules")for(let[i,a]of(r.rules??[]).entries()){let l=a.match??{};if(l.prefix&&e.startsWith(l.prefix))return{group:a.group,source:"rules",ruleIndex:i};if(l.regex&&new RegExp(l.regex).test(e))return{group:a.group,source:"rules",ruleIndex:i};if(l.tag&&(t.tags??[]).includes(l.tag))return{group:a.group,source:"rules",ruleIndex:i};if(l.operationId&&t.operationId===l.operationId)return{group:a.group,source:"rules",ruleIndex:i}}else if(o==="tag"){let i=(t.tags??[])[0];if(i)return{group:String(i),source:"tag"}}else if(o==="path"){let i=e.split("/").filter(Boolean),a=r.pathDepth??0;if(i[a])return{group:i[a],source:"path"}}return{group:s,source:"fallback"}}function Qe(e,t){let r=t.fallback??"misc",n=[],s=new Set;for(let[c,m]of Object.entries(e.paths??{}))for(let f of Yt){let d=m[f];if(!d||typeof d!="object")continue;let h=Xt(c,d,t);h.ruleIndex!==void 0&&s.add(h.ruleIndex),n.push({path:c,method:f,operation:d,group:h.group,ruleIndex:h.ruleIndex})}if(t.collapse){let c=new Map;for(let m of[...new Set(n.map(f=>f.group))].sort()){let f=_(m);f&&!c.has(f)&&c.set(f,m)}n.forEach(m=>{let f=c.get(_(m.group));f&&(m.group=f)})}if(t.split!==void 0&&t.split!==!1){let c=xe(n.map(f=>f.group),t.names),m=typeof t.split=="object"?t.split:{};return er(n,t,m,c,s)}let o=new Map;n.forEach(({group:c})=>o.set(c,(o.get(c)??0)+1));for(let c of n){let m=o.get(c.group)??0;if(t.minRoutes&&m<t.minRoutes&&c.group!==r)c.group=r;else if(t.maxRoutes&&m>t.maxRoutes){let d=c.path.split("/").filter(Boolean)[(t.pathDepth??0)+1];d&&(c.group=`${c.group}_${d}`)}}let i=xe(n.map(c=>c.group),t.names),a=new Map(i.entries.map(c=>[c.raw,c])),l={},u={};for(let c of n){let m=Array.isArray(c.operation.tags)?c.operation.tags.join(", "):"";m&&(l[`${c.method.toUpperCase()}:${c.path}`]=m);let f=a.get(c.group);f&&(c.operation.tags=[f.fileName]),u[c.group]=(u[c.group]??0)+1}let p=Array.from({length:t.rules?.length??0},(c,m)=>m).filter(c=>!s.has(c));return{counts:u,originalTags:l,entries:i.entries,unmatchedRules:p,errors:i.errors,warnings:i.warnings}}function Zt(e,t){let r=(s,o,i)=>s===void 0?o:!Number.isFinite(s)||s<1?(t.push(`grouping.split.${i} \u65E0\u6548\uFF08${s}\uFF09\uFF0C\u56DE\u843D\u5230 ${o}`),o):Math.floor(s),n=[];if(e.categories!==void 0&&!Array.isArray(e.categories))t.push("grouping.split.categories \u5FC5\u987B\u662F\u6570\u7EC4\uFF0C\u5DF2\u5FFD\u7565");else for(let s of e.categories??[]){if(!s||typeof s.name!="string"||!s.name){t.push("grouping.split.categories \u5B58\u5728\u7F3A\u5C11 name \u7684\u9879\uFF0C\u5DF2\u5FFD\u7565");continue}let o=s.match?.regex;if(o)try{new RegExp(o)}catch{t.push(`grouping.split.categories \u7684\u6B63\u5219\u65E0\u6548\uFF08${s.name}\uFF1A${o}\uFF09\uFF0C\u5DF2\u5FFD\u7565\u8BE5\u9879`);continue}n.push(s)}return{minRoutes:r(e.minRoutes,150,"minRoutes"),targetRoutes:r(e.targetRoutes,300,"targetRoutes"),maxRoutes:r(e.maxRoutes,450,"maxRoutes"),minBucketRoutes:r(e.minBucketRoutes,60,"minBucketRoutes"),categories:n,fallback:typeof e.fallback=="string"&&e.fallback?e.fallback:"misc"}}function er(e,t,r,n,s){let o=[...n.warnings];(t.minRoutes!==void 0||t.maxRoutes!==void 0)&&o.push("\u5DF2\u542F\u7528 grouping.split\uFF0C\u5FFD\u7565 grouping.minRoutes / grouping.maxRoutes\uFF0C\u9608\u503C\u6539\u7531 grouping.split \u63D0\u4F9B");let i=Zt(r,o),a=new Map(n.entries.map(g=>[g.raw,g])),l=new Map;for(let g of e){let N=l.get(g.group);N?N.push(g):l.set(g.group,[g])}let u=n.entries.map(g=>({raw:g.raw,fileName:g.fileName,className:g.className,routes:l.get(g.raw)?.length??0,bucket:null,chunks:[]})),p=new Set(Qt.map(g=>g.toLowerCase()));u.filter(g=>g.routes>i.maxRoutes).forEach(g=>p.add(g.fileName.toLowerCase()));for(let g of u){if(g.routes<=i.maxRoutes)continue;let N=l.get(g.raw)??[];g.chunks=rr(g,N,t.pathDepth??0,i,p)}let c=e.length,m=or(u.filter(g=>g.chunks.length===0),c,i,p,o),f=new Map(u.map(g=>[g.raw,g]));for(let g of m)g.namespaces.forEach(N=>{let A=f.get(N);A&&(A.bucket=g.fileName)});let d={},h={};for(let g of e){let N=a.get(g.group),A=f.get(g.group);if(!N||!A)continue;let v=Array.isArray(g.operation.tags)?g.operation.tags.join(", "):"";v&&(d[`${g.method.toUpperCase()}:${g.path}`]=v);let J=g.splitTag??A.bucket;J&&(g.operation.tags=[J,N.fileName]),h[g.group]=(h[g.group]??0)+1}for(let g of u){let N=a.get(g.raw);N&&(N.importFrom=g.chunks.length?g.fileName:g.bucket??g.fileName)}let w={},k=(g,N)=>{w[g]=N,w[g.charAt(0).toLowerCase()+g.slice(1)]=N};n.entries.forEach(g=>k(g.fileName,g.className)),u.forEach(g=>g.chunks.forEach(N=>k(N.fileName,N.className)));let b={};for(let g of m){let N=g.namespaces.map(A=>{let v=f.get(A);return{tag:v.fileName,className:v.className,title:v.raw,routes:v.routes}});b[g.fileName]=N,b[g.fileName.charAt(0).toLowerCase()+g.fileName.slice(1)]=N}let I=Array.from({length:t.rules?.length??0},(g,N)=>N).filter(g=>!s.has(g));return{counts:h,originalTags:d,entries:n.entries,unmatchedRules:I,errors:n.errors,warnings:o,split:{total:c,buckets:m,namespaces:u,bucketLayout:b},moduleClassNames:w}}function tr(e,t,r){let n=e.split("/").filter(Boolean),s=n.indexOf(t),o=s>=0?s+1:r+1;for(let i=o;i<n.length;i+=1){let a=n[i];if(!/^v\d+$/i.test(a)&&!/^\{.*\}$/.test(a))return a}return"rest"}function rr(e,t,r,n,s){let o=new Map;for(let l of t){let u=tr(l.path,e.raw,r),p=o.get(u);p?p.push(l):o.set(u,[l])}let i=[],a={items:[],categories:new Set};for(let[l,u]of[...o.entries()].sort(([p],[c])=>p<c?-1:p>c?1:0))for(let p of u)a.items.length>=n.targetRoutes&&(i.push(a),a={items:[],categories:new Set}),a.items.push(p),a.categories.add(l);return a.items.length&&i.push(a),i.map((l,u)=>{let p=u+1,c=`${e.className}Part${p}`;for(;s.has(c.toLowerCase());)p+=1,c=`${e.className}Part${p}`;return s.add(c.toLowerCase()),l.items.forEach(m=>{m.splitTag=c}),{tag:c,fileName:c,className:c,routes:l.items.length,categories:[...l.categories].sort()}})}function nr(e,t){let r=t.match??{};return!!(r.prefix&&e.raw.startsWith(r.prefix)||r.regex&&new RegExp(r.regex).test(e.raw))}function Xe(e,t){let r=e,n=2;for(;t.has(r.toLowerCase());)r=`${e}${n}`,n+=1;return t.add(r.toLowerCase()),r}function sr(e,t){let r=0;for(;e.length>1&&r<e.length;){let n=e[r];if(n.routes>=t.minBucketRoutes){r+=1;continue}let s=e[r-1];if(s&&s.routes+n.routes<=t.maxRoutes){s.plans.push(...n.plans),s.routes+=n.routes,e.splice(r,1),r=Math.max(r-1,0);continue}let o=e[r+1];if(o&&o.routes+n.routes<=t.maxRoutes){o.plans.unshift(...n.plans),o.routes+=n.routes,e.splice(r,1);continue}r+=1}}function Re(e,t,r,n){let s=[],o=[],i=0;for(let a of e)i>0&&i+a.routes>r.targetRoutes&&(s.push({plans:o,routes:i}),o=[],i=0),o.push(a),i+=a.routes;return o.length&&s.push({plans:o,routes:i}),sr(s,r),s.map(a=>{let l=t?K(re(t).slug||"bucket"):s.length===1?"Modules":a.plans[0].fileName,u=Xe(l,n);return{fileName:u,className:u,category:t,routes:a.routes,namespaces:a.plans.map(p=>p.raw)}})}function or(e,t,r,n,s){if(e.length===0)return[];if(t<=r.minRoutes){let l=Xe("Modules",n),u=e.reduce((p,c)=>p+c.routes,0);return[{fileName:l,className:l,category:"",routes:u,namespaces:e.map(p=>p.raw)}]}if(r.categories.length===0)return Re(e,"",r,n);let o=[],i=new Set(e.map(l=>l.raw));for(let l of r.categories){let u=e.filter(p=>i.has(p.raw)&&nr(p,l));u.forEach(p=>i.delete(p.raw)),u.length&&o.push(...Re(u,l.name,r,n))}let a=e.filter(l=>i.has(l.raw));return a.length&&(s.push(`\u672A\u547D\u4E2D\u5206\u7C7B\u7684\u547D\u540D\u7A7A\u95F4\u5F52\u5165 ${r.fallback}\uFF1A${a.map(l=>l.raw).join("\u3001")}`),o.push(...Re(a,r.fallback,r,n))),o}import V from"fs";import B from"path";import $ from"typescript";var Ee=`${E}/index`;function ir(e){return $.isInterfaceDeclaration(e)||$.isTypeAliasDeclaration(e)||$.isEnumDeclaration(e)||$.isClassDeclaration(e)||$.isFunctionDeclaration(e)||$.isVariableStatement(e)}function ke(e){if($.isVariableStatement(e)){let r=e.declarationList.declarations[0];return r&&$.isIdentifier(r.name)?r.name.text:null}let t=e;return t.name&&$.isIdentifier(t.name)?t.name.text:null}function ar(e){return $.canHaveModifiers(e)?!!$.getModifiers(e)?.some(t=>t.kind===$.SyntaxKind.ExportKeyword):!1}function cr(e,t){let r={target:$.ScriptTarget.ESNext,module:$.ModuleKind.ESNext,noResolve:!0,skipLibCheck:!0,noEmit:!0},n=$.createCompilerHost(r),s=n.getSourceFile.bind(n),o=$.createSourceFile(e,t,$.ScriptTarget.Latest,!0,$.ScriptKind.TS);n.getSourceFile=(a,l,u,p)=>a===e?o:s(a,l,u,p);let i=$.createProgram({rootNames:[e],options:r,host:n});return{sourceFile:o,checker:i.getTypeChecker()}}function lr(e,t=`${E}/index.ts`){let{sourceFile:r,checker:n}=cr(t,e),s=new Map,o=r.statements.filter(ir),i=new Set;for(let p of o){let c=ke(p);c&&(s.set(p,c),i.add(c))}let a=r.statements[0],l=a?e.slice(0,a.getStart(r)).trimEnd():"",u=[];for(let p of o){let c=ke(p);if(!c)continue;let m=ar(p),f=p.getStart(r,!0),d=p.getStart(r)-f,h=e.slice(f,p.getEnd()),w=m?h:`${h.slice(0,d)}export ${h.slice(d)}`,k=new Set,b=I=>{if($.isIdentifier(I)&&I.text!==c&&i.has(I.text)){let N=n.getSymbolAtLocation(I)?.declarations?.find(v=>s.has(v)),A=N?s.get(N):void 0;A&&A!==c&&k.add(A)}$.forEachChild(I,b)};b(p),u.push({name:c,value:$.isEnumDeclaration(p),exported:m,text:w,refs:k})}return{header:l,declarations:u}}function ur(e,t="module.ts"){let r=$.createSourceFile(t,e,$.ScriptTarget.Latest,!0,$.ScriptKind.TS),n=new Set;for(let s of r.statements){if(!$.isImportDeclaration(s)||!$.isStringLiteral(s.moduleSpecifier)||!s.moduleSpecifier.text.endsWith(Ee))continue;let i=s.importClause?.namedBindings;if(!(!i||!$.isNamedImports(i)))for(let a of i.elements)n.add((a.propertyName??a.name).text)}return n}function pr(e,t){let r=new Set(e.map(i=>i.name)),n=new Map;for(let i of e)n.set(i.name,new Set);for(let i of t)for(let a of ur(i.source,`${i.file}.ts`))r.has(a)&&n.get(a)?.add(i.file);let s=!0;for(;s;){s=!1;for(let i of e){let a=n.get(i.name);if(a)for(let l of i.refs){let u=n.get(l);if(u)for(let p of a)u.has(p)||(u.add(p),s=!0)}}}let o=new Map;for(let i of e){let a=n.get(i.name)??new Set;o.set(i.name,a.size===1?[...a][0]:q)}return o}function fr(e,t,r,n,s){let o=new Map;for(let a of t)for(let l of a.refs){let u=r.get(l);if(!u||u===e)continue;let p=o.get(u)??{values:[],types:[]};!s&&n.has(l)?p.values.push(l):p.types.push(l),o.set(u,p)}let i=[];for(let[a,l]of[...o.entries()].sort(([u],[p])=>u.localeCompare(p)))l.values.length&&i.push(`import { ${[...new Set(l.values)].sort().join(", ")} } from "./${a}"`),l.types.length&&i.push(`import type { ${[...new Set(l.types)].sort().join(", ")} } from "./${a}"`);return i}function be(e,t,r){let n=new Map;for(let o of e){if(!o.exported||r.runtimeOnly&&!o.value)continue;let i=t.get(o.name)??q,a=n.get(i)??{values:[],types:[]};o.value?a.values.push(o.name):a.types.push(o.name),n.set(i,a)}let s=[];for(let[o,i]of[...n.entries()].sort(([a],[l])=>a.localeCompare(l)))i.values.length&&s.push(`export { ${i.values.join(", ")} } from "./${o}"`),i.types.length&&s.push(`export type { ${i.types.join(", ")} } from "./${o}"`);return s}function mr(e,t,r){let n=new Map;for(let l of e.declarations){let u=t.get(l.name)??q,p=n.get(u);p?p.push(l):n.set(u,[l])}let s=new Set(e.declarations.filter(l=>l.value).map(l=>l.name)),o=new Map,i=e.header?`${e.header}
8
+ `:"",a=r.toJS?".d.ts":".ts";for(let[l,u]of n){let p=fr(l,u,t,s,r.toJS),c=u.map(m=>m.text.trimEnd()).join(`
9
+
10
+ `);o.set(`${l}${a}`,[i,p.length?`${p.join(`
11
+ `)}
12
+ `:"",c,""].filter(Boolean).join(`
13
+ `))}return r.toJS?(o.set("index.js",[i,...be(e.declarations,t,{runtimeOnly:!0}),""].filter(Boolean).join(`
14
+ `)),o.set("index.d.ts",[i,...be(e.declarations,t,{runtimeOnly:!1}),""].filter(Boolean).join(`
15
+ `))):o.set("index.ts",[i,...be(e.declarations,t,{runtimeOnly:!1}),""].filter(Boolean).join(`
16
+ `)),o}function gr(e){let t=$.createSourceFile(`${Ee}.js`,e,$.ScriptTarget.Latest,!0,$.ScriptKind.JS),r=new Map;for(let n=0;n<t.statements.length;n+=1){let s=t.statements[n];if(!$.isVariableStatement(s))continue;let o=ke(s);if(!o)continue;let i=s.getEnd(),a=t.statements[n+1];a&&$.isExpressionStatement(a)&&a.expression.getText(t).includes(o)&&(i=a.getEnd(),n+=1),r.set(o,e.slice(s.getStart(t),i))}return r}function dr(e,t,r){let n=gr(e),s=new Map;for(let[i,a]of n){let l=t.get(i)??q,u=s.get(l);u?u.push(a):s.set(l,[a])}let o=new Map;for(let[i,a]of s)o.set(i,[r,...a,""].filter(Boolean).join(`
17
+ `));return o}function Ce(e){return V.existsSync(e)?V.readFileSync(e,"utf8"):null}function ve(e){let t=B.join(e.dir,E),r=e.toJS?"index.d.ts":"index.ts",n=Ce(B.join(t,r));if(!n)return{written:[],errors:[`\u7F3A\u5C11\u5951\u7EA6\u51FA\u53E3\uFF1A${E}/${r}`]};let s=lr(n,`${Ee}${B.extname(r)}`),o=e.moduleFiles.map(c=>({file:c,source:Ce(B.join(e.dir,`${c}${e.toJS?".d.ts":".ts"}`))})).filter(c=>!!c.source),i=pr(s.declarations,o),a=mr(s,i,{toJS:e.toJS});if(e.toJS){let c=Ce(B.join(t,"index.js"));if(c)for(let[m,f]of dr(c,i,s.header))a.set(`${m}.js`,f)}let l=[],u=new Set(["index.ts","index.js","index.d.ts"]);for(let c of a.keys()){if(u.has(c)||!e.knownFiles)continue;let m=`${E}/${c}`;V.existsSync(B.join(e.dir,m))&&!e.knownFiles.has(m)&&l.push(`\u8F93\u51FA\u76EE\u5F55\u5B58\u5728\u540C\u540D\u624B\u5199\u6587\u4EF6\uFF1A${m}\uFF08\u4E0D\u5C5E\u4E8E\u4E0A\u4E00\u8F6E\u751F\u6210\u6E05\u5355\uFF09`)}if(l.length>0)return{written:[],errors:l};let p=[];for(let[c,m]of a){let f=`${E}/${c}`;V.mkdirSync(B.dirname(B.join(e.dir,f)),{recursive:!0}),V.writeFileSync(B.join(e.dir,f),m),p.push(f)}return{written:p,errors:l}}var x={files:[],param:{}},y={home:tt.homedir(),enum:{}},G=0,P=[],M=null,Sr=()=>process.argv.includes("--dry-run"),$r=()=>process.argv.includes("--json"),T=()=>process.argv.includes("--check");function Ze(){return R.join(tt.tmpdir(),`swagger2api-${process.pid}-${Date.now()}.json`)}function ce(e,t=0){e&&console.log(e),process.exit(t)}async function wr(){y.param={config:D(["--config","-c"]),configScan:S(["--config-scan","-cs"])??!0,configAll:S(["--config-all","-ca"]),quick:S(["--quick","-q"]),replaceTags:Fe(["--replace-tags","-rt"],{length:2}),convertGet:S(["--convert-get","-cg"]),removeParam:S(["--remove-param","-rp"]),removePrefixIndex:D(["--remove-prefix-index","-rpi"]),removeDts:S(["--remove-dts","-rd"]),removeEmptyComponents:S(["--remove-empty-components","-rec"])??!0,extractRequestQuery:D(["--extract-request-query","-erq"]),extractResponseRaw:S(["--extract-response-raw","-err"]),template:R.resolve(Ae(),"./templates")},y.config={templates:D(["--templates","-t"])??y.param.template,defaultResponseAsSuccess:S(["--default-as-success","-d"]),generateResponses:S(["--responses","-r"]),generateUnionEnums:S("--union-enums"),addReadonly:S("--add-readonly"),generateRouteTypes:S("--route-types"),generateClient:!S("--no-client"),enumNamesAsValues:S("--enum-names-as-values"),extractRequestParams:S("--extract-request-params"),extractRequestBody:S("--extract-request-body"),extractResponseBody:S("--extract-response-body"),extractResponseError:S("--extract-response-error"),modular:S("--modular"),toJS:S("--js"),moduleNameIndex:Number(D("--module-name-index")??0),moduleNameFirstTag:S("--module-name-first-tag"),httpClientType:S("--axios")?"axios":"fetch",unwrapResponseData:S("--unwrap-response-data"),disableThrowOnError:S("--disable-throw-on-error"),singleHttpClient:S("--single-http-client"),silent:S("--silent")??!0,defaultResponseType:D("--default-response")??"void",typePrefix:D("--type-prefix")??"",typeSuffix:D("--type-suffix")??"",cleanOutput:S("--clean-output"),pruneOutput:S("--prune-output"),...D("--api-class-name")?{apiClassName:D("--api-class-name")}:{},patch:S("--patch"),debug:S("--debug"),anotherArrayType:S("--another-array-type"),sortTypes:S("--sort-types"),extractEnums:S("--extract-enums")},Nr()}function O(e){let t=process.argv.slice(2);return e.some(r=>t.includes(r))}function Nr(){let e=He(),t=_e(process.cwd(),{projectFile:e.configFile});t.warnings.forEach(m=>console.error("\u26A0\uFE0F",m));let r=Be(he(Ue(he(t.merged),e.profile))),n=r.input??{},s=r.output??{},o=r.types??{},i=r.naming??{},a=r.grouping??{},l=n.url??n.file;if(!l)return;let u=t.project.file?R.dirname(R.resolve(t.project.file)):process.cwd();y.rcDriven=!0,y.rcUrl=Y(l)?l:R.resolve(u,l),y.rcOutput=R.resolve(u,s.dir??"./src/api"),y.rcName=s.name??"index";let p=y.param;p.quick=!0,!O(["--remove-prefix-index","-rpi"])&&i.pathPrefixIndex!==void 0&&(p.removePrefixIndex=String(i.pathPrefixIndex)),!O(["--convert-get","-cg"])&&i.convertGetToQuery!==void 0&&(p.convertGet=i.convertGetToQuery),!O(["--remove-param","-rp"])&&i.dropPathParams!==void 0&&(p.removeParam=i.dropPathParams),!O(["--extract-request-query","-erq"])&&o.extractQuery!==void 0&&(p.extractRequestQuery=o.extractQuery),!O(["--extract-response-raw","-err"])&&o.extractResponseRaw!==void 0&&(p.extractResponseRaw=!!o.extractResponseRaw),!O(["--remove-dts","-rd"])&&o.removeDts!==void 0&&(p.removeDts=o.removeDts),!O(["--replace-tags","-rt"])&&i.tagRewrite&&(p.replaceTags=i.tagRewrite);let c=y.config;!O(["--axios"])&&r.client?.type&&(c.httpClientType=r.client.type==="axios"?"axios":"fetch"),!O(["--js"])&&r.language?.target&&(c.toJS=r.language.target==="js"),!O(["--responses","-r"])&&o.responses!==void 0&&(c.generateResponses=!!o.responses),!O(["--unwrap-response-data"])&&o.unwrapData!==void 0&&(c.unwrapResponseData=!!o.unwrapData),!O(["--extract-request-params"])&&o.extractParams!==void 0&&(c.extractRequestParams=!!o.extractParams),!O(["--clean-output"])&&s.clean!==void 0&&(c.cleanOutput=!!s.clean),!O(["--modular"])&&s.mode==="grouped"&&(c.modular=!0),O(["--prune-output"])||(c.pruneOutput=s.prune===void 0?!!c.modular:!!s.prune),!O(["--module-name-index"])&&a.pathDepth!==void 0&&(c.moduleNameIndex=Number(a.pathDepth)),Object.keys(a).length&&(c.grouping=a)}async function Rr(){if(y.rcDriven){x.files=["(swagger2apirc)"];return}y.param.config?x.files=y.param.config.split(","):y.param.configScan&&(x.files=Oe()),x.files.length==0&&(x.files=["saconfig.json"]),!y.param.configAll&&x.files.length>1&&(x.files=(await rt({type:"multiselect",name:"files",message:"\u9009\u62E9\u914D\u7F6E\u6587\u4EF6",hint:"\u53EF\u591A\u9009\uFF0C\u7A7A\u683C\u952E\u52FE\u9009\uFF0C\u56DE\u8F66\u5B8C\u6210",choices:x.files.map(e=>({title:e.replace(/\\/g,"/"),value:e}))}).then(e=>e.files?.length!=0?e:ce("\u7ED3\u675F\uFF1A\u81F3\u5C11\u9009\u62E9\u4E00\u4E2A\u914D\u7F6E\u6587\u4EF6"))).files),x.files?.length>0||ce("\u7ED3\u675F\uFF1A\u624B\u52A8\u9000\u51FA")}async function br(){if(y.rcDriven){x.param={url:y.rcUrl,output:y.rcOutput,name:y.rcName},y.docFile=Ze();return}try{x.param={},x.param=JSON.parse(L.readFileSync(x.file,"utf-8"))}catch{}(!y.param.quick||[x.param.url,x.param.output,x.param.name].includes(void 0))&&(x.param=await rt([{name:"url",type:"text",message:"Swagger docs \u5730\u5740:",initial:x.param.url??"https://example.com/v3/api-docs"},{name:"output",type:"text",message:"\u8F93\u51FA\u5730\u5740:",initial:x.param.output??"./src/api"},{name:"name",type:"text",message:"\u6587\u4EF6\u540D:",initial:x.param.name??"index"}])),[x.param.url,x.param.output,x.param.name].includes(void 0)&&ce("\u7ED3\u675F\uFF1A\u624B\u52A8\u9000\u51FA"),y.docFile=Ze()}async function nt(e=0){if(x.file=x.files[e],await br(),Y(x.param.url))await yr.get(x.param.url).then(t=>et(t.data)).catch(t=>console.log("\u5931\u8D25\uFF1A",t));else try{await et(JSON.parse(L.readFileSync(R.resolve(x.param.url),"utf8")))}catch(t){console.log("\u5931\u8D25\uFF1A",t)}x.files[e+1]?await nt(e+1):G>0&&ce(`\u7ED3\u675F\uFF1A${G} \u4E2A\u6587\u6863\u672A\u751F\u6210\uFF0C\u5931\u8D25\u539F\u56E0\u89C1\u4E0A\u65B9\u8F93\u51FA`,1)}function Cr(e){let t=y.param.replaceTags;if(!t?.length)return;let[r,n]=t;if(!r||typeof n!="string"){console.error("\u26A0\uFE0F \u5DF2\u5FFD\u7565 --replace-tags\uFF1A\u9700\u8981\u300C\u5339\u914D + \u66FF\u6362\u300D\u4E24\u4E2A\u503C\uFF0C\u56DE\u843D\u5230\u4FDD\u7559\u539F\u59CB\u6807\u7B7E");return}Object.values(e.paths??{}).forEach(s=>{Object.values(s).forEach(o=>{Array.isArray(o?.tags)&&(o.tags=o.tags.map(i=>i.replace(new RegExp(`^${r}$`,"g"),n)))})})}function ae(e,t){let r=t?[...t.buckets.map(n=>n.fileName),...t.namespaces.flatMap(n=>n.chunks.map(s=>s.fileName)),...t.namespaces.filter(n=>n.chunks.length>0).map(n=>n.fileName)]:e.map(n=>n.fileName);return[...new Set(r)]}function st(e,t=e){let r=[];for(let n of L.readdirSync(e,{withFileTypes:!0})){let s=R.join(e,n.name);n.isDirectory()?r.push(...st(s,t)):r.push(R.relative(t,s).split(R.sep).join("/"))}return r.sort()}function kr(e,t){let r=st(t),n=[];for(let o of r){let i=R.join(e,o);if(!L.existsSync(i)){n.push(`\u7F3A\u5C11\u4EA7\u7269\uFF1A${o}`);continue}let a=L.readFileSync(R.join(t,o),"utf8").replace(/\r\n/g,`
18
+ `),l=L.readFileSync(i,"utf8").replace(/\r\n/g,`
19
+ `);a!==l&&n.push(`\u4EA7\u7269\u4E0D\u4E00\u81F4\uFF1A${o}`)}let s=oe(W(e));for(let o of s?.files??[])r.includes(o)||n.push(`\u4EA7\u7269\u5DF2\u8FC7\u671F\uFF1A${o}`);if(n.length>0){G+=1,console.error(`
20
+ \u2716 \u4EA7\u7269\u6821\u9A8C\u672A\u901A\u8FC7\uFF1A${n.length} \u9879`),n.forEach(o=>console.error(` - ${o}`));return}console.log("\u6821\u9A8C\uFF1A\u4EA7\u7269\u4E0E\u5F53\u524D\u914D\u7F6E\u4E00\u81F4")}function Er(e,t,r){let n=!!y.config.toJS,s=n?".js":".ts",o=R.resolve(x.param.output??"./src/api"),i=L.existsSync(o)?L.readdirSync(o):[],a=ae(e,r),u=a.flatMap(c=>n?[`${c}${s}`,`${c}.d.ts`]:[`${c}${s}`]).filter(c=>!i.includes(c)),p=se(i,e,s,a);if($r()){console.log(JSON.stringify({groups:e.map(({raw:c,fileName:m,className:f,property:d,importFrom:h,reason:w,source:k})=>({raw:c,fileName:m,className:f,property:d,importFrom:h,reason:w,source:k})),unmatchedRules:t,add:u,orphans:p,split:r?{total:r.total,buckets:r.buckets.map(({fileName:c,category:m,routes:f,namespaces:d})=>({fileName:c,category:m,routes:f,namespaces:d})),shards:r.namespaces.filter(c=>c.chunks.length>0).map(({raw:c,fileName:m,className:f,routes:d,chunks:h})=>({raw:c,fileName:m,className:f,routes:d,chunks:h.map(({fileName:w,routes:k,categories:b})=>({fileName:w,routes:k,categories:b}))}))}:void 0},null,2));return}e.forEach(c=>console.log(`\u547D\u540D\uFF1A${c.raw} \u2192 ${c.fileName}\uFF08\u7C7B ${c.className}${c.reason?`\uFF0C${c.reason}`:""}\uFF09`)),r?.buckets.forEach(c=>console.log(`\u6876\uFF1A${c.fileName}\uFF08${c.namespaces.length} \u4E2A\u547D\u540D\u7A7A\u95F4 / ${c.routes} \u6761${c.category?`\uFF0C\u5206\u7C7B ${c.category}`:""}\uFF09`)),r?.namespaces.filter(c=>c.chunks.length>0).forEach(c=>console.log(`\u5206\u7247\uFF1A${c.raw} \u2192 ${c.chunks.map(m=>`${m.fileName}\uFF08${m.routes} \u6761\uFF09`).join("\u3001")}`)),t.length&&console.error(`\u26A0\uFE0F \u672A\u547D\u4E2D\u89C4\u5219\uFF1A${t.map(c=>c+1).join("\u3001")}`),u.length&&console.log(`\u9884\u8BA1\u65B0\u589E\uFF1A${u.join("\u3001")}`),p.length&&console.error(`\u26A0\uFE0F \u8868\u5916\u4EA7\u7269\uFF08\u5EFA\u8BAE\u5F00\u542F output.prune\uFF09\uFF1A${p.join("\u3001")}`)}function vr(){let e=new Map;return{onCreateRouteName(t,r){let n=`${r?.tags?.[1]??""}|${t.original}`,s=(e.get(n)??0)+1;return e.set(n,s),{...t,usage:s>1?`${t.original}${s}`:t.original,duplicate:s>1}}}}async function et(e){let t=null;if(typeof e?.paths!="object")return console.log("\u5931\u8D25\uFF1A\u7F3A\u5C11paths\u5B57\u6BB5");let r=await Te(e,{baseUrl:Y(x.param.url)?x.param.url:void 0});if(r.errors.length>0){r.errors.forEach(a=>console.error("\u5931\u8D25\uFF1A",a)),G+=1;return}let n=R.resolve(x.param.output),s=null;if(T()){if(!L.existsSync(n)){console.error(`\u5931\u8D25\uFF1A--check \u9700\u8981\u5DF2\u6709\u4EA7\u7269\u76EE\u5F55\uFF1A${n}`),G+=1;return}s=L.mkdtempSync(R.join(R.dirname(n),".swagger2api-check-")),x.param.output=s,process.once("exit",()=>L.rmSync(s,{recursive:!0,force:!0}))}P=[],M=null,y.param.moduleClassNames=void 0,y.param.splitBuckets=void 0,Cr(e);let o=y.config.grouping;if(y.config.modular&&o&&(o.strategy?.length||o.rules?.length||o.split)){let a=Qe(e,o);if(a.warnings.forEach(l=>console.error("\u26A0\uFE0F",l)),a.errors.length>0){a.errors.forEach(l=>console.error("\u5931\u8D25\uFF1A",l)),G+=1;return}if(P=a.entries,M=a.split??null,y.config.moduleNameFirstTag=!0,y.param.moduleClassNames=a.moduleClassNames??We(a.entries),y.param.splitBuckets=a.split?.bucketLayout,o.preserveTags!==!1&&(y.param.groupOriginalTags=a.originalTags),console.log("\u5206\u7EC4\uFF1A",...Object.entries(a.counts).map(([l,u])=>`${l}-${u}`)),Sr()){Er(a.entries,a.unmatchedRules,M);return}}if(y.config.modular&&P.length){let a=R.resolve(x.param.output);t=oe(W(a));let u=Ve(a,M?[]:P,!!y.config.toJS,t,ae(P,M));if(u.length>0){u.forEach(p=>console.error(`\u5931\u8D25\uFF1A\u8F93\u51FA\u76EE\u5F55\u5B58\u5728\u540C\u540D\u624B\u5199\u6587\u4EF6\uFF1A${p}\uFF08\u4E0D\u5C5E\u4E8E\u4E0A\u4E00\u8F6E\u751F\u6210\u6E05\u5355\uFF09\uFF0C\u5DF2\u7EC8\u6B62\u751F\u6210\uFF1B\u786E\u8BA4\u53EF\u8986\u76D6\u540E\u5220\u9664\u8BE5\u6587\u4EF6\u6216\u8C03\u6574\u5206\u7EC4\u540D`)),G+=1;return}}if(Object.entries(e.paths).forEach(a=>{Object.keys(a[1]).forEach(l=>{let u=`${a[0]}/${l}`;if(y.param.convertGet&&(u=u.replace(/([^\}]\/)get$/g,"$1query")),y.param.removeParam&&(u=u.replace(/\/\{.+?\}/g,"")),y.param.removePrefixIndex){let c=u.split("/");c=c.slice(0,1).concat(c.slice(Number(y.param.removePrefixIndex)+2)),u=c.join("/")}u=u.replace(/["\\`\r\n]/g,"_").replace(/\$\{/g,"_"),e.paths[a[0]][l].operationId=u;let p=u.split("/").slice(-1)[0];typeof y.enum[p]=="number"?y.enum[p]++:y.enum[p]=1})}),Object.entries(e.components).forEach(a=>{Object.keys(a[1]).forEach(l=>{y.param.removeEmptyComponents&&!Object.keys(e.components[a[0]][l]).length&&delete e.components[a[0]][l]})}),console.log("\u5C31\u7EEA\uFF1A",...Object.entries(y.enum).map(a=>a.join("-"))),pe(y.docFile,JSON.stringify(e)),y.config.modular){let a=y.config;a.fileNames={...a.fileNames??{},dataContracts:`${E}/index`,httpClient:j},L.mkdirSync(R.join(R.resolve(x.param.output),E),{recursive:!0})}console.log("\u6267\u884C\uFF1A",x.file);let i=await xr({fileName:`${x.param.name}.ts`,output:R.resolve(x.param.output),input:y.docFile,...y.config,...M?{hooks:vr()}:{},param:y.param});if(console.log(T()?"\u6821\u9A8C\uFF1A":"\u5B8C\u6210\uFF1A",R.resolve(T()?n:x.param.output,`${x.param.name}${y.config.toJS?".js":".ts"}`)),y.config.modular){let a=R.resolve(x.param.output),l=String(y.config.apiClassName??"Api"),u=!!y.config.toJS;if(P.length){let p=ae(P,M);M&&Ye(a,M.namespaces,u);let c=ve({dir:a,moduleFiles:p,toJS:u,knownFiles:new Set(t?.files??[])});if(c.errors.length>0){c.errors.forEach(h=>console.error("\u5931\u8D25\uFF1A",h)),G+=1;return}let m=Ne(a,P,u,{aggregate:!1,extraFiles:p});if(m.errors.length>0){m.errors.forEach(h=>console.error("\u5931\u8D25\uFF1A",h)),G+=1;return}we(a,l,u,ze(P));let{errors:f,orphans:d}=Ne(a,P,u,{extraFiles:p});if(f.length>0){f.forEach(h=>console.error("\u5931\u8D25\uFF1A",h)),G+=1;return}d.forEach(h=>console.error("\u26A0\uFE0F \u8868\u5916\u4EA7\u7269\uFF08\u5EFA\u8BAE\u5F00\u542F output.prune\uFF09\uFF1A",h))}else{let p=(i.files??[]).map(f=>`${String(f.fileName??"").replace(/\\/g,"/")}${f.fileExtension??""}`).filter(f=>!!f&&!f.startsWith(".")),c=p.filter(f=>!f.includes("/")&&!f.endsWith(".d.ts")).map(f=>f.slice(0,f.lastIndexOf("."))).filter(f=>!!f&&!["index",j,"route-types"].includes(f)&&!f.endsWith("Route"));if(!T()){let f=oe(W(a));$e(a,f,p.length>0?p:ie(a,[],u)).forEach(d=>console.log("\u6E05\u7406\uFF1A",R.resolve(a,d)))}let m=ve({dir:a,moduleFiles:c,toJS:u,knownFiles:null});if(m.errors.length>0){m.errors.forEach(f=>console.error("\u5931\u8D25\uFF1A",f)),G+=1;return}we(a,l,u),T()||Se(W(a),ie(a,[],u,c))}if(T()||Ke(a,u).forEach(p=>console.log("\u6E05\u7406\uFF1A",R.resolve(a,p))),P.length){let p=ie(a,M?[]:P,u,ae(P,M));(y.config.pruneOutput&&!T()?$e(a,t,p):[]).forEach(m=>console.log("\u6E05\u7406\uFF1A",R.resolve(a,m))),T()||Se(W(a),p)}}y.config.toJS&&console.log(T()?"\u6821\u9A8C\uFF1A":"\u5B8C\u6210\uFF1A",R.resolve(T()?n:x.param.output,`${x.param.name}.d.ts`)),s&&kr(n,s),L.existsSync(y.docFile)&&L.unlinkSync(y.docFile),y.param.removeDts&&!T()&&(console.log("\u6E05\u7406\uFF1A",R.resolve(x.param.output,`${x.param.name}.d.ts`)),hr(`npx rimraf ${R.resolve(x.param.output,`${x.param.name}.d.ts`)}`,{cwd:y.home}).toString()),y.rcDriven||pe(x.file,JSON.stringify(x.param,null,2))}async function En(){await wr(),await Rr(),nt()}export{En as generateApi};
@@ -8,7 +8,9 @@ const isModular = Boolean(config.modular && route);
8
8
  const moduleName = isModular ? route.moduleName : "";
9
9
  // 分组模式由命名表提供类名,与聚合入口同源;未分组时沿用依赖的 pascalCase
10
10
  const moduleClassName = isModular ? (config.param?.moduleClassNames?.[moduleName] ?? pascalCase(moduleName)) : "";
11
- const moduleRoutes = isModular ? (route.routes || []) : [];
11
+ const moduleRoutes = isModular ? (route.routes || []) : [];
12
+ // 分桶文件:按命名空间渲染多个类;未配置时走单类分支
13
+ const bucketNamespaces = isModular ? config.param?.splitBuckets?.[moduleName] : undefined;
12
14
  const dataContractsFile = config.fileNames?.dataContracts ?? "data-contracts";
13
15
  const httpClientFile = config.fileNames?.httpClient ?? "http-client";
14
16
  const dataContracts = isModular ? _.map(it.modelTypes, "name") : [];
@@ -43,13 +45,49 @@ import { HttpClient, RequestParams, ContentType } from "./<%~ httpClientFile %>"
43
45
  import { <%~ dataContracts.join(", ") %> } from "./<%~ dataContractsFile %>"
44
46
  <% } %>
45
47
 
48
+ <% if (bucketNamespaces) { %>
49
+ <% for (const ns of bucketNamespaces) { %>
50
+ <% const nsRoutes = moduleRoutes.filter((item) => item.raw?.tags?.[1] === ns.tag); %>
51
+ /** <%~ ns.title %> 模块 */
52
+ export class <%~ ns.className %><SecurityDataType = unknown> {
53
+ /** 共享请求器:由聚合入口注入;仅供模块内部调用,勿在业务侧直接使用 */
54
+ http: HttpClient<SecurityDataType>
55
+
56
+ constructor(http: HttpClient<SecurityDataType>) {
57
+ this.http = http
58
+ }
59
+
60
+ /** 底层请求实例:与聚合入口保持同一个 */
61
+ get instance(): HttpClient<SecurityDataType>["instance"] {
62
+ return this.http.instance
63
+ }
64
+ <% for (const item of nsRoutes) { %>
65
+
66
+ <%~ includeFile('./procedure-call.ejs', { ...it, route: { ...item, namespace: undefined }, moduleClient: true }) %>
67
+ <% } %>
68
+ }
69
+
70
+ <% } %>
71
+ <% } else { %>
46
72
  /** <%~ moduleName %> 模块 */
47
- export class <%~ moduleClassName %><SecurityDataType = unknown> extends HttpClient<SecurityDataType> {
73
+ export class <%~ moduleClassName %><SecurityDataType = unknown> {
74
+ /** 共享请求器:由聚合入口注入;仅供模块内部调用,勿在业务侧直接使用 */
75
+ http: HttpClient<SecurityDataType>
76
+
77
+ constructor(http: HttpClient<SecurityDataType>) {
78
+ this.http = http
79
+ }
80
+
81
+ /** 底层请求实例:与聚合入口保持同一个 */
82
+ get instance(): HttpClient<SecurityDataType>["instance"] {
83
+ return this.http.instance
84
+ }
48
85
  <% for (const item of moduleRoutes) { %>
49
86
 
50
- <%~ includeFile('./procedure-call.ejs', { ...it, route: { ...item, namespace: undefined } }) %>
87
+ <%~ includeFile('./procedure-call.ejs', { ...it, route: { ...item, namespace: undefined }, moduleClient: true }) %>
51
88
  <% } %>
52
89
  }
90
+ <% } %>
53
91
 
54
92
  <% } else { %>
55
93
 
@@ -1,5 +1,5 @@
1
1
  <%
2
- const { utils, route, config } = it;
2
+ const { utils, route, config, moduleClient } = it;
3
3
  const { requestBodyInfo, responseBodyInfo, specificArgNameResolver } = route;
4
4
  const { _, getInlineParseContent, getParseContent, parseSchema, getComponentByRef, require } = utils;
5
5
  const { parameters, path, method, payload, query, formData, security, requestParams } = route.request;
@@ -72,12 +72,20 @@ const bodyContentKindTmpl = requestContentKind[requestBodyInfo.contentKind] || n
72
72
  const responseFormatTmpl = responseContentKind[responseBodyInfo.success && responseBodyInfo.success.schema && responseBodyInfo.success.schema.contentKind] || null;
73
73
  const securityTmpl = security ? 'true' : null;
74
74
 
75
+ // 响应类型:分组模式的声明由 tsc 生成,用内联导入避免模块声明丢失类型导入
76
+ const httpClientFile = config.fileNames?.httpClient ?? "http-client";
77
+ const responseTypeRef = () => {
78
+ if (!moduleClient) return "AxiosResponse";
79
+ const target = config.param?.extractResponseRaw ? `./${httpClientFile}` : "axios";
80
+ return `import("${target}").AxiosResponse`;
81
+ };
82
+
75
83
  const describeReturnType = () => {
76
84
  if (!config.toJS) return "";
77
85
 
78
86
  switch(config.httpClientType) {
79
87
  case HTTP_CLIENT.AXIOS: {
80
- return `Promise<AxiosResponse<${type}>>`
88
+ return `Promise<${responseTypeRef()}<${type}>>`
81
89
  }
82
90
  default: {
83
91
  return `Promise<HttpResponse<${type}, ${errorType}>`
@@ -97,7 +105,7 @@ const isValidIdentifier = (name) => /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name);
97
105
 
98
106
  */
99
107
  <% if (isValidIdentifier(route.routeName.usage)) { %><%~ route.routeName.usage %><%~ route.namespace ? ': ' : ' = ' %><% } else { %>"<%~ route.routeName.usage %>"<%~ route.namespace ? ': ' : ' = ' %><% } %>(<%~ wrapperArgs %>)<%~ config.toJS ? `: ${describeReturnType()}` : "" %> =>
100
- <%~ config.singleHttpClient ? 'this.http.request' : 'this.request' %><<%~ type %>, <%~ errorType %>>({
108
+ <%~ config.singleHttpClient || moduleClient ? 'this.http.request' : 'this.request' %><<%~ type %>, <%~ errorType %>>({
101
109
  path: `<%~ path %>`,
102
110
  method: '<%~ _.upperCase(method) %>',
103
111
  <%~ queryTmpl ? `query: ${queryTmpl},` : '' %>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fxri/swagger2api",
3
- "version": "1.3.0",
3
+ "version": "1.3.1",
4
4
  "description": "基于 swagger-typescript-api,将 Swagger 文档自动转为 TypeScript 格式的 API 文件。",
5
5
  "license": "MIT",
6
6
  "author": {
@@ -24,6 +24,7 @@
24
24
  },
25
25
  "files": [
26
26
  "dist",
27
+ "skills",
27
28
  "README.md",
28
29
  "CHANGELOG.md",
29
30
  "LICENSE",
@@ -31,6 +32,7 @@
31
32
  "NOTICE",
32
33
  "package.json"
33
34
  ],
35
+ "agentSkills": "./skills",
34
36
  "keywords": [
35
37
  "swagger",
36
38
  "typescript",
@@ -44,7 +46,8 @@
44
46
  "dependencies": {
45
47
  "axios": "^1.21.0",
46
48
  "prompts": "^2.4.2",
47
- "swagger-typescript-api": "13.0.28"
49
+ "swagger-typescript-api": "13.0.28",
50
+ "typescript": "^5.9.3"
48
51
  },
49
52
  "devDependencies": {
50
53
  "@types/node": "^18.19.0",
@@ -56,7 +59,6 @@
56
59
  "eslint": "^10.15.0",
57
60
  "eslint-config-prettier": "^10.1.8",
58
61
  "tsup": "^8.5.1",
59
- "typescript": "^5.9.3",
60
62
  "vitepress": "^1.6.4",
61
63
  "vitest": "^4.1.12"
62
64
  },
@@ -0,0 +1,51 @@
1
+ ---
2
+ name: fxri-swagger2api
3
+ description: 首次为项目初始化 swagger2api 配置、迁移旧脚本配置或调整产物结构时加载:给出最小配置、先预览再落盘、说明分组产物与验收方式。日常生成、--check 与验收不加载。不用于一般 TypeScript / axios 用法或接口文档编写。
4
+ license: MIT
5
+ metadata:
6
+ version: "1.0.0"
7
+ tier: optional
8
+ author: fxri
9
+ source: https://github.com/fxri-net/swagger2api
10
+ ---
11
+
12
+ # swagger2api 接入
13
+
14
+ > 本技能版本 1.0.0(随 @fxri/swagger2api 分发)。被问版本时即报此值(不读磁盘、不跑 CLI);与已安装依赖的技能版本不一致即说明会话上下文已过期,开新会话即可。
15
+
16
+ ## 何时使用
17
+
18
+ - **首次给项目接入**:还没有 `swagger2api.json`,需要定最小配置并生成第一版产物。
19
+ - **迁移旧用法**:从 npm script 或旧的 `saconfig.json` 迁到分层配置,需要判断哪些参数仍适用。
20
+ - **调整产物结构**:从单文件切到分组、改客户端或语言、调整命名与契约拆分。
21
+
22
+ 不适用:日常生成、`--check`、CI 验收——这些直接跑既有脚本,不要为一次生成加载本技能。
23
+ 也不用于一般 TypeScript / axios 用法或接口文档写作。
24
+
25
+ ## 工作流
26
+
27
+ 1. **先判断是否真的需要**:只有配置形态要变时才读本技能;日常生成按项目里的既有命令执行即可。
28
+ 2. **定最小配置**:只写 `input`、`output`、`client`,其余按默认;需要分组、JS、响应类型或 query 提取时再逐项加。
29
+ 决策项与默认值见 `references/config.md`。
30
+ 3. **写入项目层**:配置落到仓库根 `swagger2api.json`(随仓库提交);个人差异写本地层,不入库。
31
+ 4. **先预览再落盘**:分组模式加 `--dry-run --json`,确认命名映射、桶与分片规划、预计新增文件;
32
+ 单文件模式可先 `--dry-run` 看报表。发现拆法不符合预期时改分组规则,不要生成后再手改。
33
+ 5. **生成**:用项目既有脚本或 `swagger2api`(本地安装后)执行;首次生成后确认产物目录与配置一致。
34
+ 6. **验收**:跑 `swagger2api --check` 确认产物与配置一致;再跑项目类型检查。产物结构与验收口径见 `references/output.md`。
35
+ 7. **记录边界**:生成物沿用 `// @ts-nocheck`,类型错误不进入下游检查;需要更强约束时在项目侧单独加类型探针,不要手改生成物。
36
+
37
+ ## 不做
38
+
39
+ - 不手改生成物,也不删除 `@ts-nocheck` 后提交;下次生成会覆盖。
40
+ - 不在日常生成、`--check` 或验收时加载本技能,避免把低频能力写成常驻流程。
41
+ - 不猜分桶 / 分片阈值:阈值属于工具默认,业务配置只决定分组策略与命名。
42
+ - 不把本机绝对路径、令牌或私网地址写进配置与示例。
43
+ - 不在未预览的情况下直接切换 `mode`,尤其是已有产物需要清理或迁移时。
44
+
45
+ ## 参考
46
+
47
+ - 配置决策:`references/config.md`
48
+ - CLI 参数与常用组合:`references/cli.md`
49
+ - 产物结构与验收:`references/output.md`
50
+ - 旧用法迁移:`references/migration.md`
51
+ - 定位本技能:`swagger2api skill`(入口路径)/ `swagger2api skill --print`(入口全文)/ `swagger2api skill --json`(结构化定位)
@@ -0,0 +1,36 @@
1
+ # CLI 参数
2
+
3
+ > 由 `../SKILL.md` 按需加载。可执行文件短名 `swagger2api`;npx / dlx 时用全名 `@fxri/swagger2api`。
4
+
5
+ ## 常用命令
6
+
7
+ ```bash
8
+ swagger2api # 按最近的 swagger2api.json 生成
9
+ swagger2api --check # 生成到临时目录并与现有产物比对,不写真实目录
10
+ swagger2api init # 交互生成 swagger2api.json
11
+ swagger2api init --from-script package.json # 从既有 npm script 迁移参数
12
+ swagger2api grouping # 查看分组分布并写入分组配置
13
+ swagger2api config status # 查看配置分层与生效结果
14
+ swagger2api skill # 输出包内技能入口绝对路径
15
+ swagger2api skill --print # 输出技能入口全文
16
+ swagger2api skill --json # 输出入口、references 目录与技能版本
17
+ ```
18
+
19
+ ## 生成相关开关
20
+
21
+ | 参数 | 作用 |
22
+ | --- | --- |
23
+ | `--modular` | 按组拆分为多文件并生成聚合入口 |
24
+ | `--dry-run` | 只输出报表,不写产物;分组模式给出命名、桶 / 分片规划与预计新增文件 |
25
+ | `--json` | 与 `--dry-run` 组合时输出结构化报表 |
26
+ | `--prune-output` | 按上一轮清单清理已消失模块,不触碰手写文件 |
27
+ | `--config <path>` | 显式指定项目层配置 |
28
+ | `--profile <name>` | 选用配置内的命名预设 |
29
+
30
+ ## 使用顺序
31
+
32
+ 1. 改配置后先 `--dry-run --json`,重点看命名映射、桶与分片规划、预计新增文件。
33
+ 2. 确认后生成;产物结构有变化时先清理旧产物或确认清单已覆盖。
34
+ 3. 最后用 `--check` 验收,不要在 `--check` 模式下期待写盘。
35
+
36
+ 完整参数与边界见仓库 `docs/cli.md`。
@@ -0,0 +1,40 @@
1
+ # 配置决策
2
+
3
+ > 由 `../SKILL.md` 按需加载。只列需要判断的字段;完整字段与层级规则见仓库 `docs/config.md`。
4
+
5
+ ## 最小配置
6
+
7
+ ```json
8
+ {
9
+ "input": { "url": "https://example.com/v3/api-docs" },
10
+ "output": { "dir": "./src/api", "name": "index" },
11
+ "client": { "type": "axios" }
12
+ }
13
+ ```
14
+
15
+ 本地文件用 `input.file`,相对路径按配置文件所在目录解析。
16
+
17
+ ## 决策项
18
+
19
+ | 字段 | 取值 | 什么时候改 |
20
+ | --- | --- | --- |
21
+ | `output.mode` | `single`(默认)/ `grouped` | 接口多、单文件过大时切 `grouped` |
22
+ | `client.type` | `fetch`(默认)/ `axios` | 项目已用 axios 或需要拦截器时选 `axios` |
23
+ | `language.target` | `ts`(默认)/ `js` | 产物要与现有 JS 代码共存时选 `js`(同时生成声明) |
24
+ | `types.responses` | 布尔 | 需要响应类型信息时开启 |
25
+ | `types.extractQuery` | 字段名数组 | 后端把分页 / 筛选包在 query 对象里,需要提到根部时 |
26
+ | `types.extractResponseRaw` | 布尔 | 需要在响应里保留原始 `raw` 时 |
27
+ | `naming.pathPrefixIndex` | 非负整数 | 路径首段是网关前缀、不该进命名时去掉 |
28
+ | `naming.tagRewrite` | `[匹配, 替换]` | 标签带环境前缀或需要统一命名时 |
29
+
30
+ ## 分层
31
+
32
+ - 项目层 `swagger2api.json`:随仓库提交,团队共用。
33
+ - 本地层:个人地址、令牌等放本地文件,加入忽略清单,不提交。
34
+ - 环境变量可覆盖地址等敏感项;优先级与字段映射见 `docs/config.md`。
35
+
36
+ ## 判断顺序
37
+
38
+ 1. 先确认输入地址可访问、返回 OpenAPI / Swagger 文档。
39
+ 2. 再定 `mode`:不确定时先用 `single` 生成,确认调用形态后再评估是否分组。
40
+ 3. 最后按需加 `language`、`types`、`naming`;每加一项都跑一次 `--dry-run` 对比报表。
@@ -0,0 +1,26 @@
1
+ # 旧用法迁移
2
+
3
+ > 由 `../SKILL.md` 按需加载。迁移只在首次接入或结构调整时做一次。
4
+
5
+ ## 从 npm script 迁移
6
+
7
+ ```bash
8
+ swagger2api init --from-script package.json
9
+ ```
10
+
11
+ - 读取 `package.json` 里调用本工具的脚本,把可识别的参数转成配置。
12
+ - 未能识别的参数会在 stderr 列出,逐项确认后再手工补进 `swagger2api.json`。
13
+ - 有未识别参数时退出码非 0;补完后重跑一次直到干净。
14
+
15
+ ## 从 saconfig.json 迁移
16
+
17
+ - 新项目优先用分层 `swagger2api.json`;旧的 `saconfig.json` 仍兼容,但不再承载分组与清理能力。
18
+ - 迁移时只搬实际生效的字段,不照抄整份旧配置。
19
+ - 路径、输出目录与名字按新项目重定;旧项目的绝对路径不要带过来。
20
+
21
+ ## 迁移后的验收
22
+
23
+ 1. `--dry-run --json` 对比迁移前后的命名与预计文件。
24
+ 2. 生成一次,确认产物结构与旧产物差异符合预期。
25
+ 3. `--check` 通过后删除旧配置文件与旧产物;不要把两套配置同时留在仓库。
26
+ 4. 更新项目脚本与文档中的命令;后续日常生成不再需要加载本技能。
@@ -0,0 +1,32 @@
1
+ # 产物结构与验收
2
+
3
+ > 由 `../SKILL.md` 按需加载。产物由工具生成,不手改。
4
+
5
+ ## 单文件模式
6
+
7
+ - 入口文件 `index.ts`(名称取 `output.name`),导出 API 类与全部契约。
8
+ - 客户端实例与请求参数类型由生成器内置,调用形态为 `api.<方法>()`。
9
+
10
+ ## 分组模式
11
+
12
+ 固定产物:
13
+
14
+ - `index.ts`:聚合入口,按命名空间挂载模块实例,共享同一个请求实例。
15
+ - `client.ts`:客户端底座。
16
+ - `types/index.ts`:契约出口;契约按业务文件拆到 `types/<业务文件>.ts`,共享或未归类进 `types/shared.ts`。
17
+ - 业务模块文件:按命名空间装箱;超大命名空间按子分类分片,由门面类合并实例与类型。
18
+
19
+ 调用形态仍为 `api.<命名空间>.<方法>`;替换 `api.instance` 或调用 `setSecurityData` 会对所有组生效。
20
+
21
+ ## 边界
22
+
23
+ - 生成物沿用 `// @ts-nocheck`:类型错误不进入下游检查,不要靠手改生成物修类型。
24
+ - 生成清单落在系统临时目录,不进入仓库;`--check` 据此判断缺失、多出与内容不一致。
25
+ - 旧版 `data-contracts.ts` / `http-client.ts` 不再生成,重新生成成功后会清理残留。
26
+ - 手写文件不在清单内时不会被清理;同名冲突会终止生成并提示。
27
+
28
+ ## 验收
29
+
30
+ 1. `swagger2api --check` 通过(产物与配置一致)。
31
+ 2. 项目类型检查通过;需要更强约束时在项目侧写类型探针,不改生成物。
32
+ 3. 抽查聚合入口:模块挂载、`export * from "./types"`、`export * from "./client"` 均存在。