anl 1.4.12 → 1.4.13

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 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e="1.4.12",i="FE command line tool",s="bin/an-cli.js",l={dev:"rollup --config rollup.config.ts --configPlugin @rollup/plugin-typescript -w",build:"rimraf lib && rollup --config rollup.config.ts --configPlugin @rollup/plugin-typescript",pub:"bash publish.sh",ts:"tsc ./src/int.ts --noEmit --watch",blink:"npm run build && npm link"},p={anl:"bin/an-cli.js"},t="Gleason <bianliuzhu@gmail.com>",r={"@commitlint/cli":"^17.4.3","@commitlint/config-conventional":"^17.4.3","@rollup/plugin-commonjs":"^21.0.1","@rollup/plugin-json":"^4.1.0","@rollup/plugin-node-resolve":"^13.1.3","@rollup/plugin-typescript":"^8.3.0","@types/inquirer":"^9.0.3","@types/shelljs":"^0.8.11","@typescript-eslint/eslint-plugin":"^5.52.0","@typescript-eslint/parser":"^5.52.0","cross-env":"^7.0.3",eslint:"^8.7.0",husky:"^8.0.3","openapi-types":"^12.1.3",prettier:"^3.3.2",rimraf:"^5.0.7",rollup:"^2.64.0","rollup-plugin-cleandir":"^2.0.0","rollup-plugin-copy":"^3.5.0","rollup-plugin-terser":"^7.0.2",typescript:"^4.5.4"},o={"app-root-path":"^3.1.0",cac:"^6.7.12",chalk:"4.*","clear-console":"^1.1.0",commander:"^10.0.0",figures:"^6.1.0",inquirer:"^10.1.8","log-symbols":"^5.1.0",ora:"5.*","progress-estimator":"^0.3.0",shelljs:"^0.8.5"},n=["typescript","cli","typescript 脚手架","ts 脚手架","ts-cli","脚手架"],c=["package.json","README.md","lib","template"],u={type:"git",url:"https://github.com/bianliuzhu/an-cli.git"},a="commonjs",m={name:"anl",version:e,description:i,main:s,scripts:l,bin:p,author:t,license:"ISC",devDependencies:r,dependencies:o,keywords:n,files:c,repository:u,type:a};exports.author=t,exports.bin=p,exports.default=m,exports.dependencies=o,exports.description=i,exports.devDependencies=r,exports.files=c,exports.keywords=n,exports.license="ISC",exports.main=s,exports.name="anl",exports.repository=u,exports.scripts=l,exports.type=a,exports.version=e;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e="1.4.13",i="FE command line tool",s="bin/an-cli.js",l={dev:"rollup --config rollup.config.ts --configPlugin @rollup/plugin-typescript -w",build:"rimraf lib && rollup --config rollup.config.ts --configPlugin @rollup/plugin-typescript",pub:"bash publish.sh",ts:"tsc ./src/int.ts --noEmit --watch",blink:"npm run build && npm link"},p={anl:"bin/an-cli.js"},t="Gleason <bianliuzhu@gmail.com>",r={"@commitlint/cli":"^17.4.3","@commitlint/config-conventional":"^17.4.3","@rollup/plugin-commonjs":"^21.0.1","@rollup/plugin-json":"^4.1.0","@rollup/plugin-node-resolve":"^13.1.3","@rollup/plugin-typescript":"^8.3.0","@types/inquirer":"^9.0.3","@types/shelljs":"^0.8.11","@typescript-eslint/eslint-plugin":"^5.52.0","@typescript-eslint/parser":"^5.52.0","cross-env":"^7.0.3",eslint:"^8.7.0",husky:"^8.0.3","openapi-types":"^12.1.3",prettier:"^3.3.2",rimraf:"^5.0.7",rollup:"^2.64.0","rollup-plugin-cleandir":"^2.0.0","rollup-plugin-copy":"^3.5.0","rollup-plugin-terser":"^7.0.2",typescript:"^4.5.4"},o={"app-root-path":"^3.1.0",cac:"^6.7.12",chalk:"4.*","clear-console":"^1.1.0",commander:"^10.0.0",figures:"^6.1.0",inquirer:"^10.1.8","log-symbols":"^5.1.0",ora:"5.*","progress-estimator":"^0.3.0",shelljs:"^0.8.5"},n=["typescript","cli","typescript 脚手架","ts 脚手架","ts-cli","脚手架"],c=["package.json","README.md","lib","template"],u={type:"git",url:"https://github.com/bianliuzhu/an-cli.git"},a="commonjs",m={name:"anl",version:e,description:i,main:s,scripts:l,bin:p,author:t,license:"ISC",devDependencies:r,dependencies:o,keywords:n,files:c,repository:u,type:a};exports.author=t,exports.bin=p,exports.default=m,exports.dependencies=o,exports.description=i,exports.devDependencies=r,exports.files=c,exports.keywords=n,exports.license="ISC",exports.main=s,exports.name="anl",exports.repository=u,exports.scripts=l,exports.type=a,exports.version=e;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("../../utils/index.js");const t="\t";var r;!function(e){e.GET="get",e.PUT="put",e.POST="post",e.DELETE="delete",e.OPTIONS="options",e.HEAD="head",e.PATCH="patch",e.TRACE="trace"}(r||(r={}));const n={typeMapping:new Map([["integer","number"],["string","string"],["boolean","boolean"],["binary","File"]]),errorHandling:{throwOnError:!1,logErrors:!0}},s="#/components/schemas/",a="#/components/parameters/",o="#/definitions/",i=["application/json","text/json","text/plain","application/x-www-form-urlencoded","application/xml","text/xml","*/*","application/octet-stream","multipart/form-data"],p=["application/octet-stream","multipart/form-data"];class c{pathsObject={};nonArrayType=["boolean","object","number","string","integer"];pathKey="";contentBody={payload:{path:[],query:[],body:[]},response:"",_response:"",fileName:"",method:"",requestPath:"",summary:"",apiName:"",typeName:"",deprecated:!1,contentType:"application/json"};Map=new Map;config;errors=[];referenceCache=new Map;parameters={};templates={exportConst:e=>`export const ${e}`,typeDefinition:(e,t)=>`type ${e} = ${t}`,interfaceDefinition:e=>`interface ${e}`};constructor(e,t,r){this.pathsObject=e,this.parameters=t??{},this.config={...n,...r,typeMapping:new Map([...n.typeMapping||[],...r.typeMapping||[]])}}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 new Error(`${t.type}: ${t.message}`)}getIndentation(){return this.config.formatting?.indentation||t}typeNameToFileName(e){return e=(e=(e=e.replace(/_/g,"-")).replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()).replace(/-+/g,"-")}handleComplexType(e){try{return e.oneOf?e.oneOf.map((e=>this.schemaParse(e))).join(" | "):e.allOf?e.allOf.map((e=>this.schemaParse(e))).join(" & "):e.anyOf?e.anyOf.map((e=>this.schemaParse(e))).join(" | "):e.enum?"number"===e.type||"integer"===e.type?e.enum.join(" | "):e.enum.map((e=>`'${e}'`)).join(" | "):"unknown"}catch(e){return this.handleError({type:"SCHEMA",message:"Failed to handle complex type",details:e}),"unknown"}}propertiesParse(e){if(!e)return[];const r=[];for(const n in e){const s=e[n],a=this.schemaParse(s);let o="";o=Array.isArray(a)?`${t}${t}${n}: {${a.join("\n")}};`:`${t}${t}${n}: ${a};`,r.push(o)}return r}nonArraySchemaObjectParse(e){if(!e)return"unknown";if("binary"===e.format||"string"===e.type&&"binary"===e.format)return"File";switch(e.type){case"boolean":return"boolean";case"integer":case"number":return"number";case"object":return this.propertiesParse(e.properties);case"string":return"binary"===e.format?"File":"string";default:return"unknown"}}arraySchemaObjectParse(e){if("array"!==e.type)return"";const{items:t}=e,r="$ref"in t?t:null,n=t;if(r){return`Array<${this.referenceObjectParse(r)}>`}if(n){const e=this.schemaParse(t);return Array.isArray(e)?`Array<{${e.join("\n")}}>`:`Array<${e}>`}return""}referenceObjectParse(e){try{const t=e.$ref,r=this.referenceCache.get(t);if(r)return r;let n=t;t.startsWith(s)&&(n=t.replace(s,"")),t.startsWith(a)&&(n=t.replace(a,"")),t.startsWith(o)&&(n=t.replace(o,""));const i=this.typeNameToFileName(n),p=/enum/gi.test(n)?`import('${this.config.importEnumPath}/${i}').${n}`:`import('../models/${i}').${n}`;return this.referenceCache.set(t,p),p}catch(e){return this.handleError({type:"REFERENCE",message:"Failed to parse reference object",details:e}),"unknown"}}schemaParse(e){try{if(!e)return"unknown";if("oneOf"in e||"allOf"in e||"anyOf"in e||"enum"in e)return this.handleComplexType(e);if("$ref"in e)return this.referenceObjectParse(e);const t=e,r=t.type,n=!0===t.nullable?" | null":"";if(e.format&&this.config.typeMapping?.has(e.format))return this.config.typeMapping.get(e.format)+n;if(r&&this.config.typeMapping?.has(r))return this.config.typeMapping.get(r)+n;if("array"===r&&t.items){const e=this.schemaParse(t.items);if(Array.isArray(e)){const t=this.config.formatting?.lineEnding,r=this.config.formatting?.indentation;return`Array<{${t}${e.join("\n")}${t}${r}${r}}>`}return`Array<${e}>`}if("object"===r){if(t.properties){const e=this.propertiesParse(t.properties);return e.length?e:["unknown"]}if(!0===t.additionalProperties)return"Record<string, unknown>"+n;if("object"==typeof t.additionalProperties){return`Record<string, ${this.schemaParse(t.additionalProperties)}>`+n}}return"unknown"}catch(e){return this.handleError({type:"SCHEMA",message:"Failed to parse schema",details:e}),"unknown"}}responseObjectParse(e){try{const t=e.content;if(!t)return"";let r;for(const e of i)if(t[e]?.schema){r=t[e].schema;break}return r?this.schemaParse(r):""}catch(e){return this.handleError({type:"RESPONSE",message:"Failed to parse response object",details:e}),""}}responseHandle(e){const t=e[200];if(!t)return;const r="content"in t?t:null,n="$ref"in t?t:null;if(null===r&&null===n&&(this.contentBody.response="type Response = unknown",this.contentBody._response="unknown"),n){const e=this.referenceObjectParse(n);this.contentBody.response=`type Response = ${e}`,this.contentBody._response=e}if(r){const e=this.responseObjectParse(r);if(Array.isArray(e)){if(1===e.length&&"unknown"===e[0])this.contentBody.response=`type Response = ${e.join("\n")};`;else{const t=this.config.formatting?.lineEnding,r=this.config.formatting?.indentation;this.contentBody.response=`interface Response {${t}${e.join("\n")}${t}${r}};`}this.contentBody._response=`${e.join("\n")}`}else this.contentBody.response=`type Response = ${e}`,this.contentBody._response=`${e}`}}requestBodyObjectParse(e){const r=Object.values(e.content),{schema:n}=r[0]||{schema:null};if(n){const e=n?.type,r="$ref"in n?n:null,s="array"===e?n:null,a=e&&this.nonArrayType.includes(e)?n:null;if(r){const e=this.referenceObjectParse(r);return`${t}type Body = ${e}`}if(s){const e=this.arraySchemaObjectParse(s);return`${t}type Body = ${e}`}if(a){const e=this.nonArraySchemaObjectParse(a);return Array.isArray(e)?0===e.length?[`${t}type Body = ${a.type};`]:[`${t}interface Body {`,...e.map((e=>e.replace(/: string;/,": File;"))),"}"]:[`${t}type Body = ${e}`]}}}requestBodyParse(e){if(!e)return"{}";const r="$ref"in e?e:null,n="content"in e?e:null;if(r){const e=this.referenceObjectParse(r);return`${t}type Body = ${e}`}return n&&"[object Object]"===String(e)&&0!==Reflect.ownKeys(e).length?this.requestBodyObjectParse(n):"{}"}parametersItemHandle(e,r,n){const s="$ref"in e?e:null,o="name"in e?e:null;if(s&&s.$ref&&s.$ref.startsWith(a)&&this.parameters){const e=s.$ref.replace(a,""),t=this.parameters[e];this.parametersItemHandle(t,r,n)}if(o){if("path"===o.in){const e=this.schemaParse(o.schema);r.push(`${t}${t}type ${o.name} = ${e};`),this.contentBody.payload._path?"string"==typeof e?this.contentBody.payload._path[o.name]=e:console.log("Unexpected v2value type:",e):"string"==typeof e?this.contentBody.payload._path={[o.name]:e}:console.log("Unexpected v2value type:",e)}if("query"===o.in){const e=this.schemaParse(o.schema);n.push(`${t}${t}${o.name}: ${e};`),this.contentBody.payload._query?"string"==typeof e?this.contentBody.payload._query[o.name]=e:console.log("Unexpected v2value type:",e):"string"==typeof e?this.contentBody.payload._query={[o.name]:e}:console.log("Unexpected v2value type:",e)}}}requestParametersParse(e){const r=[],n=[];e?.map((e=>this.parametersItemHandle(e,r,n))),0!==r.length&&(r.unshift(`${t}namespace Path {`),r.push(`${t}}`)),0!==n.length&&(n.unshift(`${t}interface Query {`),n.push(`${t}}`)),this.contentBody.payload.path=r,this.contentBody.payload.query=n}requestHandle(e){if(e.parameters&&this.requestParametersParse(e.parameters),e.requestBody){const t=this.requestBodyParse(e.requestBody);if(Array.isArray(t))this.contentBody.payload.body=t;else if(t){const e=t?.split("\n")||[];this.contentBody.payload.body=e}}}apiRequestItemHandle(e){const{payload:t,requestPath:r,_response:n,method:s,typeName:a,apiName:o,contentType:i}=e,{_path:c,_query:h,body:l}=t,y=(()=>{const e=[];for(const t in c)e.push(`${t}: ${a}.Path.${t}`);const t=e.join(e.length>1?",":"");return""===t?t:t+","})(),d=(()=>{const e=h?`query: ${a}.Query,`:"";return""===e?"":`${e}`})(),u=(()=>{const e=l.length>0?`body: ${a}.Body,`:"";return""===e?"":`${e}`})(),m=(y+d+u).replace(/,$/,"");return[`export const ${o} = `,"(",m,""===m?"params?: IRequestFnRestParams":", params?: IRequestFnRestParams",")"," => ",s,""+(n?`<${a}.Response>`:""),"(","`"+r+"`,",(()=>{const e=p.includes(i)?`{ headers: { 'Content-Type': '${i}' } }`:void 0;return["{",""===d?"":"query,",""===u?"":"body,",e?`config: ${e},`:"",`datalevel: '${this.config.dataLevel}'`,",...params","}"].join("")})(),");"].join("")}parsePathItemObject(e,t){if(e)for(const r in e){const n=e[r];if(n){const e=r.toUpperCase(),s=t+"|"+e,{apiName:a,typeName:o,fileName:p,path:c}=this.convertEndpointString(s),h=n.requestBody&&"content"in n.requestBody&&n.requestBody.content,l="object"==typeof h?Object.keys(h)[0]:"application/json";this.contentBody={payload:{path:[],query:[],body:[]},response:"",_response:"",fileName:p,method:e,typeName:o,requestPath:c,apiName:a,summary:n.summary,deprecated:n.deprecated??!1,contentType:i.includes(l)?l:"application/json"},this.requestHandle(n),this.responseHandle(n.responses),this.Map.has(s)||this.Map.set(s,JSON.parse(JSON.stringify(this.contentBody)))}}}convertEndpointString(e){let t=e;e.startsWith("/")||(t="/"+e);const[r,n]=t.split("|"),s=`${r.replace("/api/","").split("/").map((e=>e.includes("{")?`$${e.slice(1,-1)}`:e.charAt(0).toUpperCase()+e.slice(1))).join("")}_${n}`;return{apiName:s.charAt(0).toLowerCase()+s.slice(1),fileName:(r.slice(1).replace(/\//g,"-").replace("api-","")+"-"+n).toLowerCase(),typeName:s.charAt(0).toUpperCase()+s.slice(1),path:r.replace(/(\/api)|(api)/g,"").replace(/\{\w+\}/g,(e=>`$${e}`))}}parseData(){return new Promise(((e,t)=>{try{for(const e in this.pathsObject){const t=this.pathsObject[e];t&&this.parsePathItemObject(t,e)}e(this.Map)}catch(e){this.handleError({type:"SCHEMA",message:"Failed to parse schema",details:e}),t(e)}}))}async writeFile(){const r=[],n=[],s=this.config.saveTypeFolderPath,a=[],o=(r,o)=>new Promise(((i,p)=>{try{const{payload:c,response:h,fileName:l,summary:y,typeName:d,deprecated:u}=o,[,m]=r.split("|");!a.includes(m)&&a.push(m);const f=[`declare namespace ${d} {`,...c.path,...c.query,...c.body,`${t}${h}`,"}"];y&&n.push(["/**","\n",u?` * @deprecated ${y}`:` * ${y}`,"\n"," */"].join(""));const $=this.apiRequestItemHandle(o);n.push($,"\n"),e.writeFileRecursive(`${s}/connectors/${l}.d.ts`,f.join("\n")).then((()=>i(1))).catch((e=>{this.handleError({type:"FILE_WRITE",message:"Failed to write type definition file",path:l,details:e}),p(e)}))}catch(e){this.handleError({type:"PATH",message:"Failed to process path item",path:r,details:e}),p(e)}}));for(const[e,t]of this.Map)r.push(o(e,t));try{await Promise.all(r),n.unshift(`import { ${a.join(", ")} } from '${this.config.requestMethodsImportPath||"./api"}';`,"\n"),await e.clearDir(this.config.saveApiListFolderPath+"/index.ts"),await e.writeFileRecursive(this.config.saveApiListFolderPath+"/index.ts",n.join("\n")),this.Map=new Map,this.errors.length>0&&e.log.warning(`Completed with ${this.errors.length} errors`)}catch(e){throw this.handleError({type:"FILE_WRITE",message:"Failed to write API list file",details:e}),e}}async handle(){try{await this.parseData(),await this.writeFile(),e.log.success("Path parse & write done!")}catch(e){if(this.handleError({type:"SCHEMA",message:"Failed to handle schema",details:e}),this.config.errorHandling?.throwOnError)throw e}}}exports.PathParse=c,exports.default=c;
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("../../utils/index.js");const t="\t";var r;!function(e){e.GET="get",e.PUT="put",e.POST="post",e.DELETE="delete",e.OPTIONS="options",e.HEAD="head",e.PATCH="patch",e.TRACE="trace"}(r||(r={}));const n={typeMapping:new Map([["integer","number"],["string","string"],["boolean","boolean"],["binary","File"]]),errorHandling:{throwOnError:!1,logErrors:!0}},s="#/components/schemas/",a="#/components/parameters/",o="#/definitions/",i=["application/json","text/json","text/plain","application/x-www-form-urlencoded","application/xml","text/xml","*/*","application/octet-stream","multipart/form-data"],p=["application/octet-stream","multipart/form-data"];class c{pathsObject={};nonArrayType=["boolean","object","number","string","integer"];pathKey="";contentBody={payload:{path:[],query:[],body:[]},response:"",_response:"",fileName:"",method:"",requestPath:"",summary:"",apiName:"",typeName:"",deprecated:!1,contentType:"application/json"};Map=new Map;config;errors=[];referenceCache=new Map;parameters={};templates={exportConst:e=>`export const ${e}`,typeDefinition:(e,t)=>`type ${e} = ${t}`,interfaceDefinition:e=>`interface ${e}`};constructor(e,t,r){this.pathsObject=e,this.parameters=t??{},this.config={...n,...r,typeMapping:new Map([...n.typeMapping||[],...r.typeMapping||[]])}}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 new Error(`${t.type}: ${t.message}`)}getIndentation(){return this.config.formatting?.indentation||t}typeNameToFileName(e){return e=(e=(e=e.replace(/_/g,"-")).replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()).replace(/-+/g,"-")}handleComplexType(e){try{return e.oneOf?e.oneOf.map((e=>this.schemaParse(e))).join(" | "):e.allOf?e.allOf.map((e=>this.schemaParse(e))).join(" & "):e.anyOf?e.anyOf.map((e=>this.schemaParse(e))).join(" | "):e.enum?"number"===e.type||"integer"===e.type?e.enum.join(" | "):e.enum.map((e=>`'${e}'`)).join(" | "):"unknown"}catch(e){return this.handleError({type:"SCHEMA",message:"Failed to handle complex type",details:e}),"unknown"}}propertiesParse(e){if(!e)return[];const r=[];for(const n in e){const s=e[n],a=this.schemaParse(s);let o="";o=Array.isArray(a)?`${t}${t}${n}: {${a.join("\n")}};`:`${t}${t}${n}: ${a};`,r.push(o)}return r}nonArraySchemaObjectParse(e){if(!e)return"unknown";if("binary"===e.format||"string"===e.type&&"binary"===e.format)return"File";switch(e.type){case"boolean":return"boolean";case"integer":case"number":return"number";case"object":return this.propertiesParse(e.properties);case"string":return"binary"===e.format?"File":"string";default:return"unknown"}}arraySchemaObjectParse(e){if("array"!==e.type)return"";const{items:t}=e,r="$ref"in t?t:null,n=t;if(r){return`Array<${this.referenceObjectParse(r)}>`}if(n){const e=this.schemaParse(t);return Array.isArray(e)?`Array<{${e.join("\n")}}>`:`Array<${e}>`}return""}referenceObjectParse(e){try{const t=e.$ref,r=this.referenceCache.get(t);if(r)return r;let n=t;t.startsWith(s)&&(n=t.replace(s,"")),t.startsWith(a)&&(n=t.replace(a,"")),t.startsWith(o)&&(n=t.replace(o,""));const i=this.typeNameToFileName(n),p=/enum/gi.test(n)?`import('${this.config.importEnumPath}/${i}').${n}`:`import('../models/${i}').${n}`;return this.referenceCache.set(t,p),p}catch(e){return this.handleError({type:"REFERENCE",message:"Failed to parse reference object",details:e}),"unknown"}}schemaParse(e){try{if(!e)return"unknown";if("oneOf"in e||"allOf"in e||"anyOf"in e||"enum"in e)return this.handleComplexType(e);if("$ref"in e)return this.referenceObjectParse(e);const t=e,r=t.type,n=!0===t.nullable?" | null":"";if(e.format&&this.config.typeMapping?.has(e.format))return this.config.typeMapping.get(e.format)+n;if(r&&this.config.typeMapping?.has(r))return this.config.typeMapping.get(r)+n;if("array"===r&&t.items){const e=this.schemaParse(t.items);if(Array.isArray(e)){const t=this.config.formatting?.lineEnding,r=this.config.formatting?.indentation;return`Array<{${t}${e.join("\n")}${t}${r}${r}}>`}return`Array<${e}>`}if("object"===r){if(t.properties){const e=this.propertiesParse(t.properties);return e.length?e:["unknown"]}if(!0===t.additionalProperties)return"Record<string, unknown>"+n;if("object"==typeof t.additionalProperties){return`Record<string, ${this.schemaParse(t.additionalProperties)}>`+n}}return"unknown"}catch(e){return this.handleError({type:"SCHEMA",message:"Failed to parse schema",details:e}),"unknown"}}responseObjectParse(e){try{const t=e.content;if(!t)return"";let r;for(const e of i)if(t[e]?.schema){r=t[e].schema;break}return r?this.schemaParse(r):""}catch(e){return this.handleError({type:"RESPONSE",message:"Failed to parse response object",details:e}),""}}responseHandle(e){const t=e[200];if(!t)return;const r="content"in t?t:null,n="$ref"in t?t:null;if(null===r&&null===n&&(this.contentBody.response="type Response = unknown",this.contentBody._response="unknown"),n){const e=this.referenceObjectParse(n);this.contentBody.response=`type Response = ${e}`,this.contentBody._response=e}if(r){const e=this.responseObjectParse(r);if(Array.isArray(e)){if(1===e.length&&"unknown"===e[0])this.contentBody.response=`type Response = ${e.join("\n")};`;else{const t=this.config.formatting?.lineEnding,r=this.config.formatting?.indentation;this.contentBody.response=`interface Response {${t}${e.join("\n")}${t}${r}};`}this.contentBody._response=`${e.join("\n")}`}else this.contentBody.response=`type Response = ${e}`,this.contentBody._response=`${e}`}}requestBodyObjectParse(e){const r=Object.values(e.content),{schema:n}=r[0]||{schema:null};if(n){const e=n?.type,r="$ref"in n?n:null,s="array"===e?n:null,a=e&&this.nonArrayType.includes(e)?n:null;if(r){const e=this.referenceObjectParse(r);return`${t}type Body = ${e}`}if(s){const e=this.arraySchemaObjectParse(s);return`${t}type Body = ${e}`}if(a){const e=this.nonArraySchemaObjectParse(a);return Array.isArray(e)?0===e.length?[`${t}type Body = ${a.type};`]:[`${t}interface Body {`,...e.map((e=>e.replace(/: string;/,": File;"))),"}"]:[`${t}type Body = ${e}`]}}}requestBodyParse(e){if(!e)return"{}";const r="$ref"in e?e:null,n="content"in e?e:null;if(r){const e=this.referenceObjectParse(r);return`${t}type Body = ${e}`}return n&&"[object Object]"===String(e)&&0!==Reflect.ownKeys(e).length?this.requestBodyObjectParse(n):"{}"}parametersItemHandle(e,r,n){const s="$ref"in e?e:null,o="name"in e?e:null;if(s&&s.$ref&&s.$ref.startsWith(a)&&this.parameters){const e=s.$ref.replace(a,""),t=this.parameters[e];this.parametersItemHandle(t,r,n)}if(o){if("path"===o.in){const e=this.schemaParse(o.schema);r.push(`${t}${t}type ${o.name} = ${e};`),this.contentBody.payload._path?"string"==typeof e?this.contentBody.payload._path[o.name]=e:console.log("Unexpected v2value type:",e):"string"==typeof e?this.contentBody.payload._path={[o.name]:e}:console.log("Unexpected v2value type:",e)}if("query"===o.in){const e=this.schemaParse(o.schema);n.push(`${t}${t}${o.name}: ${e};`),this.contentBody.payload._query?"string"==typeof e?this.contentBody.payload._query[o.name]=e:console.log("Unexpected v2value type:",e):"string"==typeof e?this.contentBody.payload._query={[o.name]:e}:console.log("Unexpected v2value type:",e)}}}requestParametersParse(e){const r=[],n=[];e?.map((e=>this.parametersItemHandle(e,r,n))),0!==r.length&&(r.unshift(`${t}namespace Path {`),r.push(`${t}}`)),0!==n.length&&(n.unshift(`${t}interface Query {`),n.push(`${t}}`)),this.contentBody.payload.path=r,this.contentBody.payload.query=n}requestHandle(e){if(e.parameters&&this.requestParametersParse(e.parameters),e.requestBody){const t=this.requestBodyParse(e.requestBody);if(Array.isArray(t))this.contentBody.payload.body=t;else if(t){const e=t?.split("\n")||[];this.contentBody.payload.body=e}}}apiRequestItemHandle(e){const{payload:t,requestPath:r,_response:n,method:s,typeName:a,apiName:o,contentType:i}=e,{_path:c,_query:h,body:l}=t,y=(()=>{const e=[];for(const t in c)e.push(`${t}: ${a}.Path.${t}`);const t=e.join(e.length>1?",":"");return""===t?t:t+","})(),d=(()=>{const e=h?`query: ${a}.Query,`:"";return""===e?"":`${e}`})(),u=(()=>{const e=l.length>0?`body: ${a}.Body,`:"";return""===e?"":`${e}`})(),m=(y+d+u).replace(/,$/,"");return[`export const ${o} = `,"(",m,""===m?"params?: IRequestFnParams":", params?: IRequestFnParams",")"," => ",s,""+(n?`<${a}.Response>`:""),"(","`"+r+"`,",(()=>{const e=p.includes(i)?`headers: { 'Content-Type': '${i}' }`:void 0;return["{",e?`${e},`:"","...params, ",""===d?"":"query,",""===u?"":"body,","},"].join("")})(),`'${this.config.dataLevel}'`,");"].join("")}parsePathItemObject(e,t){if(e)for(const r in e){const n=e[r];if(n){const e=r.toUpperCase(),s=t+"|"+e,{apiName:a,typeName:o,fileName:p,path:c}=this.convertEndpointString(s),h=n.requestBody&&"content"in n.requestBody&&n.requestBody.content,l="object"==typeof h?Object.keys(h)[0]:"application/json";this.contentBody={payload:{path:[],query:[],body:[]},response:"",_response:"",fileName:p,method:e,typeName:o,requestPath:c,apiName:a,summary:n.summary,deprecated:n.deprecated??!1,contentType:i.includes(l)?l:"application/json"},this.requestHandle(n),this.responseHandle(n.responses),this.Map.has(s)||this.Map.set(s,JSON.parse(JSON.stringify(this.contentBody)))}}}convertEndpointString(e){let t=e;e.startsWith("/")||(t="/"+e);const[r,n]=t.split("|"),s=`${r.replace("/api/","").split("/").map((e=>e.includes("{")?`$${e.slice(1,-1)}`:e.charAt(0).toUpperCase()+e.slice(1))).join("")}_${n}`;return{apiName:s.charAt(0).toLowerCase()+s.slice(1),fileName:(r.slice(1).replace(/\//g,"-").replace("api-","")+"-"+n).toLowerCase(),typeName:s.charAt(0).toUpperCase()+s.slice(1),path:r.replace(/(\/api)|(api)/g,"").replace(/\{\w+\}/g,(e=>`$${e}`))}}parseData(){return new Promise(((e,t)=>{try{for(const e in this.pathsObject){const t=this.pathsObject[e];t&&this.parsePathItemObject(t,e)}e(this.Map)}catch(e){this.handleError({type:"SCHEMA",message:"Failed to parse schema",details:e}),t(e)}}))}async writeFile(){const r=[],n=[],s=this.config.saveTypeFolderPath,a=[],o=(r,o)=>new Promise(((i,p)=>{try{const{payload:c,response:h,fileName:l,summary:y,typeName:d,deprecated:u}=o,[,m]=r.split("|");!a.includes(m)&&a.push(m);const f=[`declare namespace ${d} {`,...c.path,...c.query,...c.body,`${t}${h}`,"}"];y&&n.push(["/**","\n",u?` * @deprecated ${y}`:` * ${y}`,"\n"," */"].join(""));const $=this.apiRequestItemHandle(o);n.push($,"\n"),e.writeFileRecursive(`${s}/connectors/${l}.d.ts`,f.join("\n")).then((()=>i(1))).catch((e=>{this.handleError({type:"FILE_WRITE",message:"Failed to write type definition file",path:l,details:e}),p(e)}))}catch(e){this.handleError({type:"PATH",message:"Failed to process path item",path:r,details:e}),p(e)}}));for(const[e,t]of this.Map)r.push(o(e,t));try{await Promise.all(r),n.unshift(`import { ${a.join(", ")} } from '${this.config.requestMethodsImportPath||"./api"}';`,"\n"),await e.clearDir(this.config.saveApiListFolderPath+"/index.ts"),await e.writeFileRecursive(this.config.saveApiListFolderPath+"/index.ts",n.join("\n")),this.Map=new Map,this.errors.length>0&&e.log.warning(`Completed with ${this.errors.length} errors`)}catch(e){throw this.handleError({type:"FILE_WRITE",message:"Failed to write API list file",details:e}),e}}async handle(){try{await this.parseData(),await this.writeFile(),e.log.success("Path parse & write done!")}catch(e){if(this.handleError({type:"SCHEMA",message:"Failed to handle schema",details:e}),this.config.errorHandling?.throwOnError)throw e}}}exports.PathParse=c,exports.default=c;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "anl",
3
- "version": "1.4.12",
3
+ "version": "1.4.13",
4
4
  "description": "FE command line tool",
5
5
  "main": "bin/an-cli.js",
6
6
  "scripts": {