anl 26.105.0 → 26.106.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/lib/package.json.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e="26.
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e="26.106.1",i="FE command line tool",t="bin/an-cli.js",s={registry:"https://registry.npmjs.org"},o={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","sync-docs":"node scripts/sync-docs.js"},r={anl:"bin/an-cli.js"},n="Gleason <bianliuzhu@gmail.com>",l={"@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.7","@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"},p={"app-root-path":"^3.1.0",cac:"^6.7.12",chalk:"4.*","clear-console":"^1.1.0",commander:"14.0.1",figures:"^6.1.0",inquirer:"^10.1.8","log-symbols":"^5.1.0",ora:"5.*","progress-estimator":"^0.3.0",shelljs:"^0.8.5"},c=["cli","command-line","frontend","typescript","type-generation","code-generator","swagger","openapi","api","rest-api","eslint","stylelint","prettier","commitlint","linter","formatter","react","vue","git","gitflow","developer-tools","automation","scaffolding"],a=["package.json","README.md","lib","template"],u={type:"git",url:"git+https://github.com/bianliuzhu/an-cli.git"},g="commonjs",m={name:"anl",version:e,description:i,main:t,publishConfig:s,scripts:o,bin:r,author:n,license:"ISC",devDependencies:l,dependencies:p,keywords:c,files:a,repository:u,type:g};exports.author=n,exports.bin=r,exports.default=m,exports.dependencies=p,exports.description=i,exports.devDependencies=l,exports.files=a,exports.keywords=c,exports.license="ISC",exports.main=t,exports.name="anl",exports.publishConfig=s,exports.repository=u,exports.scripts=o,exports.type=g,exports.version=e;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("http"),r=require("https"),t=require("path"),o=require("../tools/index.js");function s(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var n=s(e),u=s(r),c=s(t);function
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("http"),r=require("https"),t=require("path"),o=require("../tools/index.js");function s(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var n=s(e),u=s(r),c=s(t);function a({swaggerJsonUrl:e="",headers:r={}}){return new Promise((t,o)=>{let s;const c=/^https/.test(e)?u.default.request:n.default.request;console.info(`Request Start: ${e}`);const a=c(e,{method:"GET",rejectUnauthorized:!1,headers:{Accept:"*/*","Accept-Encoding":"utf-8","Content-Type":"application/x-www-form-urlencoded",...r}},r=>{r.setEncoding("utf-8");let n="";r.on("data",e=>{n+=e.toString()}),r.on("end",()=>{clearTimeout(s);try{const r=JSON.parse(n);console.info(`Request Successful: ${e}`),t(r)}catch(r){console.error(`Request Failed: ${e}`,!0),o(r)}}),r.on("error",r=>{console.error(`Request Failed: ${e}`,!0),o(r)})});a.on("timeout",e=>{console.error(e,!0),o(e)}),s=setTimeout(()=>{const r=new Error;r.name="Request Timeout",r.message=e,a.emit("timeout",r)},15e3),a.end()})}exports.getSwaggerJson=async function(e){if(!e.swaggerJsonUrl)return Promise.reject(new Error("swaggerJsonUrl 未配置,请检查 swaggerServers.url"));if(/^https?:\/\//.test(e.swaggerJsonUrl))return a(e);try{const r=c.default.isAbsolute(e.swaggerJsonUrl)?e.swaggerJsonUrl:c.default.resolve(process.cwd(),e.swaggerJsonUrl),t=o.requireModule(r);return Promise.resolve(t)}catch(e){return console.error(e,!0),Promise.reject(e)}},exports.requestJson=a;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("../../utils/index.js");const t="\t";var n;!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"}(n||(n={}));const r={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}},s="#/components/schemas/",a="#/components/parameters/",i="#/definitions/",o=["application/json","text/json","text/plain","application/x-www-form-urlencoded","application/xml","text/xml","*/*","application/octet-stream","multipart/form-data"],c=["application/octet-stream","multipart/form-data"];class p{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={};schemas={};templates={exportConst:e=>`export const ${e}`,typeDefinition:(e,t)=>`type ${e} = ${t}`,interfaceDefinition:e=>`interface ${e}`};constructor(e,t,n,s){this.pathsObject=e,this.parameters=t??{},this.schemas=n??{},this.config={...r,...s,typeMapping:new Map([...r.typeMapping||[],...s.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}getEnumTypeName(e){return this.config.enmuConfig.erasableSyntaxOnly?`${e}Type`:e}typeNameToFileName(e){return e=(e=(e=e.replace(/_/g,"-")).replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()).replace(/-+/g,"-")}stringifySchemaResult(e){if(Array.isArray(e)){const t=this.config.formatting?.lineEnding??"\n",n=this.getIndentation();return`{${t}${e.join(t)}${t}${n}}`}return e}handleComplexType(e){try{return e.oneOf?e.oneOf.map(e=>this.stringifySchemaResult(this.schemaParse(e))).join(" | "):e.allOf?e.allOf.map(e=>this.stringifySchemaResult(this.schemaParse(e))).join(" & "):e.anyOf?e.anyOf.map(e=>this.stringifySchemaResult(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 n=[];for(const r in e){const s=e[r],a=this.schemaParse(s);let i="";i=Array.isArray(a)?`${t}${t}${r}: {${a.join("\n")}};`:`${t}${t}${r}: ${a};`,n.push(i)}return n}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,n="$ref"in t?t:null,r=t;if(n){return`Array<${this.referenceObjectParse(n)}>`}if(r){const e=this.schemaParse(t);return Array.isArray(e)?`Array<{${e.join("\n")}}>`:`Array<${e}>`}return""}referenceObjectParse(e){try{const t=e.$ref,n=this.referenceCache.get(t);if(n)return n;let r=t;t.startsWith(s)&&(r=t.replace(s,"")),t.startsWith(a)&&(r=t.replace(a,"")),t.startsWith(i)&&(r=t.replace(i,""));const o=this.typeNameToFileName(r),c=/enum/gi.test(r),p=this.schemas?.[r],l=p&&"enum"in p&&Array.isArray(p.enum),h=c||l,y=h?this.getEnumTypeName(r):r,m=h?`import('${this.config.importEnumPath}/${o}').${y}`:`import('../models/${o}').${r}`;return this.referenceCache.set(t,m),m}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,n=t.type,r=!0===t.nullable?" | null":"";if(e.format&&this.config.typeMapping?.has(e.format))return this.config.typeMapping.get(e.format)+r;if(n&&this.config.typeMapping?.has(n))return this.config.typeMapping.get(n)+r;if("array"===n&&t.items){const e=this.schemaParse(t.items);if(Array.isArray(e)){const t=this.config.formatting?.lineEnding,n=this.config.formatting?.indentation;return`Array<{${t}${e.join("\n")}${t}${n}${n}}>`}return`Array<${e}>`}if("object"===n||"object"==typeof t){if(t.properties){const e=this.propertiesParse(t.properties);return e.length?e:["unknown"]}if(!0===t.additionalProperties)return"Record<string, unknown>"+r;if("object"==typeof t.additionalProperties){return`Record<string, ${this.schemaParse(t.additionalProperties)}>`+r}}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 n;for(const e of o)if(t[e]?.schema){n=t[e].schema;break}return n?this.schemaParse(n):""}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 n="content"in t?t:null,r="$ref"in t?t:null;if(null===n&&null===r&&(this.contentBody.response="type Response = unknown",this.contentBody._response="unknown"),r){const e=this.referenceObjectParse(r);this.contentBody.response=`type Response = ${e}`,this.contentBody._response=e}if(n){const e=this.responseObjectParse(n);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,n=this.config.formatting?.indentation;this.contentBody.response=`interface Response {${t}${e.join("\n")}${t}${n}};`}this.contentBody._response=`${e.join("\n")}`}else this.contentBody.response=`type Response = ${e}`,this.contentBody._response=`${e}`}}requestBodyObjectParse(e){const n=Object.values(e.content),{schema:r}=n[0]||{schema:null};if(r){const e=r?.type,n="$ref"in r?r:null,s="array"===e?r:null,a=e&&this.nonArrayType.includes(e)?r:null;if(n){const e=this.referenceObjectParse(n);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 n="$ref"in e?e:null,r="content"in e?e:null;if(n){const e=this.referenceObjectParse(n);return`${t}type Body = ${e}`}return r&&"[object Object]"===String(e)&&0!==Reflect.ownKeys(e).length?this.requestBodyObjectParse(r):"{}"}parametersItemHandle(e,n,r){const s="$ref"in e?e:null,i="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,n,r)}if(i){if("path"===i.in){const e=this.schemaParse(i.schema);n.push(`${t}${t}type ${i.name} = ${e};`),this.contentBody.payload._path?"string"==typeof e?this.contentBody.payload._path[i.name]=e:console.log("Unexpected v2value type:",e):"string"==typeof e?this.contentBody.payload._path={[i.name]:e}:console.log("Unexpected v2value type:",e)}if("query"===i.in){const e=this.schemaParse(i.schema);r.push(`${t}${t}${i.name}: ${e};`),this.contentBody.payload._query?"string"==typeof e?this.contentBody.payload._query[i.name]=e:console.log("Unexpected v2value type:",e):"string"==typeof e?this.contentBody.payload._query={[i.name]:e}:console.log("Unexpected v2value type:",e)}}}requestParametersParse(e){const n=[],r=[];e?.map(e=>this.parametersItemHandle(e,n,r)),0!==n.length&&(n.unshift(`${t}namespace Path {`),n.push(`${t}}`)),0!==r.length&&(r.unshift(`${t}interface Query {`),r.push(`${t}}`)),this.contentBody.payload.path=n,this.contentBody.payload.query=r}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:n,_response:r,method:s,typeName:a,apiName:i,contentType:o}=e,{_path:p,_query:l,body:h}=t,y=(()=>{const e=[];for(const t in p)e.push(`${t}: ${a}.Path.${t}`);const t=e.join(e.length>1?",":"");return""===t?t:t+","})(),m=(()=>{const e=l?`query: ${a}.Query,`:"";return""===e?"":`${e}`})(),u=(()=>{const e=h.length>0?`body: ${a}.Body,`:"";return""===e?"":`${e}`})(),d=(y+m+u).replace(/,$/,"");return[`export const ${i} = `,"(",d,""===d?"params?: IRequestFnParams":", params?: IRequestFnParams",")"," => ",s,""+(r?`<${a}.Response>`:""),"(","`"+n+"`,",(()=>{const e=c.includes(o)?`headers: { 'Content-Type': '${o}' }`:void 0;return["{",e?`${e},`:"","...params, ",""===m?"":"query,",""===u?"":"body,","},"].join("")})(),`'${this.config.dataLevel}'`,");"].join("")}parsePathItemObject(e,t){if(e)for(const n in e){const r=e[n];if(r){if(this.config.includeInterface&&this.config.includeInterface.length>0){const e=this.config.includeInterface?.find(e=>t.includes(e.path)&&e.method===n);if(!e)return}else if(this.config.excludeInterface&&this.config.excludeInterface.length>0){const e=this.config.excludeInterface?.find(e=>t.includes(e.path)&&e.method===n);if(e)return}const e=n.toUpperCase(),s=t+"|"+e,{apiName:a,typeName:i,fileName:c,path:p}=this.convertEndpointString(s),l=r.requestBody&&"content"in r.requestBody&&r.requestBody.content,h="object"==typeof l?Object.keys(l)[0]:"application/json";this.contentBody={payload:{path:[],query:[],body:[]},response:"",_response:"",fileName:c,method:e,typeName:i,requestPath:p,apiName:a,summary:r.summary,deprecated:r.deprecated??!1,contentType:o.includes(h)?h:"application/json"},this.requestHandle(r),this.responseHandle(r.responses),this.Map.has(s)||this.Map.set(s,JSON.parse(JSON.stringify(this.contentBody)))}}}cleanSegment(e){let t=e.replace(/^[0-9]+/,"");return t?(t=t.replace(/[^a-zA-Z0-9_.-]/g,""),t):"num"+e}toCamelCase(e,t=!1){const n=this.cleanSegment(e).split(/[-_.]+/).filter(e=>e.length>0);return 0===n.length?"":n.map((e,n)=>0===n&&t?e.toLowerCase():e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join("")}toPascalCase(e){const t=this.cleanSegment(e).split(/[-_.]+/).filter(e=>e.length>0);return 0===t.length?"":t.map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join("")}convertEndpointString(e){let t=e;e.startsWith("/")||(t="/"+e);const[n,r]=t.split("|");let s="";this.config.publicPrefix&&(s=this.config.publicPrefix.replace(/^\/+|\/+$/g,""));let a=n.replace(/^\/+/,"");if(s&&a.startsWith(s+"/"))a=a.slice(s.length+1);else if(s&&a===s)a="";else if(s&&a.startsWith(s)){const e=a.slice(s.length);(e.startsWith("/")||""===e)&&(a=e.replace(/^\/+/,""))}const i=a?a.split("/").filter(e=>e):[],o=i.map(e=>{if(e.startsWith("{")&&e.endsWith("}")){const t=e.slice(1,-1);return{type:"param",original:e,normalized:t}}return{type:"normal",original:e,normalized:e}}),c=[];for(let e=0;e<o.length;e++){const t=o[e],n=o[e+1];if("normal"===t.type&&n&&"param"===n.type){if(this.cleanSegment(t.normalized).toLowerCase().replace(/[-_.]/g,"")===this.cleanSegment(n.normalized).toLowerCase().replace(/[-_.]/g,""))continue}c.push(t)}const p=this.config.parameterSeparator||"_";let l="",h=[];const y=e=>{if(h.length>0){const t=h.map((t,n)=>this.toCamelCase(t,e&&0===n)).join("");l+=(l&&h.length>0?p:"")+t,h=[]}};for(let e=0;e<c.length;e++){const t=c[e];if("normal"===t.type)h.push(t.normalized);else{y(""===l);const e=this.cleanSegment(t.normalized);l+=(l?p:"")+e}}y(""===l);let m="";h=[];const u=()=>{if(h.length>0){const e=h.map(e=>this.toPascalCase(e)).join("");m+=(m&&h.length>0?p:"")+e,h=[]}};for(let e=0;e<c.length;e++){const t=c[e];if("normal"===t.type)h.push(t.normalized);else{u();const e=this.toPascalCase(t.normalized);m+=(m?p:"")+e}}u();let d="";i.length>0?(d=i.map(e=>e.replace(/[{}]/g,"")).join("-"),d=`${d}-${r}`.toLowerCase()):d=`${r}`.toLowerCase();let f="/"+a;a||(f="/"),f=f.replace(/\{(\w+)\}/g,(e,t)=>`\${${t}}`);return{apiName:l?`${l}_${r}`:r,fileName:d,typeName:m?`${m}_${r}`:r,path:f}}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 n=[],r=[],s=this.config.saveTypeFolderPath,a=[],i=(n,i)=>new Promise((o,c)=>{try{const{payload:p,response:l,fileName:h,summary:y,typeName:m,deprecated:u}=i,[,d]=n.split("|");!a.includes(d)&&a.push(d);const f=[`declare namespace ${m} {`,...p.path,...p.query,...p.body,`${t}${l}`,"}"];y&&r.push(["/**","\n",u?` * @deprecated ${y}`:` * ${y}`,"\n"," */"].join(""));const g=this.apiRequestItemHandle(i);r.push(g,"");const $=`${s}/connectors/${h}.d.ts`;e.writeFileRecursive($,f.join("\n")).then(()=>{e.log.info(`${$.padEnd(80)} - Write done!`),o(1)}).catch(e=>{this.handleError({type:"FILE_WRITE",message:"Failed to write type definition file",path:h,details:e}),c(e)})}catch(e){this.handleError({type:"PATH",message:"Failed to process path item",path:n,details:e}),c(e)}});for(const[e,t]of this.Map)n.push(i(e,t));try{await Promise.all(n),e.log.success("Path parse & write done!"),r.unshift(`import { ${a.join(", ")} } from '${this.config.requestMethodsImportPath||"./api"}';`,"\n");const t=this.config.apiListFileName||"index.ts",s=`${this.config.saveApiListFolderPath}/${t}`;await e.clearDir(s),await e.writeFileRecursive(s,r.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()}catch(e){if(this.handleError({type:"SCHEMA",message:"Failed to handle schema",details:e}),this.config.errorHandling?.throwOnError)throw e}}}exports.PathParse=p,exports.default=p;
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("../../utils/index.js");const t="\t";var n;!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"}(n||(n={}));const r={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}},s="#/components/schemas/",a="#/components/parameters/",i="#/definitions/",o=["application/json","text/json","text/plain","application/x-www-form-urlencoded","application/xml","text/xml","*/*","application/octet-stream","multipart/form-data"],c=["application/octet-stream","multipart/form-data"];class p{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={};schemas={};templates={exportConst:e=>`export const ${e}`,typeDefinition:(e,t)=>`type ${e} = ${t}`,interfaceDefinition:e=>`interface ${e}`};constructor(e,t,n,s){this.pathsObject=e,this.parameters=t??{},this.schemas=n??{},this.config={...r,...s,typeMapping:new Map([...r.typeMapping||[],...s.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}getEnumTypeName(e){return this.config.enmuConfig.erasableSyntaxOnly?`${e}Type`:e}typeNameToFileName(e){return e=(e=(e=e.replace(/_/g,"-")).replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase()).replace(/-+/g,"-")}stringifySchemaResult(e){if(Array.isArray(e)){const t=this.config.formatting?.lineEnding??"\n",n=this.getIndentation();return`{${t}${e.join(t)}${t}${n}}`}return e}handleComplexType(e){try{return e.oneOf?e.oneOf.map(e=>this.stringifySchemaResult(this.schemaParse(e))).join(" | "):e.allOf?e.allOf.map(e=>this.stringifySchemaResult(this.schemaParse(e))).join(" & "):e.anyOf?e.anyOf.map(e=>this.stringifySchemaResult(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 n=[];for(const r in e){const s=e[r],a=this.schemaParse(s);let i="";i=Array.isArray(a)?`${t}${t}${r}: {${a.join("\n")}};`:`${t}${t}${r}: ${a};`,n.push(i)}return n}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,n="$ref"in t?t:null,r=t;if(n){return`Array<${this.referenceObjectParse(n)}>`}if(r){const e=this.schemaParse(t);return Array.isArray(e)?`Array<{${e.join("\n")}}>`:`Array<${e}>`}return""}referenceObjectParse(e){try{const t=e.$ref,n=this.referenceCache.get(t);if(n)return n;let r=t;t.startsWith(s)&&(r=t.replace(s,"")),t.startsWith(a)&&(r=t.replace(a,"")),t.startsWith(i)&&(r=t.replace(i,""));const o=this.typeNameToFileName(r),c=/enum/gi.test(r),p=this.schemas?.[r],l=p&&"enum"in p&&Array.isArray(p.enum),h=c||l,y=h?this.getEnumTypeName(r):r,m=h?`import('${this.config.importEnumPath}/${o}').${y}`:`import('../models/${o}').${r}`;return this.referenceCache.set(t,m),m}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,n=t.type,r=!0===t.nullable?" | null":"";if(e.format&&this.config.typeMapping?.has(e.format))return this.config.typeMapping.get(e.format)+r;if(n&&this.config.typeMapping?.has(n))return this.config.typeMapping.get(n)+r;if("array"===n&&t.items){const e=this.schemaParse(t.items);if(Array.isArray(e)){const t=this.config.formatting?.lineEnding,n=this.config.formatting?.indentation;return`Array<{${t}${e.join("\n")}${t}${n}${n}}>`}return`Array<${e}>`}if("object"===n||"object"==typeof t){if(t.properties){const e=this.propertiesParse(t.properties);return e.length?e:["unknown"]}if(!0===t.additionalProperties)return"Record<string, unknown>"+r;if("object"==typeof t.additionalProperties){return`Record<string, ${this.schemaParse(t.additionalProperties)}>`+r}}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 n;for(const e of o)if(t[e]?.schema){n=t[e].schema;break}return n?this.schemaParse(n):""}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 n="content"in t?t:null,r="$ref"in t?t:null;if(null===n&&null===r&&(this.contentBody.response="type Response = unknown",this.contentBody._response="unknown"),r){const e=this.referenceObjectParse(r);this.contentBody.response=`type Response = ${e}`,this.contentBody._response=e}if(n){const e=this.responseObjectParse(n);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,n=this.config.formatting?.indentation;this.contentBody.response=`interface Response {${t}${e.join("\n")}${t}${n}};`}this.contentBody._response=`${e.join("\n")}`}else this.contentBody.response=`type Response = ${e}`,this.contentBody._response=`${e}`}}requestBodyObjectParse(e){const n=Object.values(e.content),{schema:r}=n[0]||{schema:null};if(r){const e=r?.type,n="$ref"in r?r:null,s="array"===e?r:null,a=e&&this.nonArrayType.includes(e)?r:null;if(n){const e=this.referenceObjectParse(n);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 n="$ref"in e?e:null,r="content"in e?e:null;if(n){const e=this.referenceObjectParse(n);return`${t}type Body = ${e}`}return r&&"[object Object]"===String(e)&&0!==Reflect.ownKeys(e).length?this.requestBodyObjectParse(r):"{}"}parametersItemHandle(e,n,r){const s="$ref"in e?e:null,i="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,n,r)}if(i){if("path"===i.in){const e=this.schemaParse(i.schema);n.push(`${t}${t}type ${i.name} = ${e};`),this.contentBody.payload._path?"string"==typeof e?this.contentBody.payload._path[i.name]=e:console.log("Unexpected v2value type:",e):"string"==typeof e?this.contentBody.payload._path={[i.name]:e}:console.log("Unexpected v2value type:",e)}if("query"===i.in){const e=this.schemaParse(i.schema);r.push(`${t}${t}${i.name}: ${e};`),this.contentBody.payload._query?"string"==typeof e?this.contentBody.payload._query[i.name]=e:console.log("Unexpected v2value type:",e):"string"==typeof e?this.contentBody.payload._query={[i.name]:e}:console.log("Unexpected v2value type:",e)}}}requestParametersParse(e){const n=[],r=[];e?.map(e=>this.parametersItemHandle(e,n,r)),0!==n.length&&(n.unshift(`${t}namespace Path {`),n.push(`${t}}`)),0!==r.length&&(r.unshift(`${t}interface Query {`),r.push(`${t}}`)),this.contentBody.payload.path=n,this.contentBody.payload.query=r}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:n,_response:r,method:s,typeName:a,apiName:i,contentType:o}=e,{_path:p,_query:l,body:h}=t,y=this.config.dataLevel||"serve",m=(()=>{const e=[];for(const t in p)e.push(`${t}: ${a}.Path.${t}`);const t=e.join(e.length>1?",":"");return""===t?t:t+","})(),u=(()=>{const e=l?`query: ${a}.Query,`:"";return""===e?"":`${e}`})(),d=(()=>{const e=h.length>0?`body: ${a}.Body,`:"";return""===e?"":`${e}`})(),f=(m+u+d).replace(/,$/,"");return[`export const ${i} = `,"(",f,""===f?"params?: IRequestFnParams":", params?: IRequestFnParams",")"," => ",s,""+(r?`<${a}.Response>`:""),"(","`"+n+"`,",(()=>{const e=c.includes(o)?`headers: { 'Content-Type': '${o}' }`:void 0;return["{",e?`${e},`:"","...params, ",""===u?"":"query,",""===d?"":"body,","},"].join("")})(),`'${y}'`,");"].join("")}parsePathItemObject(e,t){if(e)for(const n in e){const r=e[n];if(r){if(this.config.includeInterface&&this.config.includeInterface.length>0){const e=this.config.includeInterface?.find(e=>t.includes(e.path)&&e.method===n);if(!e)return}else if(this.config.excludeInterface&&this.config.excludeInterface.length>0){const e=this.config.excludeInterface?.find(e=>t.includes(e.path)&&e.method===n);if(e)return}const e=n.toUpperCase(),s=t+"|"+e,{apiName:a,typeName:i,fileName:c,path:p}=this.convertEndpointString(s),l=r.requestBody&&"content"in r.requestBody&&r.requestBody.content,h="object"==typeof l?Object.keys(l)[0]:"application/json";this.contentBody={payload:{path:[],query:[],body:[]},response:"",_response:"",fileName:c,method:e,typeName:i,requestPath:p,apiName:a,summary:r.summary,deprecated:r.deprecated??!1,contentType:o.includes(h)?h:"application/json"},this.requestHandle(r),this.responseHandle(r.responses),this.Map.has(s)||this.Map.set(s,JSON.parse(JSON.stringify(this.contentBody)))}}}cleanSegment(e){let t=e.replace(/^[0-9]+/,"");return t?(t=t.replace(/[^a-zA-Z0-9_.-]/g,""),t):"num"+e}toCamelCase(e,t=!1){const n=this.cleanSegment(e).split(/[-_.]+/).filter(e=>e.length>0);return 0===n.length?"":n.map((e,n)=>0===n&&t?e.toLowerCase():e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join("")}toPascalCase(e){const t=this.cleanSegment(e).split(/[-_.]+/).filter(e=>e.length>0);return 0===t.length?"":t.map(e=>e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join("")}convertEndpointString(e){let t=e;e.startsWith("/")||(t="/"+e);const[n,r]=t.split("|");let s="";this.config.publicPrefix&&(s=this.config.publicPrefix.replace(/^\/+|\/+$/g,""));let a=n.replace(/^\/+/,"");if(s&&a.startsWith(s+"/"))a=a.slice(s.length+1);else if(s&&a===s)a="";else if(s&&a.startsWith(s)){const e=a.slice(s.length);(e.startsWith("/")||""===e)&&(a=e.replace(/^\/+/,""))}const i=a?a.split("/").filter(e=>e):[],o=i.map(e=>{if(e.startsWith("{")&&e.endsWith("}")){const t=e.slice(1,-1);return{type:"param",original:e,normalized:t}}return{type:"normal",original:e,normalized:e}}),c=[];for(let e=0;e<o.length;e++){const t=o[e],n=o[e+1];if("normal"===t.type&&n&&"param"===n.type){if(this.cleanSegment(t.normalized).toLowerCase().replace(/[-_.]/g,"")===this.cleanSegment(n.normalized).toLowerCase().replace(/[-_.]/g,""))continue}c.push(t)}const p=this.config.parameterSeparator||"_";let l="",h=[];const y=e=>{if(h.length>0){const t=h.map((t,n)=>this.toCamelCase(t,e&&0===n)).join("");l+=(l&&h.length>0?p:"")+t,h=[]}};for(let e=0;e<c.length;e++){const t=c[e];if("normal"===t.type)h.push(t.normalized);else{y(""===l);const e=this.cleanSegment(t.normalized);l+=(l?p:"")+e}}y(""===l);let m="";h=[];const u=()=>{if(h.length>0){const e=h.map(e=>this.toPascalCase(e)).join("");m+=(m&&h.length>0?p:"")+e,h=[]}};for(let e=0;e<c.length;e++){const t=c[e];if("normal"===t.type)h.push(t.normalized);else{u();const e=this.toPascalCase(t.normalized);m+=(m?p:"")+e}}u();let d="";i.length>0?(d=i.map(e=>e.replace(/[{}]/g,"")).join("-"),d=`${d}-${r}`.toLowerCase()):d=`${r}`.toLowerCase();let f="/"+a;a||(f="/"),f=f.replace(/\{(\w+)\}/g,(e,t)=>`\${${t}}`);return{apiName:l?`${l}_${r}`:r,fileName:d,typeName:m?`${m}_${r}`:r,path:f}}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 n=[],r=[],s=this.config.saveTypeFolderPath,a=[],i=(n,i)=>new Promise((o,c)=>{try{const{payload:p,response:l,fileName:h,summary:y,typeName:m,deprecated:u}=i,[,d]=n.split("|");!a.includes(d)&&a.push(d);const f=[`declare namespace ${m} {`,...p.path,...p.query,...p.body,`${t}${l}`,"}"];y&&r.push(["/**","\n",u?` * @deprecated ${y}`:` * ${y}`,"\n"," */"].join(""));const g=this.apiRequestItemHandle(i);r.push(g,"");const $=`${s}/connectors/${h}.d.ts`;e.writeFileRecursive($,f.join("\n")).then(()=>{e.log.info(`${$.padEnd(80)} - Write done!`),o(1)}).catch(e=>{this.handleError({type:"FILE_WRITE",message:"Failed to write type definition file",path:h,details:e}),c(e)})}catch(e){this.handleError({type:"PATH",message:"Failed to process path item",path:n,details:e}),c(e)}});for(const[e,t]of this.Map)n.push(i(e,t));try{await Promise.all(n),e.log.success("Path parse & write done!"),r.unshift(`import { ${a.join(", ")} } from '${this.config.requestMethodsImportPath||"./api"}';`,"\n");const t=this.config.apiListFileName||"index.ts",s=`${this.config.saveApiListFolderPath}/${t}`;await e.clearDir(s),await e.writeFileRecursive(s,r.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()}catch(e){if(this.handleError({type:"SCHEMA",message:"Failed to handle schema",details:e}),this.config.errorHandling?.throwOnError)throw e}}}exports.PathParse=p,exports.default=p;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("fs"),
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e=require("fs"),r=require("../utils/index.js"),a=require("./core/components.js"),s=require("./core/get-data.js"),t=require("./core/path.js"),i=require("shelljs"),o=require("chalk"),n=require("path");function l(e){return e&&"object"==typeof e&&"default"in e?e:{default:e}}var c=l(e),g=l(o),u=l(n);let d;const p="debug"===process.env.NODE_ENV,f={saveTypeFolderPath:p?"apps/types":"src/api/types",saveApiListFolderPath:p?"apps/types":"src/api",saveEnumFolderPath:p?"apps/types/enums":"src/enums",importEnumPath:"../../../enums",requestMethodsImportPath:"./fetch",formatting:{indentation:"\t",lineEnding:"\n"},swaggerServers:{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"}};class h{schemas={};paths={};async handle(e,r){try{const i=await s.getSwaggerJson(e);if(!i)throw new Error("无法获取 Swagger 数据");this.schemas=i.components?.schemas||{},this.paths=i.paths||{};const o=new a.default(this.schemas,e,{appendMode:r}),n=new t.PathParse(this.paths,i.components?.parameters,this.schemas,e);return await o.handle(),await n.handle(),!0}catch(e){if(e instanceof Error)throw new Error(`Handle Swagger data failed: ${e.message}`);throw new Error("Handle Swagger data failed: unknown error")}}async formatGeneratedFiles(e){const a=`npx prettier --write "${e.saveTypeFolderPath}/**/*.{ts,d.ts}"`;try{await c.default.promises.access(e.saveTypeFolderPath);const{stderr:s}=await new Promise((e,r)=>{i.exec(a,(a,s,t)=>{a?r(a):e({stdout:s,stderr:t})})});s&&(console.log("\n"),console.log("$",g.default.yellow(a)),console.log("\n")),r.log.success("File formatting successful"),console.log("\n")}catch(e){console.log(""),console.log(e),r.log.error("Format failed, please manually execute the following command:"),console.log("$",g.default.yellow(a)),console.log("")}}async copyAjaxConfigFiles(e){try{const a=["config.ts","error-message.ts","fetch.ts","api-type.d.ts"],s=p?u.default.join(__dirname,"..","..","postbuild-assets","ajax-config"):u.default.join(__dirname,"..","..","ajax-config"),t=e;for(const e of a){const a=u.default.join(s,e),i=u.default.join(t,e);try{await c.default.promises.access(a);try{await c.default.promises.access(i),r.log.info(`${e} already exists, skipping generation.`)}catch{await c.default.promises.copyFile(a,i),r.log.success(`${e} create done.`)}}catch(e){r.log.error(`Source file ${a} does not exist`);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){const r={url:e.swaggerJsonUrl||"https://your.swagger.json",publicPrefix:e.publicPrefix||"",apiListFileName:e.apiListFileName||"index.ts",headers:e.headers||{}},a=this.getSystemLocale();a.startsWith("zh")||a.includes("chinese")?(console.log("\n检测到旧版配置,请更新 an.config.json:"),console.log("1) 将 swaggerJsonUrl / publicPrefix / headers 移到 swaggerServers 字段。"),console.log("2) 单个服务可直接填写对象,多个服务请使用数组,并确保 apiListFileName 唯一。"),console.log("示例:"),console.log(JSON.stringify({swaggerServers:r},null,2)),console.log("")):(console.log("\nLegacy configuration detected, please update an.config.json:"),console.log("1) Move swaggerJsonUrl / publicPrefix / headers to swaggerServers 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({swaggerServers:r},null,2)),console.log(""))}normalizeSwaggerServers(e,r){let a=!1,s=r?e.swaggerServers:void 0;s||(a=!0,s={url:e.swaggerJsonUrl||"",publicPrefix:e.publicPrefix||"",apiListFileName:e.apiListFileName||"index.ts",headers:e.headers||{}});const t=(r,s)=>{const t=r.url||e.swaggerJsonUrl;if(!t)throw new Error(`swaggerServers[${s}] 缺少 url,请补充后重试。`);const i=r.publicPrefix??e.publicPrefix??"";!r.url&&e.swaggerJsonUrl&&(a=!0);return{url:t,publicPrefix:i,apiListFileName:(r.apiListFileName||e.apiListFileName||"index.ts").trim()||"index.ts",headers:r.headers||e.headers||{},dataLevel:r.dataLevel||e.dataLevel||"serve",parameterSeparator:r.parameterSeparator||e.parameterSeparator||"_",includeInterface:r.includeInterface||e.includeInterface||[],excludeInterface:r.excludeInterface||e.excludeInterface||[]}},i=Array.isArray(s)?s.map((e,r)=>t(e,r)):[t(s,0)];if(0===i.length)throw new Error("swaggerServers 不能为空,请至少配置一个 swagger 服务。");if(i.length>1){const e=new Set;i.forEach(r=>{if(e.has(r.apiListFileName))throw new Error(`swaggerServers 中 apiListFileName 重复:${r.apiListFileName},请为每个服务设置唯一文件名。`);e.add(r.apiListFileName)})}return a&&this.showLegacyConfigHint(e),i}buildServerConfig(e,r){return{...e,swaggerJsonUrl:r.url,publicPrefix:r.publicPrefix??e.publicPrefix,headers:r.headers,apiListFileName:r.apiListFileName,dataLevel:r.dataLevel,parameterSeparator:r.parameterSeparator,includeInterface:r.includeInterface,excludeInterface:r.excludeInterface,swaggerServers:r}}async getConfig(e){try{const r=await c.default.promises.readFile(e,"utf8");return d=!0,JSON.parse(r)}catch(a){return d=!1,r.log.warning("Config file does not exist, will automatically create config file."),await r.writeFileRecursive(e,JSON.stringify(f,null,2)),r.log.success("Please check the an.config.json file in the project root directory"),f}}async initialize(){const e=process.cwd()+"/an.config.json";try{const a=await this.getConfig(e),s={...f,...a},t=Object.prototype.hasOwnProperty.call(a,"swaggerServers"),i=this.normalizeSwaggerServers(s,t);if(!d)return;await c.default.promises.mkdir(s.saveApiListFolderPath,{recursive:!0}),await this.copyAjaxConfigFiles(s.saveApiListFolderPath),await r.clearDir(s.saveTypeFolderPath),await r.clearDir(s.saveEnumFolderPath);for(let e=0;e<i.length;e++){const r=this.buildServerConfig(s,i[e]),a=e>0;await this.handle(r,a)}await this.formatGeneratedFiles(s),r.log.success("Successfully, all done, see you next time!"),console.log("\n")}catch(e){const a=e instanceof Error?e.message:"Unknown error";r.log.error(`Initialization failed: ${a}`)}}}if(p){(new h).initialize()}exports.Main=h;
|
package/package.json
CHANGED
package/lib/data/openapi.json.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:!0});var e="3.0.3",t={title:"Swagger Petstore - OpenAPI 3.0",description:"This is a sample Pet Store Server based on the OpenAPI 3.0 specification. You can find out more about\nSwagger at [https://swagger.io](https://swagger.io). In the third iteration of the pet store, we've switched to the design first approach!\nYou can now help us improve the API whether it's by making changes to the definition itself or to the code.\nThat way, with time, we can improve the API in general, and expose some of the new features in OAS3.\n\n_If you're looking for the Swagger 2.0/OAS 2.0 version of Petstore, then click [here](https://editor.swagger.io/?url=https://petstore.swagger.io/v2/swagger.yaml). Alternatively, you can load via the `Edit > Load Petstore OAS 2.0` menu option!_\n\nSome useful links:\n- [The Pet Store repository](https://github.com/swagger-api/swagger-petstore)\n- [The source API definition for the Pet Store](https://github.com/swagger-api/swagger-petstore/blob/master/src/main/resources/openapi.yaml)",termsOfService:"http://swagger.io/terms/",contact:{email:"apiteam@swagger.io"},license:{name:"Apache 2.0",url:"http://www.apache.org/licenses/LICENSE-2.0.html"},version:"1.0.11"},s={description:"Find out more about Swagger",url:"http://swagger.io"},r=[{url:"https://petstore3.swagger.io/api/v3"}],a=[{name:"pet",description:"Everything about your Pets",externalDocs:{description:"Find out more",url:"http://swagger.io"}},{name:"store",description:"Access to Petstore orders",externalDocs:{description:"Find out more about our store",url:"http://swagger.io"}},{name:"user",description:"Operations about user"}],o={"/pet":{put:{tags:["pet"],summary:"Update an existing pet",description:"Update an existing pet by Id",operationId:"updatePet",requestBody:{description:"Update an existent pet in the store",content:{"application/json":{schema:{$ref:"#/components/schemas/Pet"}},"application/xml":{schema:{$ref:"#/components/schemas/Pet"}},"application/x-www-form-urlencoded":{schema:{$ref:"#/components/schemas/Pet"}}},required:!0},responses:{200:{description:"Successful operation",content:{"application/json":{schema:{$ref:"#/components/schemas/Pet"}},"application/xml":{schema:{$ref:"#/components/schemas/Pet"}}}},400:{description:"Invalid ID supplied"},404:{description:"Pet not found"},422:{description:"Validation exception"}},security:[{petstore_auth:["write:pets","read:pets"]}]},post:{tags:["pet"],summary:"Add a new pet to the store",description:"Add a new pet to the store",operationId:"addPet",requestBody:{description:"Create a new pet in the store",content:{"application/json":{schema:{$ref:"#/components/schemas/Pet"}},"application/xml":{schema:{$ref:"#/components/schemas/Pet"}},"application/x-www-form-urlencoded":{schema:{$ref:"#/components/schemas/Pet"}}},required:!0},responses:{200:{description:"Successful operation",content:{"application/json":{schema:{$ref:"#/components/schemas/Pet"}},"application/xml":{schema:{$ref:"#/components/schemas/Pet"}}}},400:{description:"Invalid input"},422:{description:"Validation exception"}},security:[{petstore_auth:["write:pets","read:pets"]}]}},"/pet/findByStatus":{get:{tags:["pet"],summary:"Finds Pets by status",description:"Multiple status values can be provided with comma separated strings",operationId:"findPetsByStatus",parameters:[{name:"status",in:"query",description:"Status values that need to be considered for filter",required:!1,explode:!0,schema:{type:"string",default:"available",enum:["available","pending","sold"]}}],responses:{200:{description:"successful operation",content:{"application/json":{schema:{type:"array",items:{$ref:"#/components/schemas/Pet"}}},"application/xml":{schema:{type:"array",items:{$ref:"#/components/schemas/Pet"}}}}},400:{description:"Invalid status value"}},security:[{petstore_auth:["write:pets","read:pets"]}]}},"/pet/findByTags":{get:{tags:["pet"],summary:"Finds Pets by tags",description:"Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.",operationId:"findPetsByTags",parameters:[{name:"tags",in:"query",description:"Tags to filter by",required:!1,explode:!0,schema:{type:"array",items:{type:"string"}}}],responses:{200:{description:"successful operation",content:{"application/json":{schema:{type:"array",items:{$ref:"#/components/schemas/Pet"}}},"application/xml":{schema:{type:"array",items:{$ref:"#/components/schemas/Pet"}}}}},400:{description:"Invalid tag value"}},security:[{petstore_auth:["write:pets","read:pets"]}]}},"/pet/{petId}":{get:{tags:["pet"],summary:"Find pet by ID",description:"Returns a single pet",operationId:"getPetById",parameters:[{name:"petId",in:"path",description:"ID of pet to return",required:!0,schema:{type:"integer",format:"int64"}}],responses:{200:{description:"successful operation",content:{"application/json":{schema:{$ref:"#/components/schemas/Pet"}},"application/xml":{schema:{$ref:"#/components/schemas/Pet"}}}},400:{description:"Invalid ID supplied"},404:{description:"Pet not found"}},security:[{api_key:[]},{petstore_auth:["write:pets","read:pets"]}]},post:{tags:["pet"],summary:"Updates a pet in the store with form data",description:"",operationId:"updatePetWithForm",parameters:[{name:"petId",in:"path",description:"ID of pet that needs to be updated",required:!0,schema:{type:"integer",format:"int64"}},{name:"name",in:"query",description:"Name of pet that needs to be updated",schema:{type:"string"}},{name:"status",in:"query",description:"Status of pet that needs to be updated",schema:{type:"string"}}],responses:{400:{description:"Invalid input"}},security:[{petstore_auth:["write:pets","read:pets"]}]},delete:{tags:["pet"],summary:"Deletes a pet",description:"delete a pet",operationId:"deletePet",parameters:[{name:"api_key",in:"header",description:"",required:!1,schema:{type:"string"}},{name:"petId",in:"path",description:"Pet id to delete",required:!0,schema:{type:"integer",format:"int64"}}],responses:{400:{description:"Invalid pet value"}},security:[{petstore_auth:["write:pets","read:pets"]}]}},"/pet/{petId}/uploadImage":{post:{tags:["pet"],summary:"uploads an image",description:"",operationId:"uploadFile",parameters:[{name:"petId",in:"path",description:"ID of pet to update",required:!0,schema:{type:"integer",format:"int64"}},{name:"additionalMetadata",in:"query",description:"Additional Metadata",required:!1,schema:{type:"string"}}],requestBody:{content:{"application/octet-stream":{schema:{type:"string",format:"binary"}}}},responses:{200:{description:"successful operation",content:{"application/json":{schema:{$ref:"#/components/schemas/ApiResponse"}}}}},security:[{petstore_auth:["write:pets","read:pets"]}]}},"/store/inventory":{get:{tags:["store"],summary:"Returns pet inventories by status",description:"Returns a map of status codes to quantities",operationId:"getInventory",responses:{200:{description:"successful operation",content:{"application/json":{schema:{type:"object",additionalProperties:{type:"integer",format:"int32"}}}}}},security:[{api_key:[]}]}},"/store/order":{post:{tags:["store"],summary:"Place an order for a pet",description:"Place a new order in the store",operationId:"placeOrder",requestBody:{content:{"application/json":{schema:{$ref:"#/components/schemas/Order"}},"application/xml":{schema:{$ref:"#/components/schemas/Order"}},"application/x-www-form-urlencoded":{schema:{$ref:"#/components/schemas/Order"}}}},responses:{200:{description:"successful operation",content:{"application/json":{schema:{$ref:"#/components/schemas/Order"}}}},400:{description:"Invalid input"},422:{description:"Validation exception"}}}},"/store/order/{orderId}":{get:{tags:["store"],summary:"Find purchase order by ID",description:"For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions.",operationId:"getOrderById",parameters:[{name:"orderId",in:"path",description:"ID of order that needs to be fetched",required:!0,schema:{type:"integer",format:"int64"}}],responses:{200:{description:"successful operation",content:{"application/json":{schema:{$ref:"#/components/schemas/Order"}},"application/xml":{schema:{$ref:"#/components/schemas/Order"}}}},400:{description:"Invalid ID supplied"},404:{description:"Order not found"}}},delete:{tags:["store"],summary:"Delete purchase order by ID",description:"For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors",operationId:"deleteOrder",parameters:[{name:"orderId",in:"path",description:"ID of the order that needs to be deleted",required:!0,schema:{type:"integer",format:"int64"}}],responses:{400:{description:"Invalid ID supplied"},404:{description:"Order not found"}}}},"/user":{post:{tags:["user"],summary:"Create user",description:"This can only be done by the logged in user.",operationId:"createUser",requestBody:{description:"Created user object",content:{"application/json":{schema:{$ref:"#/components/schemas/User"}},"application/xml":{schema:{$ref:"#/components/schemas/User"}},"application/x-www-form-urlencoded":{schema:{$ref:"#/components/schemas/User"}}}},responses:{default:{description:"successful operation",content:{"application/json":{schema:{$ref:"#/components/schemas/User"}},"application/xml":{schema:{$ref:"#/components/schemas/User"}}}}}}},"/user/createWithList":{post:{tags:["user"],summary:"Creates list of users with given input array",description:"Creates list of users with given input array",operationId:"createUsersWithListInput",requestBody:{content:{"application/json":{schema:{type:"array",items:{$ref:"#/components/schemas/User"}}}}},responses:{200:{description:"Successful operation",content:{"application/json":{schema:{$ref:"#/components/schemas/User"}},"application/xml":{schema:{$ref:"#/components/schemas/User"}}}},default:{description:"successful operation"}}}},"/user/login":{get:{tags:["user"],summary:"Logs user into the system",description:"",operationId:"loginUser",parameters:[{name:"username",in:"query",description:"The user name for login",required:!1,schema:{type:"string"}},{name:"password",in:"query",description:"The password for login in clear text",required:!1,schema:{type:"string"}}],responses:{200:{description:"successful operation",headers:{"X-Rate-Limit":{description:"calls per hour allowed by the user",schema:{type:"integer",format:"int32"}},"X-Expires-After":{description:"date in UTC when token expires",schema:{type:"string",format:"date-time"}}},content:{"application/xml":{schema:{type:"string"}},"application/json":{schema:{type:"string"}}}},400:{description:"Invalid username/password supplied"}}}},"/user/logout":{get:{tags:["user"],summary:"Logs out current logged in user session",description:"",operationId:"logoutUser",parameters:[],responses:{default:{description:"successful operation"}}}},"/user/{username}":{get:{tags:["user"],summary:"Get user by user name",description:"",operationId:"getUserByName",parameters:[{name:"username",in:"path",description:"The name that needs to be fetched. Use user1 for testing. ",required:!0,schema:{type:"string"}}],responses:{200:{description:"successful operation",content:{"application/json":{schema:{$ref:"#/components/schemas/User"}},"application/xml":{schema:{$ref:"#/components/schemas/User"}}}},400:{description:"Invalid username supplied"},404:{description:"User not found"}}},put:{tags:["user"],summary:"Update user",description:"This can only be done by the logged in user.",operationId:"updateUser",parameters:[{name:"username",in:"path",description:"name that need to be deleted",required:!0,schema:{type:"string"}}],requestBody:{description:"Update an existent user in the store",content:{"application/json":{schema:{$ref:"#/components/schemas/User"}},"application/xml":{schema:{$ref:"#/components/schemas/User"}},"application/x-www-form-urlencoded":{schema:{$ref:"#/components/schemas/User"}}}},responses:{default:{description:"successful operation"}}},delete:{tags:["user"],summary:"Delete user",description:"This can only be done by the logged in user.",operationId:"deleteUser",parameters:[{name:"username",in:"path",description:"The name that needs to be deleted",required:!0,schema:{type:"string"}}],responses:{400:{description:"Invalid username supplied"},404:{description:"User not found"}}}}},n={schemas:{Order:{type:"object",properties:{id:{type:"integer",format:"int64",example:10},petId:{type:"integer",format:"int64",example:198772},quantity:{type:"integer",format:"int32",example:7},shipDate:{type:"string",format:"date-time"},status:{type:"string",description:"Order Status",example:"approved",enum:["placed","approved","delivered"]},complete:{type:"boolean"}},xml:{name:"order"}},Customer:{type:"object",properties:{id:{type:"integer",format:"int64",example:1e5},username:{type:"string",example:"fehguy"},address:{type:"array",xml:{name:"addresses",wrapped:!0},items:{$ref:"#/components/schemas/Address"}}},xml:{name:"customer"}},Address:{type:"object",properties:{street:{type:"string",example:"437 Lytton"},city:{type:"string",example:"Palo Alto"},state:{type:"string",example:"CA"},zip:{type:"string",example:"94301"}},xml:{name:"address"}},Category:{type:"object",properties:{id:{type:"integer",format:"int64",example:1},name:{type:"string",example:"Dogs"}},xml:{name:"category"}},User:{type:"object",properties:{id:{type:"integer",format:"int64",example:10},username:{type:"string",example:"theUser"},firstName:{type:"string",example:"John"},lastName:{type:"string",example:"James"},email:{type:"string",example:"john@email.com"},password:{type:"string",example:"12345"},phone:{type:"string",example:"12345"},userStatus:{type:"integer",description:"User Status",format:"int32",example:1}},xml:{name:"user"}},Tag:{type:"object",properties:{id:{type:"integer",format:"int64"},name:{type:"string"}},xml:{name:"tag"}},Pet:{required:["name","photoUrls"],type:"object",properties:{id:{type:"integer",format:"int64",example:10},name:{type:"string",example:"doggie"},category:{$ref:"#/components/schemas/Category"},photoUrls:{type:"array",xml:{wrapped:!0},items:{type:"string",xml:{name:"photoUrl"}}},tags:{type:"array",xml:{wrapped:!0},items:{$ref:"#/components/schemas/Tag"}},status:{type:"string",description:"pet status in the store",enum:["available","pending","sold"]}},xml:{name:"pet"}},ApiResponse:{type:"object",properties:{code:{type:"integer",format:"int32"},type:{type:"string"},message:{type:"string"}},xml:{name:"##default"}}},requestBodies:{Pet:{description:"Pet object that needs to be added to the store",content:{"application/json":{schema:{$ref:"#/components/schemas/Pet"}},"application/xml":{schema:{$ref:"#/components/schemas/Pet"}}}},UserArray:{description:"List of user object",content:{"application/json":{schema:{type:"array",items:{$ref:"#/components/schemas/User"}}}}}},securitySchemes:{petstore_auth:{type:"oauth2",flows:{implicit:{authorizationUrl:"https://petstore3.swagger.io/oauth/authorize",scopes:{"write:pets":"modify pets in your account","read:pets":"read your pets"}}}},api_key:{type:"apiKey",name:"api_key",in:"header"}}},i={openapi:e,info:t,externalDocs:s,servers:r,tags:a,paths:o,components:n};exports.components=n,exports.default=i,exports.externalDocs=s,exports.info=t,exports.openapi=e,exports.paths=o,exports.servers=r,exports.tags=a;
|