@acrool/rtk-query-codegen-openapi 1.1.0-alpha.2 → 1.1.0-alpha.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +0 -8
- package/lib/bin/cli.mjs +3 -3
- package/lib/bin/cli.mjs.map +1 -1
- package/lib/index.js +6 -0
- package/lib/index.js.map +1 -1
- package/lib/index.mjs +6 -0
- package/lib/index.mjs.map +1 -1
- package/package.json +1 -1
- package/src/services/openapi-parser-service.ts +10 -1
package/README.md
CHANGED
|
@@ -54,14 +54,6 @@ This is a utility library meant to be used with [RTK Query](https://redux-toolki
|
|
|
54
54
|
|
|
55
55
|
### Test
|
|
56
56
|
|
|
57
|
-
```bash
|
|
58
|
-
yarn build && npx acrool-rtk-query-codegen-openapi ./rtk-query-codegen.config.ts
|
|
59
|
-
yarn build && npx acrool-rtk-query-codegen-openapi ./rtk-query-codegen-slice.config.ts
|
|
60
|
-
rm -rf test_output3/* && node lib/bin/cli.mjs rtk-query-codegen-slice.config.ts
|
|
61
|
-
```
|
|
62
|
-
|
|
63
|
-
new
|
|
64
|
-
|
|
65
57
|
```bash
|
|
66
58
|
yarn cli ./react-rtk-query.config.ts
|
|
67
59
|
```
|
package/lib/bin/cli.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
2
|
+
var G=Object.defineProperty;var Ce=Object.getOwnPropertyDescriptor;var Ae=Object.getOwnPropertyNames;var Te=Object.prototype.hasOwnProperty;var k=(n,e)=>()=>(n&&(e=n(n=0)),e);var Se=(n,e)=>{for(var t in e)G(n,t,{get:e[t],enumerable:!0})},Ne=(n,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of Ae(e))!Te.call(n,o)&&o!==t&&G(n,o,{get:()=>e[o],enumerable:!(r=Ce(e,o))||r.enumerable});return n};var $e=n=>Ne(G({},"__esModule",{value:!0}),n);import{fileURLToPath as Re}from"node:url";var Ee,l,p=k(()=>{"use strict";Ee=()=>Re(import.meta.url),l=Ee()});var ie={};Se(ie,{argumentMatches:()=>Be,defaultIsDataResponse:()=>Qe,getOperationName:()=>N,getOverrides:()=>M,getTags:()=>_e,operationMatches:()=>oe});import{getOperationName as We}from"oazapfts/generate";function Qe(n,e){if(e&&n==="default")return!0;let t=Number(n);return!Number.isNaN(t)&&t>=200&&t<300}function N({verb:n,path:e}){return We(n,e,void 0)}function _e({verb:n,pathItem:e}){return n?e[n]?.tags||[]:[]}function ne(n){let e=Array.isArray(n)?n:[n];return function(r){return n?e.some(o=>typeof o=="string"?o===r:o?.test(r)):!0}}function oe(n){let e=typeof n=="function"?n:ne(n);return function(r){if(!n)return!0;let o=N(r);return e(o,r)}}function Be(n){let e=typeof n=="function"?n:ne(n);return function(r){if(!n||r.in==="path")return!0;let o=r.name;return e(o,r)}}function M(n,e){return e?.find(t=>oe(t.pattern)(n))}var K=k(()=>{"use strict";p()});p();import q from"commander";import{createRequire as tt}from"node:module";p();import we from"commander";import{createRequire as Fe}from"node:module";import{resolve as V}from"node:path";import{existsSync as D,rmSync as qe,readdirSync as Ie,statSync as Ge,mkdirSync as De}from"node:fs";import U from"node:path";var x=Fe(l);function je(n){let e=new Map;if(!D(n))return e;function t(r){try{let o=Ie(r);for(let i of o){let c=U.join(r,i);if(Ge(c).isDirectory())t(c);else if(i==="enhanceEndpoints.ts"){let u=x("node:fs").readFileSync(c);e.set(c,u)}}}catch{}}return t(n),e}function Me(n){for(let[e,t]of n)try{let r=U.dirname(e);D(r)||De(r,{recursive:!0}),x("node:fs").writeFileSync(e,t)}catch(r){console.warn(`Failed to restore ${e}:`,r)}}function W(n){let e=["/","/usr","/etc","/var","/home","/Users",".",".."],t=V(n);if(e.some(r=>t===V(r))&&(console.error(`Dangerous path detected: ${t}. Refusing to delete.`),process.exit(1)),D(n)){console.log(`Cleaning output directory: ${n}`);let r=je(n);qe(n,{recursive:!0,force:!0}),r.size>0&&(Me(r),console.log(`Protected ${r.size} enhanceEndpoints.ts file(s) from deletion`)),console.log(`Directory cleaned: ${n}`)}}function Q(){try{if(x.resolve("esbuild")&&x.resolve("esbuild-runner"))return x("esbuild-runner/register"),!0}catch{}try{if(x.resolve("typescript")&&x.resolve("ts-node"))return x("ts-node").register({transpileOnly:!0,compilerOptions:{target:"es6",module:"commonjs"}}),!0}catch{}return!1}function _(n){(!n||!/\.([mc]?(jsx?|tsx?)|jsonc?)?$/.test(n))&&(console.error("Please provide a valid configuration file."),we.help())}function B(n,e){/\.[mc]?tsx?$/.test(n)&&!e&&(console.error("Encountered a TypeScript config file, but neither esbuild-runner nor ts-node are installed."),process.exit(1))}import{dirname as rt,resolve as nt}from"node:path";p();p();import w from"node:path";import ye from"typescript";p();p();function C(n){return n.replace(n[0],n[0].toUpperCase())}p();import j from"node:fs";import Ke from"node:path";p();function z(n){try{new URL(n)}catch{return!1}return!0}async function L(n,e){if(!z(n))throw new Error(`remoteFile must be a valid URL: ${n}`);try{let t=Ke.dirname(e);j.existsSync(t)||await j.promises.mkdir(t,{recursive:!0});let r=await fetch(n);if(!r.ok)throw new Error(`Failed to download schema from ${n}: ${r.statusText}`);let o=await r.text();return await j.promises.writeFile(e,o,"utf-8"),console.log(`Schema downloaded from ${n} to ${e}`),e}catch(t){throw console.error(`Error downloading schema from ${n}:`,t),t}}p();p();var H=["get","put","post","delete","options","head","patch","trace"];function Z(n){return Object.entries(n.paths).flatMap(([e,t])=>t?Object.entries(t).filter(r=>H.includes(r[0])).map(([r,o])=>({path:e,verb:r,pathItem:t,operation:o})):[])}p();import ke from"@apidevtools/swagger-parser";import Ve from"swagger2openapi";async function Y(n,e){let t=await ke.bundle(n,{resolve:{http:e}});return"openapi"in t&&t.openapi.startsWith("3")?t:(await Ve.convertObj(t,{})).openapi}p();function J(n,e,t,r){return r?r(n,e):t?.type?t.type==="query":n==="get"}var A=class{docCache={};async getDocument(e,t){if(this.docCache[e])return this.docCache[e];let r=await Y(e,t);return this.docCache[e]=r,r}async downloadSchema(e,t){return L(e,t)}getPaths(e){return Object.keys(e.paths||{})}clearCache(){this.docCache={}}};p();import X from"lodash.camelcase";var T=class{groupPaths(e,t){let{groupKeyMatch:r,outputDir:o}=t,i=e.reduce((s,u)=>{let a=r(u),m=a?X(a):"_common";return s[m]||(s[m]=[]),s[m].push(u),s},{}),c={};for(let[s,u]of Object.entries(i))c[s]={groupKey:s,paths:u,outputPath:`${o}/${s}/query.service.ts`};return c}createGroupFilter(e,t){return(r,o)=>{let i=o.path,c=X(t.groupKeyMatch(i)||"");return c!==e&&(c||"_common")!==e?!1:t.filterEndpoint?t.filterEndpoint(r,i,e):!0}}};p();import re from"node:fs";import h from"node:path";p();import Ue from"node:path";import ee from"node:fs";async function te(n){let e=Ue.dirname(n);ee.existsSync(e)||await ee.promises.mkdir(e,{recursive:!0})}var S=class{async writeFile(e,t){try{let r=h.resolve(process.cwd(),e);return h.basename(r)==="enhanceEndpoints.ts"&&re.existsSync(r)?{path:r,success:!0}:(await te(r),re.writeFileSync(r,t),{path:r,success:!0})}catch(r){return{path:e,success:!1,error:r}}}async writeFiles(e){let t=[];for(let[r,o]of Object.entries(e)){let i=await this.writeFile(r,o);t.push(i)}return t}async writeGroupFiles(e,t){let r={};return t.types&&(r[h.join(e,"types.ts")]=t.types),t.queryService&&(r[h.join(e,"query.generated.ts")]=t.queryService),t.enhanceEndpoints&&(r[h.join(e,"enhanceEndpoints.ts")]=t.enhanceEndpoints),t.index&&(r[h.join(e,"index.ts")]=t.index),this.writeFiles(r)}async writeSharedFiles(e,t){let r={};return t.commonTypes&&(r[h.join(e,"common-types.ts")]=t.commonTypes),t.doNotModify&&(r[h.join(e,"DO_NOT_MODIFY.md")]=t.doNotModify),t.utils&&(r[h.join(e,"utils.ts")]=t.utils),this.writeFiles(r)}async writeSchemaFile(e,t){let r={};return r[h.join(e,"schema.ts")]=t,this.writeFiles(r)}};p();import ze from"oazapfts/generate";var $=class{constructor(e,t){this.v3Doc=e;this.apiGen=new ze(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}=(K(),$e(ie));return Z(this.v3Doc).filter(t(e))}getApiGenerator(){return this.apiGen}getDocument(){return this.v3Doc}getSchemaTypeNames(){return new Set}};p();function se(){return`/* eslint-disable */
|
|
3
3
|
// [Warning] Generated automatically - do not edit manually
|
|
4
4
|
|
|
5
5
|
export interface RequestOptions {
|
|
@@ -115,7 +115,7 @@ ${n.map(o=>o.isQuery?` ${o.operationName}: {
|
|
|
115
115
|
});
|
|
116
116
|
|
|
117
117
|
export default enhancedApi;
|
|
118
|
-
`}var
|
|
118
|
+
`}var E=class{constructor(e,t){this.parserService=e;this.options=t;this.infoExtractor=new R(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),r=me(e,this.options),o=le(e,this.options),i=this.generateIndex();return{operationNames:e.map(s=>s.operationName),files:{types:t,queryService:r,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((c,s)=>{if(fe.isInterfaceDeclaration(s)||fe.isTypeAliasDeclaration(s)){let u=s.name.text;return{...c,[u]:s}}return c},{}),i=this.parserService.getOperationDefinitions(this.options.filterEndpoints);return ue(e,t,o,i)}generateIndex(){let e=this.options.groupKey||"";return`/* eslint-disable */
|
|
119
119
|
// [Warning] Generated automatically - do not edit manually
|
|
120
120
|
|
|
121
121
|
export { default as ${e?`${e.charAt(0).toLowerCase()+e.slice(1)}Api`:"api"} } from "./enhanceEndpoints";
|
|
@@ -134,7 +134,7 @@ export function withoutUndefined(obj?: Record<string, any>) {
|
|
|
134
134
|
);
|
|
135
135
|
}
|
|
136
136
|
|
|
137
|
-
`}var F=class{_options;openApiService=new A;groupService=new T;fileWriterService=new S;openApiDoc=null;parserService=null;schemaInterfaces={};actualSchemaFile="";generatedContent={groups:[],commonTypes:"",componentSchema:"",doNotModify:"",utils:""};constructor(e){this._options=e}async generateAll(){return await this.prepare(),await this.generateApi(),this.generateCommonTypesContent(),this.generateSchemaContent(),this.generateUtilsContent(),this.generateDoNotModifyContent(),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 $(this.openApiDoc,this._options),this.parserService.initialize();let e=this.parserService.getApiGenerator();this.schemaInterfaces=e.aliases.reduce((t,r)=>{if(ye.isInterfaceDeclaration(r)||ye.isTypeAliasDeclaration(r)){let o=r.name.text;return{...t,[o]:r}}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 r of Object.values(t))try{let o=await this.generateApiGroupContent(this._options,r);o.operationNames.length>0&&this.generatedContent.groups.push({groupKey:r.groupKey,outputPath:r.outputPath,content:o})}catch(o){throw new Error(`\u7FA4\u7D44 ${r.groupKey} \u751F\u6210\u5931\u6557: ${o}`)}}async generateCommonTypesContent(){this.generatedContent.commonTypes=se()}async generateSchemaContent(){this.generatedContent.componentSchema=ae(this.schemaInterfaces)}async generateDoNotModifyContent(){this.generatedContent.doNotModify=pe()}async generateUtilsContent(){this.generatedContent.utils=ge()}async release(){let e=[],t=[],r=[];try{for(let s of this.generatedContent.groups)try{if(s.content?.files){let u=
|
|
137
|
+
`}var F=class{_options;openApiService=new A;groupService=new T;fileWriterService=new S;openApiDoc=null;parserService=null;schemaInterfaces={};actualSchemaFile="";generatedContent={groups:[],commonTypes:"",componentSchema:"",doNotModify:"",utils:""};constructor(e){this._options=e}async generateAll(){return await this.prepare(),await this.generateApi(),this.generateCommonTypesContent(),this.generateSchemaContent(),this.generateUtilsContent(),this.generateDoNotModifyContent(),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 $(this.openApiDoc,this._options),this.parserService.initialize();let e=this.parserService.getApiGenerator();this.schemaInterfaces=e.aliases.reduce((t,r)=>{if(ye.isInterfaceDeclaration(r)||ye.isTypeAliasDeclaration(r)){let o=r.name.text;return{...t,[o]:r}}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 r of Object.values(t))try{let o=await this.generateApiGroupContent(this._options,r);o.operationNames.length>0&&this.generatedContent.groups.push({groupKey:r.groupKey,outputPath:r.outputPath,content:o})}catch(o){throw new Error(`\u7FA4\u7D44 ${r.groupKey} \u751F\u6210\u5931\u6557: ${o}`)}}async generateCommonTypesContent(){this.generatedContent.commonTypes=se()}async generateSchemaContent(){this.generatedContent.componentSchema=ae(this.schemaInterfaces)}async generateDoNotModifyContent(){this.generatedContent.doNotModify=pe()}async generateUtilsContent(){this.generatedContent.utils=ge()}async release(){let e=[],t=[],r=[];try{for(let s of this.generatedContent.groups)try{if(s.content?.files){let u=w.dirname(s.outputPath),a=await this.fileWriterService.writeGroupFiles(u,{types:s.content.files.types,queryService:s.content.files.queryService,enhanceEndpoints:s.content.files.enhanceEndpoints,index:s.content.files.index});e.push(...a),r.push(s.groupKey)}}catch(u){t.push(new Error(`\u5BEB\u5165\u7FA4\u7D44 ${s.groupKey} \u5931\u6557: ${u}`))}let o=this.generatedContent.groups[0]?w.dirname(w.dirname(this.generatedContent.groups[0].outputPath)):"./generated";if(this.generatedContent.commonTypes||this.generatedContent.doNotModify||this.generatedContent.utils){let s=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(...s)}if(this.generatedContent.componentSchema){let s=await this.fileWriterService.writeSchemaFile(o,this.generatedContent.componentSchema);e.push(...s)}let i=this.generateMainIndex(r),c=await this.fileWriterService.writeFile(w.join(o,"index.ts"),i);e.push(c)}catch(o){t.push(o)}return{success:t.length===0,writtenFiles:e,errors:t,generatedGroups:r}}async generateApiGroupContent(e,t){let{outputFiles:r,...o}=e,i={...o,schemaFile:this.actualSchemaFile,outputFile:t.outputPath,sharedTypesFile:`${r.outputDir}/common-types.ts`,filterEndpoints:this.groupService.createGroupFilter(t.groupKey,r),queryMatch:r.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()");return await new E(this.parserService,i).generate()}generateMainIndex(e){return`/* eslint-disable */
|
|
138
138
|
// [Warning] Generated automatically - do not edit manually
|
|
139
139
|
|
|
140
140
|
${e.map(r=>`export * from "./${r}";`).join(`
|