anl 26.601.0 → 26.806.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.
package/lib/package.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var e=`26.
|
|
1
|
+
var e=`26.806.0`;Object.defineProperty(exports,`version`,{enumerable:!0,get:function(){return e}});
|
|
@@ -2,6 +2,7 @@ const e=require(`../../utils/logger.cjs`),t=require(`../../utils/index.cjs`),n=r
|
|
|
2
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(`
|
|
3
3
|
`)?e.split(`
|
|
4
4
|
`).forEach(e=>u.push(`${r} * ${e}`)):u.push(`${r} * ${e}`))}),u.push(`${r} */`),u.join(`
|
|
5
|
-
`)}nameTheHumpCenterStroke(e){let t=e.replace(`#/components/schemas/`,``),n=r.resolveSchemaName(t),i={typeName:n,fileName:r.typeNameToFileName(n),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:n,dataType:i=``}=this.nameTheHumpCenterStroke(e),a;if(i===`enum`){let e=r.getEnumTypeName(this.config,n),t=r.getServerSegment(this.config);a=`import type { ${e} } from '${r.appendEnumSegment(r.adjustImportPathForSegment(this.config.importEnumPath??``,t),r.getEnumSegment(this.config))}';`}else a=`import type { ${n} } from './${t}';`;return{headerRefStr:a,typeName:n,dataType:i}}parseArray(e,i){let a=e,{items:o={},nullable:s}=a,c=o?.$ref;if(c){let{headerRefStr:e,typeName:o,dataType:l}=this.parseRef(c),u=a.example;if(l===`enum`&&typeof u==`string`&&t.isValidJSON(u)){let e=this.enumParser.convertJsonToEnumString(u,o);this.enumParser.addEnumByName(o,e)}let d=l===`enum`?r.getEnumTypeName(this.config,o):o;return{headerRef:e,renderStr:`${n.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:`${n.getIndentation(this.config)}${i}${this.isRequired(i)?``:`?`}: Array<${u}>${this.nullable(s)};`,typeName:u}}parseBoolean(e,t){return e.type===`boolean`?`${n.getIndentation(this.config)}${t}${this.isRequired(t)?``:`?`}: boolean${this.nullable(e.nullable)};`:``}parseInteger(e,t){return Array.isArray(e.enum)?this.enumParser.handleEnum(e,t,this.isRequired(t))?.renderStr??``:`${n.getIndentation(this.config)}${t}${this.isRequired(t)?``:`?`}: number${this.nullable(e.nullable)};`}parseNumber(e,t){if(e.type!==`number`)return null;if(e.enum){let n=this.enumParser.handleEnum(e,t,this.isRequired(t));if(n)return n}return{headerRef:``,renderStr:`${n.getIndentation(this.config)}${t}${this.isRequired(t)?``:`?`}: 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,t){if(e.type!==`string`)return null;if(e.enum){let n=this.enumParser.handleEnum(e,t,this.isRequired(t));if(n)return n}let r=this.getStringTypeByFormat(e.format);return{headerRef:``,renderStr:`${n.getIndentation(this.config)}${t}${this.isRequired(t)?``:`?`}: ${r}${this.nullable(e.nullable)};`}}parseObject(e,t){
|
|
5
|
+
`)}nameTheHumpCenterStroke(e){let t=e.replace(`#/components/schemas/`,``),n=r.resolveSchemaName(t),i={typeName:n,fileName:r.typeNameToFileName(n),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:n,dataType:i=``}=this.nameTheHumpCenterStroke(e),a;if(i===`enum`){let e=r.getEnumTypeName(this.config,n),t=r.getServerSegment(this.config);a=`import type { ${e} } from '${r.appendEnumSegment(r.adjustImportPathForSegment(this.config.importEnumPath??``,t),r.getEnumSegment(this.config))}';`}else a=`import type { ${n} } from './${t}';`;return{headerRefStr:a,typeName:n,dataType:i}}parseArray(e,i){let a=e,{items:o={},nullable:s}=a,c=o?.$ref;if(c){let{headerRefStr:e,typeName:o,dataType:l}=this.parseRef(c),u=a.example;if(l===`enum`&&typeof u==`string`&&t.isValidJSON(u)){let e=this.enumParser.convertJsonToEnumString(u,o);this.enumParser.addEnumByName(o,e)}let d=l===`enum`?r.getEnumTypeName(this.config,o):o;return{headerRef:e,renderStr:`${n.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:`${n.getIndentation(this.config)}${i}${this.isRequired(i)?``:`?`}: Array<${u}>${this.nullable(s)};`,typeName:u}}parseBoolean(e,t){return e.type===`boolean`?`${n.getIndentation(this.config)}${t}${this.isRequired(t)?``:`?`}: boolean${this.nullable(e.nullable)};`:``}parseInteger(e,t){return Array.isArray(e.enum)?this.enumParser.handleEnum(e,t,this.isRequired(t))?.renderStr??``:`${n.getIndentation(this.config)}${t}${this.isRequired(t)?``:`?`}: number${this.nullable(e.nullable)};`}parseNumber(e,t){if(e.type!==`number`)return null;if(e.enum){let n=this.enumParser.handleEnum(e,t,this.isRequired(t));if(n)return n}return{headerRef:``,renderStr:`${n.getIndentation(this.config)}${t}${this.isRequired(t)?``:`?`}: 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,t){if(e.type!==`string`)return null;if(e.enum){let n=this.enumParser.handleEnum(e,t,this.isRequired(t));if(n)return n}let r=this.getStringTypeByFormat(e.format);return{headerRef:``,renderStr:`${n.getIndentation(this.config)}${t}${this.isRequired(t)?``:`?`}: ${r}${this.nullable(e.nullable)};`}}parseObject(e,t){if(e.type!==`object`)return{headerRef:``,renderStr:``};let r=e,i=n.getIndentation(this.config),a=this.isRequired(t)?``:`?`,o=this.nullable(r.nullable),s=r.additionalProperties;if(s&&typeof s==`object`){let e=this.parseArray(s,t)??this.defaultReturn;return{headerRef:e?.headerRef??``,renderStr:e?.renderStr??``}}if(r.properties&&Object.keys(r.properties).length>0){let e=[],n=this.renderInlineObjectType(r,e);return{headerRef:e.join(`
|
|
6
|
+
`),renderStr:`${i}${t}${a}: ${n}${o};`}}return s===!0?{headerRef:``,renderStr:`${i}${t}${a}: Record<string, unknown>${o};`}:{headerRef:``,renderStr:`${i}${t}${a}: object${o};`}}renderInlineObjectType(e,t){let n=e.properties;if(!n||Object.keys(n).length===0)return e.additionalProperties===!0?`Record<string, unknown>`:`object`;let i=new Set(e.required??[]),a=[];for(let e of Object.keys(n).sort()){let o=n[e],s=r.formatPropertyName(e),c=s.startsWith(`"`)&&s.endsWith(`"`)?s.slice(1,-1):s,l=i.has(c)?``:`?`,u=this.renderInlineTypeString(o,t),d=`$ref`in o?``:this.nullable(o.nullable);a.push(`${s}${l}: ${u}${d};`)}return`{ ${a.join(` `)} }`}renderInlineTypeString(e,t){if(`$ref`in e&&e.$ref){let{headerRefStr:n,typeName:i,dataType:a}=this.parseRef(e.$ref);return n&&!t.includes(n)&&t.push(n),a===`enum`?r.getEnumTypeName(this.config,i):i}let n=e;switch(n.type){case`string`:return Array.isArray(n.enum)?n.enum.map(e=>`'${e}'`).join(` | `):this.getStringTypeByFormat(n.format);case`integer`:case`number`:return Array.isArray(n.enum)?n.enum.join(` | `):`number`;case`boolean`:return`boolean`;case`array`:return`Array<${this.renderInlineTypeString(n.items,t)}>`;case`object`:return this.renderInlineObjectType(n,t);default:return`unknown`}}parseProperties(e,i){let a=[],o=[];if(!e)return{headerRef:``,renderStr:`export interface ${i} {}`};let s=Object.keys(e).sort();for(let c of s){let s=e[c],l=r.formatPropertyName(c);if(s?.$ref){let{headerRefStr:e,typeName:c,dataType:u}=this.parseRef(s.$ref);!o.includes(e)&&c!==i&&o.push(e);let d=s,f=this.buildDocComment(d,l);f!==``&&a.push(f);let p=u===`enum`?r.getEnumTypeName(this.config,c):c;a.push(`${n.getIndentation(this.config)}${l}${this.isRequired(l)?``:`?`}: ${p};`);let m=s.example;if(u===`enum`&&m&&t.isValidJSON(m)){let e=this.enumParser.convertJsonToEnumString(m,c);this.enumParser.addEnumByName(c,e)}continue}if(`allOf`in s||`anyOf`in s||`oneOf`in s){let e=s.allOf?.length?`allOf`:s.anyOf?.length?`anyOf`:s.oneOf?.length?`oneOf`:null;if(e){let t=e===`allOf`?` & `:` | `,c=s[e],u=[];for(let e of c)if(e?.$ref){let{headerRefStr:t,typeName:n,dataType:a}=this.parseRef(e.$ref),s=a===`enum`?r.getEnumTypeName(this.config,n):n;!o.includes(t)&&n!==i&&o.push(t),u.push(s)}else switch(e.type){case`string`:u.push(`string`);break;case`number`:case`integer`:u.push(`number`);break;case`boolean`:u.push(`boolean`);break;case`array`:u.push(`unknown[]`);break;case`object`:u.push(`Record<string, unknown>`);break;default:u.push(`unknown`);break}if(u.length>0){let e=this.buildDocComment(s,l);e!==``&&a.push(e);let r=u.join(t),i=u.length>1&&s.nullable?`(${r})`:r;a.push(`${n.getIndentation(this.config)}${l}${this.isRequired(l)?``:`?`}: ${i}${this.nullable(s.nullable)};`);continue}}}let u=s,d=this.buildDocComment(u,l);switch(d!==``&&a.push(d),u.type){case`array`:{let e=this.parseArray(u,l)??this.defaultReturn;a.push(e?.renderStr??``),!o.includes(e.headerRef)&&i!==e.typeName&&o.push(e.headerRef)}break;case`boolean`:a.push(this.parseBoolean(u,l));break;case`integer`:a.push(this.parseInteger(u,l));break;case`number`:{let e=this.parseNumber(u,l);e&&(e.headerRef&&!o.includes(e.headerRef)&&o.push(e.headerRef),a.push(e.renderStr))}break;case`string`:if(u.enum){let e=this.enumParser.handleEnum(u,l,this.isRequired(l));e&&(e.headerRef&&!o.includes(e.headerRef)&&o.push(e.headerRef),e.renderStr&&a.push(e.renderStr))}else a.push(this.parseString(u,l)?.renderStr??``);break;case`object`:{let{headerRef:e,renderStr:t}=this.parseObject(u,l)??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(`
|
|
6
7
|
`);return{headerRef:o.join(`
|
|
7
8
|
`),renderStr:l}}generateContent(t,n){if(`items`in t)return e.log.warn(`数组类型未处理: ${n}`),``;switch(t.type){case`boolean`:return this.parseBoolean(t,n);case`integer`:return this.parseInteger(t,n);case`number`:return this.parseNumber(t,n)?.renderStr??``;case`object`:return this.parseProperties(t.properties,n)?.renderStr??``;case`string`:return this.parseString(t,n)?.renderStr??``;default:return``}}main(){if(!this.schemas)return e.log.warn(`schemas 为空`),{enumsMap:this.enumParser.enumsMap,schemasMap:this.schemasMap};let t=Object.keys(this.schemas).sort();for(let n of t){let t=this.schemas[n];if(`$ref`in t){e.log.warn(`跳过 ReferenceObject: ${n}`);continue}let i=`type`in t?t:null;if(!i?.type){e.log.warn(`无效的 schema 对象: ${n}`);continue}if(Array.isArray(t.enum)){let e=r.resolveSchemaName(n),i=this.enumParser.parseEnum(t,e);i?.renderStr&&!this.enumParser.hasEnum(e)&&this.enumParser.addEnumByName(e,i.renderStr);continue}this.requiredFieldSet=new Set(t.required??[]);let a=r.resolveSchemaName(n),o=r.typeNameToFileName(a),s=this.generateContent(i,a);s&&((s.includes(`export enum `)||s.includes(`export const `)&&s.includes(`as const`))&&!this.enumParser.hasEnum(a)?this.enumParser.addEnumByName(a,s):this.schemasMap.set(a,{fileName:o,content:s}))}return{enumsMap:this.enumParser.enumsMap,schemasMap:this.schemasMap}}};exports.ComponentSchemaResolver=o;
|
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
const e=require(`../../utils/logger.cjs`);require(`../../utils/index.cjs`);const 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;allInterfaceKeys=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(!t.path&&this.contentBody.requestPath&&(t.path=this.contentBody.requestPath),!t.method&&this.contentBody.method&&(t.method=this.contentBody.method),this.errors.push(t),this.config.errorHandling?.logErrors&&e.log.error(e.formatParseError(t)),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(`
|
|
1
|
+
const e=require(`../../utils/logger.cjs`);require(`../../utils/index.cjs`);const 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:``,description:``,apiName:``,typeName:``,deprecated:!1,contentType:`application/json`};Map=new Map;config;errors=[];parameters={};schemas={};schemaResolver;writer;apiListFileContent=[];allowedInterfaceKeys=new Set;allInterfaceKeys=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(!t.path&&this.contentBody.requestPath&&(t.path=this.contentBody.requestPath),!t.method&&this.contentBody.method&&(t.method=this.contentBody.method),this.errors.push(t),this.config.errorHandling?.logErrors&&e.log.error(e.formatParseError(t)),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(t,r,i,a){let o=this.getDoubleIndentation(),s=`$ref`in t?t:null,c=`name`in t?t:null;if(s?.$ref&&s.$ref.startsWith(`#/components/parameters/`)&&this.parameters){let e=s.$ref.replace(`#/components/parameters/`,``),t=this.parameters[e];this.parametersItemHandle(t,r,i,a)}if(c){if(!c.schema){this.handleError({type:`PARAMETERS`,message:`Parameter "${c.name}" has no schema defined, skipping`});return}let t=this.schemaResolver.main(c.schema);if(!t||typeof t!=`string`){this.handleError({type:`PARAMETERS`,message:`Failed to parse schema for parameter "${c.name}"`,details:t});return}if(c.in===`path`){this.generateParamComment(c,o).forEach(e=>r.push(e));let e=n.sanitizeIdentifierName(c.name);r.push(`${o}type ${e} = ${t};`),this.contentBody.payload._path?this.contentBody.payload._path[e]=t:this.contentBody.payload._path={[e]:t}}else if(c.in===`query`){this.generateParamComment(c,o).forEach(e=>i.push(e));let e=c.required===!0?``:`?`,r=n.formatPropertyName(c.name);i.push(`${o}${r}${e}: ${t};`),this.contentBody.payload._query?this.contentBody.payload._query[c.name]=t:this.contentBody.payload._query={[c.name]:t}}else if(c.in===`header`){this.generateParamComment(c,o).forEach(e=>a.push(e));let e=c.required===!0?``:`?`,r=n.formatPropertyName(c.name);a.push(`${o}${r}${e}: ${t};`),this.contentBody.payload._header?this.contentBody.payload._header[c.name]=t:this.contentBody.payload._header={[c.name]:t}}else c.in===`cookie`?e.log.verbose(`Cookie parameter "${c.name}" detected but not added to type definition`):this.handleError({type:`PARAMETERS`,message:`Unknown parameter location "${c.in}" for parameter "${c.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}
|
|
4
|
+
`).forEach(e=>{n.push(`${t} * ${e}`)}):n.push(`${t} * ${e}`)}),n.push(`${t} */`))),n}parametersItemHandle(t,r,i,a){let o=this.getDoubleIndentation(),s=`$ref`in t?t:null,c=`name`in t?t:null;if(s?.$ref&&s.$ref.startsWith(`#/components/parameters/`)&&this.parameters){let e=s.$ref.replace(`#/components/parameters/`,``),t=this.parameters[e];this.parametersItemHandle(t,r,i,a)}if(c){if(!c.schema){this.handleError({type:`PARAMETERS`,message:`Parameter "${c.name}" has no schema defined, skipping`});return}let t=this.schemaResolver.main(c.schema);if(!t||typeof t!=`string`){this.handleError({type:`PARAMETERS`,message:`Failed to parse schema for parameter "${c.name}"`,details:t});return}if(c.in===`path`){this.generateParamComment(c,o).forEach(e=>r.push(e));let e=n.sanitizeIdentifierName(c.name);r.push(`${o}type ${e} = ${t};`),this.contentBody.payload._path?this.contentBody.payload._path[e]=t:this.contentBody.payload._path={[e]:t}}else if(c.in===`query`){this.generateParamComment(c,o).forEach(e=>i.push(e));let e=c.required===!0?``:`?`,r=n.formatPropertyName(c.name);i.push(`${o}${r}${e}: ${t};`),this.contentBody.payload._query?this.contentBody.payload._query[c.name]=t:this.contentBody.payload._query={[c.name]:t}}else if(c.in===`header`){this.generateParamComment(c,o).forEach(e=>a.push(e));let e=c.required===!0?``:`?`,r=n.formatPropertyName(c.name);a.push(`${o}${r}${e}: ${t};`),this.contentBody.payload._header?this.contentBody.payload._header[c.name]=t:this.contentBody.payload._header={[c.name]:t}}else c.in===`cookie`?e.log.verbose(`Cookie parameter "${c.name}" detected but not added to type definition`):this.handleError({type:`PARAMETERS`,message:`Unknown parameter location "${c.in}" for parameter "${c.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}pickPreferredRequestMediaType(e){if(!(!e||typeof e!=`object`)){for(let t of[`multipart/form-data`,`application/x-www-form-urlencoded`,`application/json`])if(e[t])return t;return Object.keys(e).sort()[0]}}pickRequestBodyContent(e){let t=e.content;if(!t||typeof t!=`object`)return{mediaType:`application/json`,schema:null};let n=this.pickPreferredRequestMediaType(t),i=n&&r.SUPPORTED_REQUEST_TYPES_ALL.includes(n)?n:`application/json`,a=n?t[n]:null;return{mediaType:i,schema:a&&typeof a==`object`&&a.schema?a.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(``)}pickPreferredResponse(e){let t=e[200];if(t)return t;let n=Object.keys(e).filter(e=>/^2\d\d$/.test(e)).sort((e,t)=>Number(e)-Number(t));if(n.length>0)return e[n[0]];let r=e.default;if(r)return r}responseHandle(e){let t=this.pickPreferredResponse(e);if(!t){this.contentBody.response=`type Response = unknown`,this.contentBody._response=`unknown`;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(`
|
|
8
|
-
`)||[];this.contentBody.payload.body=e}}}computeAllowedInterfaceKeys(){let e=[],t=Object.keys(this.pathsObject).sort();for(let n of t){let t=this.pathsObject[n];if(!t)continue;let r=Object.keys(t).sort();for(let i of r){let r=t[i];if(!r||typeof r!=`object`||!Object.values(s).includes(i))continue;let a=`${n}|${String(i).toUpperCase()}`,o=Array.isArray(r.tags)?r.tags:[];e.push({key:a,pathKey:n,method:i,tags:o})}}this.allInterfaceKeys=new Set(e.map(e=>e.key));let n;n=this.config.excludeTags&&this.config.excludeTags.length>0?new Set(e.filter(e=>!e.tags.some(e=>this.config.excludeTags.includes(e))).map(e=>e.key)):new Set(e.map(e=>e.key));let r;if(this.config.excludeInterface&&this.config.excludeInterface.length>0){let e=new Set(this.config.excludeInterface.map(e=>`${e.path}|${e.method.toUpperCase()}`));r=new Set([...n].filter(t=>!e.has(t)))}else r=new Set(n);let i;i=this.config.includeTags&&this.config.includeTags.length>0?new Set(e.filter(e=>r.has(e.key)&&e.tags.some(e=>this.config.includeTags.includes(e))).map(e=>e.key)):new Set;let a;if(this.config.includeInterface&&this.config.includeInterface.length>0){let e=new Set(this.config.includeInterface.map(e=>`${e.path}|${e.method.toUpperCase()}`));a=new Set([...r].filter(t=>e.has(t)))}else a=new Set;return i.size===0&&a.size===0?new Set(r):new Set([...i,...a])}parsePathItemObject(e,t,n){if(!e)return;let
|
|
9
|
-
`,
|
|
10
|
-
`,` */`].join(``));let
|
|
8
|
+
`)||[];this.contentBody.payload.body=e}}}computeAllowedInterfaceKeys(){let e=[],t=Object.keys(this.pathsObject).sort();for(let n of t){let t=this.pathsObject[n];if(!t)continue;let r=Object.keys(t).sort();for(let i of r){let r=t[i];if(!r||typeof r!=`object`||!Object.values(s).includes(i))continue;let a=`${n}|${String(i).toUpperCase()}`,o=Array.isArray(r.tags)?r.tags:[];e.push({key:a,pathKey:n,method:i,tags:o})}}this.allInterfaceKeys=new Set(e.map(e=>e.key));let n;n=this.config.excludeTags&&this.config.excludeTags.length>0?new Set(e.filter(e=>!e.tags.some(e=>this.config.excludeTags.includes(e))).map(e=>e.key)):new Set(e.map(e=>e.key));let r;if(this.config.excludeInterface&&this.config.excludeInterface.length>0){let e=new Set(this.config.excludeInterface.map(e=>`${e.path}|${e.method.toUpperCase()}`));r=new Set([...n].filter(t=>!e.has(t)))}else r=new Set(n);let i;i=this.config.includeTags&&this.config.includeTags.length>0?new Set(e.filter(e=>r.has(e.key)&&e.tags.some(e=>this.config.includeTags.includes(e))).map(e=>e.key)):new Set;let a;if(this.config.includeInterface&&this.config.includeInterface.length>0){let e=new Set(this.config.includeInterface.map(e=>`${e.path}|${e.method.toUpperCase()}`));a=new Set([...r].filter(t=>e.has(t)))}else a=new Set;return i.size===0&&a.size===0?new Set(r):new Set([...i,...a])}parsePathItemObject(e,t,n){if(!e)return;let r=Object.keys(e).sort();for(let a of r){let r=e[a];if(r){let e=a.toUpperCase(),o=t+`|`+e;if(!this.allowedInterfaceKeys.has(o))continue;let s=this.config.includeInterface?.find(e=>t===e.path&&e.method===a),{apiName:c,typeName:l,fileName:u,path:d}=i.convertEndpointString(o,this.config),f=r.requestBody&&`content`in r.requestBody?this.pickRequestBodyContent(r.requestBody).mediaType:`application/json`;this.contentBody={payload:{path:[],query:[],header:[],body:[]},response:``,_response:``,fileName:u,method:e,typeName:l,requestPath:d,apiName:c,summary:r.summary,description:r.description,deprecated:r.deprecated??!1,contentType:f,dataLevel:s?.dataLevel},this.requestHandle(r),this.responseHandle(r.responses),r.summary&&n.push([`/**`,`
|
|
9
|
+
`,r.deprecated?` * @deprecated ${r.summary}`:` * ${r.summary}`,`
|
|
10
|
+
`,` */`].join(``));let p=this.apiRequestItemHandle(this.contentBody);if(n.push(p,``),!this.Map.has(o)){let{payload:e}=this.contentBody,t={...this.contentBody,payload:{...e,path:[...e.path],query:[...e.query],header:[...e.header],body:[...e.body]}};this.Map.set(o,t)}}}}parseData(){this.allowedInterfaceKeys=this.computeAllowedInterfaceKeys();let e=Object.keys(this.pathsObject).sort();for(let t of e){let e=this.pathsObject[t];e&&this.parsePathItemObject(e,t,this.apiListFileContent)}return this.Map}async writeFile(){if(await this.writer.write(this.Map,this.apiListFileContent,[]),this.Map=new Map,this.errors.length>0){e.log.warning(`Completed with ${this.errors.length} error(s):`);let t=new Map;for(let e of this.errors){let n=e.type;t.has(n)||t.set(n,[]),t.get(n).push(e)}for(let[n,r]of t){e.log.warning(` ${n}: ${r.length} error(s)`);for(let t of r){let n=[t.method,t.path].filter(Boolean).join(` `);e.log.warn(` ${n?n+` - `:``}${t.message}`)}}}}async handle(){try{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}}getGeneratedInterfacesForOutput(){return[...this.allowedInterfaceKeys].sort().map(e=>{let t=e.lastIndexOf(`|`);return{path:e.slice(0,t),method:e.slice(t+1).toLowerCase()}})}getMissingInterfacesForOutput(){return[...this.allInterfaceKeys].filter(e=>!this.allowedInterfaceKeys.has(e)).sort().map(e=>{let t=e.lastIndexOf(`|`);return{path:e.slice(0,t),method:e.slice(t+1).toLowerCase()}})}};exports.default=l;
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
const e=require(`../../utils/logger.cjs`),t=require(`../../utils/index.cjs`),n=require(`../shared/format.cjs`),r=require(`../shared/naming.cjs`),i=require(`../shared/constants.cjs`);var a=class{config;
|
|
2
|
-
`)
|
|
1
|
+
const e=require(`../../utils/logger.cjs`),t=require(`../../utils/index.cjs`),n=require(`../shared/format.cjs`),r=require(`../shared/naming.cjs`),i=require(`../shared/constants.cjs`);var a=class{config;formatFileHeaderComment(e){if(!e)return[];let t=e.split(`
|
|
2
|
+
`).map(e=>e.replace(/\*\//g,`*\\/`));return t.length===1?[`/** ${t[0]} */`]:[`/**`,...t.map(e=>` * ${e}`),` */`]}constructor(e){this.config=e}async write(a,o,s){let c=this.config.saveTypeFolderPath,l=r.getServerSegment(this.config),u=l?`${c}/connectors/${l}`:`${c}/connectors`,d=async(r,a)=>{let{payload:o,response:c,fileName:l}=a,[,d]=r.split(`|`);s.includes(d)||s.push(d);let f=this.formatFileHeaderComment(a.description),p=[...f,...f.length?[``]:[],`declare namespace ${a.typeName} {`,...o.path,...o.query,...o.header,...o.body,`${n.getIndentation(this.config)}${c}`,`}`],m=`${u}/${l}.d.ts`;await t.writeFileRecursive(m,p.join(`
|
|
3
|
+
`)),e.log.info(`${m.padEnd(i.PAD_END)} - Write done!`)};await t.runWithConcurrency(Array.from(a.entries()).sort((e,t)=>e[0].localeCompare(t[0])),32,([e,t])=>d(e,t)),s.sort(),o.unshift(`import { ${s.join(`, `)} } from '${this.config.requestMethodsImportPath||`./api`}';`,`
|
|
3
4
|
`);let f=this.config.apiListFileName??`index.ts`,p=`${this.config.saveApiListFolderPath}/${f}`;await t.clearDir(p),await t.writeFileRecursive(p,o.join(`
|
|
4
5
|
`)),e.log.step(`Paths parsed & written`)}};exports.PathWriter=a;
|