@acrool/rtk-query-codegen-openapi 1.3.0 → 1.4.0-alpha.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/bin/cli.mjs +41 -39
- package/lib/bin/cli.mjs.map +1 -1
- package/lib/index.js +297 -35
- package/lib/index.js.map +1 -1
- package/lib/index.mjs +297 -35
- package/lib/index.mjs.map +1 -1
- package/package.json +1 -1
- package/src/generators/component-schema-generator.ts +10 -1
- package/src/generators/types-generator.ts +121 -32
- package/src/services/unified-code-generator.ts +100 -14
- package/src/utils/schema-ref-analyzer.ts +218 -0
package/lib/bin/cli.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
2
|
+
var U=Object.defineProperty;var Ne=Object.getOwnPropertyDescriptor;var $e=Object.getOwnPropertyNames;var Ee=Object.prototype.hasOwnProperty;var z=(r,e)=>()=>(r&&(e=r(r=0)),e);var De=(r,e)=>{for(var t in e)U(r,t,{get:e[t],enumerable:!0})},Fe=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of $e(e))!Ee.call(r,o)&&o!==t&&U(r,o,{get:()=>e[o],enumerable:!(n=Ne(e,o))||n.enumerable});return r};var Ie=r=>Fe(U({},"__esModule",{value:!0}),r);import{fileURLToPath as je}from"node:url";var qe,g,u=z(()=>{"use strict";qe=()=>je(import.meta.url),g=qe()});var le={};De(le,{argumentMatches:()=>Je,defaultIsDataResponse:()=>Ze,getOperationName:()=>q,getOverrides:()=>_,getTags:()=>Ye,operationMatches:()=>fe});import{getOperationName as He}from"oazapfts/generate";function Ze(r,e){if(e&&r==="default")return!0;let t=Number(r);return!Number.isNaN(t)&&t>=200&&t<300}function q({verb:r,path:e}){return He(r,e,void 0)}function Ye({verb:r,pathItem:e}){return r?e[r]?.tags||[]:[]}function me(r){let e=Array.isArray(r)?r:[r];return function(n){return r?e.some(o=>typeof o=="string"?o===n:o?.test(n)):!0}}function fe(r){let e=typeof r=="function"?r:me(r);return function(n){if(!r)return!0;let o=q(n);return e(o,n)}}function Je(r){let e=typeof r=="function"?r:me(r);return function(n){if(!r||n.in==="path")return!0;let o=n.name;return e(o,n)}}function _(r,e){return e?.find(t=>fe(t.pattern)(r))}var B=z(()=>{"use strict";u()});u();import V from"commander";import{createRequire as mt}from"node:module";u();import Ge from"commander";import{createRequire as Ke}from"node:module";import{resolve as H}from"node:path";import{existsSync as W,rmSync as Me,readdirSync as ke,statSync as Ve,mkdirSync as Ue}from"node:fs";import Z from"node:path";var R=Ke(g);function We(r){let e=new Map;if(!W(r))return e;function t(n){try{let o=ke(n);for(let i of o){let s=Z.join(n,i);if(Ve(s).isDirectory())t(s);else if(i==="enhanceEndpoints.ts"){let c=R("node:fs").readFileSync(s);e.set(s,c)}}}catch{}}return t(r),e}function Qe(r){for(let[e,t]of r)try{let n=Z.dirname(e);W(n)||Ue(n,{recursive:!0}),R("node:fs").writeFileSync(e,t)}catch(n){console.warn(`Failed to restore ${e}:`,n)}}function Y(r){let e=["/","/usr","/etc","/var","/home","/Users",".",".."],t=H(r);if(e.some(n=>t===H(n))&&(console.error(`Dangerous path detected: ${t}. Refusing to delete.`),process.exit(1)),W(r)){console.log(`Cleaning output directory: ${r}`);let n=We(r);Me(r,{recursive:!0,force:!0}),n.size>0&&(Qe(n),console.log(`Protected ${n.size} enhanceEndpoints.ts file(s) from deletion`)),console.log(`Directory cleaned: ${r}`)}}function J(){try{if(R.resolve("esbuild")&&R.resolve("esbuild-runner"))return R("esbuild-runner/register"),!0}catch{}try{if(R.resolve("typescript")&&R.resolve("ts-node"))return R("ts-node").register({transpileOnly:!0,compilerOptions:{target:"es6",module:"commonjs"}}),!0}catch{}return!1}function X(r){(!r||!/\.([mc]?(jsx?|tsx?)|jsonc?)?$/.test(r))&&(console.error("Please provide a valid configuration file."),Ge.help())}function ee(r,e){/\.[mc]?tsx?$/.test(r)&&!e&&(console.error("Encountered a TypeScript config file, but neither esbuild-runner nor ts-node are installed."),process.exit(1))}import{dirname as ft,resolve as lt}from"node:path";u();u();import E from"node:path";import Pe from"typescript";u();u();function D(r){return r.replace(r[0],r[0].toUpperCase())}u();import Q from"node:fs";import _e from"node:path";u();function te(r){try{new URL(r)}catch{return!1}return!0}async function re(r,e){if(!te(r))throw new Error(`remoteFile must be a valid URL: ${r}`);try{let t=_e.dirname(e);Q.existsSync(t)||await Q.promises.mkdir(t,{recursive:!0});let n=await fetch(r);if(!n.ok)throw new Error(`Failed to download schema from ${r}: ${n.statusText}`);let o=await n.text();return await Q.promises.writeFile(e,o,"utf-8"),console.log(`Schema downloaded from ${r} to ${e}`),e}catch(t){throw console.error(`Error downloading schema from ${r}:`,t),t}}u();u();var ne=["get","put","post","delete","options","head","patch","trace"];function oe(r){return Object.entries(r.paths).flatMap(([e,t])=>t?Object.entries(t).filter(n=>ne.includes(n[0])).map(([n,o])=>({path:e,verb:n,pathItem:t,operation:o})):[])}u();import Be from"@apidevtools/swagger-parser";import Le from"swagger2openapi";async function ie(r,e){let t=await Be.bundle(r,{resolve:{http:e}});return"openapi"in t&&t.openapi.startsWith("3")?t:(await Le.convertObj(t,{})).openapi}u();function se(r,e,t,n){return n?n(r,e):t?.type?t.type==="query":r==="get"}var F=class{docCache={};async getDocument(e,t){if(this.docCache[e])return this.docCache[e];let n=await ie(e,t);return this.docCache[e]=n,n}async downloadSchema(e,t){return re(e,t)}getPaths(e){return Object.keys(e.paths||{})}clearCache(){this.docCache={}}};u();import ae from"lodash.camelcase";var I=class{groupPaths(e,t){let{groupKeyMatch:n,outputDir:o}=t,i=e.reduce((a,c)=>{let m=n(c),f=m?ae(m):"_common";return a[f]||(a[f]=[]),a[f].push(c),a},{}),s={};for(let[a,c]of Object.entries(i))s[a]={groupKey:a,paths:c,outputPath:`${o}/${a}/query.service.ts`};return s}createGroupFilter(e,t){return(n,o)=>{let i=o.path,s=ae(t.groupKeyMatch(i)||"");return s!==e&&(s||"_common")!==e?!1:t.filterEndpoint?t.filterEndpoint(n,i,e):!0}}};u();import ue from"node:fs";import T from"node:path";u();import ze from"node:path";import pe from"node:fs";async function ce(r){let e=ze.dirname(r);pe.existsSync(e)||await pe.promises.mkdir(e,{recursive:!0})}var j=class{async writeFile(e,t){try{let n=T.resolve(process.cwd(),e);return T.basename(n)==="enhanceEndpoints.ts"&&ue.existsSync(n)?{path:n,success:!0}:(await ce(n),ue.writeFileSync(n,t),{path:n,success:!0})}catch(n){return{path:e,success:!1,error:n}}}async writeFiles(e){let t=[];for(let[n,o]of Object.entries(e)){let i=await this.writeFile(n,o);t.push(i)}return t}async writeGroupFiles(e,t){let n={};return t.types&&(n[T.join(e,"types.ts")]=t.types),t.queryService&&(n[T.join(e,"query.generated.ts")]=t.queryService),t.enhanceEndpoints&&(n[T.join(e,"enhanceEndpoints.ts")]=t.enhanceEndpoints),t.index&&(n[T.join(e,"index.ts")]=t.index),this.writeFiles(n)}async writeSharedFiles(e,t){let n={};return t.commonTypes&&(n[T.join(e,"common-types.ts")]=t.commonTypes),t.doNotModify&&(n[T.join(e,"DO_NOT_MODIFY.md")]=t.doNotModify),t.utils&&(n[T.join(e,"utils.ts")]=t.utils),this.writeFiles(n)}async writeSchemaFile(e,t){let n={};return n[T.join(e,"schema.ts")]=t,this.writeFiles(n)}};u();import Xe from"oazapfts/generate";var G=class{constructor(e,t){this.v3Doc=e;this.apiGen=new Xe(e,{unionUndefined:t.unionUndefined,mergeReadWriteOnly:t.mergeReadWriteOnly})}apiGen;initialize(){this.apiGen.spec.components?.schemas&&(Object.keys(this.apiGen.spec.components.schemas).forEach(e=>{let t=this.apiGen.spec.components.schemas[e];t&&typeof t=="object"&&"title"in t&&delete t.title}),this.apiGen.preprocessComponents(this.apiGen.spec.components.schemas),Object.keys(this.apiGen.spec.components.schemas).forEach(e=>{try{this.apiGen.getRefAlias({$ref:`#/components/schemas/${e}`})}catch{}}))}getOperationDefinitions(e){let{operationMatches:t}=(B(),Ie(le));return oe(this.v3Doc).filter(t(e))}getApiGenerator(){return this.apiGen}getDocument(){return this.v3Doc}getSchemaTypeNames(){return new Set}};u();function ge(){return`/* eslint-disable */
|
|
3
3
|
// [Warning] Generated automatically - do not edit manually
|
|
4
4
|
|
|
5
5
|
export interface RequestOptions {
|
|
@@ -20,12 +20,12 @@ export type IRestFulEndpointsQueryReturn<TVariables> = TVariables extends void ?
|
|
|
20
20
|
variables: TVariables;
|
|
21
21
|
fetchOptions?: IRequestConfig;
|
|
22
22
|
};
|
|
23
|
-
`}
|
|
23
|
+
`}u();import x from"typescript";function et(r){return r.charAt(0).toUpperCase()+r.slice(1)}function tt(r,e,t){return x.transform(r,[n=>o=>x.visitNode(o,function i(s){return x.isIdentifier(s)&&s.text===e?x.factory.createIdentifier(t):x.visitEachChild(s,i,n)})]).transformed[0]}function de(r,e){let t=x.createPrinter({newLine:x.NewLineKind.LineFeed}),n=x.createSourceFile("component-schema.ts","",x.ScriptTarget.Latest,!1,x.ScriptKind.TS),o=[],i={};return Object.entries(r).forEach(([s,a])=>{let c=et(s);if(i[s]=c,e&&!e.has(s))return;let m=tt(a,s,c),f=t.printNode(x.EmitHint.Unspecified,m,n);o.push(f)}),`/* eslint-disable */
|
|
24
24
|
// [Warning] Generated automatically - do not edit manually
|
|
25
25
|
|
|
26
|
-
${
|
|
26
|
+
${o.join(`
|
|
27
27
|
`)}
|
|
28
|
-
`}
|
|
28
|
+
`}u();function ye(){return`# \u8ACB\u52FF\u4FEE\u6539\u6B64\u8CC7\u6599\u593E
|
|
29
29
|
|
|
30
30
|
\u26A0\uFE0F **\u91CD\u8981\u63D0\u9192\uFF1A\u8ACB\u52FF\u4FEE\u6539\u6B64\u8CC7\u6599\u593E\u4E2D\u7684\u4EFB\u4F55\u6A94\u6848**
|
|
31
31
|
|
|
@@ -44,48 +44,49 @@ ${n.join(`
|
|
|
44
44
|
\u9019\u4E9B\u6A94\u6848\u662F\u7531 @acrool/rtk-query-codegen-openapi \u7522\u751F\u5668\u6240\u5EFA\u7ACB\u3002
|
|
45
45
|
|
|
46
46
|
\u5982\u6709\u7591\u554F\uFF0C\u8ACB\u53C3\u8003\u5C08\u6848\u6587\u4EF6\u6216\u806F\u7E6B\u958B\u767C\u5718\u968A\u3002
|
|
47
|
-
`}
|
|
48
|
-
// [Warning] Generated automatically - do not edit manually
|
|
49
|
-
|
|
50
|
-
`;
|
|
51
|
-
`),
|
|
52
|
-
`;let
|
|
53
|
-
`)),i.
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
`)}function
|
|
57
|
-
`)
|
|
58
|
-
${m.join(
|
|
47
|
+
`}u();import Se from"typescript";u();B();import{supportDeepObjects as rt}from"oazapfts/generate";var $=class{constructor(e){this.options=e}extractEndpointInfos(e){return e.map(t=>this.extractSingleEndpointInfo(t))}extractSingleEndpointInfo(e){let{verb:t,path:n,operation:o}=e,{operationNameSuffix:i="",argSuffix:s="Req",responseSuffix:a="Res",queryMatch:c,endpointOverrides:m}=this.options,f=q({verb:t,path:n}),p=i?D(f+i):f,l=D(f+i+s),h=D(f+i+a),y=se(t,n,_(e,m),c),v=`${f.replace(/([A-Z])/g,"_$1").toUpperCase()}`,S=o.summary||`${t.toUpperCase()} ${n}`,{queryParams:b,pathParams:C,isVoidArg:w,hasRequestBody:N}=this.extractParameters(e),Re=this.extractContentType(o),we=Array.isArray(o.tags)?o.tags:[];return{operationName:p,argTypeName:l,responseTypeName:h,isQuery:y,verb:t.toUpperCase(),path:n,queryKeyName:v,queryParams:b,pathParams:C,isVoidArg:w,summary:S,contentType:Re,hasRequestBody:N,tags:we}}extractParameters(e){let{operation:t,pathItem:n}=e,o=this.resolveArray(t.parameters),i=this.resolveArray(n.parameters).filter(p=>!o.some(l=>l.name===p.name&&l.in===p.in)),s=rt([...i,...o]).filter(p=>p.in!=="header"),a=s.filter(p=>p.in==="query"),c=s.filter(p=>p.in==="path"),m=!!t.requestBody,f=a.length===0&&c.length===0&&!t.requestBody;return{queryParams:a,pathParams:c,isVoidArg:f,hasRequestBody:m}}resolveArray(e){return e?Array.isArray(e)?e:[e]:[]}extractContentType(e){if(!e.requestBody)return"application/json";let t=e.requestBody.content;if(!t||typeof t!="object")return"application/json";let n=Object.keys(t);return n.length===0?"application/json":n[0]}};u();import O from"typescript";var L=r=>r.charAt(0).toUpperCase()+r.slice(1);function nt(r,e,t){return O.transform(r,[n=>o=>O.visitNode(o,function i(s){return O.isIdentifier(s)&&s.text===e?O.factory.createIdentifier(t):O.visitEachChild(s,i,n)})]).transformed[0]}function ot(r,e,t,n){let o=new Set;for(let i of e)t.has(i)||o.add(L(i));return O.transform(r,[i=>s=>O.visitNode(s,function a(c){if(O.isTypeReferenceNode(c)&&O.isIdentifier(c.typeName)){let m=c.typeName.text;if(o.has(m)&&m!==n){let f=O.factory.createQualifiedName(O.factory.createIdentifier("Schema"),O.factory.createIdentifier(m));return O.factory.createTypeReferenceNode(f,c.typeArguments)}}return O.visitEachChild(c,a,i)})]).transformed[0]}function K(r,e,t,n,o){let i=o?.localSchemaNames??new Set,s=o?.localSchemaInterfaces??{},a={};t&&Object.keys(t).forEach(l=>{if(a[l]=l,l.endsWith("Vo")){let h=l.slice(0,-2)+"VO";a[h]=l}if(l.endsWith("Dto")){let h=l.slice(0,-3)+"DTO";a[h]=l}});let c=t&&Object.keys(t).some(l=>!i.has(l)),m=`/* eslint-disable */
|
|
48
|
+
// [Warning] Generated automatically - do not edit manually
|
|
49
|
+
|
|
50
|
+
`;c&&(m+=`import * as Schema from "../schema";
|
|
51
|
+
`),m+=`
|
|
52
|
+
`;let f=[];if(Object.keys(s).length>0){let l=O.createPrinter({newLine:O.NewLineKind.LineFeed}),h=O.createSourceFile("types.ts","",O.ScriptTarget.Latest,!1,O.ScriptKind.TS),y=[],v=new Set(t?Object.keys(t):[]);for(let[S,b]of Object.entries(s)){let C=L(S),w=nt(b,S,C);w=ot(w,v,i,C);let N=l.printNode(O.EmitHint.Unspecified,w,h);y.push(N)}y.length>0&&f.push(y.join(`
|
|
53
|
+
`))}let p=[];return r.forEach(l=>{let h=l.argTypeName,y=l.responseTypeName;if(h){let v=it(l,n,a,i);v.trim()===""?p.push(`export type ${h} = void;`,""):p.push(`export type ${h} = {`,v,"};","")}if(y){let v=st(l,n,a,i);v.content.trim()===""?p.push(`export type ${y} = void;`,""):v.isDirectType?p.push(`export type ${y} = ${v.content};`,""):p.push(`export type ${y} = {`,v.content,"};","")}}),p.length>0&&f.push(p.join(`
|
|
54
|
+
`)),f.length===0&&f.push("// \u6B64\u6A94\u6848\u7528\u65BC\u5B9A\u7FA9 API \u76F8\u95DC\u7684\u985E\u578B","// \u985E\u578B\u5B9A\u7FA9\u6703\u6839\u64DA OpenAPI Schema \u81EA\u52D5\u751F\u6210",""),m+f.join(`
|
|
55
|
+
|
|
56
|
+
`)}function it(r,e,t={},n=new Set){let o=[];r.queryParams&&r.queryParams.length>0&&r.queryParams.forEach(s=>{let a=s.required?"":"?",c=he(s,t,n);o.push(` ${s.name}${a}: ${c};`)}),r.pathParams&&r.pathParams.length>0&&r.pathParams.forEach(s=>{let a=s.required?"":"?",c=he(s,t,n);o.push(` ${s.name}${a}: ${c};`)});let i=e?.find(s=>s.operation?.operationId===r.operationName||s.operation?.operationId===r.operationName.toLowerCase()||s.verb===r.verb.toLowerCase()&&s.path===r.path);if(i?.operation?.requestBody){let a=i.operation.requestBody.content,c=a["application/json"]||a["*/*"],m=a["multipart/form-data"]||a["application/x-www-form-urlencoded"];if(c?.schema){let f=P(c.schema,t,1,n);o.push(` body: ${f};`)}else if(m?.schema){let f=P(m.schema,t,1,n);o.push(` body: ${f};`)}else{let f=Object.values(a)[0];if(f?.schema){let p=P(f.schema,t,1,n);o.push(` body: ${p};`)}else o.push(" body?: any; // Request body from OpenAPI")}}return o.length===0?"":o.join(`
|
|
57
|
+
`)}function st(r,e,t={},n=new Set){let o=e?.find(i=>i.operation?.operationId===r.operationName||i.operation?.operationId===r.operationName.toLowerCase()||i.verb===r.verb.toLowerCase()&&i.path===r.path);if(o?.operation?.responses){let i=o.operation.responses[200]||o.operation.responses[201];if(i?.content){let s=i.content["application/json"]||i.content["*/*"]||Object.values(i.content)[0];if(s?.schema){let a=s.schema;if(a.$ref||a.type!=="object"||!a.properties){let m=P(a,t,0,n);if(m&&m!=="any")return{content:m,isDirectType:!0}}let c=at(a,t,n);if(c.length>0)return{content:c.join(`
|
|
58
|
+
`),isDirectType:!1}}}}return{content:"",isDirectType:!1}}function at(r,e={},t=new Set){let n=[];if(r.type==="object"&&r.properties){let o=r.required||[];Object.entries(r.properties).forEach(([i,s])=>{let c=o.includes(i)?"":"?",m=P(s,e,1,t),p=/[^a-zA-Z0-9_$]/.test(i)?`"${i}"`:i;s.description&&n.push(` /** ${s.description} */`),n.push(` ${p}${c}: ${m};`)})}return n}function P(r,e={},t=0,n=new Set){if(!r)return"any";if(r.$ref){let i=r.$ref;if(i.startsWith("#/components/schemas/")){let s=i.replace("#/components/schemas/",""),a=e[s]||s,c=L(a),m=n.has(s)?c:`Schema.${c}`;return r.nullable?`${m} | null`:m}}let o;switch(r.type){case"string":r.enum?o=r.enum.map(a=>`"${a}"`).join(" | "):r.format==="binary"?o="Blob":o="string";break;case"number":case"integer":o="number";break;case"boolean":o="boolean";break;case"array":let i=r.items?P(r.items,e,t,n):"any";o=i.includes("|")?`(${i})[]`:`${i}[]`;break;case"object":if(r.properties){let a=Object.entries(r.properties);if(a.length===0)r.additionalProperties?o=`Record<string, ${r.additionalProperties===!0?"any":P(r.additionalProperties,e,t,n)}>`:o="{}";else{let c=" ".repeat(t+1),m=" ".repeat(t),f=[];a.forEach(([p,l])=>{let y=(r.required||[]).includes(p)?"":"?",v=P(l,e,t+1,n),b=/[^a-zA-Z0-9_$]/.test(p)?`"${p}"`:p;l.description&&f.push(`${c}/** ${l.description} */`),f.push(`${c}${b}${y}: ${v};`)}),o=`{
|
|
59
|
+
${f.join(`
|
|
59
60
|
`)}
|
|
60
|
-
${
|
|
61
|
+
${m}}`}}else r.additionalProperties?o=`Record<string, ${r.additionalProperties===!0?"any":P(r.additionalProperties,e,t,n)}>`:o="any";break;default:o="any";break}return r.nullable?`${o} | null`:o}function he(r,e={},t=new Set){return r.schema?P(r.schema,e,0,t):"any"}u();function Oe(r,e){let{groupKey:t}=e,n=e.httpClient?.importReturnTypeName||"IRestFulEndpointsQueryReturn",o=r.map(p=>{let l=p.isQuery?"query":"mutation",h=p.isVoidArg?"void":`${n}<${p.argTypeName}>`,y=p.path;p.pathParams&&p.pathParams.length>0?(p.pathParams.forEach(b=>{y=y.replace(`{${b.name}}`,`\${queryArg.variables.${b.name}}`)}),y="`"+y+"`"):y=`"${y}"`;let v="";p.queryParams&&p.queryParams.length>0&&(v=`
|
|
61
62
|
params: {
|
|
62
63
|
${p.queryParams.map(C=>` ${C.name}: queryArg.variables.${C.name},`).join(`
|
|
63
64
|
`)}
|
|
64
|
-
},`);let
|
|
65
|
-
providesTags: [${
|
|
66
|
-
invalidatesTags: (result, error) => error ? [] : [${
|
|
67
|
-
${p.operationName}: build.${
|
|
65
|
+
},`);let S="";if(p.tags&&p.tags.length>0){let b=p.tags.map(C=>`ECacheTagTypes.${C.split(/\s+/).map(N=>N.charAt(0).toUpperCase()+N.slice(1)).join("")}`).join(", ");p.isQuery?S=`
|
|
66
|
+
providesTags: [${b}],`:S=`
|
|
67
|
+
invalidatesTags: (result, error) => error ? [] : [${b}],`}return` /** ${p.summary||p.operationName} */
|
|
68
|
+
${p.operationName}: build.${l}<
|
|
68
69
|
${p.responseTypeName},
|
|
69
|
-
${
|
|
70
|
-
>({${
|
|
70
|
+
${h}
|
|
71
|
+
>({${S}
|
|
71
72
|
query: (queryArg) => ({
|
|
72
|
-
url: ${
|
|
73
|
+
url: ${y},
|
|
73
74
|
method: "${p.verb.toUpperCase()}",
|
|
74
|
-
contentType: "${p.contentType}",${
|
|
75
|
+
contentType: "${p.contentType}",${v}${p.hasRequestBody?`
|
|
75
76
|
body: queryArg.variables.body,`:""}${p.isVoidArg?"":`
|
|
76
77
|
fetchOptions: queryArg?.fetchOptions,`}
|
|
77
78
|
}),
|
|
78
79
|
}),`}).join(`
|
|
79
|
-
`),
|
|
80
|
+
`),i=[...new Set([...r.map(p=>p.argTypeName),...r.map(p=>p.responseTypeName)])].filter(p=>p!=="VoidApiArg"),s=i.length>0?`import type { ${i.join(", ")} } from "./types";`:"",a=e.apiConfiguration?`import {${e.apiConfiguration.importName} as api} from "${e.apiConfiguration.file.replace(/\.ts$/,"")}";
|
|
80
81
|
`:`import {baseApi as api} from "../../../library/redux/baseApi";
|
|
81
|
-
`,
|
|
82
|
+
`,c=e.httpClient?`import {${e.httpClient.importReturnTypeName}} from "${e.httpClient.file}";
|
|
82
83
|
`:`import {IRestFulEndpointsQueryReturn} from "@acrool/react-fetcher";
|
|
83
|
-
`,
|
|
84
|
+
`,f=r.some(p=>p.tags&&p.tags.length>0)?`import {ECacheTagTypes} from "../tagTypes";
|
|
84
85
|
`:"";return`/* eslint-disable */
|
|
85
86
|
// [Warning] Generated automatically - do not edit manually
|
|
86
87
|
|
|
87
|
-
${
|
|
88
|
-
${
|
|
88
|
+
${a}${c}${f}
|
|
89
|
+
${s}
|
|
89
90
|
|
|
90
91
|
|
|
91
92
|
const injectedRtkApi = api.injectEndpoints({
|
|
@@ -95,13 +96,13 @@ ${o}
|
|
|
95
96
|
});
|
|
96
97
|
|
|
97
98
|
export const {
|
|
98
|
-
${r.map(p=>{let
|
|
99
|
-
${
|
|
99
|
+
${r.map(p=>{let l=p.operationName.charAt(0).toUpperCase()+p.operationName.slice(1);if(p.isQuery){let h=`use${l}Query`;if(e.useLazyQueries){let y=`useLazy${l}Query`;return` ${h},
|
|
100
|
+
${y},`}else return` ${h},`}else return` ${`use${l}Mutation`},`}).join(`
|
|
100
101
|
`)}
|
|
101
102
|
} = injectedRtkApi;
|
|
102
103
|
|
|
103
104
|
export default injectedRtkApi;
|
|
104
|
-
`}
|
|
105
|
+
`}u();function ve(r,e){return`/* eslint-disable */
|
|
105
106
|
// [Warning] Generated automatically - do not edit manually
|
|
106
107
|
|
|
107
108
|
import api from "./query.generated";
|
|
@@ -118,13 +119,13 @@ ${r.map(o=>o.isQuery?` ${o.operationName}: {
|
|
|
118
119
|
});
|
|
119
120
|
|
|
120
121
|
export default enhancedApi;
|
|
121
|
-
`}var
|
|
122
|
+
`}var M=class{constructor(e,t){this.parserService=e;this.options=t;this.infoExtractor=new $(t)}infoExtractor;async generate(){let e=this.parserService.getOperationDefinitions(this.options.filterEndpoints),t=this.infoExtractor.extractEndpointInfos(e);return this.generateRtkQueryCode(t)}generateRtkQueryCode(e){let t=this.generateTypes(e),n=Oe(e,this.options),o=ve(e,this.options),i=this.generateIndex(),s=e.map(c=>c.operationName),a=new Set;return e.forEach(c=>{c.tags&&Array.isArray(c.tags)&&c.tags.forEach(m=>a.add(m))}),{operationNames:s,tags:Array.from(a),files:{types:t,queryService:n,index:i,enhanceEndpoints:o}}}generateTypes(e){let t={...this.options,apiConfiguration:this.options.apiConfiguration||{file:"@/store/webapi",importName:"WebApiConfiguration"}},o=this.parserService.getApiGenerator().aliases.reduce((s,a)=>{if(Se.isInterfaceDeclaration(a)||Se.isTypeAliasDeclaration(a)){let c=a.name.text;return{...s,[c]:a}}return s},{}),i=this.parserService.getOperationDefinitions(this.options.filterEndpoints);return K(e,t,o,i)}generateIndex(){let e=this.options.groupKey||"";return`/* eslint-disable */
|
|
122
123
|
// [Warning] Generated automatically - do not edit manually
|
|
123
124
|
|
|
124
125
|
export { default as ${e?`${e.charAt(0).toLowerCase()+e.slice(1)}Api`:"api"} } from "./enhanceEndpoints";
|
|
125
126
|
export * from "./query.generated";
|
|
126
127
|
export * from "./types";
|
|
127
|
-
`}};
|
|
128
|
+
`}};u();function be(){return`/* eslint-disable */
|
|
128
129
|
// [Warning] Generated automatically - do not edit manually
|
|
129
130
|
|
|
130
131
|
/**
|
|
@@ -137,7 +138,7 @@ export function withoutUndefined(obj?: Record<string, any>) {
|
|
|
137
138
|
);
|
|
138
139
|
}
|
|
139
140
|
|
|
140
|
-
`}
|
|
141
|
+
`}u();function pt(r){return r.split(/\s+/).map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("")}function xe(r){return r.length===0?`/* eslint-disable */
|
|
141
142
|
// [Warning] Generated automatically - do not edit manually
|
|
142
143
|
|
|
143
144
|
export enum ECacheTagTypes {
|
|
@@ -146,13 +147,14 @@ export enum ECacheTagTypes {
|
|
|
146
147
|
// [Warning] Generated automatically - do not edit manually
|
|
147
148
|
|
|
148
149
|
export enum ECacheTagTypes {
|
|
149
|
-
${r.sort().map(t=>` ${
|
|
150
|
+
${r.sort().map(t=>` ${pt(t)} = '${t}',`).join(`
|
|
150
151
|
`)}
|
|
151
152
|
}
|
|
152
|
-
`}var
|
|
153
|
+
`}u();function A(r,e){if(!(!r||typeof r!="object")){if(r.$ref&&typeof r.$ref=="string"){let t=r.$ref.match(/^#\/components\/schemas\/(.+)$/);t&&e.add(t[1])}if(r.properties)for(let t of Object.values(r.properties))A(t,e);r.items&&A(r.items,e),r.additionalProperties&&typeof r.additionalProperties=="object"&&A(r.additionalProperties,e);for(let t of["allOf","oneOf","anyOf"])if(Array.isArray(r[t]))for(let n of r[t])A(n,e)}}function ct(r){let e=new Set;for(let t of r){let n=t.operation;if(n.parameters)for(let o of n.parameters){let i=o;i.schema&&A(i.schema,e)}if(n.requestBody){let o=n.requestBody;if(o.content)for(let i of Object.values(o.content))i.schema&&A(i.schema,e)}if(n.responses)for(let o of Object.values(n.responses)){let i=o;if(i.content)for(let s of Object.values(i.content))s.schema&&A(s.schema,e)}}return e}function ut(r,e){let t=new Set,n=[...r];for(;n.length>0;){let o=n.pop();if(t.has(o))continue;t.add(o);let i=e[o];if(!i)continue;let s=new Set;A(i,s);for(let a of s)t.has(a)||n.push(a)}return t}function Te(r,e,t){let n=new Map;for(let[m,f]of r){let p=ct(f),l=ut(p,e);n.set(m,l)}let o=new Map;for(let[m,f]of n)for(let p of f)o.has(p)||o.set(p,new Set),o.get(p).add(m);let i=new Set,s=new Map,a=new Set;for(let m of t){let f=o.get(m);if(!f||f.size===0)a.add(m);else if(f.size===1){let p=[...f][0];s.has(p)||s.set(p,new Set),s.get(p).add(m)}else i.add(m)}let c=!0;for(;c;){c=!1;for(let[m,f]of s)for(let p of[...f]){let l=e[p];if(!l)continue;let h=new Set;A(l,h);for(let y of h)for(let[v,S]of s)v!==m&&S.has(y)&&(i.add(y),i.add(p),S.delete(y),f.delete(p),c=!0)}}return{sharedSchemas:i,groupLocalSchemas:s,unusedSchemas:a}}var k=class{_options;openApiService=new F;groupService=new I;fileWriterService=new j;openApiDoc=null;parserService=null;schemaInterfaces={};actualSchemaFile="";generatedContent={groups:[],commonTypes:"",componentSchema:"",doNotModify:"",utils:"",tagTypes:""};allTags=new Set;groupOperationDefs=new Map;groupGenerationOptions=new Map;constructor(e){this._options=e}async generateAll(){return await this.prepare(),await this.generateApi(),this.splitSchemaByUsage(),this.generateCommonTypesContent(),this.generateSchemaContent(),this.generateUtilsContent(),this.generateDoNotModifyContent(),this.generateTagTypesContent(),await this.release()}async prepare(){this.actualSchemaFile=this._options.schemaFile,this._options.remoteFile&&(this.actualSchemaFile=await this.openApiService.downloadSchema(this._options.remoteFile,this._options.schemaFile)),this.openApiDoc=await this.openApiService.getDocument(this.actualSchemaFile,this._options.httpResolverOptions),this.parserService=new G(this.openApiDoc,this._options),this.parserService.initialize();let e=this.parserService.getApiGenerator();this.schemaInterfaces=e.aliases.reduce((t,n)=>{if(Pe.isInterfaceDeclaration(n)||Pe.isTypeAliasDeclaration(n)){let o=n.name.text;return{...t,[o]:n}}return t},{})}async generateApi(){if(!this.openApiDoc||!this.parserService)throw new Error("\u8ACB\u5148\u8ABF\u7528 prepare() \u65B9\u6CD5");let e=this.openApiService.getPaths(this.openApiDoc),t=this.groupService.groupPaths(e,this._options.outputFiles);for(let n of Object.values(t))try{let o=await this.generateApiGroupContent(this._options,n);o.operationNames.length>0&&(this.generatedContent.groups.push({groupKey:n.groupKey,outputPath:n.outputPath,content:o}),o.tags&&Array.isArray(o.tags)&&o.tags.forEach(i=>this.allTags.add(i)))}catch(o){throw new Error(`\u7FA4\u7D44 ${n.groupKey} \u751F\u6210\u5931\u6557: ${o}`)}}splitSchemaByUsage(){if(!this.openApiDoc||this.groupOperationDefs.size===0)return;let e=this.openApiDoc.components?.schemas??{},t=Object.keys(this.schemaInterfaces),n=Te(this.groupOperationDefs,e,t);this.sharedSchemaNames=n.sharedSchemas;for(let o of this.generatedContent.groups){let i=n.groupLocalSchemas.get(o.groupKey);if(!i||i.size===0)continue;let s=this.groupGenerationOptions.get(o.groupKey);if(!s||!this.parserService)continue;let a={};for(let h of i)this.schemaInterfaces[h]&&(a[h]=this.schemaInterfaces[h]);let c=new $(s),m=this.groupOperationDefs.get(o.groupKey)??[],f=c.extractEndpointInfos(m),p={...s,apiConfiguration:s.apiConfiguration||{file:"@/store/webapi",importName:"WebApiConfiguration"}},l=K(f,p,this.schemaInterfaces,m,{localSchemaInterfaces:a,localSchemaNames:i});o.content.files.types=l}}sharedSchemaNames=null;async generateCommonTypesContent(){this.generatedContent.commonTypes=ge()}async generateSchemaContent(){this.generatedContent.componentSchema=de(this.schemaInterfaces,this.sharedSchemaNames??void 0)}async generateDoNotModifyContent(){this.generatedContent.doNotModify=ye()}async generateUtilsContent(){this.generatedContent.utils=be()}async generateTagTypesContent(){let e=Array.from(this.allTags);this.generatedContent.tagTypes=xe(e)}async release(){let e=[],t=[],n=[];try{for(let a of this.generatedContent.groups)try{if(a.content?.files){let c=E.dirname(a.outputPath),m=await this.fileWriterService.writeGroupFiles(c,{types:a.content.files.types,queryService:a.content.files.queryService,enhanceEndpoints:a.content.files.enhanceEndpoints,index:a.content.files.index});e.push(...m),n.push(a.groupKey)}}catch(c){t.push(new Error(`\u5BEB\u5165\u7FA4\u7D44 ${a.groupKey} \u5931\u6557: ${c}`))}let o=this.generatedContent.groups[0]?E.dirname(E.dirname(this.generatedContent.groups[0].outputPath)):"./generated";if(this.generatedContent.commonTypes||this.generatedContent.doNotModify||this.generatedContent.utils){let a=await this.fileWriterService.writeSharedFiles(o,{commonTypes:this.generatedContent.commonTypes||void 0,doNotModify:this.generatedContent.doNotModify||void 0,utils:this.generatedContent.utils||void 0});e.push(...a)}if(this.generatedContent.tagTypes){let a=await this.fileWriterService.writeFile(E.join(o,"tagTypes.ts"),this.generatedContent.tagTypes);e.push(a)}if(this.generatedContent.componentSchema){let a=await this.fileWriterService.writeSchemaFile(o,this.generatedContent.componentSchema);e.push(...a)}let i=this.generateMainIndex(n),s=await this.fileWriterService.writeFile(E.join(o,"index.ts"),i);e.push(s)}catch(o){t.push(o)}return{success:t.length===0,writtenFiles:e,errors:t,generatedGroups:n}}async generateApiGroupContent(e,t){let{outputFiles:n,...o}=e,i={...o,schemaFile:this.actualSchemaFile,outputFile:t.outputPath,sharedTypesFile:`${n.outputDir}/common-types.ts`,filterEndpoints:this.groupService.createGroupFilter(t.groupKey,n),queryMatch:n.queryMatch,groupKey:t.groupKey};if(!this.openApiDoc||!this.parserService)throw new Error("OpenAPI \u6587\u6A94\u672A\u521D\u59CB\u5316\uFF0C\u8ACB\u5148\u8ABF\u7528 prepare()");let s=this.parserService.getOperationDefinitions(i.filterEndpoints);return this.groupOperationDefs.set(t.groupKey,s),this.groupGenerationOptions.set(t.groupKey,i),await new M(this.parserService,i).generate()}generateMainIndex(e){return`/* eslint-disable */
|
|
153
154
|
// [Warning] Generated automatically - do not edit manually
|
|
154
155
|
|
|
156
|
+
export * from "./schema";
|
|
155
157
|
${e.map(n=>`export * from "./${n}";`).join(`
|
|
156
158
|
`)}
|
|
157
|
-
`}};async function
|
|
159
|
+
`}};async function Ce(r){let t=await new k(r).generateAll();if(!t.success&&t.errors.length>0)throw t.errors[0]}var Ae=mt(g);async function gt(r){let e=lt(process.cwd(),r);process.chdir(ft(e));let t=Ae(e),n=t.default??t;"outputFiles"in n||(console.error('Configuration must include "outputFiles" property. Single file output is no longer supported.'),process.exit(1)),n.outputFiles&&n.outputFiles.outputDir&&Y(n.outputFiles.outputDir);try{console.log("Generating multiple outputs..."),await Ce(n),console.log("Done")}catch(o){console.error("Generation failed:",o),process.exit(1)}}async function dt(){let r=Ae("../../package.json"),e=J();V.version(r.version).usage("<path/to/config.js>").parse(process.argv);let t=V.args[0];if(V.args.length===0){V.help();return}X(t),ee(t,e),await gt(t)}dt().catch(r=>{console.error("CLI execution failed:",r),process.exit(1)});export{gt as runGeneration};
|
|
158
160
|
//# sourceMappingURL=cli.mjs.map
|