@bitstack/ng-query-codegen-openapi 0.0.30 → 0.0.31-alpha.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/README.md CHANGED
@@ -63,10 +63,17 @@ rm -rf test_output3/* && node lib/bin/cli.mjs rtk-query-codegen-slice.config.ts
63
63
  new
64
64
 
65
65
  ```bash
66
- npm run cli ./rtk-query-codegen-slice.config.ts
66
+ npm run cli ./openapi-micro.config.ts
67
+
67
68
  ```
68
69
 
69
70
 
71
+ ## Publish
72
+
73
+ ```bash
74
+ npm run build
75
+ npm publish --access=public
76
+ ```
70
77
 
71
78
  ## Step
72
79
 
package/lib/bin/cli.mjs CHANGED
@@ -1,32 +1,5 @@
1
1
  #!/usr/bin/env node
2
- var K=Object.defineProperty;var Ne=Object.getOwnPropertyDescriptor;var Ae=Object.getOwnPropertyNames;var Se=Object.prototype.hasOwnProperty;var V=(r,t)=>()=>(r&&(t=r(r=0)),t);var Te=(r,t)=>{for(var e in t)K(r,e,{get:t[e],enumerable:!0})},Pe=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Ae(t))!Se.call(r,o)&&o!==e&&K(r,o,{get:()=>t[o],enumerable:!(n=Ne(t,o))||n.enumerable});return r};var $e=r=>Pe(K({},"__esModule",{value:!0}),r);import{fileURLToPath as Ee}from"node:url";var Fe,m,s=V(()=>{"use strict";Fe=()=>Ee(import.meta.url),m=Fe()});var ne={};Te(ne,{argumentMatches:()=>ke,defaultIsDataResponse:()=>Qe,getOperationName:()=>A,getOverrides:()=>G,getTags:()=>Ue,operationMatches:()=>re});import{getOperationName as Ve}from"oazapfts/generate";function Qe(r,t){if(t&&r==="default")return!0;let e=Number(r);return!Number.isNaN(e)&&e>=200&&e<300}function A({verb:r,path:t}){return Ve(r,t,void 0)}function Ue({verb:r,pathItem:t}){return r?t[r]?.tags||[]:[]}function te(r){let t=Array.isArray(r)?r:[r];return function(n){return r?t.some(o=>typeof o=="string"?o===n:o?.test(n)):!0}}function re(r){let t=typeof r=="function"?r:te(r);return function(n){if(!r)return!0;let o=A(n);return t(o,n)}}function ke(r){let t=typeof r=="function"?r:te(r);return function(n){if(!r||n.in==="path")return!0;let o=n.name;return t(o,n)}}function G(r,t){return t?.find(e=>re(e.pattern)(r))}var I=V(()=>{"use strict";s()});s();import R from"commander";import{createRequire as Ye}from"node:module";s();import Re from"commander";import{createRequire as we}from"node:module";import{resolve as Q}from"node:path";import{existsSync as Ke,rmSync as qe}from"node:fs";var d=we(m);function U(r){let t=["/","/usr","/etc","/var","/home","/Users",".",".."],e=Q(r);t.some(n=>e===Q(n))&&(console.error(`Dangerous path detected: ${e}. Refusing to delete.`),process.exit(1)),Ke(r)&&(console.log(`Cleaning output directory: ${r}`),qe(r,{recursive:!0,force:!0}),console.log(`Directory cleaned: ${r}`))}function k(){try{if(d.resolve("esbuild")&&d.resolve("esbuild-runner"))return d("esbuild-runner/register"),!0}catch{}try{if(d.resolve("typescript")&&d.resolve("ts-node"))return d("ts-node").register({transpileOnly:!0,compilerOptions:{target:"es6",module:"commonjs"}}),!0}catch{}return!1}function W(r){(!r||!/\.([mc]?(jsx?|tsx?)|jsonc?)?$/.test(r))&&(console.error("Please provide a valid configuration file."),Re.help())}function _(r,t){/\.[mc]?tsx?$/.test(r)&&!t&&(console.error("Encountered a TypeScript config file, but neither esbuild-runner nor ts-node are installed."),process.exit(1))}import{dirname as Ze,resolve as Je}from"node:path";s();s();import D from"node:path";import he from"typescript";s();s();function b(r){return r.replace(r[0],r[0].toUpperCase())}s();import q from"node:fs";import Ge from"node:path";s();function L(r){try{new URL(r)}catch{return!1}return!0}async function z(r,t){if(!L(r))throw new Error(`remoteFile must be a valid URL: ${r}`);try{let e=Ge.dirname(t);q.existsSync(e)||await q.promises.mkdir(e,{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(t,o,"utf-8"),console.log(`Schema downloaded from ${r} to ${t}`),t}catch(e){throw console.error(`Error downloading schema from ${r}:`,e),e}}s();s();var B=["get","put","post","delete","options","head","patch","trace"];function H(r){return Object.entries(r.paths).flatMap(([t,e])=>e?Object.entries(e).filter(n=>B.includes(n[0])).map(([n,o])=>({path:t,verb:n,pathItem:e,operation:o})):[])}s();import Ie from"@apidevtools/swagger-parser";import De from"swagger2openapi";async function Y(r,t){let e=await Ie.bundle(r,{resolve:{http:t}});return"openapi"in e&&e.openapi.startsWith("3")?e:(await De.convertObj(e,{})).openapi}s();function Z(r,t,e,n){return n?n(r,t):e?.type?e.type==="query":r==="get"}var x=class{docCache={};async getDocument(t,e){if(this.docCache[t])return this.docCache[t];let n=await Y(t,e);return this.docCache[t]=n,n}async downloadSchema(t,e){return z(t,e)}getPaths(t){return Object.keys(t.paths||{})}clearCache(){this.docCache={}}};s();import J from"lodash.camelcase";var C=class{groupPaths(t,e){let{groupKeyMatch:n,outputDir:o}=e,p=t.reduce((c,u)=>{let i=n(u),g=i?J(i):"_common";return c[g]||(c[g]=[]),c[g].push(u),c},{}),a={};for(let[c,u]of Object.entries(p))a[c]={groupKey:c,paths:u,outputPath:`${o}/${c}/query.service.ts`};return a}createGroupFilter(t,e){return(n,o)=>{let p=o.path,a=J(e.groupKeyMatch(p)||"");return a!==t&&(a||"_common")!==t?!1:e.filterEndpoint?e.filterEndpoint(n,p,t):!0}}};s();import Me from"node:fs";import h from"node:path";s();import je from"node:path";import X from"node:fs";async function ee(r){let t=je.dirname(r);X.existsSync(t)||await X.promises.mkdir(t,{recursive:!0})}var N=class{async writeFile(t,e){try{let n=h.resolve(process.cwd(),t);return await ee(n),Me.writeFileSync(n,e),{path:n,success:!0}}catch(n){return{path:t,success:!1,error:n}}}async writeFiles(t){let e=[];for(let[n,o]of Object.entries(t)){let p=await this.writeFile(n,o);e.push(p)}return e}async writeGroupFiles(t,e){let n={};return e.types&&(n[h.join(t,"types.ts")]=e.types),e.apiService&&(n[h.join(t,"api.service.ts")]=e.apiService),e.queryService&&(n[h.join(t,"query.service.ts")]=e.queryService),e.index&&(n[h.join(t,"index.ts")]=e.index),this.writeFiles(n)}async writeSharedFiles(t,e){let n={};return e.commonTypes&&(n[h.join(t,"common-types.ts")]=e.commonTypes),e.cacheKeys&&(n[h.join(t,"cache-keys.ts")]=e.cacheKeys),e.doNotModify&&(n[h.join(t,"DO_NOT_MODIFY.md")]=e.doNotModify),e.utils&&(n[h.join(t,"utils.ts")]=e.utils),this.writeFiles(n)}async writeSchemaFile(t,e){let n={};return n[h.join(t,"schema.ts")]=e,this.writeFiles(n)}};s();import We from"oazapfts/generate";var S=class{constructor(t,e){this.v3Doc=t;this.apiGen=new We(t,{unionUndefined:e.unionUndefined,useEnumType:e.useEnumType,mergeReadWriteOnly:e.mergeReadWriteOnly})}apiGen;initialize(){this.apiGen.spec.components?.schemas&&(this.apiGen.preprocessComponents(this.apiGen.spec.components.schemas),Object.keys(this.apiGen.spec.components.schemas).forEach(t=>{try{this.apiGen.getRefAlias({$ref:`#/components/schemas/${t}`})}catch{}}))}getOperationDefinitions(t){let{operationMatches:e}=(I(),$e(ne));return H(this.v3Doc).filter(e(t))}getApiGenerator(){return this.apiGen}getDocument(){return this.v3Doc}getSchemaTypeNames(){return new Set}};s();s();function oe(){return`/* eslint-disable */
3
- // [Warning] Generated automatically - do not edit manually
4
-
5
- /**
6
- * Clear undefined in object
7
- */
8
- export function withoutUndefined(obj?: Record<string, any>) {
9
- if(typeof obj === 'undefined') return;
10
- return Object.fromEntries(
11
- Object.entries(obj).filter(([_, v]) => v !== undefined && v !== null)
12
- );
13
- }
14
-
15
- `}function ie(r){return r.toLowerCase().replace(/_([a-z])/g,(t,e)=>e.toUpperCase())}function se(r){let t=r.reduce((n,o)=>(n[o.groupKey]||(n[o.groupKey]=[]),n[o.groupKey].push({operationName:o.operationName,queryKeyName:o.queryKeyName}),n),{});return`// [Warning] Generated automatically - do not edit manually
16
-
17
- /**
18
- * Cache keys enum for all API queries
19
- */
20
- export enum ECacheKeys {
21
- ${Object.entries(t).map(([n,o])=>{let p=` // ${n.charAt(0).toUpperCase()+n.slice(1)} related cache keys`,a=o.map(c=>` ${c.queryKeyName} = '${ie(c.queryKeyName)}',`).join(`
22
- `);return`${p}
23
- ${a}`}).join(`
24
-
25
- `)}
26
- }
27
-
28
- export default ECacheKeys;
29
- `}s();function ae(){return`/* eslint-disable */
2
+ var I=Object.defineProperty;var $e=Object.getOwnPropertyDescriptor;var Ce=Object.getOwnPropertyNames;var Ne=Object.prototype.hasOwnProperty;var K=(r,t)=>()=>(r&&(t=r(r=0)),t);var Re=(r,t)=>{for(var e in t)I(r,e,{get:t[e],enumerable:!0})},Se=(r,t,e,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Ce(t))!Ne.call(r,o)&&o!==e&&I(r,o,{get:()=>t[o],enumerable:!(n=$e(t,o))||n.enumerable});return r};var Ee=r=>Se(I({},"__esModule",{value:!0}),r);import{fileURLToPath as Fe}from"node:url";var we,g,c=K(()=>{"use strict";we=()=>Fe(import.meta.url),g=we()});var ie={};Re(ie,{argumentMatches:()=>Le,defaultIsDataResponse:()=>Be,getOperationName:()=>S,getOverrides:()=>M,getTags:()=>ze,operationMatches:()=>oe});import{getOperationName as _e}from"oazapfts/generate";function Be(r,t){if(t&&r==="default")return!0;let e=Number(r);return!Number.isNaN(e)&&e>=200&&e<300}function S({verb:r,path:t}){return _e(r,t,void 0)}function ze({verb:r,pathItem:t}){return r?t[r]?.tags||[]:[]}function ne(r){let t=Array.isArray(r)?r:[r];return function(n){return r?t.some(o=>typeof o=="string"?o===n:o?.test(n)):!0}}function oe(r){let t=typeof r=="function"?r:ne(r);return function(n){if(!r)return!0;let o=S(n);return t(o,n)}}function Le(r){let t=typeof r=="function"?r:ne(r);return function(n){if(!r||n.in==="path")return!0;let o=n.name;return t(o,n)}}function M(r,t){return t?.find(e=>oe(e.pattern)(r))}var V=K(()=>{"use strict";c()});c();import j from"commander";import{createRequire as nt}from"node:module";c();import qe from"commander";import{createRequire as je}from"node:module";import{resolve as k}from"node:path";import{existsSync as G,rmSync as Ie,readdirSync as Ge,statSync as De,mkdirSync as Me}from"node:fs";import Q from"node:path";var O=je(g);function Ve(r){let t=new Map;if(!G(r))return t;function e(n){try{let o=Ge(n);for(let s of o){let a=Q.join(n,s);if(De(a).isDirectory())e(a);else if(s==="enhanceEndpoints.ts"){let u=O("node:fs").readFileSync(a);t.set(a,u)}}}catch{}}return e(r),t}function Ke(r){for(let[t,e]of r)try{let n=Q.dirname(t);G(n)||Me(n,{recursive:!0}),O("node:fs").writeFileSync(t,e)}catch(n){console.warn(`Failed to restore ${t}:`,n)}}function U(r){let t=["/","/usr","/etc","/var","/home","/Users",".",".."],e=k(r);if(t.some(n=>e===k(n))&&(console.error(`Dangerous path detected: ${e}. Refusing to delete.`),process.exit(1)),G(r)){console.log(`Cleaning output directory: ${r}`);let n=Ve(r);Ie(r,{recursive:!0,force:!0}),n.size>0&&(Ke(n),console.log(`Protected ${n.size} enhanceEndpoints.ts file(s) from deletion`)),console.log(`Directory cleaned: ${r}`)}}function W(){try{if(O.resolve("esbuild")&&O.resolve("esbuild-runner"))return O("esbuild-runner/register"),!0}catch{}try{if(O.resolve("typescript")&&O.resolve("ts-node"))return O("ts-node").register({transpileOnly:!0,compilerOptions:{target:"es6",module:"commonjs"}}),!0}catch{}return!1}function _(r){(!r||!/\.([mc]?(jsx?|tsx?)|jsonc?)?$/.test(r))&&(console.error("Please provide a valid configuration file."),qe.help())}function B(r,t){/\.[mc]?tsx?$/.test(r)&&!t&&(console.error("Encountered a TypeScript config file, but neither esbuild-runner nor ts-node are installed."),process.exit(1))}import{dirname as ot,resolve as it}from"node:path";c();c();import P from"node:path";import fe from"typescript";c();c();function $(r){return r.replace(r[0],r[0].toUpperCase())}c();import D from"node:fs";import ke from"node:path";c();function z(r){try{new URL(r)}catch{return!1}return!0}async function L(r,t){if(!z(r))throw new Error(`remoteFile must be a valid URL: ${r}`);try{let e=ke.dirname(t);D.existsSync(e)||await D.promises.mkdir(e,{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 D.promises.writeFile(t,o,"utf-8"),console.log(`Schema downloaded from ${r} to ${t}`),t}catch(e){throw console.error(`Error downloading schema from ${r}:`,e),e}}c();c();var H=["get","put","post","delete","options","head","patch","trace"];function Z(r){return Object.entries(r.paths).flatMap(([t,e])=>e?Object.entries(e).filter(n=>H.includes(n[0])).map(([n,o])=>({path:t,verb:n,pathItem:e,operation:o})):[])}c();import Qe from"@apidevtools/swagger-parser";import Ue from"swagger2openapi";async function Y(r,t){let e=await Qe.bundle(r,{resolve:{http:t}});return"openapi"in e&&e.openapi.startsWith("3")?e:(await Ue.convertObj(e,{})).openapi}c();function J(r,t,e,n){return n?n(r,t):e?.type?e.type==="query":r==="get"}var C=class{docCache={};async getDocument(t,e){if(this.docCache[t])return this.docCache[t];let n=await Y(t,e);return this.docCache[t]=n,n}async downloadSchema(t,e){return L(t,e)}getPaths(t){return Object.keys(t.paths||{})}clearCache(){this.docCache={}}};c();import X from"lodash.camelcase";var N=class{groupPaths(t,e){let{groupKeyMatch:n,outputDir:o}=e,s=t.reduce((p,u)=>{let i=n(u),m=i?X(i):"_common";return p[m]||(p[m]=[]),p[m].push(u),p},{}),a={};for(let[p,u]of Object.entries(s))a[p]={groupKey:p,paths:u,outputPath:`${o}/${p}/query.service.ts`};return a}createGroupFilter(t,e){return(n,o)=>{let s=o.path,a=X(e.groupKeyMatch(s)||"");return a!==t&&(a||"_common")!==t?!1:e.filterEndpoint?e.filterEndpoint(n,s,t):!0}}};c();import re from"node:fs";import v from"node:path";c();import We from"node:path";import ee from"node:fs";async function te(r){let t=We.dirname(r);ee.existsSync(t)||await ee.promises.mkdir(t,{recursive:!0})}var R=class{async writeFile(t,e){try{let n=v.resolve(process.cwd(),t);return v.basename(n)==="enhanceEndpoints.ts"&&re.existsSync(n)?{path:n,success:!0}:(await te(n),re.writeFileSync(n,e),{path:n,success:!0})}catch(n){return{path:t,success:!1,error:n}}}async writeFiles(t){let e=[];for(let[n,o]of Object.entries(t)){let s=await this.writeFile(n,o);e.push(s)}return e}async writeGroupFiles(t,e){let n={};return e.types&&(n[v.join(t,"types.ts")]=e.types),e.queryService&&(n[v.join(t,"query.generated.ts")]=e.queryService),e.enhanceEndpoints&&(n[v.join(t,"enhanceEndpoints.ts")]=e.enhanceEndpoints),e.index&&(n[v.join(t,"index.ts")]=e.index),this.writeFiles(n)}async writeSharedFiles(t,e){let n={};return e.commonTypes&&(n[v.join(t,"common-types.ts")]=e.commonTypes),e.doNotModify&&(n[v.join(t,"DO_NOT_MODIFY.md")]=e.doNotModify),e.utils&&(n[v.join(t,"utils.ts")]=e.utils),this.writeFiles(n)}async writeSchemaFile(t,e){let n={};return n[v.join(t,"schema.ts")]=e,this.writeFiles(n)}};c();import He from"oazapfts/generate";var E=class{constructor(t,e){this.v3Doc=t;this.apiGen=new He(t,{unionUndefined:e.unionUndefined,mergeReadWriteOnly:e.mergeReadWriteOnly})}apiGen;initialize(){this.apiGen.spec.components?.schemas&&(Object.keys(this.apiGen.spec.components.schemas).forEach(t=>{let e=this.apiGen.spec.components.schemas[t];e&&typeof e=="object"&&"title"in e&&delete e.title}),this.apiGen.preprocessComponents(this.apiGen.spec.components.schemas),Object.keys(this.apiGen.spec.components.schemas).forEach(t=>{try{this.apiGen.getRefAlias({$ref:`#/components/schemas/${t}`})}catch{}}))}getOperationDefinitions(t){let{operationMatches:e}=(V(),Ee(ie));return Z(this.v3Doc).filter(e(t))}getApiGenerator(){return this.apiGen}getDocument(){return this.v3Doc}getSchemaTypeNames(){return new Set}};c();function se(){return`/* eslint-disable */
30
3
  // [Warning] Generated automatically - do not edit manually
31
4
 
32
5
  export interface RequestOptions {
@@ -43,19 +16,23 @@ export interface QueryConfig {
43
16
  keepUnusedDataFor?: number,
44
17
  }
45
18
 
19
+ export interface IRequestConfig extends RequestOptions {
20
+ timeout?: number;
21
+ }
22
+
46
23
  export type IRestFulEndpointsQueryReturn<TVariables> = TVariables extends void ?
47
- void | {fetchOptions?: RequestOptions;config?: QueryConfig;}:
24
+ (void | {fetchOptions?: IRequestConfig;}):
48
25
  {
49
26
  variables: TVariables;
50
- fetchOptions?: RequestOptions;
27
+ fetchOptions?: IRequestConfig;
51
28
  config?: QueryConfig;
52
29
  };
53
- `}s();import v from"typescript";function pe(r){let t=v.createPrinter({newLine:v.NewLineKind.LineFeed}),e=v.createSourceFile("component-schema.ts","",v.ScriptTarget.Latest,!1,v.ScriptKind.TS);return`/* eslint-disable */
54
- // [Warning] Generated automatically - do not edit manually
55
-
56
- ${Object.values(r).map(n=>t.printNode(v.EmitHint.Unspecified,n,e)).join(`
30
+ `}c();import f from"typescript";function Ze(r){return r.charAt(0).toUpperCase()+r.slice(1)}function Ye(r,t,e){return f.transform(r,[n=>o=>f.visitNode(o,function s(a){return f.isIdentifier(a)&&a.text===t?f.factory.createIdentifier(e):f.visitEachChild(a,s,n)})]).transformed[0]}function ae(r){let t=f.createPrinter({newLine:f.NewLineKind.LineFeed}),e=f.createSourceFile("component-schema.ts","",f.ScriptTarget.Latest,!1,f.ScriptKind.TS),n=[],o={};return Object.entries(r).forEach(([s,a])=>{let p=Ze(s);o[s]=p;let u=Ye(a,s,p),i=t.printNode(f.EmitHint.Unspecified,u,e);n.push(i)}),`/* eslint-disable */
31
+ // [Warning] Generated automatically - do not edit manually
32
+
33
+ ${n.join(`
57
34
  `)}
58
- `}s();function ce(){return`# \u8ACB\u52FF\u4FEE\u6539\u6B64\u8CC7\u6599\u593E
35
+ `}c();function pe(){return`# \u8ACB\u52FF\u4FEE\u6539\u6B64\u8CC7\u6599\u593E
59
36
 
60
37
  \u26A0\uFE0F **\u91CD\u8981\u63D0\u9192\uFF1A\u8ACB\u52FF\u4FEE\u6539\u6B64\u8CC7\u6599\u593E\u4E2D\u7684\u4EFB\u4F55\u6A94\u6848**
61
38
 
@@ -74,20 +51,20 @@ ${Object.values(r).map(n=>t.printNode(v.EmitHint.Unspecified,n,e)).join(`
74
51
  \u9019\u4E9B\u6A94\u6848\u662F\u7531 @bitstack/ng-query-codegen-openapi \u7522\u751F\u5668\u6240\u5EFA\u7ACB\u3002
75
52
 
76
53
  \u5982\u6709\u7591\u554F\uFF0C\u8ACB\u53C3\u8003\u5C08\u6848\u6587\u4EF6\u6216\u806F\u7E6B\u958B\u767C\u5718\u968A\u3002
77
- `}s();import fe from"typescript";s();I();import{supportDeepObjects as _e}from"oazapfts/generate";var T=class{constructor(t){this.options=t}extractEndpointInfos(t){return t.map(e=>this.extractSingleEndpointInfo(e))}extractSingleEndpointInfo(t){let{verb:e,path:n,operation:o}=t,{operationNameSuffix:p="",argSuffix:a="Req",responseSuffix:c="Res",queryMatch:u,endpointOverrides:i}=this.options,g=A({verb:e,path:n}),l=p?b(g+p):g,w=b(g+p+a),f=b(g+p+c),j=Z(e,n,G(t,i),u),M=`${g.replace(/([A-Z])/g,"_$1").toUpperCase()}`,Oe=o.summary||`${e.toUpperCase()} ${n}`,{queryParams:be,pathParams:xe,isVoidArg:Ce}=this.extractParameters(t);return{operationName:l,argTypeName:w,responseTypeName:f,isQuery:j,verb:e.toUpperCase(),path:n,queryKeyName:M,queryParams:be,pathParams:xe,isVoidArg:Ce,summary:Oe}}extractParameters(t){let{operation:e,pathItem:n}=t,o=this.resolveArray(e.parameters),p=this.resolveArray(n.parameters).filter(g=>!o.some(l=>l.name===g.name&&l.in===g.in)),a=_e([...p,...o]).filter(g=>g.in!=="header"),c=a.filter(g=>g.in==="query"),u=a.filter(g=>g.in==="path"),i=c.length===0&&u.length===0&&!e.requestBody;return{queryParams:c,pathParams:u,isVoidArg:i}}resolveArray(t){return t?Array.isArray(t)?t:[t]:[]}};s();function me(r,t,e,n){let o=`/* eslint-disable */
54
+ `}c();import le from"typescript";c();V();import{supportDeepObjects as Je}from"oazapfts/generate";var F=class{constructor(t){this.options=t}extractEndpointInfos(t){return t.map(e=>this.extractSingleEndpointInfo(e))}extractSingleEndpointInfo(t){let{verb:e,path:n,operation:o}=t,{operationNameSuffix:s="",argSuffix:a="Req",responseSuffix:p="Res",queryMatch:u,endpointOverrides:i}=this.options,m=S({verb:e,path:n}),y=s?$(m+s):m,d=$(m+s+a),T=$(m+s+p),h=J(e,n,M(t,i),u),A=`${m.replace(/([A-Z])/g,"_$1").toUpperCase()}`,x=o.summary||`${e.toUpperCase()} ${n}`,{queryParams:be,pathParams:Oe,isVoidArg:xe,hasRequestBody:Te}=this.extractParameters(t),Pe=this.extractContentType(o),Ae=Array.isArray(o.tags)?o.tags:[];return{operationName:y,argTypeName:d,responseTypeName:T,isQuery:h,verb:e.toUpperCase(),path:n,queryKeyName:A,queryParams:be,pathParams:Oe,isVoidArg:xe,summary:x,contentType:Pe,hasRequestBody:Te,tags:Ae}}extractParameters(t){let{operation:e,pathItem:n}=t,o=this.resolveArray(e.parameters),s=this.resolveArray(n.parameters).filter(y=>!o.some(d=>d.name===y.name&&d.in===y.in)),a=Je([...s,...o]).filter(y=>y.in!=="header"),p=a.filter(y=>y.in==="query"),u=a.filter(y=>y.in==="path"),i=!!e.requestBody,m=p.length===0&&u.length===0&&!e.requestBody;return{queryParams:p,pathParams:u,isVoidArg:m,hasRequestBody:i}}resolveArray(t){return t?Array.isArray(t)?t:[t]:[]}extractContentType(t){if(!t.requestBody)return"application/json";let e=t.requestBody.content;if(!e||typeof e!="object")return"application/json";let n=Object.keys(e);return n.length===0?"application/json":n[0]}};c();var Xe=r=>r.charAt(0).toUpperCase()+r.slice(1);function ue(r,t,e,n){let o={};e&&Object.keys(e).forEach(i=>{if(o[i]=i,i.endsWith("Vo")){let m=i.slice(0,-2)+"VO";o[m]=i}if(i.endsWith("Dto")){let m=i.slice(0,-3)+"DTO";o[m]=i}});let s=`/* eslint-disable */
78
55
  // [Warning] Generated automatically - do not edit manually
79
56
 
80
- `;e&&Object.keys(e).length>0&&(o+=`import * as Schema from "../schema";
81
- `),o+=`
82
- `;let a=[],c=[];return r.forEach(u=>{let i=u.argTypeName,g=u.responseTypeName;if(i){let l=Le(u,n);l.trim()===""||l.includes("TODO")||l.includes("[key: string]: any")?c.push(`export type ${i} = void;`,""):c.push(`export type ${i} = {`,l,"};","")}if(g){let l=ze(u,n);l.trim()===""||l.includes("TODO")||l.includes("[key: string]: any")?c.push(`export type ${g} = void;`,""):c.push(`export type ${g} = {`,l,"};","")}}),c.length>0&&a.push(c.join(`
83
- `)),a.length===0&&a.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",""),o+a.join(`
84
-
85
- `)}function Le(r,t){let e=[];r.queryParams&&r.queryParams.length>0&&r.queryParams.forEach(o=>{let p=o.required?"":"?",a=ue(o);e.push(` ${o.name}${p}: ${a};`)}),r.pathParams&&r.pathParams.length>0&&r.pathParams.forEach(o=>{let p=o.required?"":"?",a=ue(o);e.push(` ${o.name}${p}: ${a};`)});let n=t?.find(o=>o.operation?.operationId===r.operationName||o.operation?.operationId===r.operationName.toLowerCase()||o.verb===r.verb.toLowerCase()&&o.path===r.path);if(n?.operation?.requestBody){let p=n.operation.requestBody.content,a=p["application/json"],c=p["multipart/form-data"]||p["application/x-www-form-urlencoded"];if(a?.schema){let u=O(a.schema);e.push(` body: ${u};`)}else if(c?.schema){let u=O(c.schema);e.push(` body: ${u};`)}else e.push(" body?: any; // Request body from OpenAPI")}return e.length===0?"":e.join(`
86
- `)}function ze(r,t){let e=[],n=t?.find(o=>o.operation?.operationId===r.operationName||o.operation?.operationId===r.operationName.toLowerCase()||o.verb===r.verb.toLowerCase()&&o.path===r.path);if(n?.operation?.responses){let o=n.operation.responses[200]||n.operation.responses[201];if(o?.content){let p=o.content["application/json"];if(p?.schema){let a=Be(p.schema);e.push(...a)}else e.push(" // Success response from OpenAPI"),e.push(" data?: any;")}}return e.length===0?"":e.join(`
87
- `)}function Be(r){let t=[];if(r.type==="object"&&r.properties){let e=r.required||[];Object.entries(r.properties).forEach(([n,o])=>{let a=e.includes(n)?"":"?",c=O(o),u=o.description?` // ${o.description}`:"";t.push(` ${n}${a}: ${c};${u}`)})}return t}function O(r){if(!r)return"any";if(r.$ref){let t=r.$ref;if(t.startsWith("#/components/schemas/"))return`Schema.${t.replace("#/components/schemas/","")}`}switch(r.type){case"string":return r.enum?r.enum.map(e=>`"${e}"`).join(" | "):"string";case"number":case"integer":return"number";case"boolean":return"boolean";case"array":return`${r.items?O(r.items):"any"}[]`;case"object":return r.properties?`{ ${Object.entries(r.properties).map(([n,o])=>{let a=(r.required||[]).includes(n)?"":"?",c=O(o);return`${n}${a}: ${c}`}).join("; ")} }`:"any";default:return"any"}}function ue(r){return r.schema?O(r.schema):"any"}s();function ye(r,t){let{groupKey:e}=t;return`export * from './types';
88
- export * from './api.service';
89
- export * from './query.service';
90
- `}s();s();function ge(r,t){let{groupKey:e,refetchOnMountOrArgChange:n=60}=t,o=e?`${e.charAt(0).toUpperCase()+e.slice(1)}QueryService`:"QueryService",p=e?`${e.charAt(0).toUpperCase()+e.slice(1)}ApiService`:"ApiService",a=r.filter(i=>i.isQuery).map(i=>`
57
+ `;e&&Object.keys(e).length>0&&(s+=`import * as Schema from "../schema";
58
+ `),s+=`
59
+ `;let p=[],u=[];return r.forEach(i=>{let m=i.argTypeName,y=i.responseTypeName;if(m){let d=et(i,n,o);d.trim()===""?u.push(`export type ${m} = void;`,""):u.push(`export type ${m} = {`,d,"};","")}if(y){let d=tt(i,n,o);d.trim()===""?u.push(`export type ${y} = void;`,""):u.push(`export type ${y} = {`,d,"};","")}}),u.length>0&&p.push(u.join(`
60
+ `)),p.length===0&&p.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",""),s+p.join(`
61
+
62
+ `)}function et(r,t,e={}){let n=[];r.queryParams&&r.queryParams.length>0&&r.queryParams.forEach(s=>{let a=s.required?"":"?",p=ce(s,e);n.push(` ${s.name}${a}: ${p};`)}),r.pathParams&&r.pathParams.length>0&&r.pathParams.forEach(s=>{let a=s.required?"":"?",p=ce(s,e);n.push(` ${s.name}${a}: ${p};`)});let o=t?.find(s=>s.operation?.operationId===r.operationName||s.operation?.operationId===r.operationName.toLowerCase()||s.verb===r.verb.toLowerCase()&&s.path===r.path);if(o?.operation?.requestBody){let a=o.operation.requestBody.content,p=a["application/json"]||a["*/*"],u=a["multipart/form-data"]||a["application/x-www-form-urlencoded"];if(p?.schema){let i=b(p.schema,e,1);n.push(` body: ${i};`)}else if(u?.schema){let i=b(u.schema,e,1);n.push(` body: ${i};`)}else{let i=Object.values(a)[0];if(i?.schema){let m=b(i.schema,e,1);n.push(` body: ${m};`)}else n.push(" body?: any; // Request body from OpenAPI")}}return n.length===0?"":n.join(`
63
+ `)}function tt(r,t,e={}){let n=[],o=t?.find(s=>s.operation?.operationId===r.operationName||s.operation?.operationId===r.operationName.toLowerCase()||s.verb===r.verb.toLowerCase()&&s.path===r.path);if(o?.operation?.responses){let s=o.operation.responses[200]||o.operation.responses[201];if(s?.content){let a=s.content["application/json"]||s.content["*/*"]||Object.values(s.content)[0];if(a?.schema){let p=rt(a.schema,e);n.push(...p)}else n.push(" // Success response from OpenAPI"),n.push(" data?: any;")}}return n.length===0?"":n.join(`
64
+ `)}function rt(r,t={}){let e=[];if(r.type==="object"&&r.properties){let n=r.required||[];Object.entries(r.properties).forEach(([o,s])=>{let p=n.includes(o)?"":"?",u=b(s,t,1),m=/[^a-zA-Z0-9_$]/.test(o)?`"${o}"`:o;s.description&&e.push(` /** ${s.description} */`),e.push(` ${m}${p}: ${u};`)})}return e}function b(r,t={},e=0){if(!r)return"any";if(r.$ref){let o=r.$ref;if(o.startsWith("#/components/schemas/")){let s=o.replace("#/components/schemas/",""),a=t[s]||s,u=`Schema.${Xe(a)}`;return r.nullable?`${u} | null`:u}}let n;switch(r.type){case"string":r.enum?n=r.enum.map(a=>`"${a}"`).join(" | "):r.format==="binary"?n="Blob":n="string";break;case"number":case"integer":n="number";break;case"boolean":n="boolean";break;case"array":let o=r.items?b(r.items,t,e):"any";n=o.includes("|")?`(${o})[]`:`${o}[]`;break;case"object":if(r.properties){let a=Object.entries(r.properties);if(a.length===0)r.additionalProperties?n=`Record<string, ${r.additionalProperties===!0?"any":b(r.additionalProperties,t,e)}>`:n="{}";else{let p=" ".repeat(e+1),u=" ".repeat(e),i=[];a.forEach(([m,y])=>{let T=(r.required||[]).includes(m)?"":"?",h=b(y,t,e+1),x=/[^a-zA-Z0-9_$]/.test(m)?`"${m}"`:m;y.description&&i.push(`${p}/** ${y.description} */`),i.push(`${p}${x}${T}: ${h};`)}),n=`{
65
+ ${i.join(`
66
+ `)}
67
+ ${u}}`}}else r.additionalProperties?n=`Record<string, ${r.additionalProperties===!0?"any":b(r.additionalProperties,t,e)}>`:n="any";break;default:n="any";break}return r.nullable?`${n} | null`:n}function ce(r,t={}){return r.schema?b(r.schema,t):"any"}c();function me(r,t){let{groupKey:e,refetchOnMountOrArgChange:n=60}=t,o=e?`${e.charAt(0).toUpperCase()+e.slice(1)}QueryService`:"QueryService",s=e?`${e.charAt(0).toUpperCase()+e.slice(1)}ApiService`:"ApiService",a=r.filter(i=>i.isQuery).map(i=>`
91
68
  /**
92
69
  * ${i.summary}
93
70
  */
@@ -100,7 +77,7 @@ export * from './query.service';
100
77
  fetchOptions: args?.fetchOptions,
101
78
  config: args?.config,
102
79
  })${i.argTypeName!=="VoidApiArg"?"(args)":"()"};
103
- }`).join(""),c=r.filter(i=>!i.isQuery).map(i=>`
80
+ }`).join(""),p=r.filter(i=>!i.isQuery).map(i=>`
104
81
  /**
105
82
  * ${i.summary}
106
83
  */
@@ -141,7 +118,7 @@ import {Observable} from 'rxjs';
141
118
  import {HttpErrorResponse} from '@angular/common/http';
142
119
  import {NtkQueryService, MutationState, QueryState, MutationResponse} from '@core/ntk-query';
143
120
  import {ECacheKeys} from '../cache-keys';
144
- import {${p}} from './api.service';
121
+ import {${s}} from './api.service';
145
122
  import {IRestFulEndpointsQueryReturn, RequestOptions} from '../common-types';
146
123
  import {${r.map(i=>` ${i.argTypeName}, ${i.responseTypeName}`).join(",")}} from './types';
147
124
 
@@ -149,14 +126,14 @@ import {${r.map(i=>` ${i.argTypeName}, ${i.responseTypeName}`).join(",")}} from
149
126
  providedIn: 'root',
150
127
  })
151
128
  export class ${o} {
152
- private apiService = inject(${p});
129
+ private apiService = inject(${s});
153
130
  private ntkQuery = inject(NtkQueryService);
154
- ${a}${c}${u}
131
+ ${a}${p}${u}
155
132
  }
156
- `}var P=class{constructor(t){this.options=t}generateQueryService(t){let e={...this.options,apiConfiguration:this.options.apiConfiguration||{file:"@/store/webapi",importName:"WebApiConfiguration"}};return ge(t,e)}};s();s();function le(r,t){let{apiConfiguration:e,httpClient:n,groupKey:o}=t,p=o?`${o.charAt(0).toUpperCase()+o.slice(1)}ApiService`:"ApiService";return`/* eslint-disable */
133
+ `}c();function ge(r,t){let{apiConfiguration:e,httpClient:n,groupKey:o}=t,s=o?`${o.charAt(0).toUpperCase()+o.slice(1)}ApiService`:"ApiService";return`/* eslint-disable */
157
134
  // [Warning] Generated automatically - do not edit manually
158
135
 
159
- import { ${n.importName} } from '${n.file}';
136
+ import { ${n.importReturnTypeName} } from '${n.file}';
160
137
  import { Injectable, inject } from '@angular/core';
161
138
  import { Observable } from 'rxjs';
162
139
  import { ${e.importName} } from '${e.file}';
@@ -167,20 +144,61 @@ import {${r.map(a=>` ${a.argTypeName}, ${a.responseTypeName}`).join(",")} } from
167
144
  @Injectable({
168
145
  providedIn: 'root',
169
146
  })
170
- export class ${p} {
147
+ export class ${s} {
171
148
  private config = inject(${e.importName});
172
- private http = inject(${n.importName});
173
-
174
- ${r.map(a=>{let c=a.verb.toUpperCase()==="GET",u=a.argTypeName!=="VoidApiArg",i=f=>f.includes("{")&&u?`\`\${this.config.rootUrl}${f.replace(/\{([^}]+)\}/g,"${args.variables.$1}")}\``:`\`\${this.config.rootUrl}${f}\``,g=a.queryParams.length>0,l=!c&&u&&!a.isVoidArg,w=()=>{let f=["...args.fetchOptions"];return(l||!c)&&f.push("headers: { 'Content-Type': 'application/json', ...args.fetchOptions?.headers }"),g&&u&&f.push(He(a.queryParams)),l&&f.push("body: args.variables.body"),f.length>0?`{ ${f.join(", ")} }`:"{}"};return`
149
+ private http = inject(${n.importReturnTypeName});
150
+
151
+ ${r.map(a=>{let p=a.verb.toUpperCase()==="GET",u=a.argTypeName!=="VoidApiArg",i=a.hasRequestBody,m=h=>h.includes("{")&&u?`\`\${this.config.rootUrl}${h.replace(/\{([^}]+)\}/g,"${args.variables.$1}")}\``:`\`\${this.config.rootUrl}${h}\``,y=a.queryParams.length>0,d=!p&&u,T=()=>{let h="";return a.queryParams&&a.queryParams.length>0&&(h=`params: {${a.queryParams.map(x=>`${x.name}: args.variables.${x.name},`).join(`
152
+ `)}},`),`{
153
+ ...args.fetchOptions,
154
+ headers: { 'Content-Type': '${a.contentType}', ...args.fetchOptions?.headers },
155
+ ${h}${a.hasRequestBody?"body: args.variables.body,":""}
156
+ }`};return`
175
157
  /**
176
158
  * ${a.summary}
177
159
  */
178
160
  ${a.operationName}(
179
161
  ${u?`args: IRestFulEndpointsQueryReturn<${a.argTypeName}>, `:""}
180
162
  ): Observable<${a.responseTypeName}> {
181
- const url = ${i(a.path)};
182
- return this.http.request('${a.verb.toLowerCase()}', url, ${w()});
163
+ const url = ${m(a.path)};
164
+ return this.http.request('${a.verb.toLowerCase()}', url, ${T()});
183
165
  }`}).join("")}
184
166
  }
185
- `}function He(r){return`params: withoutUndefined({ ${r.map(e=>`${e.name}: args.variables.${e.name}`).join(", ")} })`}var $=class{constructor(t){this.options=t}generateApiService(t){let e={...this.options,apiConfiguration:this.options.apiConfiguration||{file:"@/store/webapi",importName:"WebApiConfiguration"}};return le(t,e)}};var E=class{constructor(t,e){this.parserService=t;this.options=e;this.infoExtractor=new T(e),this.queryGenerator=new P(e),this.apiServiceGenerator=new $(e)}infoExtractor;queryGenerator;apiServiceGenerator;async generate(){let t=this.parserService.getOperationDefinitions(this.options.filterEndpoints),e=this.infoExtractor.extractEndpointInfos(t),n=this.generateTypes(e),o=this.generateApiService(e),p=this.generateQueryService(e),a=this.generateIndex(),c=e.filter(i=>i.isQuery).map(i=>({operationName:i.operationName,queryKeyName:i.queryKeyName,groupKey:this.options.groupKey||"_common"}));return{operationNames:e.map(i=>i.operationName),files:{types:n,apiService:o,queryService:p,index:a,allEndpointCacheKeys:c}}}generateTypes(t){let e={...this.options,apiConfiguration:this.options.apiConfiguration||{file:"@/store/webapi",importName:"WebApiConfiguration"}},o=this.parserService.getApiGenerator().aliases.reduce((a,c)=>{if(fe.isInterfaceDeclaration(c)||fe.isTypeAliasDeclaration(c)){let u=c.name.text;return{...a,[u]:c}}return a},{}),p=this.parserService.getOperationDefinitions(this.options.filterEndpoints);return me(t,e,o,p)}generateApiService(t){return this.apiServiceGenerator.generateApiService(t)}generateQueryService(t){return this.queryGenerator.generateQueryService(t)}generateIndex(){let t={...this.options,apiConfiguration:this.options.apiConfiguration||{file:"@/store/webapi",importName:"WebApiConfiguration"}};return ye(this.options.groupKey||"",t)}};var F=class{_options;openApiService=new x;groupService=new C;fileWriterService=new N;openApiDoc=null;parserService=null;schemaInterfaces={};allEndpointCacheKeys=[];actualSchemaFile="";generatedContent={groups:[],cacheKeys:null,commonTypes:"",componentSchema:"",doNotModify:"",utils:""};constructor(t){this._options=t}async generateAll(){return await this.prepare(),await this.generateApi(),this.generateCacheKeysContent(),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 S(this.openApiDoc,this._options),this.parserService.initialize();let t=this.parserService.getApiGenerator();this.schemaInterfaces=t.aliases.reduce((e,n)=>{if(he.isInterfaceDeclaration(n)||he.isTypeAliasDeclaration(n)){let o=n.name.text;return{...e,[o]:n}}return e},{})}async generateApi(){if(!this.openApiDoc||!this.parserService)throw new Error("\u8ACB\u5148\u8ABF\u7528 prepare() \u65B9\u6CD5");let t=this.openApiService.getPaths(this.openApiDoc),e=this.groupService.groupPaths(t,this._options.outputFiles);for(let n of Object.values(e))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})}catch(o){throw new Error(`\u7FA4\u7D44 ${n.groupKey} \u751F\u6210\u5931\u6557: ${o}`)}}async generateCacheKeysContent(){this.generatedContent.cacheKeys=se(this.allEndpointCacheKeys)}async generateCommonTypesContent(){this.generatedContent.commonTypes=ae()}async generateSchemaContent(){this.generatedContent.componentSchema=pe(this.schemaInterfaces)}async generateDoNotModifyContent(){this.generatedContent.doNotModify=ce()}async generateUtilsContent(){this.generatedContent.utils=oe()}async release(){let t=[],e=[],n=[];try{for(let p of this.generatedContent.groups)try{if(p.content?.files){let a=D.dirname(p.outputPath),c=await this.fileWriterService.writeGroupFiles(a,{types:p.content.files.types,apiService:p.content.files.apiService,queryService:p.content.files.queryService,index:p.content.files.index});t.push(...c),n.push(p.groupKey)}}catch(a){e.push(new Error(`\u5BEB\u5165\u7FA4\u7D44 ${p.groupKey} \u5931\u6557: ${a}`))}let o=this.generatedContent.groups[0]?D.dirname(D.dirname(this.generatedContent.groups[0].outputPath)):"./generated";if(this.generatedContent.cacheKeys||this.generatedContent.commonTypes||this.generatedContent.doNotModify||this.generatedContent.utils){let p=await this.fileWriterService.writeSharedFiles(o,{cacheKeys:this.generatedContent.cacheKeys||void 0,commonTypes:this.generatedContent.commonTypes||void 0,doNotModify:this.generatedContent.doNotModify||void 0,utils:this.generatedContent.utils||void 0});t.push(...p)}if(this.generatedContent.componentSchema){let p=await this.fileWriterService.writeSchemaFile(o,this.generatedContent.componentSchema);t.push(...p)}}catch(o){e.push(o)}return{success:e.length===0,writtenFiles:t,errors:e,generatedGroups:n}}async generateApiGroupContent(t,e){let{outputFiles:n,...o}=t,p={...o,schemaFile:this.actualSchemaFile,outputFile:e.outputPath,sharedTypesFile:`${n.outputDir}/common-types.ts`,filterEndpoints:this.groupService.createGroupFilter(e.groupKey,n),queryMatch:n.queryMatch,groupKey:e.groupKey};if(!this.openApiDoc||!this.parserService)throw new Error("OpenAPI \u6587\u6A94\u672A\u521D\u59CB\u5316\uFF0C\u8ACB\u5148\u8ABF\u7528 prepare()");let c=await new E(this.parserService,p).generate();if(c.files&&"allEndpointCacheKeys"in c.files){let u=c.files.allEndpointCacheKeys;this.allEndpointCacheKeys.push(...u)}return c}};async function de(r){let e=await new F(r).generateAll();if(!e.success&&e.errors.length>0)throw e.errors[0]}var ve=Ye(m);async function Xe(r){let t=Je(process.cwd(),r);process.chdir(Ze(t));let e=ve(t),n=e.default??e;"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&&U(n.outputFiles.outputDir);try{console.log("Generating multiple outputs..."),await de(n),console.log("Done")}catch(o){console.error("Generation failed:",o),process.exit(1)}}async function et(){let r=ve("../../package.json"),t=k();R.version(r.version).usage("<path/to/config.js>").parse(process.argv);let e=R.args[0];if(R.args.length===0){R.help();return}W(e),_(e,t),await Xe(e)}et().catch(r=>{console.error("CLI execution failed:",r),process.exit(1)});export{Xe as runGeneration};
167
+ `}var w=class{constructor(t,e){this.parserService=t;this.options=e;this.infoExtractor=new F(e)}infoExtractor;async generate(){let t=this.parserService.getOperationDefinitions(this.options.filterEndpoints),e=this.infoExtractor.extractEndpointInfos(t);return this.generateRtkQueryCode(e)}generateRtkQueryCode(t){let e=this.generateTypes(t),n=me(t,this.options),o=ge(t,this.options),s=this.generateIndex(),a=t.map(u=>u.operationName),p=new Set;return t.forEach(u=>{u.tags&&Array.isArray(u.tags)&&u.tags.forEach(i=>p.add(i))}),{operationNames:a,tags:Array.from(p),files:{types:e,queryService:n,index:s,enhanceEndpoints:o}}}generateTypes(t){let e={...this.options,apiConfiguration:this.options.apiConfiguration||{file:"@/store/webapi",importName:"WebApiConfiguration"}},o=this.parserService.getApiGenerator().aliases.reduce((a,p)=>{if(le.isInterfaceDeclaration(p)||le.isTypeAliasDeclaration(p)){let u=p.name.text;return{...a,[u]:p}}return a},{}),s=this.parserService.getOperationDefinitions(this.options.filterEndpoints);return ue(t,e,o,s)}generateIndex(){let t=this.options.groupKey||"";return`/* eslint-disable */
168
+ // [Warning] Generated automatically - do not edit manually
169
+
170
+ export { default as ${t?`${t.charAt(0).toLowerCase()+t.slice(1)}Api`:"api"} } from "./enhanceEndpoints";
171
+ export * from "./query.generated";
172
+ export * from "./types";
173
+ `}};c();function ye(){return`/* eslint-disable */
174
+ // [Warning] Generated automatically - do not edit manually
175
+
176
+ /**
177
+ * Clear undefined in object
178
+ */
179
+ export function withoutUndefined(obj?: Record<string, any>) {
180
+ if(typeof obj === 'undefined') return;
181
+ return Object.fromEntries(
182
+ Object.entries(obj).filter(([_, v]) => v !== undefined && v !== null)
183
+ );
184
+ }
185
+
186
+ `}c();function de(r){return r.length===0?`/* eslint-disable */
187
+ // [Warning] Generated automatically - do not edit manually
188
+
189
+ export enum ECacheTagTypes {
190
+ }
191
+ `:`/* eslint-disable */
192
+ // [Warning] Generated automatically - do not edit manually
193
+
194
+ export enum ECacheTagTypes {
195
+ ${r.sort().map(e=>` ${e} = '${e}',`).join(`
196
+ `)}
197
+ }
198
+ `}var q=class{_options;openApiService=new C;groupService=new N;fileWriterService=new R;openApiDoc=null;parserService=null;schemaInterfaces={};actualSchemaFile="";generatedContent={groups:[],commonTypes:"",componentSchema:"",doNotModify:"",utils:"",tagTypes:""};allTags=new Set;constructor(t){this._options=t}async generateAll(){return await this.prepare(),await this.generateApi(),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 E(this.openApiDoc,this._options),this.parserService.initialize();let t=this.parserService.getApiGenerator();this.schemaInterfaces=t.aliases.reduce((e,n)=>{if(fe.isInterfaceDeclaration(n)||fe.isTypeAliasDeclaration(n)){let o=n.name.text;return{...e,[o]:n}}return e},{})}async generateApi(){if(!this.openApiDoc||!this.parserService)throw new Error("\u8ACB\u5148\u8ABF\u7528 prepare() \u65B9\u6CD5");let t=this.openApiService.getPaths(this.openApiDoc),e=this.groupService.groupPaths(t,this._options.outputFiles);for(let n of Object.values(e))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(s=>this.allTags.add(s)))}catch(o){throw new Error(`\u7FA4\u7D44 ${n.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=ye()}async generateTagTypesContent(){let t=Array.from(this.allTags);this.generatedContent.tagTypes=de(t)}async release(){let t=[],e=[],n=[];try{for(let p of this.generatedContent.groups)try{if(p.content?.files){let u=P.dirname(p.outputPath),i=await this.fileWriterService.writeGroupFiles(u,{types:p.content.files.types,queryService:p.content.files.queryService,enhanceEndpoints:p.content.files.enhanceEndpoints,index:p.content.files.index});t.push(...i),n.push(p.groupKey)}}catch(u){e.push(new Error(`\u5BEB\u5165\u7FA4\u7D44 ${p.groupKey} \u5931\u6557: ${u}`))}let o=this.generatedContent.groups[0]?P.dirname(P.dirname(this.generatedContent.groups[0].outputPath)):"./generated";if(this.generatedContent.commonTypes||this.generatedContent.doNotModify||this.generatedContent.utils){let p=await this.fileWriterService.writeSharedFiles(o,{commonTypes:this.generatedContent.commonTypes||void 0,doNotModify:this.generatedContent.doNotModify||void 0,utils:this.generatedContent.utils||void 0});t.push(...p)}if(this.generatedContent.tagTypes){let p=await this.fileWriterService.writeFile(P.join(o,"tagTypes.ts"),this.generatedContent.tagTypes);t.push(p)}if(this.generatedContent.componentSchema){let p=await this.fileWriterService.writeSchemaFile(o,this.generatedContent.componentSchema);t.push(...p)}let s=this.generateMainIndex(n),a=await this.fileWriterService.writeFile(P.join(o,"index.ts"),s);t.push(a)}catch(o){e.push(o)}return{success:e.length===0,writtenFiles:t,errors:e,generatedGroups:n}}async generateApiGroupContent(t,e){let{outputFiles:n,...o}=t,s={...o,schemaFile:this.actualSchemaFile,outputFile:e.outputPath,sharedTypesFile:`${n.outputDir}/common-types.ts`,filterEndpoints:this.groupService.createGroupFilter(e.groupKey,n),queryMatch:n.queryMatch,groupKey:e.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 w(this.parserService,s).generate()}generateMainIndex(t){return`/* eslint-disable */
199
+ // [Warning] Generated automatically - do not edit manually
200
+
201
+ ${t.map(n=>`export * from "./${n}";`).join(`
202
+ `)}
203
+ `}};async function he(r){let e=await new q(r).generateAll();if(!e.success&&e.errors.length>0)throw e.errors[0]}var ve=nt(g);async function st(r){let t=it(process.cwd(),r);process.chdir(ot(t));let e=ve(t),n=e.default??e;"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&&U(n.outputFiles.outputDir);try{console.log("Generating multiple outputs..."),await he(n),console.log("Done")}catch(o){console.error("Generation failed:",o),process.exit(1)}}async function at(){let r=ve("../../package.json"),t=W();j.version(r.version).usage("<path/to/config.js>").parse(process.argv);let e=j.args[0];if(j.args.length===0){j.help();return}_(e),B(e,t),await st(e)}at().catch(r=>{console.error("CLI execution failed:",r),process.exit(1)});export{st as runGeneration};
186
204
  //# sourceMappingURL=cli.mjs.map