@ahoo-wang/fetcher-generator 3.1.2 → 3.1.5
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/dist/cli.cjs +1 -1
- package/dist/cli.js +1 -1
- package/dist/client/commandClientGenerator.d.ts.map +1 -1
- package/dist/index.cjs +6 -6
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +27 -24
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/cli.cjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const c=require("commander"),a=require("./index.cjs");require("@ahoo-wang/fetcher");require("yaml");require("fs");require("path");class f{getTimestamp(){return new Date().toTimeString().slice(0,8)}info(e,...t){const o=this.getTimestamp();t.length>0?console.log(`[${o}] ℹ️ ${e}`,...t):console.log(`[${o}] ℹ️ ${e}`)}success(e,...t){const o=this.getTimestamp();t.length>0?console.log(`[${o}] ✅ ${e}`,...t):console.log(`[${o}] ✅ ${e}`)}error(e,...t){const o=this.getTimestamp();t.length>0?console.error(`[${o}] ❌ ${e}`,...t):console.error(`[${o}] ❌ ${e}`)}progress(e,t=0,...o){const i=this.getTimestamp(),r=" ".repeat(t);o.length>0?console.log(`[${i}] 🔄 ${r}${e}`,...o):console.log(`[${i}] 🔄 ${r}${e}`)}progressWithCount(e,t,o,i=0,...r){const s=this.getTimestamp(),p=" ".repeat(i),l=`[${e}/${t}]`;r.length>0?console.log(`[${s}] 🔄 ${p}${l} ${o}`,...r):console.log(`[${s}] 🔄 ${p}${l} ${o}`)}}function h(n){if(!n)return!1;try{const e=new URL(n);return e.protocol==="http:"||e.protocol==="https:"}catch{return n.length>0}}async function $(n){const e=new f;process.on("SIGINT",()=>{e.error("Generation interrupted by user"),process.exit(130)}),h(n.input)||(e.error("Invalid input: must be a valid file path or HTTP/HTTPS URL"),process.exit(2));try{e.info("Starting code generation...");const t={inputPath:n.input,outputDir:n.output,configPath:n.config,tsConfigFilePath:n.tsConfigFilePath,logger:e};await new a.CodeGenerator(t).generate(),e.success(`Code generation completed successfully! Files generated in: ${n.output}`)}catch(t){e.error(`Error during code generation: ${t}`),process.exit(1)}}const d="3.1.
|
|
2
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const c=require("commander"),a=require("./index.cjs");require("@ahoo-wang/fetcher");require("yaml");require("fs");require("path");class f{getTimestamp(){return new Date().toTimeString().slice(0,8)}info(e,...t){const o=this.getTimestamp();t.length>0?console.log(`[${o}] ℹ️ ${e}`,...t):console.log(`[${o}] ℹ️ ${e}`)}success(e,...t){const o=this.getTimestamp();t.length>0?console.log(`[${o}] ✅ ${e}`,...t):console.log(`[${o}] ✅ ${e}`)}error(e,...t){const o=this.getTimestamp();t.length>0?console.error(`[${o}] ❌ ${e}`,...t):console.error(`[${o}] ❌ ${e}`)}progress(e,t=0,...o){const i=this.getTimestamp(),r=" ".repeat(t);o.length>0?console.log(`[${i}] 🔄 ${r}${e}`,...o):console.log(`[${i}] 🔄 ${r}${e}`)}progressWithCount(e,t,o,i=0,...r){const s=this.getTimestamp(),p=" ".repeat(i),l=`[${e}/${t}]`;r.length>0?console.log(`[${s}] 🔄 ${p}${l} ${o}`,...r):console.log(`[${s}] 🔄 ${p}${l} ${o}`)}}function h(n){if(!n)return!1;try{const e=new URL(n);return e.protocol==="http:"||e.protocol==="https:"}catch{return n.length>0}}async function $(n){const e=new f;process.on("SIGINT",()=>{e.error("Generation interrupted by user"),process.exit(130)}),h(n.input)||(e.error("Invalid input: must be a valid file path or HTTP/HTTPS URL"),process.exit(2));try{e.info("Starting code generation...");const t={inputPath:n.input,outputDir:n.output,configPath:n.config,tsConfigFilePath:n.tsConfigFilePath,logger:e};await new a.CodeGenerator(t).generate(),e.success(`Code generation completed successfully! Files generated in: ${n.output}`)}catch(t){e.error(`Error during code generation: ${t}`),process.exit(1)}}const d="3.1.5",m={version:d};function u(){return c.program.name("fetcher-generator").description("OpenAPI Specification TypeScript code generator for Wow").version(m.version,"-v, --version"),c.program.command("generate").description("Generate TypeScript code from OpenAPI specification").requiredOption("-i, --input <file>","Input OpenAPI specification file path or URL (http/https)").option("-o, --output <path>","Output directory path","src/generated").option("-c, --config <file>","Configuration file path",a.DEFAULT_CONFIG_PATH).option("-t, --ts-config-file-path <file>","TypeScript configuration file path").action($),c.program}function g(){u().parse()}g();exports.runCLI=g;exports.setupCLI=u;
|
|
3
3
|
//# sourceMappingURL=cli.cjs.map
|
package/dist/cli.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"commandClientGenerator.d.ts","sourceRoot":"","sources":["../../src/client/commandClientGenerator.ts"],"names":[],"mappings":"AAcA,OAAO,EACL,gBAAgB,EAGhB,UAAU,EAEX,MAAM,UAAU,CAAC;AAClB,OAAO,EAAE,mBAAmB,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAC;AACzF,OAAO,EAAE,eAAe,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAChE,OAAO,EAAmB,SAAS,EAAmD,MAAM,UAAU,CAAC;AAsBvG;;;GAGG;AACH,qBAAa,sBAAuB,YAAW,SAAS;aAS1B,OAAO,EAAE,eAAe;IARpD,OAAO,CAAC,QAAQ,CAAC,0BAA0B,CAA0B;IACrE,OAAO,CAAC,QAAQ,CAAC,+BAA+B,CACb;IAEnC;;;OAGG;gBACyB,OAAO,EAAE,eAAe;IAGpD;;OAEG;IACH,QAAQ,IAAI,IAAI;IAuBhB;;;OAGG;IACH,gBAAgB,CAAC,SAAS,EAAE,mBAAmB;
|
|
1
|
+
{"version":3,"file":"commandClientGenerator.d.ts","sourceRoot":"","sources":["../../src/client/commandClientGenerator.ts"],"names":[],"mappings":"AAcA,OAAO,EACL,gBAAgB,EAGhB,UAAU,EAEX,MAAM,UAAU,CAAC;AAClB,OAAO,EAAE,mBAAmB,EAAE,iBAAiB,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAC;AACzF,OAAO,EAAE,eAAe,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAChE,OAAO,EAAmB,SAAS,EAAmD,MAAM,UAAU,CAAC;AAsBvG;;;GAGG;AACH,qBAAa,sBAAuB,YAAW,SAAS;aAS1B,OAAO,EAAE,eAAe;IARpD,OAAO,CAAC,QAAQ,CAAC,0BAA0B,CAA0B;IACrE,OAAO,CAAC,QAAQ,CAAC,+BAA+B,CACb;IAEnC;;;OAGG;gBACyB,OAAO,EAAE,eAAe;IAGpD;;OAEG;IACH,QAAQ,IAAI,IAAI;IAuBhB;;;OAGG;IACH,gBAAgB,CAAC,SAAS,EAAE,mBAAmB;IA4E/C,wCAAwC,CAAC,SAAS,EAAE,iBAAiB,GAAG,MAAM;IAI9E,2BAA2B,CACzB,UAAU,EAAE,UAAU,EACtB,mBAAmB,EAAE,mBAAmB,GACvC,MAAM;IA0BT,sBAAsB,CAAC,UAAU,EAAE,iBAAiB,GAAG,CAAC,SAAS,EAAE,MAAM,CAAC;IAK1E,kBAAkB,CAAC,UAAU,EAAE,UAAU,EAAE,UAAU,EAAE,iBAAiB;IAmBxE,mBAAmB,CAAC,UAAU,EAAE,UAAU,EACtB,mBAAmB,EAAE,mBAAmB;IAM5D,eAAe,CAAC,iCAAiC,EAAE,MAAM,EAAE,OAAO,EAAE,iBAAiB,GAAG,MAAM;IAI9F,oBAAoB,CAClB,UAAU,EAAE,UAAU,EACtB,mBAAmB,EAAE,mBAAmB,EACxC,iCAAiC,EAAE,MAAM;IAwB3C,0BAA0B,CACxB,UAAU,EAAE,UAAU,EACtB,mBAAmB,EAAE,mBAAmB;IA8B1C,OAAO,CAAC,iBAAiB;IAkEzB,oBAAoB,CAClB,SAAS,EAAE,mBAAmB,EAC9B,MAAM,EAAE,gBAAgB,EACxB,UAAU,EAAE,iBAAiB,EAC7B,iCAAiC,EAAE,MAAM;CAuC5C"}
|
package/dist/index.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const
|
|
2
|
-
`){if(!Array.isArray(o))return;const t=o.filter(n=>typeof n=="string"&&n.length>0);return t.length>0?t.join(e):void 0}function
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const C=require("ts-morph"),f=require("@ahoo-wang/fetcher"),k=require("@ahoo-wang/fetcher-wow"),K=require("yaml"),ye=require("fs"),L=require("path");function T(o){return o.$ref.split("/").pop()}function S(o,e){const t=T(o);return e.schemas?.[t]}function H(o,e){const t=T(o);return e.requestBodies?.[t]}function Y(o,e){const t=T(o);return e.parameters?.[t]}function v(o,e){return{key:T(o),schema:S(o,e)}}const xe=/[-_\s.]+/;function O(o){return o.split(xe)}function X(o){return Array.isArray(o)?o.flatMap(e=>z(O(e))):z(O(o))}function z(o){return o.flatMap(e=>{if(e.length===0)return[];const t=[];let n="";for(let r=0;r<e.length;r++){const i=e[r],s=/[A-Z]/.test(i),a=r>0&&/[a-z]/.test(e[r-1]);s&&a&&n?(t.push(n),n=i):n+=i}return n&&t.push(n),t})}function R(o){return o===""||o.length===0?"":X(o).filter(t=>t.length>0).map(t=>{const n=t.charAt(0),r=t.slice(1);return(/[a-zA-Z]/.test(n)?n.toUpperCase():n)+r.toLowerCase()}).join("")}function h(o){const e=R(o);return e.charAt(0).toLowerCase()+e.slice(1)}function Z(o){return o===""||Array.isArray(o)&&o.length===0?"":X(o).filter(t=>t.length>0).map(t=>t.toUpperCase()).join("_")}function g(o){return!!(o&&typeof o=="object"&&"$ref"in o)}function j(o,e){if(e&&!g(e)&&e.content)return e.content[o]?.schema}function ee(o){return j(f.ContentTypeValues.APPLICATION_JSON,o)}function Ae(o){return j(f.ContentTypeValues.TEXT_EVENT_STREAM,o)}function Ce(o){return j("*/*",o)}const Pe=["string","number","integer","boolean","null"];function te(o){return Array.isArray(o)?!0:Pe.includes(o)}function B(o){return Array.isArray(o.enum)&&o.enum.length>0}function I(o){return o.type==="object"&&!!o.properties}function N(o){return o.type==="array"&&!!o.items}function $e(o){return Array.isArray(o.anyOf)&&o.anyOf.length>0}function Te(o){return Array.isArray(o.oneOf)&&o.oneOf.length>0}function b(o){return Array.isArray(o.allOf)&&o.allOf.length>0}function U(o){return $e(o)||Te(o)||b(o)}function ve(o){return o.includes("|")||o.includes("&")?`(${o})[]`:`${o}[]`}function Ie(o){return o.type==="object"&&!o.properties&&o.additionalProperties!==void 0}function Ee(o){return o.type!=="object"?!1:o.properties?Object.keys(o.properties).length===0:!0}function Se(o){return o.readOnly===!0}function w(o){if(Array.isArray(o))return o.map(e=>w(e)).join(" | ");switch(o){case"string":return"string";case"number":case"integer":return"number";case"boolean":return"boolean";case"null":return"null";default:return"any"}}function Re(o){if(!I(o))return[];const e=o.required||[];return Object.keys(o.properties).filter(t=>!e.includes(t))}function we(o,e){return o.operation.operationId&&e.operation.operationId?o.operation.operationId.localeCompare(e.operation.operationId):o.path&&e.path?o.path.localeCompare(e.path):o.method&&e.method?o.method.localeCompare(e.method):0}function ne(o){const e=[];for(const[t,n]of Object.entries(o))oe(n).forEach(r=>{e.push({method:r.method,operation:r.operation,path:t})});return e.sort(we)}function oe(o){return[{method:"get",operation:o.get},{method:"put",operation:o.put},{method:"post",operation:o.post},{method:"delete",operation:o.delete},{method:"options",operation:o.options},{method:"head",operation:o.head},{method:"patch",operation:o.patch},{method:"trace",operation:o.trace}].filter(({operation:e})=>e!==void 0)}function G(o){return o.responses[200]}function J(o){const e=G(o);return ee(e)}function De(o,e){return o.parameters?o.parameters.map(t=>g(t)?Y(t,e):t).filter(t=>t.in==="path"):[]}const Oe="string";function re(o){return!o.schema||g(o.schema)||!o.schema.type||!te(o.schema.type)?Oe:w(o.schema.type)}function ie(o){return o.startsWith("http://")||o.startsWith("https://")?Ne(o):be(o)}async function Ne(o){return await(await fetch(o)).text()}function be(o){return new Promise((e,t)=>{ye.readFile(o,"utf-8",(n,r)=>{n?t(n):e(r)})})}async function Me(o){const e=await ie(o);switch(se(e)){case"json":return JSON.parse(e);case"yaml":return K.parse(e);default:throw new Error(`Unsupported file format: ${o}`)}}async function qe(o){const e=await ie(o);switch(se(e)){case"json":return JSON.parse(e);case"yaml":return K.parse(e);default:throw new Error(`Unsupported file format: ${o}`)}}function se(o){const e=o.trimStart();if(e.startsWith("{")||e.startsWith("["))return"json";if(e.startsWith("-")||e.startsWith("%YAML"))return"yaml";try{return JSON.parse(e),"json"}catch{if(e.length>0)return"yaml"}throw new Error("Unable to infer file format")}const ae="types.ts",Fe="@";function je(o){return f.combineURLs(o.path,ae)}function ce(o,e,t){const n=f.combineURLs(e,t),r=o.getSourceFile(n);return r||o.createSourceFile(n,"",{overwrite:!0})}function P(o,e,t){let n=o.getImportDeclaration(r=>r.getModuleSpecifierValue()===e);n||(n=o.addImportDeclaration({moduleSpecifier:e})),t.forEach(r=>{n.getNamedImports().some(s=>s.getName()===r)||n.addNamedImport(r)})}function m(o,e,t){if(t.path.startsWith(Fe)){P(o,t.path,[t.name]);return}const n=o.getDirectoryPath(),r=L.join(e,t.path,ae);let i=L.relative(n,r);i=i.replace(/\.ts$/,""),i.startsWith(".")||(i="./"+i),P(o,i,[t.name])}function Ge(o,e,t,n){o.path!==n.path&&m(e,t,n)}function ge(o,e=`
|
|
2
|
+
`){if(!Array.isArray(o))return;const t=o.filter(n=>typeof n=="string"&&n.length>0);return t.length>0?t.join(e):void 0}function $(o,e){const t=ge(e);t&&o.addJsDoc(t)}function _(o,e){const t=[o.title,o.description];return e&&t.push(`- key: ${e}`),o.format&&t.push(`- format: ${o.format}`),Q(t,o,"default"),Q(t,o,"example"),ke(t,o),Le(t,o),ze(t,o),t}function _e(o,e,t){const n=_(e,t);$(o,n)}function We(o,e,t){const n=_(e,t);pe(n,"schema",e),$(o,n)}function Q(o,e,t){const n=e[t];if(n){if(typeof n!="object"){o.push(`- ${t}: \`${n}\``);return}pe(o,t,n)}}function pe(o,e,t){o.push(`- ${e}: `),o.push("```json"),o.push(JSON.stringify(t,null,2)),o.push("```")}function ke(o,e){const t=["- Numeric Constraints"];e.minimum!==void 0&&t.push(` - minimum: ${e.minimum}`),e.maximum!==void 0&&t.push(` - maximum: ${e.maximum}`),e.exclusiveMinimum!==void 0&&t.push(` - exclusiveMinimum: ${e.exclusiveMinimum}`),e.exclusiveMaximum!==void 0&&t.push(` - exclusiveMaximum: ${e.exclusiveMaximum}`),e.multipleOf!==void 0&&t.push(` - multipleOf: ${e.multipleOf}`),t.length!==1&&o.push(...t)}function Le(o,e){const t=["- String Constraints"];e.minLength!==void 0&&t.push(` - minLength: ${e.minLength}`),e.maxLength!==void 0&&t.push(` - maxLength: ${e.maxLength}`),e.pattern!==void 0&&t.push(` - pattern: ${e.pattern}`),t.length!==1&&o.push(...t)}function ze(o,e){const t=["- Array Constraints"];e.minItems!==void 0&&t.push(` - minItems: ${e.minItems}`),e.maxItems!==void 0&&t.push(` - maxItems: ${e.maxItems}`),e.uniqueItems!==void 0&&t.push(` - uniqueItems: ${e.uniqueItems}`),t.length!==1&&o.push(...t)}function Be(o){const e=o.split(".");return e.length!=2||e[0].length===0||e[1].length===0?null:e}function Ue(o){const e=Be(o.name);return e?{tag:o,contextAlias:e[0],aggregateName:e[1]}:null}function Je(o){const e=o?.map(n=>Ue(n)).filter(n=>n!==null);if(!e)return new Map;const t=new Map;return e.forEach(n=>{t.set(n.tag.name,{aggregate:n,commands:new Map,events:new Map})}),t}function Qe(o){if(!o)return null;const e=o.split(".");return e.length!=3?null:e[2]}const Ve="#/components/responses/wow.CommandOk",Ke="#/components/parameters/wow.id";class He{constructor(e){this.openAPI=e,this.aggregates=Je(e.tags),this.build()}aggregates;build(){const e=ne(this.openAPI.paths);for(const t of e)this.commands(t.path,t),this.state(t.operation),this.events(t.operation),this.fields(t.operation)}resolve(){const e=new Map;for(const t of this.aggregates.values()){if(!t.state||!t.fields)continue;const n=t.aggregate.contextAlias;let r=e.get(n);r||(r=new Set,e.set(n,r)),r.add(t)}return e}commands(e,t){const n=t.operation;if(n.operationId==="wow.command.send")return;const r=Qe(n.operationId);if(!r)return;const i=G(n);if(!i||!g(i)||i.$ref!==Ve||!n.requestBody)return;const s=n.parameters??[],a=s.filter(l=>g(l)&&l.$ref===Ke).at(0),c=s.filter(l=>!g(l)&&l.in==="path");if(a){const l=Y(a,this.openAPI.components);c.push(l)}const p=n.requestBody.content[f.ContentTypeValues.APPLICATION_JSON].schema,A=v(p,this.openAPI.components);A.schema.title=A.schema.title||n.summary,A.schema.description=A.schema.description||n.description;const he={name:r,method:t.method,path:e,pathParameters:c,summary:n.summary,description:n.description,schema:A,operation:n};n.tags?.forEach(l=>{const W=this.aggregates.get(l);W&&W.commands.set(r,he)})}state(e){if(!e.operationId?.endsWith(".snapshot_state.single"))return;const t=J(e);if(!g(t))return;const n=v(t,this.openAPI.components);e.tags?.forEach(r=>{const i=this.aggregates.get(r);i&&(i.state=n)})}events(e){if(!this.openAPI.components||!e.operationId?.endsWith(".event.list_query"))return;const t=J(e);if(g(t))return;const n=t?.items;if(!g(n))return;const i=S(n,this.openAPI.components).properties.body.items.anyOf.map(s=>{const a=s.title,c=s.properties.name.const,u=s.properties.body,p=v(u,this.openAPI.components);return p.schema.title=p.schema.title||s.title,{title:a,name:c,schema:p}});e.tags?.forEach(s=>{const a=this.aggregates.get(s);a&&i.forEach(c=>{a.events.set(c.name,c)})})}fields(e){if(!this.openAPI.components||!e.operationId?.endsWith(".snapshot.count"))return;const n=H(e.requestBody,this.openAPI.components).content[f.ContentTypeValues.APPLICATION_JSON].schema,i=S(n,this.openAPI.components).properties?.field,s=v(i,this.openAPI.components);e.tags?.forEach(a=>{const c=this.aggregates.get(a);c&&(c.fields=s)})}}const x="@ahoo-wang/fetcher-wow",Ye={"wow.command.CommandResult":"CommandResult","wow.command.CommandResultArray":"CommandResultArray","wow.MessageHeaderSqlType":"MessageHeaderSqlType","wow.api.BindingError":"BindingError","wow.api.DefaultErrorInfo":"ErrorInfo","wow.api.RecoverableType":"RecoverableType","wow.api.command.DefaultDeleteAggregate":"DeleteAggregate","wow.api.command.DefaultRecoverAggregate":"RecoverAggregate","wow.api.messaging.FunctionInfoData":"FunctionInfo","wow.api.messaging.FunctionKind":"FunctionKind","wow.api.modeling.AggregateId":"AggregateId","wow.api.query.Condition":"Condition","wow.api.query.ConditionOptions":"ConditionOptions","wow.api.query.ListQuery":"ListQuery","wow.api.query.Operator":"Operator","wow.api.query.PagedQuery":"PagedQuery","wow.api.query.Pagination":"Pagination","wow.api.query.Projection":"Projection","wow.api.query.Sort":"FieldSort","wow.api.query.Sort.Direction":"SortDirection","wow.command.CommandStage":"CommandStage","wow.command.SimpleWaitSignal":"WaitSignal","wow.configuration.Aggregate":"Aggregate","wow.configuration.BoundedContext":"BoundedContext","wow.configuration.WowMetadata":"WowMetadata","wow.modeling.DomainEvent":"DomainEvent","wow.openapi.BatchResult":"BatchResult","wow.messaging.CompensationTarget":"CompensationTarget"};function d(o){if(!o)return{name:"",path:"/"};const e=Ye[o];if(e)return{name:e,path:x};const t=o.split(".");let n=-1;for(let c=0;c<t.length;c++)if(t[c]&&/^[A-Z]/.test(t[c])){n=c;break}const r=t.slice(0,n),i=r.length>0?`/${r.join("/")}`:"/",s=t.slice(n);return{name:R(s),path:i}}function E(o){const e=T(o);return d(e)}function D(o){return`${Z(o)}_BOUNDED_CONTEXT_ALIAS`}class Xe{constructor(e,t,n,r){this.modelInfo=e,this.sourceFile=t,this.keySchema=n,this.outputDir=r}generate(){const e=this.process();e&&We(e,this.keySchema.schema,this.keySchema.key)}process(){const{schema:e}=this.keySchema;return B(e)?this.processEnum(e):I(e)?this.processInterface(e):N(e)?this.processArray(e):b(e)?this.processIntersection(e):U(e)?this.processComposition(e):this.processTypeAlias(e)}resolveReference(e){const t=E(e);return Ge(this.modelInfo,this.sourceFile,this.outputDir,t),t}resolveAdditionalProperties(e){return e.additionalProperties===void 0||e.additionalProperties===!1?"":e.additionalProperties===!0?"[key: string]: any":`[key: string]: ${this.resolveType(e.additionalProperties)}`}resolvePropertyDefinitions(e){const{properties:t}=e;return Object.entries(t).map(([n,r])=>{const i=this.resolveType(r);if(!g(r)){const s=_(r),a=ge(s,`
|
|
3
3
|
* `);if(a)return`
|
|
4
4
|
/**
|
|
5
5
|
* ${a}
|
|
@@ -8,14 +8,14 @@
|
|
|
8
8
|
`}return`${n}: ${i}`})}resolveObjectType(e){const t=[];if(I(e)){const r=this.resolvePropertyDefinitions(e);t.push(...r)}const n=this.resolveAdditionalProperties(e);return n&&t.push(n),t.length===0?"Record<string, any>":`{
|
|
9
9
|
${t.join(`;
|
|
10
10
|
`)};
|
|
11
|
-
}`}resolveMapValueType(e){return e.additionalProperties===void 0||e.additionalProperties===!1||e.additionalProperties===!0?"any":this.resolveType(e.additionalProperties)}resolveType(e){if(g(e))return this.resolveReference(e).name;if(Ie(e))return`Record<string,${this.resolveMapValueType(e)}>`;if(e.const)return`'${e.const}'`;if(
|
|
11
|
+
}`}resolveMapValueType(e){return e.additionalProperties===void 0||e.additionalProperties===!1||e.additionalProperties===!0?"any":this.resolveType(e.additionalProperties)}resolveType(e){if(g(e))return this.resolveReference(e).name;if(Ie(e))return`Record<string,${this.resolveMapValueType(e)}>`;if(e.const)return`'${e.const}'`;if(B(e))return e.enum.map(t=>`'${t}'`).join(" | ");if(U(e)){const n=(e.oneOf||e.anyOf||e.allOf||[]).map(i=>this.resolveType(i)),r=b(e)?" & ":" | ";return`(${n.join(r)})`}if(N(e)){const t=this.resolveType(e.items);return ve(t)}return e.type==="object"?this.resolveObjectType(e):e.type?w(e.type):"any"}processEnum(e){return this.sourceFile.addEnum({name:this.modelInfo.name,isExported:!0,members:e.enum.filter(t=>typeof t=="string"&&t.length>0).map(t=>({name:Z(t),initializer:`'${t}'`}))})}addPropertyToInterface(e,t,n){const r=this.resolveType(n);let i=e.getProperty(t);i?i.setType(r):i=e.addProperty({name:t,type:r,isReadonly:Se(n)}),_e(i,n)}processInterface(e){const t=this.sourceFile.addInterface({name:this.modelInfo.name,isExported:!0}),n=e.properties||{};return Object.entries(n).forEach(([r,i])=>{this.addPropertyToInterface(t,r,i)}),e.additionalProperties&&t.addIndexSignature({keyName:"key",keyType:"string",returnType:this.resolveType(e.additionalProperties===!0?{}:e.additionalProperties)}).addJsDoc("Additional properties"),t}processArray(e){const t=this.resolveType(e.items);return this.sourceFile.addTypeAlias({name:this.modelInfo.name,type:`Array<${t}>`,isExported:!0})}processComposition(e){return this.sourceFile.addTypeAlias({name:this.modelInfo.name,type:this.resolveType(e),isExported:!0})}processIntersection(e){const t=this.sourceFile.addInterface({name:this.modelInfo.name,isExported:!0});return e.allOf.forEach(n=>{if(g(n)){const r=this.resolveType(n);t.addExtends(r);return}I(n)&&Object.entries(n.properties).forEach(([r,i])=>{this.addPropertyToInterface(t,r,i)})}),t}processTypeAlias(e){return this.sourceFile.addTypeAlias({name:this.modelInfo.name,type:this.resolveType(e),isExported:!0})}}class Ze{constructor(e){this.context=e}getOrCreateSourceFile(e){const t=je(e);return this.context.getOrCreateSourceFile(t)}generate(){const e=this.context.openAPI.components?.schemas;if(!e){this.context.logger.info("No schemas found in OpenAPI specification");return}const t=this.stateAggregatedTypeNames(),n=this.filterSchemas(e,t);this.context.logger.progress(`Generating models for ${n.length} schemas`),n.forEach((r,i)=>{this.context.logger.progressWithCount(i+1,n.length,`Processing schema: ${r.key}`,2),this.generateKeyedSchema(r)}),this.context.logger.success("Model generation completed")}filterSchemas(e,t){return Object.entries(e).map(([n,r])=>({key:n,schema:r})).filter(n=>!this.isWowSchema(n.key,t))}isWowSchema(e,t){if(e!=="wow.api.query.PagedList"&&e.startsWith("wow.api.query.")&&e.endsWith("PagedList"))return!1;if(e.startsWith("wow.")||e.endsWith("AggregatedCondition")||e.endsWith("AggregatedDomainEventStream")||e.endsWith("AggregatedDomainEventStreamPagedList")||e.endsWith("AggregatedDomainEventStreamServerSentEventNonNullData")||e.endsWith("AggregatedListQuery")||e.endsWith("AggregatedPagedQuery")||e.endsWith("AggregatedSingleQuery"))return!0;const n=d(e);return t.has(n.name)}aggregatedSchemaSuffix=["MaterializedSnapshot","MaterializedSnapshotPagedList","MaterializedSnapshotServerSentEventNonNullData","PagedList","ServerSentEventNonNullData","Snapshot","StateEvent"];stateAggregatedTypeNames(){const e=new Set;for(const[t,n]of this.context.contextAggregates){this.generateBoundedContext(t);for(const r of n)this.aggregatedSchemaSuffix.forEach(i=>{const s=d(r.state.key),a=R(s.name)+i;e.add(a)})}return e}generateKeyedSchema(e){const t=d(e.key),n=this.getOrCreateSourceFile(t);new Xe(t,n,e,this.context.outputDir).generate()}generateBoundedContext(e){const t=`${e}/boundedContext.ts`;this.context.logger.info(`Creating bounded context file: ${t}`);const n=this.context.getOrCreateSourceFile(t),r=D(e);n.addStatements(`export const ${r} = '${e}';`)}}const et="@ahoo-wang/fetcher-decorator",tt=["type ApiMetadata","type ApiMetadataCapable","type ParameterRequest","api","get","post","put","patch","del","request","attribute","path","autoGeneratedError"],nt={type:"Promise<Response>",metadata:"{resultExtractor: ResultExtractors.Response }"},V={type:"Promise<string>",metadata:"{resultExtractor: ResultExtractors.Text }"},M=`{
|
|
12
12
|
headers: { Accept: ContentTypeValues.TEXT_EVENT_STREAM },
|
|
13
13
|
resultExtractor: JsonEventStreamResultExtractor,
|
|
14
|
-
}`;function ue(o){C(o,et,tt)}function q(o,e,t=[],n=[],r){return e.addClass({name:o,isExported:!0,typeParameters:n,extends:r,decorators:[{name:"api",arguments:t}]})}function le(o,e){o.addImplements("ApiMetadataCapable"),o.addConstructor({parameters:[{name:"apiMetadata",type:"ApiMetadata",hasQuestionToken:e===void 0,scope:A.Scope.Public,isReadonly:!0,initializer:e}]})}const ot="@ahoo-wang/fetcher-eventstream";function de(o){C(o,ot,["JsonEventStreamResultExtractor","type JsonServerSentEventStream"])}function rt(o){let e=0,t=0;return o.commands.forEach(n=>{n.path.startsWith(k.ResourceAttributionPathSpec.TENANT)&&(e+=1),n.path.startsWith(k.ResourceAttributionPathSpec.OWNER)&&(t+=1)}),e===0&&t===0?"ResourceAttributionPathSpec.NONE":e>t?"ResourceAttributionPathSpec.TENANT":"ResourceAttributionPathSpec.OWNER"}function me(o,e,t,n){const r=`${t.contextAlias}/${t.aggregateName}/${n}.ts`;return ce(o,e,r)}function y(o,e){return`${R(o.aggregateName)}${e}`}function F(o){return o==="delete"?"del":o}const it="x-fetcher-method";function st(o,e){const t=o[it];if(t)return t;if(!o.operationId)return;const n=O(o.operationId);for(let r=n.length-1;r>=0;r--){const i=h(n.slice(r));if(!e(i))return i}return h(n)}class at{constructor(e){this.context=e,this.apiMetadataCtorInitializer=this.context.currentContextAlias?`{basePath:${D(this.context.currentContextAlias)}}`:void 0}defaultParameterRequestType="ParameterRequest";defaultReturnType=nt;apiMetadataCtorInitializer;generate(){this.context.logger.info("Starting API client generation");const e=this.resolveApiTags();this.context.logger.info(`Resolved ${e.size} API client tags: ${Array.from(e.keys()).join(", ")}`);const t=this.groupOperations(e);this.context.logger.info(`Grouped operations into ${t.size} tag groups`),this.generateApiClients(e,t),this.context.logger.success("API client generation completed")}generateApiClients(e,t){this.context.logger.info(`Generating ${t.size} API client classes`);let n=0;for(const[r,i]of t){n++,this.context.logger.progressWithCount(n,t.size,`Generating API client for tag: ${r}`);const s=e.get(r);this.generateApiClient(s,i)}}createApiClientFile(e){let t=e.path;return this.context.currentContextAlias&&(t=f.combineURLs(this.context.currentContextAlias,t)),t=f.combineURLs(t,`${e.name}ApiClient.ts`),this.context.logger.info(`Creating API client file: ${t}`),this.context.getOrCreateSourceFile(t)}generateApiClient(e,t){const n=d(e.name);this.context.logger.info(`Generating API client class: ${n.name}ApiClient with ${t.size} operations`);const r=this.createApiClientFile(n);ue(r),de(r);const i=q(n.name+"ApiClient",r);P(i,[e.description]),le(i,this.apiMetadataCtorInitializer),this.context.logger.info(`Processing ${t.size} operations for ${n.name}ApiClient`),t.forEach(s=>{this.processOperation(e,r,i,s)}),this.context.logger.success(`Completed API client: ${n.name}ApiClient`)}getMethodName(e,t){const n=st(t,r=>e.getMethod(r)!==void 0);if(!n)throw new Error(`Unable to resolve method name for apiClientClass:${e.getName()}.`);return n}resolveRequestType(e,t){if(!t.requestBody)return this.context.logger.info(`No request body found for operation ${t.operationId}, using default: ${this.defaultParameterRequestType}`),this.defaultParameterRequestType;let n;if(g(t.requestBody)?(this.context.logger.info(`Extracting request body from reference for operation: ${t.operationId}`),n=H(t.requestBody,this.context.openAPI.components)):n=t.requestBody,!n)return this.context.logger.info(`Request body extraction failed for operation ${t.operationId}, using default: ${this.defaultParameterRequestType}`),this.defaultParameterRequestType;if(n.content["multipart/form-data"])return this.context.logger.info(`Detected multipart/form-data content for operation ${t.operationId}, using ParameterRequest<FormData>`),"ParameterRequest<FormData>";if(n.content["application/json"]){const r=n.content["application/json"].schema;if(g(r)){const i=E(r);this.context.logger.info(`Adding import for request body model: ${i.name} from ${i.path}`),m(e,this.context.outputDir,i);const s=`ParameterRequest<${i.name}>`;return this.context.logger.info(`Resolved request type for operation ${t.operationId}: ${s}`),s}}return this.context.logger.info(`Using default request type for operation ${t.operationId}: ${this.defaultParameterRequestType}`),this.defaultParameterRequestType}resolveParameters(e,t,n){const r=De(n,this.context.openAPI.components).filter(a=>!this.context.isIgnoreApiClientPathParameters(e.name,a.name));this.context.logger.info(`Found ${r.length} path parameters for operation ${n.operationId}`);const i=r.map(a=>{const c=re(a);return this.context.logger.info(`Adding path parameter: ${a.name} (type: ${c})`),{name:a.name,type:c,hasQuestionToken:!1,decorators:[{name:"path",arguments:[`'${a.name}'`]}]}}),s=this.resolveRequestType(t,n);return this.context.logger.info(`Adding httpRequest parameter: ${s}`),i.push({name:"httpRequest",hasQuestionToken:s===this.defaultParameterRequestType,type:`${s}`,decorators:[{name:"request",arguments:[]}]}),this.context.logger.info("Adding attributes parameter: Record<string, any>"),i.push({name:"attributes",hasQuestionToken:!0,type:"Record<string, any>",decorators:[{name:"attribute",arguments:[]}]}),i}resolveSchemaReturnType(e,t){const n="Promise<any>";if(g(t)){const r=E(t);this.context.logger.info(`Adding import for response model: ${r.name} from ${r.path}`),m(e,this.context.outputDir,r);const i=`Promise<${r.name}>`;return this.context.logger.info(`Resolved reference return type: ${i}`),i}if(!t.type)return this.context.logger.info(`Schema has no type, using default return type: ${n}`),n;if(te(t.type)){const i=`Promise<${w(t.type)}>`;return this.context.logger.info(`Resolved primitive return type: ${i}`),i}return this.context.logger.info(`Using default return type: ${n}`),n}resolveReturnType(e,t){const n=G(t);if(!n)return this.context.logger.info(`No OK response found for operation ${t.operationId}, using default return type: ${this.defaultReturnType.type}`),this.defaultReturnType;const r=ee(n)||Ce(n);if(r){const s=this.resolveSchemaReturnType(e,r);return this.context.logger.info(`Resolved JSON/wildcard response return type for operation ${t.operationId}: ${s}`),{type:s,metadata:s===V.type?V.metadata:void 0}}const i=Ae(n);if(i){if(g(i)){const a=S(i,this.context.openAPI.components);if(N(a)&&g(a.items)){const c=E(a.items);this.context.logger.info(`Adding import for event stream model: ${c.name} from ${c.path}`),m(e,this.context.outputDir,c);const p=`Promise<JsonServerSentEventStream<${c.name.includes("ServerSentEvent")?`${c.name}['data']`:c.name}>>`;return this.context.logger.info(`Resolved event stream return type for operation ${t.operationId}: ${p}`),{type:p,metadata:M}}}const s="Promise<JsonServerSentEventStream<any>>";return this.context.logger.info(`Resolved generic event stream return type for operation ${t.operationId}: ${s}`),{type:s,metadata:M}}return this.context.logger.info(`Using default return type for operation ${t.operationId}: ${this.defaultReturnType.type}`),this.defaultReturnType}processOperation(e,t,n,r){this.context.logger.info(`Processing operation: ${r.operation.operationId} (${r.method} ${r.path})`);const i=this.getMethodName(n,r.operation);this.context.logger.info(`Generated method name: ${i}`);const s=this.resolveParameters(e,t,r.operation),a=this.resolveReturnType(t,r.operation),c=a.metadata?{name:F(r.method),arguments:[`'${r.path}'`,a.metadata]}:{name:F(r.method),arguments:[`'${r.path}'`]};this.context.logger.info(`Creating method with ${s.length} parameters, return type: ${a.type}`);const u=n.addMethod({name:i,decorators:[c],parameters:s,returnType:a.type,statements:[`throw autoGeneratedError(${s.map(p=>p.name).join(",")});`]});P(u,[r.operation.summary,r.operation.description,`- operationId: \`${r.operation.operationId}\``,`- path: \`${r.path}\``]),this.context.logger.success(`Operation method generated: ${i}`)}groupOperations(e){this.context.logger.info("Grouping operations by API client tags");const t=new Map,n=ne(this.context.openAPI.paths).filter(i=>{if(!i.operation.operationId)return!1;const s=i.operation.tags;return!s||s.length==0?!1:s.every(a=>e.has(a))});let r=0;for(const i of n)i.operation.tags.forEach(s=>{t.has(s)||t.set(s,new Set),t.get(s).add(i),r++});return this.context.logger.info(`Grouped ${r} operations into ${t.size} tag groups`),t}shouldIgnoreTag(e){return e==="wow"||e==="Actuator"||this.isAggregateTag(e)}resolveApiTags(){this.context.logger.info("Resolving API client tags from OpenAPI specification");const e=new Map,t=this.context.openAPI.tags?.length||0;for(const r of Object.values(this.context.openAPI.paths))oe(r).forEach(i=>{i.operation.tags?.forEach(s=>{!this.shouldIgnoreTag(s)&&!e.has(s)&&e.set(s,{name:s,description:""})})});let n=0;return this.context.openAPI.tags?.forEach(r=>{this.shouldIgnoreTag(r.name)?this.context.logger.info(`Excluded tag: ${r.name} (wow/Actuator/aggregate)`):(e.set(r.name,r),n++,this.context.logger.info(`Included API client tag: ${r.name}`))}),this.context.logger.info(`Resolved ${n} API client tags from ${t} total tags`),e}isAggregateTag(e){for(const t of this.context.contextAggregates.values())for(const n of t)if(n.aggregate.tag.name===e)return!0;return!1}}class ct{constructor(e){this.context=e}commandEndpointPathsSuffix="CommandEndpointPaths";defaultCommandClientOptionsName="DEFAULT_COMMAND_CLIENT_OPTIONS";generate(){const e=Array.from(this.context.contextAggregates.values()).reduce((n,r)=>n+r.size,0);this.context.logger.info("--- Generating Command Clients ---"),this.context.logger.progress(`Generating command clients for ${e} aggregates`);let t=0;for(const[,n]of this.context.contextAggregates)n.forEach(r=>{t++,this.context.logger.progressWithCount(t,e,`Processing command client for aggregate: ${r.aggregate.aggregateName}`),this.processAggregate(r)});this.context.logger.success("Command client generation completed")}processAggregate(e){this.context.logger.info(`Processing command client for aggregate: ${e.aggregate.aggregateName} in context: ${e.aggregate.contextAlias}`);const t=me(this.context.project,this.context.outputDir,e.aggregate,"commandClient");this.context.logger.info(`Processing command endpoint paths for ${e.commands.size} commands`);const n=this.processCommandEndpointPaths(t,e);this.processCommandTypes(t,e),this.context.logger.info(`Creating default command client options: ${this.defaultCommandClientOptionsName}`),t.addVariableStatement({declarationKind:A.VariableDeclarationKind.Const,declarations:[{name:this.defaultCommandClientOptionsName,type:"ApiMetadata",initializer:`{
|
|
14
|
+
}`;function ue(o){P(o,et,tt)}function q(o,e,t=[],n=[],r){return e.addClass({name:o,isExported:!0,typeParameters:n,extends:r,decorators:[{name:"api",arguments:t}]})}function le(o,e){o.addImplements("ApiMetadataCapable"),o.addConstructor({parameters:[{name:"apiMetadata",type:"ApiMetadata",hasQuestionToken:e===void 0,scope:C.Scope.Public,isReadonly:!0,initializer:e}]})}const ot="@ahoo-wang/fetcher-eventstream";function de(o){P(o,ot,["JsonEventStreamResultExtractor","type JsonServerSentEventStream"])}function rt(o){let e=0,t=0;return o.commands.forEach(n=>{n.path.startsWith(k.ResourceAttributionPathSpec.TENANT)&&(e+=1),n.path.startsWith(k.ResourceAttributionPathSpec.OWNER)&&(t+=1)}),e===0&&t===0?"ResourceAttributionPathSpec.NONE":e>t?"ResourceAttributionPathSpec.TENANT":"ResourceAttributionPathSpec.OWNER"}function me(o,e,t,n){const r=`${t.contextAlias}/${t.aggregateName}/${n}.ts`;return ce(o,e,r)}function y(o,e){return`${R(o.aggregateName)}${e}`}function F(o){return o==="delete"?"del":o}const it="x-fetcher-method";function st(o,e){const t=o[it];if(t)return t;if(!o.operationId)return;const n=O(o.operationId);for(let r=n.length-1;r>=0;r--){const i=h(n.slice(r));if(!e(i))return i}return h(n)}class at{constructor(e){this.context=e,this.apiMetadataCtorInitializer=this.context.currentContextAlias?`{basePath:${D(this.context.currentContextAlias)}}`:void 0}defaultParameterRequestType="ParameterRequest";defaultReturnType=nt;apiMetadataCtorInitializer;generate(){this.context.logger.info("Starting API client generation");const e=this.resolveApiTags();this.context.logger.info(`Resolved ${e.size} API client tags: ${Array.from(e.keys()).join(", ")}`);const t=this.groupOperations(e);this.context.logger.info(`Grouped operations into ${t.size} tag groups`),this.generateApiClients(e,t),this.context.logger.success("API client generation completed")}generateApiClients(e,t){this.context.logger.info(`Generating ${t.size} API client classes`);let n=0;for(const[r,i]of t){n++,this.context.logger.progressWithCount(n,t.size,`Generating API client for tag: ${r}`);const s=e.get(r);this.generateApiClient(s,i)}}createApiClientFile(e){let t=e.path;return this.context.currentContextAlias&&(t=f.combineURLs(this.context.currentContextAlias,t)),t=f.combineURLs(t,`${e.name}ApiClient.ts`),this.context.logger.info(`Creating API client file: ${t}`),this.context.getOrCreateSourceFile(t)}generateApiClient(e,t){const n=d(e.name);this.context.logger.info(`Generating API client class: ${n.name}ApiClient with ${t.size} operations`);const r=this.createApiClientFile(n);ue(r),de(r);const i=q(n.name+"ApiClient",r);$(i,[e.description]),le(i,this.apiMetadataCtorInitializer),this.context.logger.info(`Processing ${t.size} operations for ${n.name}ApiClient`),t.forEach(s=>{this.processOperation(e,r,i,s)}),this.context.logger.success(`Completed API client: ${n.name}ApiClient`)}getMethodName(e,t){const n=st(t,r=>e.getMethod(r)!==void 0);if(!n)throw new Error(`Unable to resolve method name for apiClientClass:${e.getName()}.`);return n}resolveRequestType(e,t){if(!t.requestBody)return this.context.logger.info(`No request body found for operation ${t.operationId}, using default: ${this.defaultParameterRequestType}`),this.defaultParameterRequestType;let n;if(g(t.requestBody)?(this.context.logger.info(`Extracting request body from reference for operation: ${t.operationId}`),n=H(t.requestBody,this.context.openAPI.components)):n=t.requestBody,!n)return this.context.logger.info(`Request body extraction failed for operation ${t.operationId}, using default: ${this.defaultParameterRequestType}`),this.defaultParameterRequestType;if(n.content["multipart/form-data"])return this.context.logger.info(`Detected multipart/form-data content for operation ${t.operationId}, using ParameterRequest<FormData>`),"ParameterRequest<FormData>";if(n.content["application/json"]){const r=n.content["application/json"].schema;if(g(r)){const i=E(r);this.context.logger.info(`Adding import for request body model: ${i.name} from ${i.path}`),m(e,this.context.outputDir,i);const s=`ParameterRequest<${i.name}>`;return this.context.logger.info(`Resolved request type for operation ${t.operationId}: ${s}`),s}}return this.context.logger.info(`Using default request type for operation ${t.operationId}: ${this.defaultParameterRequestType}`),this.defaultParameterRequestType}resolveParameters(e,t,n){const r=De(n,this.context.openAPI.components).filter(a=>!this.context.isIgnoreApiClientPathParameters(e.name,a.name));this.context.logger.info(`Found ${r.length} path parameters for operation ${n.operationId}`);const i=r.map(a=>{const c=re(a);return this.context.logger.info(`Adding path parameter: ${a.name} (type: ${c})`),{name:a.name,type:c,hasQuestionToken:!1,decorators:[{name:"path",arguments:[`'${a.name}'`]}]}}),s=this.resolveRequestType(t,n);return this.context.logger.info(`Adding httpRequest parameter: ${s}`),i.push({name:"httpRequest",hasQuestionToken:s===this.defaultParameterRequestType,type:`${s}`,decorators:[{name:"request",arguments:[]}]}),this.context.logger.info("Adding attributes parameter: Record<string, any>"),i.push({name:"attributes",hasQuestionToken:!0,type:"Record<string, any>",decorators:[{name:"attribute",arguments:[]}]}),i}resolveSchemaReturnType(e,t){const n="Promise<any>";if(g(t)){const r=E(t);this.context.logger.info(`Adding import for response model: ${r.name} from ${r.path}`),m(e,this.context.outputDir,r);const i=`Promise<${r.name}>`;return this.context.logger.info(`Resolved reference return type: ${i}`),i}if(!t.type)return this.context.logger.info(`Schema has no type, using default return type: ${n}`),n;if(te(t.type)){const i=`Promise<${w(t.type)}>`;return this.context.logger.info(`Resolved primitive return type: ${i}`),i}return this.context.logger.info(`Using default return type: ${n}`),n}resolveReturnType(e,t){const n=G(t);if(!n)return this.context.logger.info(`No OK response found for operation ${t.operationId}, using default return type: ${this.defaultReturnType.type}`),this.defaultReturnType;const r=ee(n)||Ce(n);if(r){const s=this.resolveSchemaReturnType(e,r);return this.context.logger.info(`Resolved JSON/wildcard response return type for operation ${t.operationId}: ${s}`),{type:s,metadata:s===V.type?V.metadata:void 0}}const i=Ae(n);if(i){if(g(i)){const a=S(i,this.context.openAPI.components);if(N(a)&&g(a.items)){const c=E(a.items);this.context.logger.info(`Adding import for event stream model: ${c.name} from ${c.path}`),m(e,this.context.outputDir,c);const p=`Promise<JsonServerSentEventStream<${c.name.includes("ServerSentEvent")?`${c.name}['data']`:c.name}>>`;return this.context.logger.info(`Resolved event stream return type for operation ${t.operationId}: ${p}`),{type:p,metadata:M}}}const s="Promise<JsonServerSentEventStream<any>>";return this.context.logger.info(`Resolved generic event stream return type for operation ${t.operationId}: ${s}`),{type:s,metadata:M}}return this.context.logger.info(`Using default return type for operation ${t.operationId}: ${this.defaultReturnType.type}`),this.defaultReturnType}processOperation(e,t,n,r){this.context.logger.info(`Processing operation: ${r.operation.operationId} (${r.method} ${r.path})`);const i=this.getMethodName(n,r.operation);this.context.logger.info(`Generated method name: ${i}`);const s=this.resolveParameters(e,t,r.operation),a=this.resolveReturnType(t,r.operation),c=a.metadata?{name:F(r.method),arguments:[`'${r.path}'`,a.metadata]}:{name:F(r.method),arguments:[`'${r.path}'`]};this.context.logger.info(`Creating method with ${s.length} parameters, return type: ${a.type}`);const u=n.addMethod({name:i,decorators:[c],parameters:s,returnType:a.type,statements:[`throw autoGeneratedError(${s.map(p=>p.name).join(",")});`]});$(u,[r.operation.summary,r.operation.description,`- operationId: \`${r.operation.operationId}\``,`- path: \`${r.path}\``]),this.context.logger.success(`Operation method generated: ${i}`)}groupOperations(e){this.context.logger.info("Grouping operations by API client tags");const t=new Map,n=ne(this.context.openAPI.paths).filter(i=>{if(!i.operation.operationId)return!1;const s=i.operation.tags;return!s||s.length==0?!1:s.every(a=>e.has(a))});let r=0;for(const i of n)i.operation.tags.forEach(s=>{t.has(s)||t.set(s,new Set),t.get(s).add(i),r++});return this.context.logger.info(`Grouped ${r} operations into ${t.size} tag groups`),t}shouldIgnoreTag(e){return e==="wow"||e==="Actuator"||this.isAggregateTag(e)}resolveApiTags(){this.context.logger.info("Resolving API client tags from OpenAPI specification");const e=new Map,t=this.context.openAPI.tags?.length||0;for(const r of Object.values(this.context.openAPI.paths))oe(r).forEach(i=>{i.operation.tags?.forEach(s=>{!this.shouldIgnoreTag(s)&&!e.has(s)&&e.set(s,{name:s,description:""})})});let n=0;return this.context.openAPI.tags?.forEach(r=>{this.shouldIgnoreTag(r.name)?this.context.logger.info(`Excluded tag: ${r.name} (wow/Actuator/aggregate)`):(e.set(r.name,r),n++,this.context.logger.info(`Included API client tag: ${r.name}`))}),this.context.logger.info(`Resolved ${n} API client tags from ${t} total tags`),e}isAggregateTag(e){for(const t of this.context.contextAggregates.values())for(const n of t)if(n.aggregate.tag.name===e)return!0;return!1}}class ct{constructor(e){this.context=e}commandEndpointPathsSuffix="CommandEndpointPaths";defaultCommandClientOptionsName="DEFAULT_COMMAND_CLIENT_OPTIONS";generate(){const e=Array.from(this.context.contextAggregates.values()).reduce((n,r)=>n+r.size,0);this.context.logger.info("--- Generating Command Clients ---"),this.context.logger.progress(`Generating command clients for ${e} aggregates`);let t=0;for(const[,n]of this.context.contextAggregates)n.forEach(r=>{t++,this.context.logger.progressWithCount(t,e,`Processing command client for aggregate: ${r.aggregate.aggregateName}`),this.processAggregate(r)});this.context.logger.success("Command client generation completed")}processAggregate(e){this.context.logger.info(`Processing command client for aggregate: ${e.aggregate.aggregateName} in context: ${e.aggregate.contextAlias}`);const t=me(this.context.project,this.context.outputDir,e.aggregate,"commandClient");this.context.logger.info(`Processing command endpoint paths for ${e.commands.size} commands`);const n=this.processCommandEndpointPaths(t,e);this.processCommandTypes(t,e),this.context.logger.info(`Creating default command client options: ${this.defaultCommandClientOptionsName}`),t.addVariableStatement({declarationKind:C.VariableDeclarationKind.Const,declarations:[{name:this.defaultCommandClientOptionsName,type:"ApiMetadata",initializer:`{
|
|
15
15
|
basePath: ${D(e.aggregate.contextAlias)}
|
|
16
|
-
}`}],isExported:!1}),this.context.logger.info(`Adding imports from ${
|
|
16
|
+
}`}],isExported:!1}),this.context.logger.info(`Adding imports from ${x}: CommandRequest, CommandResult, CommandResultEventStream, CommandBody, DeleteAggregateCommand, RecoverAggregateCommand`),t.addImportDeclaration({moduleSpecifier:x,namedImports:["CommandRequest","CommandResult","CommandResultEventStream","CommandBody","DeleteAggregateCommand","RecoverAggregateCommand"],isTypeOnly:!0}),this.context.logger.info("Adding import from @ahoo-wang/fetcher-eventstream: JsonEventStreamResultExtractor"),de(t),this.context.logger.info("Adding import from @ahoo-wang/fetcher: ContentTypeValues"),P(t,"@ahoo-wang/fetcher",["ContentTypeValues"]),this.context.logger.info("Adding imports from @ahoo-wang/fetcher-decorator: ApiMetadata types and decorators"),ue(t),this.context.logger.info("Generating standard command client class"),this.processCommandClient(t,e,n),this.context.logger.info("Generating stream command client class"),this.processStreamCommandClient(t,e),this.context.logger.success(`Command client generation completed for aggregate: ${e.aggregate.aggregateName}`)}resolveAggregateCommandEndpointPathsName(e){return y(e,this.commandEndpointPathsSuffix)}processCommandEndpointPaths(e,t){const n=this.resolveAggregateCommandEndpointPathsName(t.aggregate);this.context.logger.info(`Creating command endpoint paths enum: ${n}`);const r=e.addEnum({name:n,isExported:!0});return t.commands.forEach(i=>{this.context.logger.info(`Adding command endpoint: ${i.name.toUpperCase()} = '${i.path}'`),r.addMember({name:i.name.toUpperCase(),initializer:`'${i.path}'`})}),this.context.logger.success(`Command endpoint paths enum created with ${t.commands.size} entries`),n}resolveCommandTypeName(e){const t=d(e.schema.key);return[t,t.name+"Command"]}resolveCommandType(e,t){const[n,r]=this.resolveCommandTypeName(t);if(n.path===x)return;m(e,this.context.outputDir,n);let i=`${n.name}`;const s=Re(t.schema.schema).map(a=>`'${a}'`).join(" | ");s!==""&&(i=`PartialBy<${i},${s}>`),i=`CommandBody<${i}>`,e.addTypeAlias({name:r,type:`${i}`,isExported:!0})}processCommandTypes(e,t){t.commands.forEach(n=>{this.resolveCommandType(e,n)})}getEndpointPath(e,t){return`${e}.${t.name.toUpperCase()}`}processCommandClient(e,t,n){const r=y(t.aggregate,"CommandClient"),i=q(r,e,[],["R = CommandResult"]);le(i,this.defaultCommandClientOptionsName),t.commands.forEach(s=>{this.processCommandMethod(t,i,s,n)})}processStreamCommandClient(e,t){const n=y(t.aggregate,"CommandClient"),r=y(t.aggregate,"StreamCommandClient");q(r,e,["''",M],[],`${n}<CommandResultEventStream>`).addConstructor({parameters:[{name:"apiMetadata",type:"ApiMetadata",initializer:this.defaultCommandClientOptionsName}],statements:"super(apiMetadata);"})}resolveParameters(e,t){const[n,r]=this.resolveCommandTypeName(t);this.context.logger.info(`Adding import for command model: ${n.name} from path: ${n.path}`);const i=t.pathParameters.filter(s=>!this.context.isIgnoreCommandClientPathParameters(e.name,s.name)).map(s=>{const a=re(s);return this.context.logger.info(`Adding path parameter: ${s.name} (type: ${a})`),{name:s.name,type:a,hasQuestionToken:!1,decorators:[{name:"path",arguments:[`'${s.name}'`]}]}});return this.context.logger.info(`Adding command request parameter: commandRequest (type: CommandRequest<${r}>)`),i.push({name:"commandRequest",hasQuestionToken:Ee(t.schema.schema),type:`CommandRequest<${r}>`,decorators:[{name:"request",arguments:[]}]}),this.context.logger.info("Adding attributes parameter: attributes (type: Record<string, any>)"),i.push({name:"attributes",hasQuestionToken:!0,type:"Record<string, any>",decorators:[{name:"attribute",arguments:[]}]}),i}processCommandMethod(e,t,n,r){this.context.logger.info(`Generating command method: ${h(n.name)} for command: ${n.name}`),this.context.logger.info(`Command method details: HTTP ${n.method}, path: ${n.path}`);const i=this.resolveParameters(e.aggregate.tag,n),s=t.addMethod({name:h(n.name),decorators:[{name:F(n.method),arguments:[`${this.getEndpointPath(r,n)}`]}],parameters:i,returnType:"Promise<R>",statements:`throw autoGeneratedError(${i.map(a=>a.name).join(",")});`});this.context.logger.info(`Adding JSDoc documentation for method: ${h(n.name)}`),$(s,[n.summary,n.description,`- operationId: \`${n.operation.operationId}\``,`- path: \`${n.path}\``]),this.context.logger.success(`Command method generated: ${h(n.name)}`)}}class gt{constructor(e){this.context=e}domainEventTypeSuffix="DomainEventType";domainEventTypeMapTitleSuffix="DomainEventTypeMapTitle";generate(){const e=Array.from(this.context.contextAggregates.values()).reduce((n,r)=>n+r.size,0);this.context.logger.info("--- Generating Query Clients ---"),this.context.logger.progress(`Generating query clients for ${e} aggregates`);let t=0;for(const[,n]of this.context.contextAggregates)n.forEach(r=>{t++,this.context.logger.progressWithCount(t,e,`Processing query client for aggregate: ${r.aggregate.aggregateName}`),this.processQueryClient(r)});this.context.logger.success("Query client generation completed")}createClientFilePath(e,t){return me(this.context.project,this.context.outputDir,e,t)}processQueryClient(e){const t=this.createClientFilePath(e.aggregate,"queryClient");this.context.logger.info(`Processing query client for aggregate: ${e.aggregate.aggregateName} in context: ${e.aggregate.contextAlias}`),this.context.logger.info(`Adding imports from ${x}: QueryClientFactory, QueryClientOptions, ResourceAttributionPathSpec`),t.addImportDeclaration({moduleSpecifier:x,namedImports:["QueryClientFactory","QueryClientOptions","ResourceAttributionPathSpec"]});const n="DEFAULT_QUERY_CLIENT_OPTIONS";this.context.logger.info(`Creating default query client options: ${n}`),t.addVariableStatement({declarationKind:C.VariableDeclarationKind.Const,declarations:[{name:n,type:"QueryClientOptions",initializer:`{
|
|
17
17
|
contextAlias: ${D(e.aggregate.contextAlias)},
|
|
18
18
|
aggregateName: '${e.aggregate.aggregateName}',
|
|
19
19
|
resourceAttribution: ${rt(e)},
|
|
20
|
-
}`}],isExported:!1}),this.processAggregateDomainEventTypes(e,t);const r=this.processAggregateDomainEventType(e,t),i=`${h(e.aggregate.aggregateName)}QueryClientFactory`,s=d(e.state.key),a=d(e.fields.key);this.context.logger.info(`Adding import for state model: ${s.name} from path: ${s.path}`),m(t,this.context.outputDir,s),this.context.logger.info(`Adding import for fields model: ${a.name} from path: ${a.path}`),m(t,this.context.outputDir,a),this.context.logger.info(`Creating query client factory: ${i}`),t.addVariableStatement({declarationKind:
|
|
20
|
+
}`}],isExported:!1}),this.processAggregateDomainEventTypes(e,t);const r=this.processAggregateDomainEventType(e,t),i=`${h(e.aggregate.aggregateName)}QueryClientFactory`,s=d(e.state.key),a=d(e.fields.key);this.context.logger.info(`Adding import for state model: ${s.name} from path: ${s.path}`),m(t,this.context.outputDir,s),this.context.logger.info(`Adding import for fields model: ${a.name} from path: ${a.path}`),m(t,this.context.outputDir,a),this.context.logger.info(`Creating query client factory: ${i}`),t.addVariableStatement({declarationKind:C.VariableDeclarationKind.Const,declarations:[{name:i,initializer:`new QueryClientFactory<${s.name}, ${a.name} | string, ${r}>(${n})`}],isExported:!0}),this.context.logger.success(`Query client generation completed for aggregate: ${e.aggregate.aggregateName}`)}processAggregateDomainEventType(e,t){const n=[];this.context.logger.info(`Processing ${e.events.size} domain events for aggregate: ${e.aggregate.aggregateName}`);for(const s of e.events.values()){const a=d(s.schema.key);this.context.logger.info(`Adding import for event model: ${a.name} from path: ${a.path}`),m(t,this.context.outputDir,a),n.push(a)}const r=y(e.aggregate,this.domainEventTypeSuffix),i=n.map(s=>s.name).join(" | ");return this.context.logger.info(`Creating domain event types union: ${r} = ${i}`),t.addTypeAlias({isExported:!0,name:r,type:i}),r}processAggregateDomainEventTypes(e,t){const n=y(e.aggregate,this.domainEventTypeMapTitleSuffix),r=t.addEnum({name:n,isExported:!0});for(const i of e.events.values())r.addMember({name:i.name,initializer:`'${i.title}'`})}}class pt{constructor(e){this.context=e,this.queryClientGenerator=new gt(e),this.commandClientGenerator=new ct(e),this.apiClientGenerator=new at(e)}queryClientGenerator;commandClientGenerator;apiClientGenerator;generate(){this.context.logger.info("--- Generating Clients ---"),this.context.logger.progress(`Generating clients for ${this.context.contextAggregates.size} bounded contexts`);let e=0;for(const[t]of this.context.contextAggregates)e++,this.context.logger.progressWithCount(e,this.context.contextAggregates.size,`Processing bounded context: ${t}`,1);this.queryClientGenerator.generate(),this.commandClientGenerator.generate(),this.apiClientGenerator.generate(),this.context.logger.success("Client generation completed")}}class ut{project;openAPI;outputDir;contextAggregates;logger;config;defaultIgnorePathParameters=["tenantId","ownerId"];currentContextAlias;constructor(e){this.project=e.project,this.openAPI=e.openAPI,this.outputDir=e.outputDir,this.contextAggregates=e.contextAggregates,this.logger=e.logger,this.config=e.config??{},this.currentContextAlias=this.openAPI.info["x-wow-context-alias"]}getOrCreateSourceFile(e){return ce(this.project,this.outputDir,e)}isIgnoreApiClientPathParameters(e,t){return(this.config.apiClients?.[e]?.ignorePathParameters??this.defaultIgnorePathParameters).includes(t)}isIgnoreCommandClientPathParameters(e,t){return this.defaultIgnorePathParameters.includes(t)}}const fe="./fetcher-generator.config.json";class lt{constructor(e){this.options=e,this.project=new C.Project(e),this.options.logger.info(`Project instance created with tsConfigFilePath: ${this.options.tsConfigFilePath}`)}project;async generate(){this.options.logger.info("Starting code generation from OpenAPI specification"),this.options.logger.info(`Input path: ${this.options.inputPath}`),this.options.logger.info(`Output directory: ${this.options.outputDir}`),this.options.logger.info("Parsing OpenAPI specification");const e=await Me(this.options.inputPath);this.options.logger.info("OpenAPI specification parsed successfully"),this.options.logger.info("Resolving bounded context aggregates");const n=new He(e).resolve();this.options.logger.info(`Resolved ${n.size} bounded context aggregates`);const r=this.options.configPath??fe;let i={};try{this.options.logger.info(`Parsing configuration file: ${r}`),i=await qe(r)}catch(p){this.options.logger.info(`Configuration file parsing failed: ${p}`)}const s=new ut({openAPI:e,project:this.project,outputDir:this.options.outputDir,contextAggregates:n,logger:this.options.logger,config:i});this.options.logger.info("Generating models"),new Ze(s).generate(),this.options.logger.info("Models generated successfully"),this.options.logger.info("Generating clients"),new pt(s).generate(),this.options.logger.info("Clients generated successfully");const u=this.project.getDirectory(this.options.outputDir);if(!u){this.options.logger.info("Output directory not found.");return}this.options.logger.info("Generating index files"),this.generateIndex(u),this.options.logger.info("Index files generated successfully"),this.options.logger.info("Optimizing source files"),this.optimizeSourceFiles(u),this.options.logger.info("Source files optimized successfully"),this.options.logger.info("Saving project to disk"),await this.project.save(),this.options.logger.info("Code generation completed successfully")}generateIndex(e){this.options.logger.info(`Generating index files for output directory: ${this.options.outputDir}`),this.processDirectory(e),this.generateIndexForDirectory(e),this.options.logger.info("Index file generation completed")}processDirectory(e){const t=e.getDirectories();this.options.logger.info(`Processing ${t.length} subdirectories`);for(const n of t)this.options.logger.info(`Processing subdirectory: ${n.getPath()}`),this.generateIndexForDirectory(n),this.processDirectory(n)}generateIndexForDirectory(e){const t=e.getPath();this.options.logger.info(`Generating index for directory: ${t}`);const n=e.getSourceFiles().filter(a=>a.getBaseName().endsWith(".ts")&&a.getBaseName()!=="index.ts"),r=e.getDirectories();if(this.options.logger.info(`Found ${n.length} TypeScript files and ${r.length} subdirectories in ${t}`),n.length===0&&r.length===0){this.options.logger.info(`No files or subdirectories to export in ${t}, skipping index generation`);return}const i=`${t}/index.ts`,s=this.project.getSourceFile(i)||this.project.createSourceFile(i,"",{overwrite:!0});s.removeText();for(const a of n){const c=`./${a.getBaseNameWithoutExtension()}`;s.addExportDeclaration({moduleSpecifier:c,isTypeOnly:!1,namedExports:[]})}for(const a of r){const c=`./${a.getBaseName()}`;s.addExportDeclaration({moduleSpecifier:c,isTypeOnly:!1,namedExports:[]})}this.options.logger.info(`Index file generated for ${t} with ${n.length+r.length} exports`)}optimizeSourceFiles(e){const t=e.getDescendantSourceFiles();this.options.logger.info(`Optimizing ${t.length} source files in ${e.getPath()}`),t.forEach((n,r)=>{this.options.logger.info(`Optimizing file [${n.getFilePath()}] - ${r+1}/${t.length}`),n.formatText(),n.organizeImports(),n.fixMissingImports()}),this.options.logger.info("All source files optimized")}}exports.CodeGenerator=lt;exports.DEFAULT_CONFIG_PATH=fe;
|
|
21
21
|
//# sourceMappingURL=index.cjs.map
|