anl 26.304.0 → 26.317.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.
@@ -1,13 +1,13 @@
1
1
  import type { AxiosResponse } from 'axios';
2
2
 
3
- import { dio as axios } from './config';
3
+ import { dio } from './dio';
4
4
  import { messageTip } from './error-message';
5
5
 
6
6
  function GET<R = unknown>(url: string, params: IRequestFnParams, datalevel?: 'serve'): RServe<R>;
7
7
  function GET<R = unknown>(url: string, params: IRequestFnParams, datalevel?: 'data'): Promise<R>;
8
8
  function GET<R = unknown>(url: string, params: IRequestFnParams, datalevel?: 'axios'): RAxios<R>;
9
9
  function GET<R = unknown>(url: string, params: IRequestFnParams, datalevel: TDatalevel = 'serve') {
10
- return axios
10
+ return dio
11
11
  .request<unknown, AxiosResponse<ResponseModel<R>>>({
12
12
  ...params,
13
13
  url,
@@ -31,7 +31,7 @@ function DELETE<R = unknown>(url: string, params: IRequestFnParams, datalevel?:
31
31
  function DELETE<R = unknown>(url: string, params: IRequestFnParams, datalevel?: 'data'): Promise<R>;
32
32
  function DELETE<R = unknown>(url: string, params: IRequestFnParams, datalevel?: 'axios'): RAxios<R>;
33
33
  function DELETE<R = unknown>(url: string, params: IRequestFnParams, datalevel: TDatalevel = 'serve') {
34
- return axios
34
+ return dio
35
35
  .request<unknown, AxiosResponse<ResponseModel<R>>>({
36
36
  ...params,
37
37
  url,
@@ -55,7 +55,7 @@ function PUT<R = unknown>(url: string, params: IRequestFnParams, datalevel?: 'se
55
55
  function PUT<R = unknown>(url: string, params: IRequestFnParams, datalevel?: 'data'): Promise<R>;
56
56
  function PUT<R = unknown>(url: string, params: IRequestFnParams, datalevel?: 'axios'): RAxios<R>;
57
57
  function PUT<R = unknown>(url: string, { query, body, ...rest }: IRequestFnParams, datalevel: TDatalevel = 'serve') {
58
- return axios
58
+ return dio
59
59
  .request<unknown, AxiosResponse<ResponseModel<R>>>({
60
60
  ...rest,
61
61
  url,
@@ -80,7 +80,7 @@ function POST<R = unknown>(url: string, params: IRequestFnParams, datalevel?: 's
80
80
  function POST<R = unknown>(url: string, params: IRequestFnParams, datalevel?: 'data'): Promise<R>;
81
81
  function POST<R = unknown>(url: string, params: IRequestFnParams, datalevel?: 'axios'): RAxios<R>;
82
82
  function POST<R = unknown>(url: string, { query, body, ...rest }: IRequestFnParams, datalevel: TDatalevel = 'serve') {
83
- return axios
83
+ return dio
84
84
  .request<unknown, AxiosResponse<ResponseModel<R>>>({
85
85
  ...rest,
86
86
  url,
@@ -105,7 +105,7 @@ function PATCH<R = unknown>(url: string, params: IRequestFnParams, datalevel?: '
105
105
  function PATCH<R = unknown>(url: string, params: IRequestFnParams, datalevel?: 'data'): Promise<R>;
106
106
  function PATCH<R = unknown>(url: string, params: IRequestFnParams, datalevel?: 'axios'): RAxios<R>;
107
107
  function PATCH<R = unknown>(url: string, { query, body, ...rest }: IRequestFnParams, datalevel: TDatalevel = 'serve') {
108
- return axios
108
+ return dio
109
109
  .request<unknown, AxiosResponse<ResponseModel<R>>>({
110
110
  ...rest,
111
111
  url,
@@ -130,7 +130,7 @@ function OPTIONS<R = unknown>(url: string, params: IRequestFnParams, datalevel?:
130
130
  function OPTIONS<R = unknown>(url: string, params: IRequestFnParams, datalevel?: 'data'): Promise<R>;
131
131
  function OPTIONS<R = unknown>(url: string, params: IRequestFnParams, datalevel?: 'axios'): RAxios<R>;
132
132
  function OPTIONS<R = unknown>(url: string, { query, body, ...rest }: IRequestFnParams, datalevel: TDatalevel = 'serve') {
133
- return axios
133
+ return dio
134
134
  .request<unknown, AxiosResponse<ResponseModel<R>>>({
135
135
  ...rest,
136
136
  url,
@@ -155,7 +155,7 @@ function HEAD<R = unknown>(url: string, params: IRequestFnParams, datalevel?: 's
155
155
  function HEAD<R = unknown>(url: string, params: IRequestFnParams, datalevel?: 'data'): Promise<R>;
156
156
  function HEAD<R = unknown>(url: string, params: IRequestFnParams, datalevel?: 'axios'): RAxios<R>;
157
157
  function HEAD<R = unknown>(url: string, { query, body, ...rest }: IRequestFnParams, datalevel: TDatalevel = 'serve') {
158
- return axios
158
+ return dio
159
159
  .request<unknown, AxiosResponse<ResponseModel<R>>>({
160
160
  ...rest,
161
161
  url,
@@ -180,7 +180,7 @@ function SEARCH<R = unknown>(url: string, params: IRequestFnParams, datalevel?:
180
180
  function SEARCH<R = unknown>(url: string, params: IRequestFnParams, datalevel?: 'data'): Promise<R>;
181
181
  function SEARCH<R = unknown>(url: string, params: IRequestFnParams, datalevel?: 'axios'): RAxios<R>;
182
182
  function SEARCH<R = unknown>(url: string, { query, body, ...rest }: IRequestFnParams, datalevel: TDatalevel = 'serve') {
183
- return axios
183
+ return dio
184
184
  .request<unknown, AxiosResponse<ResponseModel<R>>>({
185
185
  ...rest,
186
186
  url,
package/lib/package.cjs CHANGED
@@ -1 +1 @@
1
- var e=`26.304.0`;Object.defineProperty(exports,`version`,{enumerable:!0,get:function(){return e}});
1
+ var e=`26.317.0`;Object.defineProperty(exports,`version`,{enumerable:!0,get:function(){return e}});
@@ -1,6 +1,5 @@
1
1
  const e=require(`../../utils/index.cjs`),t=require(`../shared/format.cjs`),n=require(`../shared/naming.cjs`),r=require(`../shared/schema-utils.cjs`),i=require(`./enum-parser.cjs`);var a=class{schemas;config;requiredFieldSet=new Set;defaultReturn={headerRef:``,renderStr:``,comment:``,typeName:``};enumParser;schemasMap=new Map;constructor(e,t){this.schemas=e,this.config=t,this.enumParser=new i.EnumParser(t)}nullable(e){return r.nullableSuffix(e)}isRequired(e){return this.requiredFieldSet.has(e)}stringifyValue(e){if(typeof e==`string`)return e;try{return JSON.stringify(e)}catch{return String(e)}}buildDocComment(e,n){let r=t.getIndentation(this.config),i=[],a=e,o=a.title,s=a.description;o&&i.push(`@title ${o}`),s&&s.split(`
2
- `).forEach((e,t)=>i.push(t===0?`@description ${e}`:e)),`deprecated`in e&&e.deprecated&&i.push(`@deprecated`),`default`in e&&e.default!==void 0&&i.push(`@default ${this.stringifyValue(e.default)}`),`example`in e&&e.example!==void 0&&i.push(`@example ${this.stringifyValue(e.example)}`),`format`in e&&e.format&&i.push(`@format ${e.format}`);let c=[[`pattern`,`@pattern`],[`minimum`,`@minimum`],[`maximum`,`@maximum`],[`exclusiveMinimum`,`@exclusiveMinimum`],[`exclusiveMaximum`,`@exclusiveMaximum`],[`minLength`,`@minLength`],[`maxLength`,`@maxLength`],[`minItems`,`@minItems`],[`maxItems`,`@maxItems`]],l=e;if(c.some(([e])=>l[e]!==void 0)){let e=c.map(([e,t])=>l[e]===void 0?``:`${t} ${this.stringifyValue(l[e])}`).filter(Boolean);i.push(...e)}if(!i.length)return``;if(i.length===1&&!i[0].includes(`
3
- `))return`${r}/** ${i[0]} */`;let u=[`${r}/**`];return i.forEach(e=>{e&&(e.includes(`
2
+ `).forEach((e,t)=>i.push(t===0?`@description ${e}`:e)),`deprecated`in e&&e.deprecated&&i.push(`@deprecated`),`default`in e&&e.default!==void 0&&i.push(`@default ${this.stringifyValue(e.default)}`),`example`in e&&e.example!==void 0&&i.push(`@example ${this.stringifyValue(e.example)}`),`format`in e&&e.format&&i.push(`@format ${e.format}`);let c=[[`pattern`,`@pattern`],[`minimum`,`@minimum`],[`maximum`,`@maximum`],[`exclusiveMinimum`,`@exclusiveMinimum`],[`exclusiveMaximum`,`@exclusiveMaximum`],[`minLength`,`@minLength`],[`maxLength`,`@maxLength`],[`minItems`,`@minItems`],[`maxItems`,`@maxItems`]],l=e;if(c.some(([e])=>l[e]!==void 0)){let e=c.map(([e,t])=>l[e]===void 0?``:`${t} ${this.stringifyValue(l[e])}`).filter(Boolean);i.push(...e)}if(!i.length)return``;let u=[`${r}/**`];return i.forEach(e=>{e&&(e.includes(`
4
3
  `)?e.split(`
5
4
  `).forEach(e=>u.push(`${r} * ${e}`)):u.push(`${r} * ${e}`))}),u.push(`${r} */`),u.join(`
6
5
  `)}nameTheHumpCenterStroke(e){let t=e.replace(`#/components/schemas/`,``),r=n.resolveSchemaName(t),i={typeName:r,fileName:n.typeNameToFileName(r),dataType:``};if(this.schemas){let e=this.schemas[t];e?.enum?i.dataType=`enum`:i.dataType=e?.type}return i}parseRef(e){if(!e?.trim())return{headerRefStr:``,typeName:``,dataType:``};let{fileName:t,typeName:r,dataType:i=``}=this.nameTheHumpCenterStroke(e),a;return a=i===`enum`?`import type { ${n.getEnumTypeName(this.config,r)} } from '${this.config.importEnumPath}';`:`import type { ${r} } from './${t}';`,{headerRefStr:a,typeName:r,dataType:i}}parseArray(r,i){let a=r,{items:o={},nullable:s}=a,c=o?.$ref;if(c){let{headerRefStr:r,typeName:o,dataType:l}=this.parseRef(c),u=a.example;if(l===`enum`&&typeof u==`string`&&e.isValidJSON(u)){let e=this.enumParser.convertJsonToEnumString(u,o);this.enumParser.addEnumByName(o,e)}let d=l===`enum`?n.getEnumTypeName(this.config,o):o;return{headerRef:r,renderStr:`${t.getIndentation(this.config)}${i}${this.isRequired(i)?``:`?`}: Array<${d}>${this.nullable(s)};`,typeName:d}}let l=o?.type,u=l===`integer`?`number`:l;return l===`object`&&(u=`Record<string, unknown>`),{headerRef:``,renderStr:`${t.getIndentation(this.config)}${i}${this.isRequired(i)?``:`?`}: Array<${u}>${this.nullable(s)};`,typeName:u}}parseBoolean(e,n){return e.type===`boolean`?`${t.getIndentation(this.config)}${n}${this.isRequired(n)?``:`?`}: boolean${this.nullable(e.nullable)};`:``}parseInteger(e,n){return Array.isArray(e.enum)?this.enumParser.handleEnum(e,n,this.isRequired(n))?.renderStr??``:`${t.getIndentation(this.config)}${n}${this.isRequired(n)?``:`?`}: number${this.nullable(e.nullable)};`}parseNumber(e,n){if(e.type!==`number`)return null;if(e.enum){let t=this.enumParser.handleEnum(e,n,this.isRequired(n));if(t)return t}return{headerRef:``,renderStr:`${t.getIndentation(this.config)}${n}${this.isRequired(n)?``:`?`}: number${this.nullable(e.nullable)};`}}getStringTypeByFormat(e){if(!e)return`string`;switch(e){case`date-time`:case`date`:case`time`:return`Date`;case`email`:case`idn-email`:case`uuid`:case`uri`:case`uri-reference`:case`iri`:case`iri-reference`:case`hostname`:case`idn-hostname`:case`ipv4`:case`ipv6`:return`string`;case`binary`:return`File`;default:return`string`}}parseString(e,n){if(e.type!==`string`)return null;if(e.enum){let t=this.enumParser.handleEnum(e,n,this.isRequired(n));if(t)return t}let r=this.getStringTypeByFormat(e.format);return{headerRef:``,renderStr:`${t.getIndentation(this.config)}${n}${this.isRequired(n)?``:`?`}: ${r}${this.nullable(e.nullable)};`}}parseObject(e,n){let r=``,i=``;if(e.type===`object`){let a=e;if(typeof a.additionalProperties==`object`){let e=this.parseArray(a.additionalProperties,n)??this.defaultReturn;r=e?.headerRef??``,i=e?.renderStr??``}i=typeof a.additionalProperties==`boolean`?`${t.getIndentation(this.config)}${n}${this.isRequired(n)?``:`?`}: Record<string, unknown>${this.nullable(a.nullable)};`:`${t.getIndentation(this.config)}${n}${this.isRequired(n)?``:`?`}: ${e.type}${this.nullable(e.nullable)};`}return{headerRef:r,renderStr:i}}parseProperties(r,i){let a=[],o=[];if(!r)return{headerRef:``,renderStr:`export interface ${i} {}`};let s=Object.keys(r).sort();for(let c of s){let s=r[c];if(s?.$ref){let{headerRefStr:r,typeName:l,dataType:u}=this.parseRef(s.$ref);!o.includes(r)&&l!==i&&o.push(r);let d=s,f=this.buildDocComment(d,c);f!==``&&a.push(f);let p=u===`enum`?n.getEnumTypeName(this.config,l):l;a.push(`${t.getIndentation(this.config)}${c}${this.isRequired(c)?``:`?`}: ${p};`);let m=s.example;if(u===`enum`&&m&&e.isValidJSON(m)){let e=this.enumParser.convertJsonToEnumString(m,l);this.enumParser.addEnumByName(l,e)}continue}if(`allOf`in s){let e=s.allOf?.[0];if(e?.$ref){let{headerRefStr:r,typeName:l,dataType:u}=this.parseRef(e.$ref),d=u===`enum`?n.getEnumTypeName(this.config,l):l;!o.includes(r)&&l!==i&&o.push(r);let f=s,p=this.buildDocComment(f,c);p!==``&&a.push(p),a.push(`${t.getIndentation(this.config)}${c}${this.isRequired(c)?``:`?`}: ${d}${this.nullable(s.nullable)};`);continue}}let l=s,u=this.buildDocComment(l,c);switch(u!==``&&a.push(u),l.type){case`array`:{let e=this.parseArray(l,c)??this.defaultReturn;a.push(e?.renderStr??``),!o.includes(e.headerRef)&&i!==e.typeName&&o.push(e.headerRef)}break;case`boolean`:a.push(this.parseBoolean(l,c));break;case`integer`:a.push(this.parseInteger(l,c));break;case`number`:{let e=this.parseNumber(l,c);e&&(e.headerRef&&!o.includes(e.headerRef)&&o.push(e.headerRef),a.push(e.renderStr))}break;case`string`:if(l.enum){let e=this.enumParser.handleEnum(l,c,this.isRequired(c));e&&(e.headerRef&&!o.includes(e.headerRef)&&o.push(e.headerRef),e.renderStr&&a.push(e.renderStr))}else a.push(this.parseString(l,c)?.renderStr??``);break;case`object`:{let{headerRef:e,renderStr:t}=this.parseObject(l,c)??this.defaultReturn;a.push(t),o.includes(e)||o.push(e)}break}}let c=[`export interface ${i} {`,...a,`}`];if(o.length>0){let e=o.filter(e=>e!==``);e.length>0&&e.push(``),c.unshift(...e)}let l=c.join(`
@@ -1,8 +1,8 @@
1
- const e=require(`../_virtual/rolldown_runtime.cjs`),t=require(`../utils/index.cjs`),n=require(`./components/index.cjs`),r=require(`./get-data.cjs`),i=require(`./path/index.cjs`);let a=require(`fs`);a=e.__toESM(a);let o=require(`path`);o=e.__toESM(o);let s=require(`chalk`);s=e.__toESM(s);let c=require(`shelljs`),l;const u=process.env.NODE_ENV===`debug`,d={saveTypeFolderPath:u?`apps/types`:`src/api/types`,saveApiListFolderPath:u?`apps/types`:`src/api`,saveEnumFolderPath:u?`apps/types/enums`:`src/enums`,importEnumPath:`../../../enums`,requestMethodsImportPath:`./fetch`,formatting:{indentation:` `,lineEnding:`
1
+ const e=require(`../_virtual/rolldown_runtime.cjs`),t=require(`../utils/index.cjs`),n=require(`./components/index.cjs`),r=require(`./get-data.cjs`),i=require(`./path/index.cjs`);let a=require(`fs`);a=e.__toESM(a);let o=require(`path`);o=e.__toESM(o);let s=require(`chalk`);s=e.__toESM(s);let c=require(`shelljs`),l;const u=process.env.NODE_ENV===`debug`,d={saveTypeFolderPath:u?`apps/types`:`src/types`,saveApiListFolderPath:u?`apps/types`:`src/apis`,saveEnumFolderPath:u?`apps/enums`:`src/enums`,importEnumPath:`../../../enums`,requestMethodsImportPath:`./config/fetch`,formatting:{indentation:` `,lineEnding:`
2
2
  `},swaggerConfig:{url:`https://generator3.swagger.io/openapi.json`,apiListFileName:`index.ts`,headers:{},dataLevel:`serve`,parameterSeparator:`_`,includeInterface:[],excludeInterface:[]},enmuConfig:{erasableSyntaxOnly:!1,varnames:`enum-varnames`,comment:`enum-descriptions`}};var f=class{schemas={};paths={};async handle(e,t){try{let a=await r.getSwaggerJson(e);if(!a)throw Error(`无法获取 Swagger 数据`);this.schemas=a.components?.schemas??{},this.paths=a.paths??{};let o=new n.default(this.schemas,e,{appendMode:t}),s=new i.default(this.paths,a.components?.parameters,this.schemas,e);return await o.handle(),await s.handle(),!0}catch(e){throw e instanceof Error?Error(`Handle Swagger data failed: ${e.message}`):Error(`Handle Swagger data failed: unknown error`)}}async formatGeneratedFiles(e){let n=`npx prettier --write "${e.saveTypeFolderPath}/**/*.{ts,d.ts}"`;try{await a.default.promises.access(e.saveTypeFolderPath);let{stderr:r}=await new Promise((e,t)=>{(0,c.exec)(n,(n,r,i)=>{n?t(Error(String(n))):e({stdout:r,stderr:i})})});r&&(console.log(`
3
3
  `),console.log(`$`,s.default.yellow(n)),console.log(`
4
4
  `)),t.log.success(`File formatting successful`),console.log(`
5
- `)}catch(e){console.log(``),console.log(e),t.log.error(`Format failed, please manually execute the following command:`),console.log(`$`,s.default.yellow(n)),console.log(``)}}async copyAjaxConfigFiles(e){try{let n=[`config.ts`,`error-message.ts`,`fetch.ts`,`api-type.d.ts`],r=u?o.default.join(__dirname,`..`,`..`,`postbuild-assets`,`ajax-config`):o.default.join(__dirname,`..`,`ajax-config`),i=e;for(let e of n){let n=o.default.join(r,e),s=o.default.join(i,e);try{await a.default.promises.access(n);try{await a.default.promises.access(s),t.log.info(`${e} already exists, skipping generation.`)}catch{await a.default.promises.copyFile(n,s),t.log.success(`${e} create done.`)}}catch(e){if(e instanceof Error)throw t.log.error(`Source file ${n} does not exist`),Error(`Source file ${n} does not exist: ${e.message}`);continue}}}catch(e){return e}}getSystemLocale(){try{return Intl.DateTimeFormat().resolvedOptions().locale.toLowerCase()}catch{return(process.env.LANG??process.env.LC_ALL??process.env.LC_MESSAGES??``).toLowerCase()}}showLegacyConfigHint(e){let t={url:e.swaggerJsonUrl??`https://your.swagger.json`,publicPrefix:e.publicPrefix??``,apiListFileName:e.apiListFileName??`index.ts`,headers:e.headers??{}},n=this.getSystemLocale();n.startsWith(`zh`)||n.includes(`chinese`)?(console.log(`
5
+ `)}catch(e){console.log(``),console.log(e),t.log.error(`Format failed, please manually execute the following command:`),console.log(`$`,s.default.yellow(n)),console.log(``)}}async copyAjaxConfigFiles(e){let n=[`dio.ts`,`error-message.ts`,`fetch.ts`,`api-type.d.ts`],r=u?o.default.join(__dirname,`..`,`..`,`postbuild-assets`,`ajax-config`):o.default.join(__dirname,`..`,`ajax-config`),i=o.default.join(e,`config`);try{await a.default.promises.access(i),t.log.info(`config folder already exists at ${i}, skipping generation.`);return}catch{await a.default.promises.mkdir(i,{recursive:!0})}for(let e of n){let n=o.default.join(r,e),s=o.default.join(i,e);try{await a.default.promises.access(n),await a.default.promises.copyFile(n,s),t.log.success(`${e} create done.`)}catch(e){throw e instanceof Error?(t.log.error(`Source file ${n} does not exist`),Error(`Source file ${n} does not exist: ${e.message}`)):Error(`Source file ${n} does not exist: unknown error`)}}}getSystemLocale(){try{return Intl.DateTimeFormat().resolvedOptions().locale.toLowerCase()}catch{return(process.env.LANG??process.env.LC_ALL??process.env.LC_MESSAGES??``).toLowerCase()}}showLegacyConfigHint(e){let t={url:e.swaggerJsonUrl??`https://your.swagger.json`,publicPrefix:e.publicPrefix??``,apiListFileName:e.apiListFileName??`index.ts`,headers:e.headers??{}},n=this.getSystemLocale();n.startsWith(`zh`)||n.includes(`chinese`)?(console.log(`
6
6
  检测到旧版配置,请更新 an.config.json:`),console.log(`1) 将 swaggerJsonUrl / publicPrefix / headers 移到 swaggerConfig 字段。`),console.log(`2) 单个服务可直接填写对象,多个服务请使用数组,并确保 apiListFileName 唯一。`),console.log(`示例:`),console.log(JSON.stringify({swaggerConfig:t},null,2)),console.log(``)):(console.log(`
7
- Legacy configuration detected, please update an.config.json:`),console.log(`1) Move swaggerJsonUrl / publicPrefix / headers to swaggerConfig field.`),console.log(`2) Single service can be an object directly, multiple services should use an array, and ensure apiListFileName is unique.`),console.log(`Example:`),console.log(JSON.stringify({swaggerConfig:t},null,2)),console.log(``))}normalizeswaggerConfig(e,t){let n=!1,r=t?e.swaggerConfig:void 0;r||=(n=!0,{url:e.swaggerJsonUrl??``,publicPrefix:e.publicPrefix??``,apiListFileName:e.apiListFileName??`index.ts`,headers:e.headers??{},modulePrefix:e.modulePrefix});let i=(t,r)=>{let i=t.url||e.swaggerJsonUrl;if(!i)throw Error(`swaggerConfig[${r}] 缺少 url,请补充后重试。`);let a=t.publicPrefix??e.publicPrefix??``;!t.url&&e.swaggerJsonUrl&&(n=!0);let o=(t.apiListFileName??e.apiListFileName??`index.ts`).trim()||`index.ts`,s=t.headers??e.headers??{},c=t.dataLevel??e.dataLevel??`serve`,l=t.parameterSeparator??e.parameterSeparator??`_`,u=t.includeInterface??e.includeInterface??[],d=t.excludeInterface??e.excludeInterface??[],f=t.includeTags??e.includeTags,p=t.excludeTags??e.excludeTags,m={url:i,publicPrefix:a,apiListFileName:o,headers:s,dataLevel:c,parameterSeparator:l,includeInterface:u,excludeInterface:d,modulePrefix:t.modulePrefix??e.modulePrefix??``,responseModelTransform:t.responseModelTransform??e.responseModelTransform};return f!==void 0&&(m.includeTags=f),p!==void 0&&(m.excludeTags=p),m},a=Array.isArray(r)?r.map((e,t)=>i(e,t)):[i(r,0)];if(a.length===0)throw Error(`swaggerConfig 不能为空,请至少配置一个 swagger 服务。`);if(a.length>1){let e=new Set;a.forEach(t=>{if(e.has(t.apiListFileName))throw Error(`swaggerConfig 中 apiListFileName 重复:${t.apiListFileName},请为每个服务设置唯一文件名。`);e.add(t.apiListFileName)})}return n&&this.showLegacyConfigHint(e),a}buildServerConfig(e,t){return{...e,swaggerJsonUrl:t.url,publicPrefix:t.publicPrefix??e.publicPrefix,headers:t.headers,apiListFileName:t.apiListFileName,dataLevel:t.dataLevel,parameterSeparator:t.parameterSeparator,includeInterface:t.includeInterface,excludeInterface:t.excludeInterface,includeTags:t.includeTags,excludeTags:t.excludeTags,modulePrefix:t.modulePrefix,responseModelTransform:t.responseModelTransform??e.responseModelTransform,swaggerConfig:t}}async getConfig(e){try{let t=await a.default.promises.readFile(e,`utf8`);l=!0;try{return JSON.parse(t)}catch(e){throw l=!0,Error(`配置文件格式错误,请检查 an.config.json 的 JSON 格式是否正确: ${e instanceof Error?e.message:String(e)}`)}}catch(n){if(n instanceof Error&&`code`in n&&n.code===`ENOENT`)return l=!1,t.log.warning(`配置文件不存在,将自动创建配置文件。`),await t.writeFileRecursive(e,JSON.stringify(d,null,2)),t.log.success(`配置文件已创建,请检查项目根目录下的 an.config.json 文件并配置后重新运行。`),d;throw n}}async initialize(){let e=process.cwd()+`/an.config.json`;try{let n=await this.getConfig(e),r={...d,...n},i=Object.prototype.hasOwnProperty.call(n,`swaggerConfig`),o=this.normalizeswaggerConfig(r,i);if(!l)return;await a.default.promises.mkdir(r.saveApiListFolderPath,{recursive:!0}),await this.copyAjaxConfigFiles(r.saveApiListFolderPath),await t.clearDirExcept(r.saveApiListFolderPath,[`api-type.d.ts`,`config.ts`,`error-message.ts`,`fetch.ts`]),await t.clearDir(r.saveTypeFolderPath),await t.clearDir(r.saveEnumFolderPath);for(let e=0;e<o.length;e++){let t=this.buildServerConfig(r,o[e]),n=e>0;await this.handle(t,n)}await this.formatGeneratedFiles(r),t.log.success(`Successfully, all done, see you next time!`),console.log(`
7
+ Legacy configuration detected, please update an.config.json:`),console.log(`1) Move swaggerJsonUrl / publicPrefix / headers to swaggerConfig field.`),console.log(`2) Single service can be an object directly, multiple services should use an array, and ensure apiListFileName is unique.`),console.log(`Example:`),console.log(JSON.stringify({swaggerConfig:t},null,2)),console.log(``))}normalizeswaggerConfig(e,t){let n=!1,r=t?e.swaggerConfig:void 0;r||=(n=!0,{url:e.swaggerJsonUrl??``,publicPrefix:e.publicPrefix??``,apiListFileName:e.apiListFileName??`index.ts`,headers:e.headers??{},modulePrefix:e.modulePrefix});let i=(t,r)=>{let i=t.url||e.swaggerJsonUrl;if(!i)throw Error(`swaggerConfig[${r}] 缺少 url,请补充后重试。`);let a=t.publicPrefix??e.publicPrefix??``;!t.url&&e.swaggerJsonUrl&&(n=!0);let o=(t.apiListFileName??e.apiListFileName??`index.ts`).trim()||`index.ts`,s=t.headers??e.headers??{},c=t.dataLevel??e.dataLevel??`serve`,l=t.parameterSeparator??e.parameterSeparator??`_`,u=t.includeInterface??e.includeInterface??[],d=t.excludeInterface??e.excludeInterface??[],f=t.includeTags??e.includeTags,p=t.excludeTags??e.excludeTags,m={url:i,publicPrefix:a,apiListFileName:o,headers:s,dataLevel:c,parameterSeparator:l,includeInterface:u,excludeInterface:d,modulePrefix:t.modulePrefix??e.modulePrefix??``,responseModelTransform:t.responseModelTransform??e.responseModelTransform};return f!==void 0&&(m.includeTags=f),p!==void 0&&(m.excludeTags=p),m},a=Array.isArray(r)?r.map((e,t)=>i(e,t)):[i(r,0)];if(a.length===0)throw Error(`swaggerConfig 不能为空,请至少配置一个 swagger 服务。`);if(a.length>1){let e=new Set;a.forEach(t=>{if(e.has(t.apiListFileName))throw Error(`swaggerConfig 中 apiListFileName 重复:${t.apiListFileName},请为每个服务设置唯一文件名。`);e.add(t.apiListFileName)})}return n&&this.showLegacyConfigHint(e),a}buildServerConfig(e,t){return{...e,swaggerJsonUrl:t.url,publicPrefix:t.publicPrefix??e.publicPrefix,headers:t.headers,apiListFileName:t.apiListFileName,dataLevel:t.dataLevel,parameterSeparator:t.parameterSeparator,includeInterface:t.includeInterface,excludeInterface:t.excludeInterface,includeTags:t.includeTags,excludeTags:t.excludeTags,modulePrefix:t.modulePrefix,responseModelTransform:t.responseModelTransform??e.responseModelTransform,swaggerConfig:t}}async getConfig(e){try{let t=await a.default.promises.readFile(e,`utf8`);l=!0;try{return JSON.parse(t)}catch(e){throw l=!0,Error(`配置文件格式错误,请检查 an.config.json 的 JSON 格式是否正确: ${e instanceof Error?e.message:String(e)}`)}}catch(n){if(n instanceof Error&&`code`in n&&n.code===`ENOENT`)return l=!1,t.log.warning(`配置文件不存在,将自动创建配置文件。`),await t.writeFileRecursive(e,JSON.stringify(d,null,2)),t.log.success(`配置文件已创建,请检查项目根目录下的 an.config.json 文件并配置后重新运行。`),d;throw n}}async initialize(){let e=process.cwd()+`/an.config.json`;try{let n=await this.getConfig(e),r={...d,...n},i=Object.prototype.hasOwnProperty.call(n,`swaggerConfig`),o=this.normalizeswaggerConfig(r,i);if(!l)return;await a.default.promises.mkdir(r.saveApiListFolderPath,{recursive:!0}),await this.copyAjaxConfigFiles(r.saveApiListFolderPath),await t.clearDirExcept(r.saveApiListFolderPath,[`config`]),await t.clearDir(r.saveTypeFolderPath),await t.clearDir(r.saveEnumFolderPath);for(let e=0;e<o.length;e++){let t=this.buildServerConfig(r,o[e]),n=e>0;await this.handle(t,n)}await this.formatGeneratedFiles(r),t.log.success(`Successfully, all done, see you next time!`),console.log(`
8
8
  `)}catch(e){let n=e instanceof Error?e.message:`Unknown error`;t.log.error(`Initialization failed: ${n}`)}}};u&&new f().initialize().catch(e=>{console.error(e)}),exports.Main=f;
@@ -1,7 +1,7 @@
1
1
  const e=require(`../../utils/index.cjs`),t=require(`../shared/format.cjs`),n=require(`../shared/naming.cjs`),r=require(`../shared/http.cjs`),i=require(`./naming.cjs`),a=require(`./schema-resolver.cjs`),o=require(`./writer.cjs`);var s=function(e){return e.GET=`get`,e.PUT=`put`,e.POST=`post`,e.DELETE=`delete`,e.OPTIONS=`options`,e.HEAD=`head`,e.PATCH=`patch`,e.TRACE=`trace`,e}(s||{});const c={typeMapping:new Map([[`integer`,`number`],[`string`,`string`],[`boolean`,`boolean`],[`binary`,`File`],[`number`,`number`],[`null`,`null`],[`undefined`,`undefined`],[`date`,`Date`],[`time`,`Date`],[`datetime`,`Date`],[`timestamp`,`Date`]]),errorHandling:{throwOnError:!1,logErrors:!0}};var l=class{pathsObject={};nonArrayType=[`boolean`,`object`,`number`,`string`,`integer`];pathKey=``;contentBody={payload:{path:[],query:[],header:[],body:[]},response:``,_response:``,fileName:``,method:``,requestPath:``,summary:``,apiName:``,typeName:``,deprecated:!1,contentType:`application/json`};Map=new Map;config;errors=[];parameters={};schemas={};schemaResolver;writer;apiListFileContent=[];allowedInterfaceKeys=new Set;constructor(e,n,r,i){this.pathsObject=e,this.parameters=n??{},this.schemas=r??{},this.config=t.applyFormattingDefaults({...c,...i,typeMapping:new Map([...c.typeMapping??[],...i.typeMapping??[]])}),this.schemaResolver=new a.SchemaResolver(this.config,this.schemas,this.parameters,this.handleError.bind(this)),this.writer=new o.PathWriter(this.config)}handleError(t){if(this.errors.push(t),this.config.errorHandling?.logErrors&&e.log.error(`${t.type}: ${t.message}${t.path?` at ${t.path}`:``}`),this.config.errorHandling?.throwOnError)throw Error(`${t.type}: ${t.message}`)}getIndentation(){return t.getIndentation(this.config)}getDoubleIndentation(){let e=this.getIndentation();return e+e}generateParamComment(e,t){let n=[],r=[];if(e.description&&r.push(e.description),e.deprecated&&r.push(`@deprecated`),e.schema&&typeof e.schema==`object`&&`example`in e.schema){let t=e.schema.example,n=typeof t==`string`?t:JSON.stringify(t);r.push(`@example ${n}`)}if(e.schema&&typeof e.schema==`object`&&`default`in e.schema){let t=e.schema.default,n=typeof t==`string`?t:JSON.stringify(t);r.push(`@default ${n}`)}return r.length>0&&(r.length===1&&!r[0].includes(`
2
2
  `)?n.push(`${t}/** ${r[0]} */`):(n.push(`${t}/**`),r.forEach(e=>{e.includes(`
3
3
  `)?e.split(`
4
- `).forEach(e=>{n.push(`${t} * ${e}`)}):n.push(`${t} * ${e}`)}),n.push(`${t} */`))),n}parametersItemHandle(e,t,r,i){let a=this.getDoubleIndentation(),o=`$ref`in e?e:null,s=`name`in e?e:null;if(o?.$ref&&o.$ref.startsWith(`#/components/parameters/`)&&this.parameters){let e=o.$ref.replace(`#/components/parameters/`,``),n=this.parameters[e];this.parametersItemHandle(n,t,r,i)}if(s){if(!s.schema){console.warn(`Parameter "${s.name}" has no schema defined, skipping...`);return}let e=this.schemaResolver.main(s.schema);if(!e||typeof e!=`string`){console.warn(`Failed to parse schema for parameter "${s.name}", got:`,e);return}if(s.in===`path`)this.generateParamComment(s,a).forEach(e=>t.push(e)),t.push(`${a}type ${s.name} = ${e};`),this.contentBody.payload._path?this.contentBody.payload._path[s.name]=e:this.contentBody.payload._path={[s.name]:e};else if(s.in===`query`){this.generateParamComment(s,a).forEach(e=>r.push(e));let t=s.required===!0?``:`?`,i=n.formatPropertyName(s.name);r.push(`${a}${i}${t}: ${e};`),this.contentBody.payload._query?this.contentBody.payload._query[s.name]=e:this.contentBody.payload._query={[s.name]:e}}else if(s.in===`header`){this.generateParamComment(s,a).forEach(e=>i.push(e));let t=s.required===!0?``:`?`,r=n.formatPropertyName(s.name);i.push(`${a}${r}${t}: ${e};`),this.contentBody.payload._header?this.contentBody.payload._header[s.name]=e:this.contentBody.payload._header={[s.name]:e}}else s.in===`cookie`?console.info(`Cookie parameter "${s.name}" detected but not added to type definition (cookies are typically handled separately)`):console.warn(`Unknown parameter location "${s.in}" for parameter "${s.name}"`)}}requestParametersParse(e){let t=this.getIndentation(),n=[],r=[],i=[];e?.map(e=>this.parametersItemHandle(e,n,r,i)),n.length!==0&&(n.unshift(`${t}namespace Path {`),n.push(`${t}}`)),r.length!==0&&(r.unshift(`${t}interface Query {`),r.push(`${t}}`)),i.length!==0&&(i.unshift(`${t}interface Header {`),i.push(`${t}}`)),this.contentBody.payload.path=n,this.contentBody.payload.query=r,this.contentBody.payload.header=i}pickRequestBodyContent(e){let t=e.content;if(!t||typeof t!=`object`)return{schema:null};for(let e of[`multipart/form-data`,`application/x-www-form-urlencoded`]){let n=t[e];if(n&&typeof n==`object`&&n.schema)return{schema:n.schema}}let n=Object.keys(t)[0],r=n?t[n]:null;return{schema:r&&typeof r==`object`&&r.schema?r.schema:null}}requestBodyObjectParse(e){let t=this.getIndentation(),{schema:n}=this.pickRequestBodyContent(e);if(n){let e=n?.type,r=`$ref`in n?n:null,i=e===`array`?n:null,a=e&&this.nonArrayType.includes(e)?n:null;if(r)return`${t}type Body = ${this.schemaResolver.referenceObjectParse(r)}`;if(i)return`${t}type Body = ${this.schemaResolver.arraySchemaObjectParse(i)}`;if(a){let e=this.schemaResolver.nonArraySchemaObjectParse(a);return Array.isArray(e)?e.length===0?[`${t}type Body = ${a.type};`]:[`${t}interface Body {`,...e.map(e=>e.replace(/: string;/,`: File;`)),`}`]:[`${t}type Body = ${e}`]}}}requestBodyParse(e){if(!e)return`{}`;let t=`$ref`in e?e:null,n=`content`in e?e:null;if(t){let e=this.schemaResolver.referenceObjectParse(t);return`${this.getIndentation()}type Body = ${e}`}return n&&Object.keys(e).length!==0?this.requestBodyObjectParse(n):`{}`}normalizemodulePrefix(e){if(!e||e.trim()===``)return``;let t=e.trim();return t=t.replace(/\/+$/g,``),t.startsWith(`/`)||(t=`/`+t),t}apiRequestItemHandle(e){let{payload:t,requestPath:n,_response:i,method:a,typeName:o,apiName:s,contentType:c}=e,{_path:l,_query:u,body:d}=t,f=e.dataLevel??this.config.dataLevel??`serve`,p=this.normalizemodulePrefix(this.config.modulePrefix),m=()=>{let e=[],t=Object.keys(l??{}).sort();for(let n of t)e.push(`${n}: ${o}.Path.${n}`);let n=e.join(e.length>1?`,`:``);return n===``?n:n+`,`},h=()=>{let e=u?`query: ${o}.Query,`:``;return e===``?``:`${e}`},g=()=>{let e=d.length>0?`body: ${o}.Body,`:``;return e===``?``:`${e}`},_=m(),v=h(),y=g(),b=()=>{let e=r.SUPPORTED_REQUEST_UPLOAD_TYPES.includes(c)?`headers: { 'Content-Type': '${c}' }`:void 0;return[`{`,e?`${e},`:``,`...params, `,v===``?``:`query,`,y===``?``:`body,`,`},`].join(``)},x=(_+v+y).replace(/,$/,``);return[`export const ${s} = `,`(`,x,x===``?`params?: IRequestFnParams`:`, params?: IRequestFnParams`,`)`,` => `,a,`${i?`<${o}.Response>`:``}`,`(`,`\`${p}${n}\`,`,b(),`'${f}'`,`);`].join(``)}responseHandle(e){let t=e[200];if(!t)return;let n=`content`in t?t:null,r=`$ref`in t?t:null;if(n===null&&r===null&&(this.contentBody.response=`type Response = unknown`,this.contentBody._response=`unknown`),r){let e=this.schemaResolver.referenceObjectParse(r);this.config.responseModelTransform&&(e=this.schemaResolver.transformResponseModel(e,this.config.responseModelTransform)),this.contentBody.response=`type Response = ${e}`,this.contentBody._response=e}if(n){let e=this.schemaResolver.responseObjectParse(n);if(this.config.responseModelTransform&&(e=this.schemaResolver.transformResponseModel(e,this.config.responseModelTransform)),Array.isArray(e)){if(e.length===1&&e[0]===`unknown`)this.contentBody.response=`type Response = ${e.join(`
4
+ `).forEach(e=>{n.push(`${t} * ${e}`)}):n.push(`${t} * ${e}`)}),n.push(`${t} */`))),n}parametersItemHandle(e,t,r,i){let a=this.getDoubleIndentation(),o=`$ref`in e?e:null,s=`name`in e?e:null;if(o?.$ref&&o.$ref.startsWith(`#/components/parameters/`)&&this.parameters){let e=o.$ref.replace(`#/components/parameters/`,``),n=this.parameters[e];this.parametersItemHandle(n,t,r,i)}if(s){if(!s.schema){console.warn(`Parameter "${s.name}" has no schema defined, skipping...`);return}let e=this.schemaResolver.main(s.schema);if(!e||typeof e!=`string`){console.warn(`Failed to parse schema for parameter "${s.name}", got:`,e);return}if(s.in===`path`)this.generateParamComment(s,a).forEach(e=>t.push(e)),t.push(`${a}type ${s.name} = ${e};`),this.contentBody.payload._path?this.contentBody.payload._path[s.name]=e:this.contentBody.payload._path={[s.name]:e};else if(s.in===`query`){this.generateParamComment(s,a).forEach(e=>r.push(e));let t=s.required===!0?``:`?`,i=n.formatPropertyName(s.name);r.push(`${a}${i}${t}: ${e};`),this.contentBody.payload._query?this.contentBody.payload._query[s.name]=e:this.contentBody.payload._query={[s.name]:e}}else if(s.in===`header`){this.generateParamComment(s,a).forEach(e=>i.push(e));let t=s.required===!0?``:`?`,r=n.formatPropertyName(s.name);i.push(`${a}${r}${t}: ${e};`),this.contentBody.payload._header?this.contentBody.payload._header[s.name]=e:this.contentBody.payload._header={[s.name]:e}}else s.in===`cookie`?console.info(`Cookie parameter "${s.name}" detected but not added to type definition (cookies are typically handled separately)`):console.warn(`Unknown parameter location "${s.in}" for parameter "${s.name}"`)}}requestParametersParse(e){let t=this.getIndentation(),n=[],r=[],i=[];e?.map(e=>this.parametersItemHandle(e,n,r,i)),n.length!==0&&(n.unshift(`${t}namespace Path {`),n.push(`${t}}`)),r.length!==0&&(r.unshift(`${t}interface Query {`),r.push(`${t}}`)),i.length!==0&&(i.unshift(`${t}interface Header {`),i.push(`${t}}`)),this.contentBody.payload.path=n,this.contentBody.payload.query=r,this.contentBody.payload.header=i}pickRequestBodyContent(e){let t=e.content;if(!t||typeof t!=`object`)return{schema:null};for(let e of[`multipart/form-data`,`application/x-www-form-urlencoded`]){let n=t[e];if(n&&typeof n==`object`&&n.schema)return{schema:n.schema}}let n=Object.keys(t)[0],r=n?t[n]:null;return{schema:r&&typeof r==`object`&&r.schema?r.schema:null}}requestBodyObjectParse(e){let t=this.getIndentation(),{schema:n}=this.pickRequestBodyContent(e);if(n){let e=n?.type,r=`$ref`in n?n:null,i=e===`array`?n:null,a=e&&this.nonArrayType.includes(e)?n:null;if(r)return`${t}type Body = ${this.schemaResolver.referenceObjectParse(r)}`;if(i)return`${t}type Body = ${this.schemaResolver.arraySchemaObjectParse(i)}`;if(a){let e=this.schemaResolver.nonArraySchemaObjectParse(a);return Array.isArray(e)?e.length===0?[`${t}type Body = ${a.type};`]:[`${t}interface Body {`,...e,`}`]:[`${t}type Body = ${e}`]}}}requestBodyParse(e){if(!e)return`{}`;let t=`$ref`in e?e:null,n=`content`in e?e:null;if(t){let e=this.schemaResolver.referenceObjectParse(t);return`${this.getIndentation()}type Body = ${e}`}return n&&Object.keys(e).length!==0?this.requestBodyObjectParse(n):`{}`}normalizemodulePrefix(e){if(!e||e.trim()===``)return``;let t=e.trim();return t=t.replace(/\/+$/g,``),t.startsWith(`/`)||(t=`/`+t),t}apiRequestItemHandle(e){let{payload:t,requestPath:n,_response:i,method:a,typeName:o,apiName:s,contentType:c}=e,{_path:l,_query:u,body:d}=t,f=e.dataLevel??this.config.dataLevel??`serve`,p=this.normalizemodulePrefix(this.config.modulePrefix),m=()=>{let e=[],t=Object.keys(l??{}).sort();for(let n of t)e.push(`${n}: ${o}.Path.${n}`);let n=e.join(e.length>1?`,`:``);return n===``?n:n+`,`},h=()=>{let e=u?`query: ${o}.Query,`:``;return e===``?``:`${e}`},g=()=>{let e=d.length>0?`body: ${o}.Body,`:``;return e===``?``:`${e}`},_=m(),v=h(),y=g(),b=()=>{let e=r.SUPPORTED_REQUEST_UPLOAD_TYPES.includes(c)?`headers: { 'Content-Type': '${c}' }`:void 0;return[`{`,e?`${e},`:``,`...params, `,v===``?``:`query,`,y===``?``:`body,`,`},`].join(``)},x=(_+v+y).replace(/,$/,``);return[`export const ${s} = `,`(`,x,x===``?`params?: IRequestFnParams`:`, params?: IRequestFnParams`,`)`,` => `,a,`${i?`<${o}.Response>`:``}`,`(`,`\`${p}${n}\`,`,b(),`'${f}'`,`);`].join(``)}responseHandle(e){let t=e[200];if(!t)return;let n=`content`in t?t:null,r=`$ref`in t?t:null;if(n===null&&r===null&&(this.contentBody.response=`type Response = unknown`,this.contentBody._response=`unknown`),r){let e=this.schemaResolver.referenceObjectParse(r);this.config.responseModelTransform&&(e=this.schemaResolver.transformResponseModel(e,this.config.responseModelTransform)),this.contentBody.response=`type Response = ${e}`,this.contentBody._response=e}if(n){let e=this.schemaResolver.responseObjectParse(n);if(this.config.responseModelTransform&&(e=this.schemaResolver.transformResponseModel(e,this.config.responseModelTransform)),Array.isArray(e)){if(e.length===1&&e[0]===`unknown`)this.contentBody.response=`type Response = ${e.join(`
5
5
  `)};`;else{let t=this.config.formatting?.lineEnding,n=this.config.formatting?.indentation;this.contentBody.response=`interface Response {${t}${e.join(`
6
6
  `)}${t}${n}};`}this.contentBody._response=`${e.join(`
7
7
  `)}`}else this.contentBody.response=`type Response = ${e}`,this.contentBody._response=`${e}`}}requestHandle(e){if(e.parameters&&this.requestParametersParse(e.parameters),e.requestBody){let t=this.requestBodyParse(e.requestBody);if(Array.isArray(t))this.contentBody.payload.body=t;else if(t){let e=t?.split(`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "anl",
3
- "version": "26.304.0",
3
+ "version": "26.317.0",
4
4
  "description": "FE command line tool",
5
5
  "main": "bin/an-cli.js",
6
6
  "publishConfig": {
File without changes