@ahoo-wang/wow-generator 9.9.0 → 10.0.0-alpha.3
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/codeGenerator-Ba5Cz8XW.cjs +31 -0
- package/dist/codeGenerator-Ba5Cz8XW.cjs.map +1 -0
- package/dist/{codeGenerator-CsWf0pZy.js → codeGenerator-CXBTLKZP.js} +1059 -613
- package/dist/codeGenerator-CXBTLKZP.js.map +1 -0
- package/dist/emitters/manifestClients.d.cts +15 -0
- package/dist/emitters/manifestClients.d.ts +15 -0
- package/dist/fetcherGeneratorCli.cjs +1 -1
- package/dist/fetcherGeneratorCli.js +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.js +1 -1
- package/dist/input/parsers.d.cts +13 -0
- package/dist/input/parsers.d.ts +13 -0
- package/dist/manifest/analyze.d.cts +132 -0
- package/dist/manifest/analyze.d.ts +132 -0
- package/dist/manifest/document.d.cts +89 -0
- package/dist/manifest/document.d.ts +89 -0
- package/dist/pipeline/codeGenerator.d.cts +7 -0
- package/dist/pipeline/codeGenerator.d.ts +7 -0
- package/dist/program-BnfzUfUQ.cjs +10 -0
- package/dist/{program-DWjbTSVJ.cjs.map → program-BnfzUfUQ.cjs.map} +1 -1
- package/dist/{program-64WQvLq1.js → program-CU0GCZqM.js} +4 -4
- package/dist/{program-64WQvLq1.js.map → program-CU0GCZqM.js.map} +1 -1
- package/package.json +3 -3
- package/dist/codeGenerator-BMyiC0tW.cjs +0 -23
- package/dist/codeGenerator-BMyiC0tW.cjs.map +0 -1
- package/dist/codeGenerator-CsWf0pZy.js.map +0 -1
- package/dist/program-DWjbTSVJ.cjs +0 -10
package/dist/cli.cjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./program-
|
|
2
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require("./program-BnfzUfUQ.cjs");e.r(),exports.collect=e.n,exports.runCLI=e.r,exports.setupCLI=e.i;
|
|
3
3
|
//# sourceMappingURL=cli.cjs.map
|
package/dist/cli.js
CHANGED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
let e=require("ts-morph"),t=require("path"),n=require("yaml"),r=require("fs"),i=require("node:path");var a=`./wow-generator.config.json`,o={success:0,internal:1,input:2,configuration:3,specification:4,output:5,interrupted:130},s=class extends Error{kind;constructor(e,t,n){super(t,n),this.kind=e,this.name=`GeneratorError`}get exitCode(){return o[this.kind]}};function c(e){return e instanceof Error?e.message:String(e)}function l(){return!!process.stdout?.isTTY&&!process.env.NO_COLOR}var u=class{level;decorate;constructor(e={}){this.level=e.level??`normal`,this.decorate=e.decorate??l()}format(e,t,n){let r=this.decorate?`${e} `:t?`${t}: `:``;return`${this.level===`verbose`?`[${new Date().toTimeString().slice(0,8)}] `:``}${r}${n}`}debug(e,...t){this.level===`verbose`&&console.log(this.format(`ℹ️ `,``,e),...t)}info(e,...t){this.level!==`quiet`&&console.log(this.format(`✅`,``,e),...t)}warn(e,...t){console.warn(this.format(`⚠️ `,`warning`,e),...t)}error(e,...t){console.error(this.format(`❌`,`error`,e),...t)}},d=class{debug(){}info(){}warn(){}error(){}},f=/[^\p{L}\p{N}$]+/u,p=new Set(`arguments.await.break.case.catch.class.const.continue.debugger.default.delete.do.else.enum.eval.export.extends.false.finally.for.function.if.implements.import.in.instanceof.interface.let.new.null.package.private.protected.public.return.static.super.switch.this.throw.true.try.typeof.var.void.while.with.yield`.split(`.`));function m(e){return/^[\p{ID_Start}$_][\p{ID_Continue}$\u200C\u200D]*$/u.test(e)&&!p.has(e)}function h(e){return/^\p{N}/u.test(e)?`_${e}`:e}function g(e){if(m(e))return e;let t=h(b(e)||`_`);return p.has(t)?`${t}_`:t}function ee(e){return/^\p{Lu}[\p{L}\p{N}$]*$/u.test(e)&&m(e)}function _(e){return h((Array.isArray(e)?e:[e]).map(e=>ee(e)?e:y(e)).join(``)||`_`)}function te(e){return e.split(f)}function v(e){return Array.isArray(e)?e.flatMap(e=>ne(te(e))):ne(te(e))}function ne(e){return e.flatMap(e=>{if(e.length===0)return[];let t=[],n=``;for(let r=0;r<e.length;r++){let i=e[r],a=/[A-Z]/.test(i),o=r>0&&/[a-z]/.test(e[r-1]);a&&o&&n?(t.push(n),n=i):n+=i}return n&&t.push(n),t})}function y(e){return e===``||e.length===0?``:v(e).filter(e=>e.length>0).map(e=>{let t=e.charAt(0),n=e.slice(1);return(/[a-zA-Z]/.test(t)?t.toUpperCase():t)+n.toLowerCase()}).join(``)}function b(e){let t=y(e);return t.charAt(0).toLowerCase()+t.slice(1)}function x(e){return e===``||Array.isArray(e)&&e.length===0?``:v(e).filter(e=>e.length>0).map(e=>e.toUpperCase()).join(`_`)}function S(e){return/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(e)?e:C(e)}function re(e){return/^\d+$/.test(e)?`NUM_${e}`:x(e)||e}function C(e){return`'${JSON.stringify(e).slice(1,-1).replace(/\\"/g,`"`).replace(/'/g,`\\'`)}'`}var ie=new Intl.Collator(`en-US`);function w(e,t){return ie.compare(e,t)}function T(e){return!!(e&&typeof e==`object`&&`$ref`in e)}function ae(e,t){let n=t.slice(1);try{n=decodeURIComponent(n)}catch{}if(n===``)return e;let r=e;for(let e of n.slice(1).split(`/`)){if(typeof r!=`object`||!r)return;let t=e.replace(/~1/g,`/`).replace(/~0/g,`~`);if(!Object.hasOwn(r,t))return;r=r[t]}return r}function oe(e){let t=[],n=new Set,r=(i,a)=>{if(typeof i!=`object`||!i||n.has(i))return;if(n.add(i),Array.isArray(i)){i.forEach((e,t)=>r(e,`${a}/${t}`));return}let o=i.$ref;typeof o==`string`&&o.startsWith(`#/components/`)&&ae(e,o)===void 0&&t.push({ref:o,location:a||`/`});for(let[e,t]of Object.entries(i))r(t,`${a}/${e.replace(/~/g,`~0`).replace(/\//g,`~1`)}`)};return r(e,``),t}var E=`#/components/`,se=`${E}parameters/`,ce=`${E}requestBodies/`,le=`${E}responses/`,ue=`${E}schemas/`;function de(e){return e.$ref.split(`/`).pop()}function D(e,t,n){let r=new Set,i=e;for(;T(i);){if(!i.$ref.startsWith(n))return;if(r.has(i.$ref))throw new s(`specification`,`Cyclic component reference: ${i.$ref}`);r.add(i.$ref),i=t?.[i.$ref.slice(n.length)]}return i}function O(e,t){return D(e,t.schemas,ue)}function fe(e,t){return D(e,t.responses,le)}function pe(e,t){return D(e,t.requestBodies,ce)}function me(e,t){return D(e,t.parameters,se)}function k(e,t){return{key:de(e),schema:O(e,t)}}var A=`application/json`,he=`text/event-stream`;function ge(e){return e.split(`;`)[0].trim().toLowerCase()}function _e(e){let t=ge(e);return t===`application/json`||/^application\/[^/]+\+json$/.test(t)}function ve(e){let t=ge(e);return t.startsWith(`text/`)&&t!==`text/event-stream`}function j(e,t,n=e=>ge(e)===t){if(!e)return;if(e[t])return e[t];let r=Object.keys(e).find(n);return r===void 0?void 0:e[r]}function ye(e,t){if(t&&!T(t))return j(t.content,e)?.schema}function be(e){if(e&&!T(e))return j(e.content,A,_e)?.schema}function xe(e){return ye(he,e)}function Se(e){return ye(`*/*`,e)}function Ce(e){return!e||T(e)?!1:Object.keys(e.content??{}).some(ve)}var we=[`string`,`number`,`integer`,`boolean`,`null`];function Te(e){return Array.isArray(e)?!0:we.includes(e)}function M(e){return Array.isArray(e.enum)&&e.enum.length>0}var Ee=`x-enum-text`;function De(e){return e[Ee]}function Oe(e){return e.type===`object`&&!!e.properties}function ke(e){return e.type===`array`&&!!e.items}function Ae(e){return Array.isArray(e.anyOf)&&e.anyOf.length>0}function je(e){return Array.isArray(e.oneOf)&&e.oneOf.length>0}function Me(e){return Array.isArray(e.allOf)&&e.allOf.length>0}function N(e){return Ae(e)||je(e)||Me(e)}function Ne(e){return e.includes(`|`)||e.includes(`&`)?`(${e})[]`:`${e}[]`}function Pe(e){return e.type===`object`&&!e.properties&&e.additionalProperties!==void 0}var Fe=`x-map-key-schema`;function Ie(e){return e[Fe]}function Le(e){return e.type===`object`?!e.properties||Object.keys(e.properties).length===0:!1}function Re(e){return e.readOnly===!0}function P(e){if(Array.isArray(e))return e.map(e=>P(e)).join(` | `);switch(e){case`string`:return`string`;case`number`:case`integer`:return`number`;case`boolean`:return`boolean`;case`null`:return`null`;default:return`any`}}function ze(e,t){let n=[],r=new Set,i=new Set,a=!1,o=e=>{if(!(!e||i.has(e)||a)){if(i.add(e),T(e))o(t&&O(e,t));else if(e.nullable||Array.isArray(e.type))a=!0;else{for(let t of e.required??[])r.add(t);for(let t of Object.keys(e.properties??{}))n.includes(t)||n.push(t);e.allOf?.forEach(o)}}};return o(e),a?[]:n.filter(e=>!r.has(e))}function Be(e,t){return e.operation.operationId&&t.operation.operationId?w(e.operation.operationId,t.operation.operationId):e.path&&t.path?w(e.path,t.path):e.method&&t.method?w(e.method,t.method):0}function Ve(e,t,n){let r=new Map;for(let i of[...e,...t]){let e=T(i)?n&&me(i,n):i,t=e?`${e.in}:${e.name}`:i.$ref;r.set(t,i)}return[...r.values()]}function He(e,t){let n=[];for(let[r,i]of Object.entries(e))Ue(i).forEach(e=>{n.push({method:e.method,operation:i.parameters?.length?{...e.operation,parameters:Ve(i.parameters,e.operation.parameters??[],t)}:e.operation,path:r})});return n.sort(Be)}function Ue(e){return[{method:`get`,operation:e.get},{method:`put`,operation:e.put},{method:`post`,operation:e.post},{method:`delete`,operation:e.delete},{method:`options`,operation:e.options},{method:`head`,operation:e.head},{method:`patch`,operation:e.patch},{method:`trace`,operation:e.trace}].filter(({operation:e})=>e!==void 0)}function We(e){let t=Object.keys(e.responses??{});if(t.includes(`200`))return`200`;let n=t.filter(e=>/^2\d\d$/.test(e)).sort();return n.length>0?n[0]:t.find(e=>e.toUpperCase()===`2XX`)}function Ge(e,t){let n=We(e),r=n?e.responses[n]:void 0;return t&&T(r)?fe(r,t):r}function Ke(e,t){return be(Ge(e,t))}function qe(e,t){return(e.parameters??[]).map(e=>T(e)?me(e,t):e).filter(e=>e!==void 0)}function Je(e,t){return e.parameters?e.parameters.map(e=>T(e)?me(e,t):e).filter(e=>e?.in===`path`):[]}function Ye(e,t){let n=t=>{let n=e.indexOf(`{${t.name}}`);return n<0?2**53-1:n};return[...t].sort((e,t)=>n(e)-n(t))}var Xe=`string`;function Ze(e){return!e.schema||T(e.schema)||!e.schema.type||!Te(e.schema.type)?Xe:P(e.schema.type)}var Qe=`8.10`,$e=`x-wow-context-alias`;function et(e){return e.info[$e]}function tt(e){let t=e.split(`.`);return t.length!=2||t[0].length===0||t[1].length===0?null:t}function nt(e){let t=tt(e.name);return t?{tag:e,contextAlias:t[0],aggregateName:t[1]}:null}function rt(e){if(!e)return null;let t=e.split(`.`);return t.length==3?t[2]:null}var it=`.snapshot_state.single`,at=`.snapshot.count`,ot=`x-wow-query-fields`,st=/^(?:\/tenant\/\{tenantId\})?(?:\/owner\/\{ownerId\})?\/(.+?)\/snapshot(?:\/|$)/,ct=[`MaterializedSnapshot`,`MaterializedSnapshotPagedList`,`MaterializedSnapshotCursorPage`,`MaterializedSnapshotServerSentEventNonNullData`,`PagedList`,`ServerSentEventNonNullData`,`Snapshot`,`StateEvent`];function lt(e){return ct.map(t=>e+t)}function ut(e,t,n){return e!==`wow.api.query.PagedList`&&e.startsWith(`wow.api.query.`)&&e.endsWith(`PagedList`)||e.startsWith(`wow.api.query.Operator`)&&e.endsWith(`Map`)?!1:e.startsWith(`wow.`)||e.endsWith(`AggregatedCondition`)||e.endsWith(`AggregatedDomainEventStream`)||e.endsWith(`AggregatedDomainEventStreamPagedList`)||e.endsWith(`AggregatedDomainEventStreamCursorPage`)||e.endsWith(`AggregatedDomainEventStreamServerSentEventNonNullData`)||e.endsWith(`AggregatedListQuery`)||e.endsWith(`AggregatedPagedQuery`)||e.endsWith(`AggregatedSingleQuery`)?!0:n.has(t())}var F=`@ahoo-wang/wow-client`,dt=`@ahoo-wang/wow-client/legacy`,ft=new Set([`Condition`,`ConditionOptions`,`ListQuery`,`Operator`,`PagedQuery`]),pt={"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.abac.DefaultApplyResourceTags":`ApplyResourceTags`,"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.api.query.DynamicDocument":`DynamicDocument`,"wow.api.query.DynamicDocumentArray":`DynamicDocumentArray`,"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 mt(e,t){let n=pt[e];if(t&&`filter`in t&&(e===`wow.api.query.ListQuery`?n=`FilterListQuery`:e===`wow.api.query.PagedQuery`&&(n=`FilterPagedQuery`)),n)return{name:n,path:ft.has(n)?dt:F}}var ht=new Set([`wow`,`Actuator`]),gt=[`tenantId`,`ownerId`];function _t(e){let t=0,n=0;return e.commands.forEach(e=>{e.path.startsWith(`/tenant/{tenantId}`)&&(t+=1),e.path.startsWith(`/owner/{ownerId}`)&&(n+=1)}),t===0&&n===0?`ResourceAttributionPathSpec.NONE`:t>n?`ResourceAttributionPathSpec.TENANT`:`ResourceAttributionPathSpec.OWNER`}function vt(e,t){return`${e.contextAlias}/${e.aggregateName}/${t}.ts`}function I(e,t){return`${_(e.aggregateName)}${t}`}var yt=`x-fetcher-method`;function bt(e,t){let n=t??e[`x-fetcher-method`];if(n!==void 0){if(typeof n!=`string`||!xt(n))throw new s(`specification`,`${yt} of ${e.operationId??`an operation`} is ${JSON.stringify(n)}, which is not a valid method name.`);return n}if(!e.operationId)return;let r=b(e.operationId.split(`.`).pop())||`_`;return/^\p{N}/u.test(r)?`_${r}`:r}function xt(e){return m(e)||/^[a-z]+$/.test(e)}function St(e,t){let n=g(e),r=n;for(let e=2;t.has(r);e++)r=`${n}${e}`;return t.add(r),r}function L(e,t){if(!e)return{name:``,path:`/`};let n=mt(e,t?.properties);if(n)return n;let r=e.split(`.`),i=-1;for(let e=0;e<r.length;e++)if(r[e]&&/^[A-Z]/.test(r[e])){i=e;break}let a=r.slice(0,i),o=a.length>0?`/${a.join(`/`)}`:`/`;return{name:_(r.slice(i)),path:o}}function Ct(e,t){if(!e.$ref.startsWith(ue))throw new s(`specification`,`Unsupported schema reference: ${e.$ref}. Bundle or inline external schemas before generation.`);return L(de(e),t?O(e,t):void 0)}function wt(e){let t=`${x(e)}_BOUNDED_CONTEXT_ALIAS`;return/^\p{N}/u.test(t)?`_${t}`:t}var Tt=`Command`;function Et(e,t){return[...t.contexts.values()].flatMap(t=>[...t].map(t=>Dt(e,t)))}function Dt(e,t){let{contextAlias:n,aggregateName:r}=t.aggregate;return{contextAlias:n,aggregateName:r,context:{alias:n,constantName:wt(n)},commandClient:Ot(e,t),queryClient:Nt(t)}}function Ot(e,t){let n=t.aggregate,r=jt(t);return{file:vt(n,`commandClient`),endpointPathsName:I(n,`CommandEndpointPaths`),className:I(n,`CommandClient`),streamClassName:I(n,`StreamCommandClient`),commands:[...t.commands.values()].map(t=>{let n=L(t.schema.key),i=new Set([`commandRequest`,`attributes`]);return{path:t.path,endpointMember:r.get(t),httpMethod:t.method,methodName:Mt(t),typeName:kt(n),body:n,bodyKey:t.schema.key,optionalFields:ze(t.schema.schema,e.components),requestOptional:Le(t.schema.schema),pathParameters:Ye(t.path,t.pathParameters).filter(e=>!gt.includes(e.name)).map(e=>({name:St(e.name,i),pathName:e.name,type:Ze(e)})),docs:[t.summary,t.description,`- operationId: \`${t.operation.operationId}\``,`- path: \`${t.path}\``]}})}}function kt(e){return e.path===`@ahoo-wang/wow-client`?`${e.name}Command`:e.name.endsWith(Tt)?void 0:`${e.name}${Tt}`}function At(e,t){for(let n of e){let e=`/${n.contextAlias}/${n.aggregateName}`,r=new Map;for(let n of t)n.info.path===e&&r.set(n.info.name,{holder:`the model of schema ${n.key}`,key:n.key});for(let{body:e,bodyKey:t}of n.commandClient.commands)e.path!==`@ahoo-wang/wow-client`&&r.set(e.name,{holder:`the model of schema ${t}`,key:t});for(let e of n.commandClient.commands){let{typeName:t,bodyKey:i}=e;if(t===void 0||e.body.path===`@ahoo-wang/wow-client`)continue;let a=r.get(t);if(a!==void 0&&a.bodyKey!==i)throw new s(`specification`,`Command ${e.methodName}() of aggregate ${n.contextAlias}.${n.aggregateName} generates the type ${t} for its body ${i}, but ${a.holder} already has that name. Rename the schema ${i} or ${a.key} in the document.`);r.set(t,{holder:`the type of command ${e.methodName}()`,key:i,bodyKey:i})}}}function jt(e){let t=new Map,n=new Set;for(let r of e.commands.values()){let e=r.name.toUpperCase().replace(/[^\p{L}\p{N}_$]/gu,`_`);(!e||/^\p{N}/u.test(e))&&(e=`_${e}`);let i=e;for(let t=2;n.has(i);t++)i=`${e}_${t}`;n.add(i),t.set(r,i)}return t}function Mt(e){let t=b(e.name)||`_`;return/^\p{N}/u.test(t)?`_${t}`:t}function Nt(e){let t=e.aggregate,n=b(t.aggregateName)||`_`;return{file:vt(t,`queryClient`),resourceName:e.resourceName,resourceAttribution:_t(e),state:L(e.state.key),fields:L(e.fields.key),eventTitlesName:I(t,`DomainEventTypeMapTitle`),eventTypeName:I(t,`DomainEventType`),events:[...e.events.values()].map(e=>({memberName:S(e.name),title:e.title,body:L(e.schema.key)})),factoryName:`${/^\p{N}/u.test(n)?`_`:``}${n}QueryClientFactory`}}function R(e,t){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)?t:t?`${e.replace(/\/+$/,``)}/${t.replace(/^\/+/,``)}`:e}var Pt=`types.ts`;function Ft(e){return R(e.path,Pt)}function It(e){return`${e}/boundedContext.ts`}function Lt(e){return e.contextAlias!==void 0||e.aggregateTags.size>0}function Rt(e,t){return t?{...e,...t}:e}var zt=[`httpRequest`,`attributes`];function Bt(e,t,n,r){return new Vt(e,t,n,r).clients()}var Vt=class{document;wow;config;warnings;basePath;wowDocument;constructor(e,t,n,r){this.document=e,this.wow=t,this.config=n,this.warnings=r,this.wowDocument=Lt(t),t.contextAlias&&(this.basePath={alias:t.contextAlias,constantName:wt(t.contextAlias)})}clients(){let e=this.tags(),t=this.groupOperations(e),n=new Map;return[...t.keys()].sort().map(r=>{let i=L(r),a=i;for(let e=2;n.has(Ut(a));e++)a={...i,name:`${i.name}${e}`};return a!==i&&this.warnings.push(`Tags ${n.get(Ut(i))} and ${r} both name the API client ${i.name}ApiClient; ${r} generates ${a.name}ApiClient.`),n.set(Ut(a),r),this.client(e.get(r),a,[...t.get(r)])})}client(e,t,n){let r=`${t.name}ApiClient`,i=t.path;this.wow.contextAlias&&(i=R(this.wow.contextAlias,i)),i=R(i,Ht(r));let a=new Map;return{tagName:e.name,className:r,file:i,description:e.description,basePath:this.basePath,methods:n.map(t=>this.method(e,r,t,a))}}method(e,t,n,r){let{operation:i}=n,a=this.methodName(e,t,n,r),o=new Set(zt),s=this.parameters(e,n,o),c=this.body(i,o),l=[...s.filter(({parameter:e})=>e.required),...s.filter(({parameter:e})=>!e.required)].filter(({description:e})=>e);return{name:a,httpMethod:n.method,path:n.path,parameters:s.map(({parameter:e})=>e),body:c,returns:this.returns(i),docs:[i.summary,i.description,`- operationId: \`${i.operationId}\``,`- path: \`${n.path}\``,...l.map(({parameter:e,description:t})=>`@param ${e.name} - ${t.replace(/\s*\n\s*/g,` `)}`)]}}methodName(e,t,n,r){let i=n.operation.operationId,a=bt(n.operation,this.config.apiClients?.[e.name]?.methodNames?.[i]),o=r.get(a);if(o!==void 0)throw new s(`specification`,`Operations ${o} and ${i} of tag ${e.name} both generate the method ${t}.${a}(). Name one of them with apiClients["${e.name}"].methodNames in the generator configuration, or with the x-fetcher-method extension.`);return r.set(a,i),a}parameters(e,t,n){let r=qe(t.operation,this.document.components??{}),i=[];for(let a of[`path`,`query`,`header`]){let o=r.filter(e=>e.in===a);for(let r of a===`path`?Ye(t.path,o):o)a===`path`&&this.ignoresPathParameter(e.name,r.name)||i.push({parameter:{name:St(r.name,n),location:a,parameterName:r.name,schema:r.schema,required:a===`path`||r.required===!0},description:r.description})}let a=r.filter(e=>e.in===`cookie`);return a.length>0&&this.warnings.push(`${t.method.toUpperCase()} ${t.path} leaves out its cookie parameter(s) ${a.map(e=>e.name).join(`, `)}: the browser sends cookies, and fetch cannot set them.`),i}ignoresPathParameter(e,t){return(this.config.apiClients?.[e]?.ignorePathParameters??(this.wowDocument?gt:[])).includes(t)}body(e,t){if(!e.requestBody)return;let n=T(e.requestBody)?pe(e.requestBody,this.document.components):e.requestBody;if(!n)return;let r=n.required===!0,i=n.content??{},a=j(i,A,_e),o=St(`body`,t);return a?.schema?{name:o,required:r,content:{kind:`json`,schema:a.schema,optionalFields:ze(a.schema,this.document.components)}}:j(i,`multipart/form-data`)?{name:o,required:r,content:{kind:`formData`}}:j(i,`application/x-www-form-urlencoded`)?{name:o,required:r,content:{kind:`urlEncoded`}}:Object.keys(i).some(ve)?{name:o,required:r,content:{kind:`text`}}:{name:o,required:r,content:{kind:`binary`}}}returns(e){let t=Ge(e,this.document.components);if(!t)return{kind:`response`};let n=be(t),r=n||Se(t);if(r)return{kind:`json`,schema:r,wildcard:!n};let i=xe(t);if(i){if(T(i)){let e=O(i,this.document.components);if(ke(e)&&T(e.items)){let t=Ct(e.items,this.document.components);return{kind:`eventStream`,items:e.items,serverSentEvent:t.name.includes(`ServerSentEvent`)}}}return{kind:`eventStream`,serverSentEvent:!1}}return Ce(t)?{kind:`text`}:{kind:`response`}}groupOperations(e){let t=new Map;for(let n of this.document.endpoints){let r=`${n.method.toUpperCase()} ${n.path}`,i=n.operation.tags??[];if(i.length===0){this.warnings.push(`Skipping ${r}: it has no tag, and the tag names its API client.`);continue}let a=i.filter(t=>e.has(t));if(!(a.length<i.length)){if(!n.operation.operationId)this.warnings.push(`Skipping ${r}: it has no operationId, and the operationId names its method.`);else for(let e of a)t.has(e)||t.set(e,new Set),t.get(e).add(n)}}return t}tags(){let e=new Map;for(let{operation:t}of this.document.endpoints)t.tags?.forEach(t=>{!this.ignoresTag(t)&&!e.has(t)&&e.set(t,{name:t,description:``})});return this.document.openAPI.tags?.forEach(t=>{this.ignoresTag(t.name)||e.set(t.name,t)}),e}ignoresTag(e){return ht.has(e)||this.wow.aggregateTags.has(e)}};function Ht(e){return`${e.charAt(0).toLowerCase()}${e.slice(1)}.ts`}function Ut(e){return`${e.path}/${e.name}`.toLowerCase()}function Wt(e){let t=new Set(e.contexts.keys());return e.contextAlias&&t.add(e.contextAlias),[...t].sort().map(e=>({alias:e,constantName:wt(e),file:It(e)}))}function Gt(e,t){let n=e.components?.schemas;if(!n)return[];let r=qt(t),i=Kt(e,t),a=Object.keys(n).filter(e=>!ut(e,()=>L(e).name,r)||!e.startsWith(`wow.`)&&i.has(e));Jt(a);let o=Yt(t);return a.map(e=>{let r=n[e],i=L(e);return{key:e,info:i,file:Ft(i),schema:r,docSchema:Rt(r,t.schemaDocOverrides.get(e)),emptyMessageBody:o.has(e)&&Xt(r)}})}function Kt(e,t){let n=new Set,r=new Set,i=e.components??{},a=e=>{if(typeof e!=`object`||!e||r.has(e))return;if(r.add(e),Array.isArray(e)){e.forEach(a);return}let{$ref:t}=e;if(typeof t==`string`&&t.startsWith(`#/components/`)){let[e,...r]=t.slice(E.length).split(`/`),o=r.join(`/`);e===`schemas`&&n.add(o),a(i[e]?.[o])}Object.values(e).forEach(a)};for(let{operation:n}of e.endpoints){let e=n.tags??[];e.length>0&&e.every(e=>!ht.has(e)&&!t.aggregateTags.has(e))&&a(n)}return n}function qt(e){let t=new Set;for(let n of e.contexts.values())for(let e of n)lt(L(e.state.key).name).forEach(e=>t.add(e));return t}function Jt(e){let t=new Map;for(let n of e){let e=L(n),r=`${e.path===`/`?``:e.path}/${e.name}`;t.set(r,[...t.get(r)??[],n])}let n=[...t].filter(([,e])=>e.length>1);if(n.length!==0)throw new s(`specification`,`Schemas generate the same model: ${n.map(([e,t])=>`${t.join(`, `)} → ${e}`).join(`; `)}. Rename all but one of them in the document.`)}function Yt(e){return new Set([...e.contexts.values()].flatMap(e=>[...e].flatMap(e=>[...[...e.commands.values()].map(e=>e.schema.key),...[...e.events.values()].map(e=>e.schema.key)])))}function Xt(e){return!T(e)&&e.type===`object`&&Object.keys(e.properties??{}).length===0&&(e.additionalProperties===void 0||e.additionalProperties===!1)&&!e.required?.length&&!N(e)&&e.enum===void 0&&e.const===void 0}function Zt(e,t,n){let r=[],i=Wt(t),a=Gt(e,t),o=Et(e,t);return At(o,a),{model:{contexts:i,models:a,aggregates:o,apiClients:Bt(e,t,n,r)},warnings:r}}var Qt=class{declarations=new Map;add(e,t){let n=this.declarations.get(e);n||(n=[],this.declarations.set(e,n));for(let e of t)n.some(t=>t.name===e)||n.push({name:e});return n}apply(e){for(let{moduleSpecifier:t,name:n,alias:r}of e){let e=this.add(t,[n]).find(e=>e.name===n);r!==void 0&&(e.alias=r)}}entries(){return[...this.declarations].flatMap(([e,t])=>t.map(({name:t,alias:n})=>n===void 0?{moduleSpecifier:e,name:t}:{moduleSpecifier:e,name:t,alias:n}))}localNames(e){return[...this.declarations.values()].flat().filter(t=>t!==e).map(e=>e.alias??e.name)}structures(){return[...this.declarations].map(([e,t])=>({moduleSpecifier:e,namedImports:t.map(({name:e,alias:t})=>t===void 0?e:{name:e,alias:t})}))}},$t=class{sourceFile;imports=new Qt;statements=[];constructor(e){this.sourceFile=e}get directoryPath(){return this.sourceFile.getDirectoryPath()}add(e){return this.statements.push(e),e}build(){let t=[],n;for(let r of this.imports.structures())n={...r,kind:e.StructureKind.ImportDeclaration},t.push(n);for(let e of this.statements)n&&nn(n,e)&&t.push(tn),t.push(e),n=e;return t.length>0&&this.sourceFile.addStatements(t),this.sourceFile}},en=class{open;modules=new Map;constructor(e){this.open=e}module(e){let t=this.open(e),n=t.getFilePath(),r=this.modules.get(n);return r||(r=new $t(t),this.modules.set(n,r)),r}build(){for(let e of this.modules.values())e.build();this.modules.clear()}},tn=e=>{e.blankLineIfLastNot()};function nn(t,n){if(typeof n==`string`)return!1;switch(n.kind){case e.StructureKind.TypeAlias:case e.StructureKind.VariableStatement:return typeof t==`string`||t.kind!==n.kind;default:return!0}}function rn(e){return e.map(e=>({...e,initializer:`${e.initializer},`}))}function an(e,t){return{name:`[key: string]`,type:e,docs:t}}var on=`@`;function z(e,t,n){return e.imports.add(t,n)}function B(e,t,n){return z(e,sn(e,t,n),[n.name])}function sn(e,n,r){return r.path.startsWith(on)?r.path:cn(e.directoryPath,(0,t.join)(n,r.path,Pt))}function cn(e,n){let r=(0,t.relative)(e,n).split(t.sep).join(`/`);return r=r.endsWith(`.ts`)?r.replace(/\.ts$/,`.js`):`${r}/index.js`,r.startsWith(`.`)?r:`./${r}`}function ln(e,n,r,i){return z(e,cn(e.directoryPath,(0,t.join)(n,It(r))),[i])}function un(e,t=`
|
|
2
|
+
`){if(!Array.isArray(e))return;let n=e.filter(e=>typeof e==`string`&&e.length>0).map(dn);return n.length>0?n.join(t):void 0}function dn(e){return e.replace(/\*\//g,`*\\/`)}function V(e,t){let n=un(t);n&&(e.docs=[...e.docs??[],n])}function fn(e,t,n=!1){e=hn(e);let r=[e.title,e.description];return t&&r.push(`- key: ${t}`),n&&gn(r,e),e.format&&r.push(e.format===`int64`?`- format: int64 (a value beyond Number.MAX_SAFE_INTEGER loses precision)`:`- format: ${e.format}`),_n(r,e,`default`),_n(r,e,`example`),yn(r,e),bn(r,e),xn(r,e),r}function pn(e,t,n){V(e,fn(t,n))}function mn(e,t,n,r=!1){let i=fn(t,n,!0);r&&vn(i,`schema`,t),V(e,i)}function hn(e){for(let t of[`anyOf`,`oneOf`]){let n=e[t];if(!Array.isArray(n)||n.length<2)continue;let r=n.filter(e=>`$ref`in e||e.type!==`null`),[i]=r;if(r.length!==1||`$ref`in i)continue;let a={...i};for(let[n,r]of Object.entries(e))n!==t&&r!==void 0&&(a[n]=r);return a}return e}function gn(e,t){let n=t.required??[];(n.length||Object.keys(t.properties??{}).length)&&e.push(`- required: ${n.length?n.join(`, `):`(none)`}`)}function _n(e,t,n){let r=t[n];r&&(typeof r==`object`?vn(e,n,r):e.push(`- ${n}: \`${r}\``))}function vn(e,t,n){e.push(`- ${t}: `),e.push("```json"),e.push(JSON.stringify(n,null,2)),e.push("```")}function yn(e,t){let n=[`- Numeric Constraints`];t.minimum!==void 0&&n.push(` - minimum: ${t.minimum}`),t.maximum!==void 0&&n.push(` - maximum: ${t.maximum}`),t.exclusiveMinimum!==void 0&&n.push(` - exclusiveMinimum: ${t.exclusiveMinimum}`),t.exclusiveMaximum!==void 0&&n.push(` - exclusiveMaximum: ${t.exclusiveMaximum}`),t.multipleOf!==void 0&&n.push(` - multipleOf: ${t.multipleOf}`),n.length!==1&&e.push(...n)}function bn(e,t){let n=[`- String Constraints`];t.minLength!==void 0&&n.push(` - minLength: ${t.minLength}`),t.maxLength!==void 0&&n.push(` - maxLength: ${t.maxLength}`),t.pattern!==void 0&&n.push(` - pattern: ${t.pattern}`),n.length!==1&&e.push(...n)}function xn(e,t){let n=[`- Array Constraints`];t.minItems!==void 0&&n.push(` - minItems: ${t.minItems}`),t.maxItems!==void 0&&n.push(` - maxItems: ${t.maxItems}`),t.uniqueItems!==void 0&&n.push(` - uniqueItems: ${t.uniqueItems}`),n.length!==1&&e.push(...n)}function Sn(e,t){let n;return{components:e,modelOf:n=>t.ofReference(n,e),namesAt(r){if(!n){n=new Map;for(let r of Object.keys(e?.schemas??{})){let e=t.ofKey(r),i=n.get(e.path);i||(i=[],n.set(e.path,i)),i.push(e.name,`${e.name}EnumText`)}}return n.get(r)??[]}}}var Cn=[`Array`,`Blob`,`Exclude`,`FormData`,`Partial`,`Promise`,`ReadonlyArray`,`Record`,`Response`,`Symbol`,`URLSearchParams`],wn=new Set([`string`,`number`,`boolean`]),Tn=new Set([`$comment`,`$schema`,`default`,`deprecated`,`description`,`example`,`examples`,`externalDocs`,`readOnly`,`title`,`writeOnly`,`xml`]);function En(e,t){return e===void 0?!1:typeof e==`string`||typeof t==`string`?e===t:e.primitive===t.primitive}function H(e,t,n=new Set){if(T(e)){if(!t||n.has(e.$ref))return;n.add(e.$ref);let r=O(e,t);return r?H(r,t,n):void 0}if(!(e.nullable||Array.isArray(e.type))){if(Me(e)&&e.type===void 0){let r=e.allOf.map(e=>H(e,t,n)),[i]=r;return i!==void 0&&r.every(e=>En(e,i))?i:void 0}if(!(N(e)||e.const!==void 0||e.type===void 0))return e.type===`object`?`object`:e.type===`array`?`array`:{primitive:P(e.type)}}}function Dn(e,t,n){let r=H(t,n);if(typeof r!=`object`)return!1;let i=H(e,n);return i===void 0||typeof i==`string`||i.primitive!==r.primitive}function On(e,t){let n=e.additionalProperties;return typeof n==`object`&&Object.values(e.properties??{}).some(e=>Dn(e,n,t))}function kn(e){return e.nullable!==!0||M(e)||!N(e)?!1:[e.allOf,e.oneOf,e.anyOf].every(e=>e===void 0||e.every(T))}function An(e,t){return t.type===void 0||e===null&&t.nullable?!0:[t.type].flat().some(t=>t===`null`?e===null:t===`array`?Array.isArray(e):t===`object`?typeof e==`object`&&!!e&&!Array.isArray(e):t===`integer`?typeof e==`number`&&Number.isInteger(e):typeof e===t)}function U(t){if(typeof t==`string`)return new e.CodeBlockWriter({useSingleQuote:!0}).quote(t).toString();if(Array.isArray(t))return`[${t.map(e=>U(e)).join(`, `)}]`;if(typeof t==`object`&&t){let e=Object.entries(t).map(([e,t])=>`${S(e)}: ${U(t)}`);return e.length?`{ ${e.join(`; `)}; readonly [globalThis.Symbol.iterator]?: never }`:`globalThis.Record<string, never>`}return JSON.stringify(t)??`never`}var jn=class{scope;entries;requested=[];constructor(e){this.scope=e,this.entries=e.imports.entries().map(e=>({...e}))}get components(){return this.scope.context.components}imports(){return this.requested.map(({moduleSpecifier:e,name:t,alias:n})=>n===void 0?{moduleSpecifier:e,name:t}:{moduleSpecifier:e,name:t,alias:n})}request(e){this.requested.includes(e)||this.requested.push(e)}reference(e){let t=this.scope.context.modelOf(e),{owner:n}=this.scope;if(n.path===t.path)return t.name;let r=this.scope.specifierOf(t),i=this.entries.find(e=>e.moduleSpecifier===r&&e.name===t.name);if(i||(i={moduleSpecifier:r,name:t.name},this.entries.push(i)),this.request(i),i.alias)return i.alias;let a=new Set([...Cn,n.name,...n.path===void 0?[]:this.scope.context.namesAt(n.path),...this.entries.filter(e=>e!==i).map(e=>e.alias??e.name)]);if(!a.has(t.name))return t.name;let o=`_${t.name}`;for(;a.has(o);)o=`_${o}`;return i.alias=o,o}additionalProperties(e){return e.additionalProperties===!1||e.additionalProperties===void 0&&!e.required?.some(t=>!Object.hasOwn(e.properties??{},t))?``:e.additionalProperties===!0||e.additionalProperties===void 0?`[key: string]: any`:`[key: string]: ${this.additionalPropertyType(e)}`}additionalPropertyType(e){return this.type(typeof e.additionalProperties==`object`?e.additionalProperties:{})}requiredAdditionalPropertyType(e){return e.additionalProperties===!1?`never`:typeof e.additionalProperties==`object`?this.type(e.additionalProperties):`null | string | number | boolean | globalThis.Record<string, unknown> | readonly unknown[]`}propertyDefinitions(e){let{properties:t}=e;return Object.entries(t).map(([e,t])=>{let n=this.type(t),r=(Re(t)?`readonly `:``)+S(e);if(!T(t)){let e=un(fn(t),`
|
|
3
|
+
* `);if(e)return`
|
|
4
|
+
/**
|
|
5
|
+
* ${e}
|
|
6
|
+
*/
|
|
7
|
+
${r}: ${n}
|
|
8
|
+
`}return`${r}: ${n}`})}objectType(e){let t=[];Oe(e)&&t.push(...this.propertyDefinitions(e));for(let n of e.required??[])Object.hasOwn(e.properties??{},n)||t.push(`${S(n)}: ${this.requiredAdditionalPropertyType(e)}`);let n=Pe(e)&&Ie(e)?this.mapType(e):On(e,this.components)?`globalThis.Record<string, ${this.additionalPropertyType(e)}>`:void 0,r=n?``:this.additionalProperties(e);if(r&&t.push(r),t.length===0)return`globalThis.Record<string, any>`;let i=`{\n ${t.join(`;
|
|
9
|
+
`)}; \n}`;return n?`(${i} & ${n})`:i}mapValueType(e){return e.additionalProperties===void 0||e.additionalProperties===!1||e.additionalProperties===!0?`any`:this.type(e.additionalProperties)}mapKeyType(e){let t=Ie(e);return t?this.type(t):`string`}mapType(e){return`globalThis.Record<${this.mapKeyType(e)},${this.mapValueType(e)}>`}objectConstrained(e){let t=e=>T(e)?this.components&&O(e,this.components):e,n=t(e),r=new Map,i=new Set,a=n?[n]:[];for(let e of a){if(r.has(e))continue;let n=[e.allOf,e.oneOf,e.anyOf].map(e=>e?.map(t)??[]);r.set(e,n);for(let e of n)for(let t of e)t&&!r.has(t)&&a.push(t);(e.type===`object`||e.type===`null`||Array.isArray(e.type)&&e.type.length>0&&e.type.every(e=>e===`object`||e===`null`))&&i.add(e)}let o=!0;for(;o;){o=!1;for(let[e,[t,n,a]]of r){if(i.has(e))continue;let r=e=>e!==void 0&&i.has(e);(t.some(r)||[n,a].some(e=>e.length>0&&e.every(r)))&&(i.add(e),o=!0)}}return n!==void 0&&i.has(n)}type(e){if(T(e))return this.reference(e);if(Array.isArray(e.type))return e.type.map(t=>{let n=this.type({...e,type:t});return/[|&]/.test(n)?`(${n})`:n}).join(` | `);if(kn(e))return`(${this.type({...e,nullable:!1})}) | null`;if(N(e)){let t=this.simpleComposition(e);if(t!==void 0)return t;let n=[`allOf`,`oneOf`,`anyOf`].flatMap(t=>{let n=e[t];return n?.length?[`(${n.map(n=>{let r=this.memberType(e,t,n);return r===`any`?`unknown`:/[|&]/.test(r)?`(${r})`:r}).join(t===`allOf`?` & `:` | `)})`]:[]}),r=n.length===1?n[0]:`(${n.join(` & `)})`,i={...e,oneOf:void 0,anyOf:void 0,allOf:void 0},a=this.type(i),o=a===`any`?r:`(${r} & (${a}))`;return this.objectConstrained(e)?`globalThis.Exclude<${o}, string | number | boolean | readonly unknown[]> & ({ readonly [globalThis.Symbol.iterator]?: never } | null)`:o}if(e.const!==void 0){if(!An(e.const,e))return`never`;let t=U(e.const),n=this.type({...e,const:void 0});return n===`any`?t:`(${t}) & (${n})`}if(e.nullable&&e.type&&!M(e))return`(${this.type({...e,nullable:!1})}) | null`;if(M(e)){let t=e.enum.filter(t=>An(t,e)).map(e=>U(e)).join(` | `)||`never`,n=this.type({...e,enum:void 0});return n===`any`||wn.has(n)?t:`(${t}) & (${n})`}return Pe(e)&&!e.required?.length?this.mapType(e):e.type===`array`?Ne(this.type(e.items??{})):e.type===`object`?this.objectType(e):e.type?P(e.type):e.required?.length||Object.keys(e.properties??{}).length>0?`(${this.objectType({...e,type:`object`,additionalProperties:e.additionalProperties??!0})} | null | string | number | boolean | readonly unknown[])`:`any`}simpleComposition(e){let t=[`allOf`,`oneOf`,`anyOf`].filter(t=>e[t]?.length);if(t.length!==1)return;let[n]=t;if(Object.keys(e).filter(e=>e!==n&&e!==`discriminator`&&!e.startsWith(`x-`)&&!Tn.has(e)).length>0)return;let r=e[n],i=e=>n!==`allOf`&&[e.type].flat().every(e=>e===`null`)&&e.type!==void 0&&Object.keys(e).every(e=>e===`type`||Tn.has(e));if(!r.every(e=>T(e)||i(e)))return;let a=r.map(t=>T(t)?this.memberType(e,n,t):`null`);return[...new Set(a)].join(n===`allOf`?` & `:` | `)}memberType(e,t,n){let r=this.type(n),i=e.discriminator;if(t===`allOf`||!i?.propertyName||!T(n))return r;let a=de(n),o=Object.entries(i.mapping??{}).filter(([,e])=>e===n.$ref||e===a).map(([e])=>e),s=(o.length>0?o:[a]).map(e=>C(e)).join(` | `);return`(${r} & { ${S(i.propertyName)}: ${s} })`}};function W(e,t){let n=new jn(e);return{text:t(n),imports:n.imports()}}function Mn(e,t){return W(t,t=>t.type(e))}function Nn(e,t){return W(t,t=>t.additionalProperties(e))}function Pn(e,t){return W(t,t=>t.additionalPropertyType(e))}function Fn(e,t){return W(t,t=>t.requiredAdditionalPropertyType(e))}function In(e,t){return W(t,t=>t.mapValueType(e))}var Ln=`@ahoo-wang/fetcher`,Rn=[`ContentTypeValues`,`ResultExtractors`],zn=`@ahoo-wang/fetcher-decorator`,Bn=[`ApiMetadata`,`ApiMetadataCapable`,`ParameterRequest`,`api`,`get`,`post`,`put`,`patch`,`del`,`request`,`attribute`,`path`,`query`,`header`,`body`,`autoGeneratedError`],Vn={type:`Promise<Response>`,metadata:`{resultExtractor: ResultExtractors.Response }`},Hn={type:`Promise<string>`,metadata:`{resultExtractor: ResultExtractors.Text }`},Un=`{
|
|
10
|
+
headers: { Accept: ContentTypeValues.TEXT_EVENT_STREAM },
|
|
11
|
+
resultExtractor: JsonEventStreamResultExtractor,
|
|
12
|
+
}`,Wn=`COMMAND_STREAM_ENDPOINT`;function Gn(e){z(e,Ln,Rn)}function Kn(e){z(e,zn,Bn)}function qn(t,n,r=[],i=[],a){return n.add({kind:e.StructureKind.Class,name:t,isExported:!0,typeParameters:i,extends:a,decorators:[{name:`api`,arguments:r}]})}function Jn(t,n){t.implements=[...[t.implements??[]].flat(),`ApiMetadataCapable`],t.ctors??=[],n===void 0?t.ctors.push({parameters:[{name:`apiMetadata`,type:`ApiMetadata`,hasQuestionToken:!0,scope:e.Scope.Public,isReadonly:!0}]}):(t.properties=[...t.properties??[],{name:`apiMetadata`,type:`ApiMetadata`,isReadonly:!0}],t.ctors.push({parameters:[{name:`apiMetadata`,type:`ApiMetadata`,hasQuestionToken:!0}],statements:`this.apiMetadata = { ${n}, ...apiMetadata };`,docs:["@param apiMetadata - Merged over the defaults, so passing only a `fetcher` keeps the base path."]}))}function Yn(e){return e===`delete`?`del`:e}var Xn=`@ahoo-wang/fetcher-eventstream`;function Zn(e){z(e,Xn,[`JsonEventStreamResultExtractor`,`JsonServerSentEventStream`])}function Qn(e,t){let n=t.modules.module(e.file);Gn(n),Kn(n),Zn(n);let r=qn(e.className,n);V(r,[e.description]);let i;e.basePath&&(ln(n,t.outputDir,e.basePath.alias,e.basePath.constantName),i=`basePath: ${e.basePath.constantName}`),Jn(r,i);let a=$n(e.className,n,t);for(let t of e.methods)(r.methods??=[]).push(er(t,a))}function $n(e,t,n){let r={context:n.types,owner:{name:e},specifierOf:e=>sn(t,n.outputDir,e),imports:t.imports};return{module:t,resolveType(e){let n=Mn(e,r);return t.imports.apply(n.imports),n.text}}}function er(e,t){let n=[],r=[];for(let i of e.parameters)(i.required?n:r).push({name:i.name,type:i.schema?t.resolveType(i.schema):`string`,hasQuestionToken:!i.required,decorators:[{name:i.location,arguments:[C(i.parameterName)]}]});e.body&&(e.body.required?n:r).push({name:e.body.name,type:tr(e.body,t),hasQuestionToken:!e.body.required,decorators:[{name:`body`,arguments:[]}]});let i=[...n,...r,{name:`httpRequest`,hasQuestionToken:!0,type:`ParameterRequest`,decorators:[{name:`request`,arguments:[]}]},{name:`attributes`,hasQuestionToken:!0,type:`Record<string, unknown>`,decorators:[{name:`attribute`,arguments:[]}]}],a=nr(e.returns,t),o=C(e.path),s={name:e.name,decorators:[{name:Yn(e.httpMethod),arguments:a.metadata?[o,a.metadata]:[o]}],parameters:i,returnType:a.type,statements:[`throw autoGeneratedError(${i.map(e=>e.name).join(`,`)});`]};return V(s,[...e.docs]),s}function tr(e,t){let{content:n}=e;switch(n.kind){case`json`:{let e=t.resolveType(n.schema),r=n.optionalFields;return r.length===0||/[|&]/.test(e)||e===`any`?e:(z(t.module,Ln,[`PartialBy`]),`PartialBy<${e}, ${r.map(C).join(` | `)}>`)}case`formData`:return`FormData`;case`urlEncoded`:return`URLSearchParams`;case`text`:return`string`;case`binary`:return`BodyInit`}}function nr(e,t){switch(e.kind){case`json`:{let n=t.resolveType(e.schema);return e.wildcard&&n===`string`?Hn:{type:`Promise<${n}>`}}case`eventStream`:{if(!e.items)return{type:`Promise<JsonServerSentEventStream<any>>`,metadata:Un};let n=t.resolveType(e.items);return{type:`Promise<JsonServerSentEventStream<${e.serverSentEvent?`${n}['data']`:n}>>`,metadata:Un}}case`text`:return Hn;case`response`:return Vn}}var rr=`DEFAULT_COMMAND_CLIENT_OPTIONS`;function ir(t,n){let r=t.commandClient;if(r.commands.length===0)return;let i=n.modules.module(r.file);i.add({kind:e.StructureKind.Enum,name:r.endpointPathsName,isExported:!0,members:rn(r.commands.map(e=>({name:e.endpointMember,initializer:C(e.path)})))});let a=new Set,o=r.commands.map(e=>ar(i,n.outputDir,e,a));ln(i,n.outputDir,t.context.alias,t.context.constantName),i.add({kind:e.StructureKind.VariableStatement,declarationKind:e.VariableDeclarationKind.Const,declarations:[{name:rr,type:`ApiMetadata`,initializer:`{
|
|
13
|
+
basePath: ${t.context.constantName}
|
|
14
|
+
}`}],isExported:!1}),z(i,F,[`CommandRequest`,`CommandResult`,`CommandResultEventStream`,`CommandBody`,Wn]),z(i,`@ahoo-wang/fetcher`,[`PartialBy`]),Kn(i);let s=qn(r.className,i,[],[`R = CommandResult`]);Jn(s,`...${rr}`);for(let[e,t]of r.commands.entries()){let n=or(t,o[e]),i={name:t.methodName,decorators:[{name:Yn(t.httpMethod),arguments:[`${r.endpointPathsName}.${t.endpointMember}`]}],parameters:n,returnType:`Promise<R>`,statements:`throw autoGeneratedError(${n.map(e=>e.name).join(`,`)});`};(s.methods??=[]).push(i),V(i,[...t.docs])}qn(r.streamClassName,i,[`''`,Wn],[],`${r.className}<CommandResultEventStream>`)}function ar(t,n,r,i){if(r.body.path===`@ahoo-wang/wow-client`)return z(t,F,[r.typeName]),r.typeName;B(t,n,r.body);let a=r.body.name,o=r.optionalFields.map(C).join(` | `);o!==``&&(a=`PartialBy<${a},${o}>`);let s=`CommandBody<${a}>`;return r.typeName===void 0?s:(i.has(r.typeName)||(i.add(r.typeName),t.add({kind:e.StructureKind.TypeAlias,name:r.typeName,type:s,isExported:!0})),r.typeName)}function or(e,t){return[...e.pathParameters.map(e=>({name:e.name,type:e.type,hasQuestionToken:!1,decorators:[{name:`path`,arguments:[C(e.pathName)]}]})),{name:`commandRequest`,hasQuestionToken:e.requestOptional,type:`CommandRequest<${t}>`,decorators:[{name:`request`,arguments:[]}]},{name:`attributes`,hasQuestionToken:!0,type:`Record<string, unknown>`,decorators:[{name:`attribute`,arguments:[]}]}]}function sr(e){return Sn(e,{ofKey:e=>L(e),ofReference:Ct})}function cr(t,n){let r=n.modules.module(t.file);t.emptyMessageBody?mn(r.add({kind:e.StructureKind.TypeAlias,name:t.info.name,type:`globalThis.Record<string, never>`,isExported:!0}),t.docSchema,t.key,n.schemaDocs===`full`):new ur(t,r,n).write()}function lr(e){let t=new Set,n=new Map;for(let r of e){let e=re(r),i=[e];/^\d/.test(r)||i.push(r);let a=i.find(e=>!t.has(e));for(let n=2;a===void 0;n++)t.has(`${e}_${n}`)||(a=`${e}_${n}`);t.add(a),n.set(r,S(a))}return n}var ur=class{model;module;target;modelInfo;components;constructor(e,t,n){this.model=e,this.module=t,this.target=n,this.modelInfo=e.info,this.components=n.types.components,this.scope={context:n.types,owner:e.info,specifierOf:e=>sn(t,n.outputDir,e),imports:t.imports}}write(){let e=this.process();e&&mn(e,this.model.docSchema,this.model.key,this.target.schemaDocs===`full`)}process(){let{schema:e}=this.model;return T(e)?this.processTypeAlias(e):M(e)?this.processEnum(e):e.const!==void 0||e.nullable&&e.type||N(e)&&(e.type||e.properties||e.required)?this.processTypeAlias(e):Oe(e)?this.processInterface(e):Pe(e)&&typeof e.additionalProperties==`object`&&!Ie(e)&&!e.required?.length?this.processIndexSignature(e):ke(e)?this.processArray(e):N(e)?this.processComposition(e):this.processTypeAlias(e)}scope;emit(e){return this.module.imports.apply(e.imports),e.text}resolveType(e){return this.emit(Mn(e,this.scope))}processEnum(t){let n=De(t);if(n){let t=lr(Object.keys(n));this.module.add({kind:e.StructureKind.Enum,name:this.modelInfo.name+`EnumText`,isExported:!0,members:[...t].map(([e,t])=>({name:t,initializer:U(n[e])}))})}let r=[...new Set(t.enum.filter(e=>typeof e==`string`))],i=lr(r);return N(t)||t.const!==void 0||t.type!==void 0&&t.type!==`string`||t.enum.some(e=>typeof e!=`string`)?(r.length&&this.module.add({kind:e.StructureKind.VariableStatement,declarationKind:e.VariableDeclarationKind.Const,isExported:!0,declarations:[{name:this.modelInfo.name,initializer:e=>{e.inlineBlock(()=>{for(let t of r)e.write(`${i.get(t)}: `).quote(t).write(`,`).newLine()}),e.write(` as const`)}}]}),this.processTypeAlias(t)):this.module.add({kind:e.StructureKind.Enum,name:this.modelInfo.name,isExported:!0,members:r.map(e=>({name:i.get(e),initializer:U(e)}))})}addPropertyToInterface(e,t,n){let r={name:S(t),type:this.resolveType(n),isReadonly:Re(n)};(e.properties??=[]).push(r),pn(r,n)}processInterface(t){if(On(t,this.components))return this.processTypeAlias(t);let n=[],r=this.module.add({kind:e.StructureKind.Interface,name:this.modelInfo.name,isExported:!0,properties:n}),i=t.properties||{};Object.entries(i).forEach(([e,t])=>{this.addPropertyToInterface(r,e,t)});for(let e of t.required??[])Object.hasOwn(i,e)||n.push({name:S(e),type:this.emit(Fn(t,this.scope))});return this.emit(Nn(t,this.scope))&&n.push(an(this.emit(Pn(t,this.scope)),[`Additional properties`])),r}processArray(t){let n=this.resolveType(t.items);return this.module.add({kind:e.StructureKind.TypeAlias,name:this.modelInfo.name,type:Ne(n),isExported:!0})}processIndexSignature(t){return this.module.add({kind:e.StructureKind.Interface,name:this.modelInfo.name,isExported:!0,properties:[an(this.emit(In(t,this.scope)))]})}processComposition(t){return this.module.add({kind:e.StructureKind.TypeAlias,name:this.modelInfo.name,type:this.resolveType(t),isExported:!0})}processTypeAlias(t){return this.module.add({kind:e.StructureKind.TypeAlias,name:this.modelInfo.name,type:this.resolveType(t),isExported:!0})}},dr=`DEFAULT_QUERY_CLIENT_OPTIONS`;function fr(t,n){let r=t.queryClient,i=n.modules.module(r.file);z(i,F,[`QueryClientFactory`,`QueryClientOptions`,`ResourceAttributionPathSpec`]),ln(i,n.outputDir,t.context.alias,t.context.constantName),i.add({kind:e.StructureKind.VariableStatement,declarationKind:e.VariableDeclarationKind.Const,declarations:[{name:dr,type:`QueryClientOptions`,initializer:`{
|
|
15
|
+
contextAlias: ${t.context.constantName},
|
|
16
|
+
aggregateName: ${C(r.resourceName)},
|
|
17
|
+
resourceAttribution: ${r.resourceAttribution},
|
|
18
|
+
}`}],isExported:!1}),i.add({kind:e.StructureKind.Enum,name:r.eventTitlesName,isExported:!0,members:rn(r.events.map(e=>({name:e.memberName,initializer:C(e.title)})))});for(let e of r.events)B(i,n.outputDir,e.body);i.add({kind:e.StructureKind.TypeAlias,isExported:!0,name:r.eventTypeName,type:r.events.map(e=>e.body.name).join(` | `)||`never`}),B(i,n.outputDir,r.state),B(i,n.outputDir,r.fields),i.add({kind:e.StructureKind.VariableStatement,declarationKind:e.VariableDeclarationKind.Const,declarations:[{name:r.factoryName,initializer:`new QueryClientFactory<${r.state.name}, \`\${${r.fields.name}}\`, ${r.eventTypeName}>(${dr})`}],isExported:!0})}function pr(e,t){e.contexts.forEach(e=>mr(e,t)),e.models.forEach(e=>cr(e,t)),e.aggregates.forEach(e=>fr(e,t)),e.aggregates.forEach(e=>ir(e,t)),e.apiClients.forEach(e=>Qn(e,t))}function mr(e,t){t.modules.module(e.file).add(`export const ${e.constantName} = ${C(e.alias)};`)}function hr(e,t){let n=[];return gr(e,t,n),n}function gr(e,t,n){let r=[];for(let t of e.getSourceFiles()){let e=t.getBaseName();e.endsWith(`.ts`)&&e!==`index.ts`&&r.push({specifier:`./${t.getBaseNameWithoutExtension()}.js`,exports:vr(t)})}for(let i of e.getDirectories()){let e=gr(i,t,n);e&&r.push({specifier:`./${i.getBaseName()}/index.js`,exports:e})}let i=e.getPath();return r.length===0?e.getProject().getSourceFile(`${i}/index.ts`)?new Map:void 0:_r(i,r,t,n)}function _r(e,t,n,r){let i=new Map;for(let e of t)for(let t of e.exports.keys())i.set(t,[...i.get(t)??[],e.specifier]);let a=[...i].filter(([,e])=>e.length>1).map(([e])=>e).sort();for(let t of a)r.push(`${t} is exported by both ${i.get(t).join(` and `)} in ${e}; its index leaves it out, so import it from its own module.`);let o=n(e);o.removeText();let s=new Map;for(let e of t){let t=[...e.exports].filter(([e])=>!a.includes(e)).sort(([e],[t])=>w(e,t));t.forEach(([e,t])=>s.set(e,t)),t.length===e.exports.size?o.addExportDeclaration({moduleSpecifier:e.specifier}):t.length>0&&o.addExportDeclaration({moduleSpecifier:e.specifier,namedExports:t.map(([e,t])=>({name:e,isTypeOnly:t}))})}return o.getStatements().length===0&&o.addStatements(`export {};`),s}function vr(t){let n=new Map;for(let[r,i]of t.getExportedDeclarations())n.set(r,i.every(t=>e.Node.isInterfaceDeclaration(t)||e.Node.isTypeAliasDeclaration(t)));return n}function yr(t){let n=t;for(let t=n.getParent();t;n=t,t=t.getParent())if(e.Node.isQualifiedName(t)){if(t.getLeft()!==n)return!1}else if(e.Node.isPropertyAccessExpression(t)){if(t.getExpression()!==n)return!1}else{if(e.Node.isExpressionWithTypeArguments(t)){let n=t.getParent(),r=n?.getParent();return!(e.Node.isHeritageClause(n)&&n.getToken()===e.SyntaxKind.ExtendsKeyword&&(e.Node.isClassDeclaration(r)||e.Node.isClassExpression(r)))}return e.Node.isTypeNode(t)}return!1}function br(t){let n=t.getImportDeclarations().filter(e=>!e.getDefaultImport()&&!e.getNamespaceImport()&&e.getNamedImports().length>0);if(n.length===0)return[];let r=new Set(n.flatMap(e=>e.getNamedImports().map(e=>(e.getAliasNode()??e.getNameNode()).getText()))),i=new Set;return t.forEachDescendant((t,n)=>{if(e.Node.isImportDeclaration(t))n.skip();else if(e.Node.isIdentifier(t)&&r.has(t.getText())&&!yr(t)){let e=t.getSymbol();e&&i.add(e.compilerSymbol)}}),n.map(e=>xr(e,e=>{let t=e.getSymbol();return!!t&&!i.has(t.compilerSymbol)}))}function xr(e,t){let n=e.getNamedImports(),r=n.map(t),i=r.every(Boolean);return()=>{n.forEach((e,t)=>{let n=!i&&r[t];e.isTypeOnly()!==n&&e.setIsTypeOnly(n)}),e.isTypeOnly()!==i&&e.setIsTypeOnly(i)}}function Sr(e){let t=e.flatMap(br);for(let e of t)e()}var Cr=new Set([2300,2304,2308,2393,2451,2456,2503,2552]);function wr(t){let n=[];for(let r of t)for(let t of r.getPreEmitDiagnostics()){if(!Cr.has(t.getCode())||t.getSourceFile()!==r)continue;let i=e.ts.flattenDiagnosticMessageText(t.compilerObject.messageText,` `);n.push(`${r.getFilePath()}:${t.getLineNumber()??0} TS${t.getCode()} ${i}`)}if(n.length>0)throw Error(`The generated code does not compile; nothing was written. This is a wow-generator bug:\n${n.join(`
|
|
19
|
+
`)}`)}var Tr=`// Code generated by wow-generator. DO NOT EDIT.
|
|
20
|
+
|
|
21
|
+
`,Er={indentSize:2,tabSize:2,convertTabsToSpaces:!0,semicolons:`insert`,insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces:!0};function Dr(e,t){e.forEach((n,r)=>{t.debug(`Optimizing file [${n.getFilePath()}] - ${r+1}/${e.length}`),n.formatText(Er),n.organizeImports(Er)}),Sr(e),wr(e);for(let t of e)t.insertText(0,Tr)}var Or=3e4;function kr(e){return/^https?:\/\//i.test(e)}function Ar(e,t={}){return kr(e)?jr(e,t):Nr(e)}async function jr(e,t={}){let n=t.timeoutMs??3e4,r;try{let i=AbortSignal.timeout(n);r=await fetch(e,{headers:t.headers,signal:t.signal?AbortSignal.any([t.signal,i]):i})}catch(e){let t=e instanceof Error&&e.name===`TimeoutError`?`no response within ${n} ms`:Mr(e);throw Error(t,{cause:e})}if(!r.ok){let e=[r.status,r.statusText].filter(Boolean).join(` `);throw Error(`HTTP ${e}`)}return await r.text()}function Mr(e){if(!(e instanceof Error))return String(e);let t=e.cause;return t instanceof Error&&t.message?`${e.message} (${t.message})`:e.message}function Nr(e){return new Promise((t,n)=>{(0,r.readFile)(e,`utf-8`,(e,r)=>{e?n(e):t(r)})})}async function Pr(e,t){let n;try{n=await Ar(e,t)}catch(t){throw new s(`input`,`Cannot read the OpenAPI document ${e}: ${c(t)}`,{cause:t})}try{return Ir(n)}catch(t){throw new s(`input`,`Cannot parse the OpenAPI document ${e}: ${c(t)}`,{cause:t})}}function Fr(e,t){if(typeof e!=`object`||!e||Array.isArray(e))throw new s(`input`,`${t} is not an OpenAPI document: expected an object at the top level.`);let n=e;if(n.swagger!==void 0)throw new s(`input`,`${t} is a Swagger ${String(n.swagger)} document; wow-generator reads OpenAPI 3.x only. Convert it first, for example with swagger2openapi.`);if(typeof n.openapi!=`string`||!/^3\.\d+/.test(n.openapi))throw new s(`input`,`${t} is not an OpenAPI 3.x document: its "openapi" field is ${n.openapi===void 0?`missing`:JSON.stringify(n.openapi)}.`);if(typeof n.info!=`object`||n.info===null||Array.isArray(n.info))throw new s(`input`,`${t} is not a valid OpenAPI document: its "info" object is missing.`);return{...n,paths:n.paths??{}}}function Ir(e){switch(Lr(e)){case`json`:return JSON.parse(e);case`yaml`:return(0,n.parse)(e)}}function Lr(e){let t=e.trimStart();if(t.startsWith(`{`)||t.startsWith(`[`))return`json`;if(t.startsWith(`-`)||t.startsWith(`%YAML`))return`yaml`;try{return JSON.parse(t),`json`}catch{if(t.length>0)return`yaml`}throw Error(`Unable to infer file format`)}var Rr=`./fetcher-generator.config.json`;async function zr(e,t,n){if(e!==void 0)return{...await Hr({path:e,explicit:!0},t,n),origin:G(e)};for(let e of[a,Rr]){let r=await Hr({path:e,explicit:!1},t,n);if(r===void 0)continue;let i=[...r.warnings];return e===`./fetcher-generator.config.json`&&i.push(`${G(e)} uses the deprecated name; rename it to ${a.slice(2)}. The old name is no longer read from v10.`),{config:r.config,origin:G(e),warnings:i}}return t.debug(`No configuration file found, generating with defaults`),{config:{},warnings:[]}}var Br=[`apiClients`],Vr=[`ignorePathParameters`,`methodNames`];async function Hr(e,t,n){let r=G(e.path);t.debug(`Reading configuration: ${r}`);let i;try{i=await Ar(e.path,n)}catch(n){if(!e.explicit&&Ur(n)){t.debug(`No configuration file at ${r}`);return}throw new s(`configuration`,`Cannot read configuration ${r}: ${c(n)}`,{cause:n})}if(!i.trim())return{config:{},warnings:[`Configuration ${r} is empty, generating with defaults`]};let a;try{a=Ir(i)}catch(e){throw new s(`configuration`,`Cannot parse configuration ${r}: ${c(e)}`,{cause:e})}let o=Gr(a,r);return t.debug(`Configuration loaded from ${r}: ${qr(o.config)}`),o}function G(e){return kr(e)||(0,t.isAbsolute)(e)?e:(0,t.resolve)(e)}function Ur(e){return typeof e==`object`&&!!e&&e.code===`ENOENT`}function K(e){return e===null?`null`:Array.isArray(e)?`an array`:`a ${typeof e}`}function q(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Wr(e,t,n,r,i){let a=Object.keys(r).filter(e=>!i.includes(e));a.length&&e.push(`Ignoring unknown ${n} option(s) in ${t}: ${a.join(`, `)}. Known option(s): ${i.join(`, `)}`)}function Gr(e,t){if(!q(e))throw new s(`configuration`,`Configuration ${t} must be a JSON or YAML object, found ${K(e)}`);let n=[];return Wr(n,t,`configuration`,e,Br),Kr(e.apiClients,t,n),{config:e,warnings:n}}function Kr(e,t,n){if(e!==void 0){if(!q(e))throw new s(`configuration`,`apiClients in ${t} must be an object keyed by tag name, found ${K(e)}`);for(let[r,i]of Object.entries(e)){if(!q(i))throw new s(`configuration`,`apiClients["${r}"] in ${t} must be an object, found ${K(i)}`);Wr(n,t,`apiClients["${r}"]`,i,Vr);let{ignorePathParameters:e}=i;if(e!==void 0&&!(Array.isArray(e)&&e.every(e=>typeof e==`string`)))throw new s(`configuration`,`apiClients["${r}"].ignorePathParameters in ${t} must be an array of strings, found ${K(e)}`);let{methodNames:a}=i;if(a!==void 0){if(!q(a))throw new s(`configuration`,`apiClients["${r}"].methodNames in ${t} must be an object mapping operationIds to method names, found ${K(a)}`);for(let[e,n]of Object.entries(a))if(typeof n!=`string`||!m(n))throw new s(`configuration`,`apiClients["${r}"].methodNames["${e}"] in ${t} must be a valid method name, found ${JSON.stringify(n)}`)}}}}function qr(e){let t=Object.keys(e.apiClients??{});return`apiClients=${t.length?t.join(`, `):`none`}`}var Jr=`#/$defs/`;function J(e){return e.startsWith(Jr)?e.slice(8):void 0}function Yr(e){if(typeof e!=`object`||!e)return!1;let t=e;return t.openapi===void 0&&t.swagger===void 0&&typeof t.format==`number`&&Array.isArray(t.contexts)}function Y(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Xr(e,t){let n=e;if(n.format!==1)throw new s(`input`,`${t} is a Wow Manifest of format ${n.format}; wow-generator reads format 1.`);let r=[];if(n.contexts.forEach((e,t)=>{!Y(e)||typeof e.name!=`string`?r.push(`contexts[${t}] has no name`):(e.aggregates??[]).forEach((t,n)=>{let i=`${e.name}.aggregates[${n}]`;!Y(t)||typeof t.name!=`string`?r.push(`${i} has no name`):!Y(t.state)||typeof t.state.schema!=`string`?r.push(`${e.name}.${t.name} has no state schema`):((t.commands??[]).forEach(n=>{(typeof n?.name!=`string`||typeof n.schema!=`string`)&&r.push(`a command of ${e.name}.${t.name} has no name or schema`)}),(t.events??[]).forEach(n=>{(typeof n?.name!=`string`||typeof n.schema!=`string`)&&r.push(`an event of ${e.name}.${t.name} has no name or schema`)}))})}),n.$defs!==void 0&&!Y(n.$defs)&&r.push(`$defs is not an object`),r.length>0)throw new s(`specification`,`${t} is not a Manifest wow-generator can read: ${r.join(`; `)}.`);return n}var Zr={"wow.lifecycle.TransferOwner":`TransferOwner`,"wow.lifecycle.TransferSpace":`TransferSpace`,"wow.lifecycle.ApplyTags":`ApplyTags`},Qr=new Set([`wow.lifecycle.DeleteAggregate`,`wow.lifecycle.RestoreAggregate`,`wow.lifecycle.TransferOwner`,`wow.lifecycle.TransferSpace`,`wow.lifecycle.ApplyTags`]),$r=4;function X(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function ei(e){let t=e.type;return typeof t==`string`?[t]:Array.isArray(t)?t.filter(e=>typeof e==`string`):[]}function ti(e,t){let n=[...new Set(e)];return n.length===1?n[0]:n.map(e=>/ [|&] /.test(e)&&!e.startsWith(`{`)?`(${e})`:e).join(t)}function ni(e){return typeof e==`string`?C(e):JSON.stringify(e)}var ri=class{defs;names=new Map;warnings=[];constructor(e){this.defs=e}inlined(e){return e.includes(`(`)}name(e){let t=new Set(e);for(let e=0;t.size>0;e++){let n=new Map;for(let r of t.keys()){let t=r.split(`.`),i=t[t.length-1].split(`$`),a=_([...t.slice(Math.max(0,t.length-1-e),t.length-1),...i].map(e=>/^[a-z]/.test(e)?y(e):e));n.set(a,[...n.get(a)??[],r])}let r=new Set(this.names.values());for(let[i,a]of n){let n=a.filter(t=>t.split(`.`).length-1<=e),o=a.length===1&&!r.has(i)?a:n;for(let e of o){let n=i;for(let e=2;r.has(n);e++)n=`${i}${e}`;r.add(n),this.names.set(e,n),t.delete(e)}}}}schemaOf(e){let t=this.defs[e];return X(t)?t:void 0}resolve(e,t=new Set){let n=e.$ref;if(typeof n!=`string`)return e;let r=J(n);if(r===void 0||t.has(r))return e;let i=this.schemaOf(r);return i?this.resolve(i,new Set([...t,r])):e}references(e,t=new Set){if(Array.isArray(e))e.forEach(e=>this.references(e,t));else if(X(e))for(let[n,r]of Object.entries(e))if(n===`$ref`&&typeof r==`string`){let e=J(r);e!==void 0&&t.add(e)}else n!==`enum`&&n!==`const`&&this.references(r,t);return t}namedReferences(e){let t=new Set;for(let n of this.references(e)){let e=this.schemaOf(n);e!==void 0&&this.inlined(n)?this.namedReferences(e).forEach(e=>t.add(e)):t.add(n)}return t}closure(e){let t=new Set,n=[...e];for(;n.length>0;){let e=n.pop();if(t.has(e))continue;t.add(e);let r=this.schemaOf(e);r&&n.push(...this.references(r))}return[...t]}refType(e,t){let n=this.schemaOf(e);if(n!==void 0&&this.inlined(e))return this.type(n,t);let r=this.names.get(e);return r!==void 0&&this.schemaOf(e)?r:(this.warnings.push(`${t} refers to the schema ${e}, which the Manifest's $defs does not hold; it is typed as unknown.`),`unknown`)}type(e,t){if(e===!0||e===void 0)return`unknown`;if(e===!1)return`never`;if(!X(e))return`unknown`;if(typeof e.$ref==`string`){let n=J(e.$ref);return n===void 0?`unknown`:this.refType(n,t)}if(`const`in e)return ni(e.const);if(Array.isArray(e.enum))return e.enum.length===0?`never`:ti(e.enum.map(ni),` | `);for(let[n,r]of[[`oneOf`,` | `],[`anyOf`,` | `],[`allOf`,` & `]]){let i=e[n];if(Array.isArray(i)&&i.length>0)return ti(i.map(e=>this.type(e,t)),r)}let n=ei(e);return n.length===0?X(e.properties)?this.objectType(e,t):`unknown`:ti(n.map(n=>this.primitive(n,e,t)),` | `)}primitive(e,t,n){switch(e){case`string`:return`string`;case`integer`:case`number`:return`number`;case`boolean`:return`boolean`;case`null`:return`null`;case`array`:{let e=t.items===void 0?`unknown`:this.type(t.items,n);return/ [|&] /.test(e)?`(${e})[]`:`${e}[]`}case`object`:return this.objectType(t,n);default:return`unknown`}}objectType(e,t){let n=this.properties(e,t),r=this.additional(e,t);if(n.length===0)return`Record<string, ${r??`unknown`}>`;let i=n.map(e=>`${e.name}${e.optional?`?`:``}: ${e.type}`);return r!==void 0&&i.push(`[key: string]: unknown`),`{ ${i.join(`; `)} }`}properties(e,t){if(!X(e.properties))return[];let n=new Set(Array.isArray(e.required)?e.required:[]);return Object.entries(e.properties).map(([e,r])=>{let i=X(r)?r.description:void 0;return{name:S(e),type:this.type(r,`${t}.${e}`),optional:!n.has(e),...typeof i==`string`?{description:i}:{}}})}additional(e,t){let n=e.additionalProperties;if(n!==void 0&&n!==!1)return this.type(n,t)}isInterface(e){let t=ei(e);return X(e.properties)&&(t.length===0||t.length===1&&t[0]===`object`)&&e.$ref===void 0&&e.allOf===void 0&&e.oneOf===void 0&&e.anyOf===void 0}fields(e,t,n=1,r=new Set){let i=this.resolve(e),a=typeof e.$ref==`string`?J(e.$ref):void 0;if(a!==void 0&&r.has(a))return[];let o=a===void 0?r:new Set([...r,a]);if(!X(i.properties))return[];let s=[];for(let[e,r]of Object.entries(i.properties)){let i=`${t}.${e}`;s.push(i),n<$r&&X(r)&&(ei(this.resolve(r)).includes(`array`)||s.push(...this.fields(r,i,n+1,o)))}return s}};function ii(e,t){if(t===void 0)return!0;let n=e.resolve(t);return!Array.isArray(n.required)||n.required.length===0}function ai(e,t){return[t.state.schema,...(t.commands??[]).map(e=>e.schema),...(t.events??[]).map(e=>e.schema)].map(J).filter(e=>e!==void 0).concat(oi(e,t))}function oi(e,t){return(t.lifecycle??[]).filter(t=>Zr[t]!==void 0&&e.schemaOf(t))}function si(e){let t=new ri(e.$defs??{}),n=e.contexts,r=new Map;for(let e of n){let n=(e.aggregates??[]).flatMap(e=>ai(t,e));for(let i of t.closure(n).sort(w))r.has(i)||r.set(i,e.name)}let i=[...r.keys()].filter(e=>t.schemaOf(e)&&!t.inlined(e));t.name([...i].sort(w));let a=i.map(e=>ci(t,e,`${r.get(e)}/types.ts`)).sort((e,t)=>w(e.file,t.file)||w(e.name,t.name)),o=n.map(e=>li(t,e));return{model:{...e.service?.name?{service:e.service.name}:{},types:a,contexts:o},warnings:[...new Set(t.warnings)]}}function ci(e,t,n){let r=e.schemaOf(t),i=e.names.get(t),a=typeof r.description==`string`?r.description:void 0,o=[...e.namedReferences(r)].map(t=>e.names.get(t)).filter(e=>e!==void 0&&e!==i),s={key:t,name:i,file:n,...a===void 0?{}:{description:a},references:[...new Set(o)].sort(w)};if(e.isInterface(r)){let n=e.additional(r,t);return{...s,properties:e.properties(r,t),...n===void 0?{}:{type:`unknown`}}}return{...s,type:e.type(r,t)}}function li(e,t){let n=`${t.name}.`;return{name:t.name,...t.description?{description:t.description}:{},typeName:_(y(t.name)),constantName:x(t.name),directory:t.name,errors:(t.errors??[]).map(e=>({member:x((e.code.startsWith(n)?e.code.slice(n.length):e.code).split(/[^A-Za-z0-9]+/))||`ERROR`,code:e.code,status:e.status,...e.description?{description:e.description}:{}})),subscriptions:[...new Set((t.subscriptions??[]).map(e=>e.name))].sort(w),aggregates:(t.aggregates??[]).map(n=>di(e,t,n))}}function ui(e,t,n){let r=J(t);return r===void 0?`unknown`:e.refType(r,n)}function di(e,t,n){let r=`${t.name}.${n.name}`,i=_(y(n.name)),a=new Set(oi(e,n)),o=(n.lifecycle??[]).filter(e=>Qr.has(e)).map(t=>{let n=t.split(`.`).pop(),i=e.schemaOf(t)?.description;return{name:t,member:x(n),method:g(b(n)),...a.has(t)?{bodyType:e.refType(t,r),bodyGenerated:!0}:Zr[t]?{bodyType:Zr[t]}:{},...typeof i==`string`?{description:i}:{}}}),s=new Set(o.map(e=>e.method)),c=(n.commands??[]).map(t=>{let n=g(b(t.name));(s.has(n)||n===`gateway`)&&(n=`${n}Command`),s.add(n);let i=x(t.name),a=(t.routes??[]).filter(e=>e.method===`POST`),o=a.find(e=>e.path.includes(`{id}`)),c=a.find(e=>!e.path.includes(`{id}`)),l=J(t.schema);return{name:t.name,method:n,...o?{byIdPath:{member:i,path:o.path}}:{},...c?{unaddressedPath:{member:o?`${i}_WITHOUT_ID`:i,path:c.path}}:{},bodyType:ui(e,t.schema,`${r}.${t.name}`),bodyOptional:ii(e,l===void 0?void 0:e.schemaOf(l)),creation:t.creation??`NONE`,mounted:t.mounted??!1,produces:t.produces??[],...t.description?{description:t.description}:{}}}),l=J(n.state.schema),u=l===void 0?void 0:e.schemaOf(l);return{context:t.name,name:n.name,...n.description?{description:n.description}:{},typeName:i,directory:`${t.name}/${n.name}`,ownership:n.ownership??`OWNER`,snapshot:n.snapshot?.enabled??!0,stateType:ui(e,n.state.schema,`${r} state`),stateFields:u===void 0?[]:e.fields({$ref:n.state.schema},`state`),commands:c,events:(n.events??[]).map(i=>({name:i.name,wireName:i.name.includes(`.`)?i.name:`${t.name}.${n.name}.${i.name}`,revision:i.revision??1,type:ui(e,i.schema,`${r}.${i.name}`)})),lifecycle:o,queryModels:(n.queries??[]).map(e=>e.model)}}var Z=`@ahoo-wang/wow-client/v10`;function Q(e,t=``){let n=e.filter(e=>typeof e==`string`&&e!==``).flatMap(e=>dn(e).split(`
|
|
22
|
+
`));return n.length===0?``:n.length===1?`${t}/** ${n[0]} */\n`:`${t}/**\n${n.map(e=>`${t} * ${e}`.trimEnd()).join(`
|
|
23
|
+
`)}\n${t} */\n`}function $(e,t){e.add(`\n${t}`)}function fi(e){return e.length===0?`never`:e.join(` | `)}function pi(e,t,n,r,a){let o=new Map;for(let e of new Set(r)){let t=n.get(e);t!==void 0&&t!==a&&o.set(t,[...o.get(t)??[],e])}for(let[n,r]of o)e.imports.add(cn(e.directoryPath,(0,i.join)(t,n)),r)}function mi(e,t,n){let r=new Map(e.types.map(e=>[e.name,e.file]));for(let i of e.types)hi(t.module(i.file),i,r,n);for(let i of e.contexts){gi(i,t);for(let e of i.aggregates)_i(e,i,t,r,n),bi(e,t,r,n),xi(e,t,r,n)}}function hi(e,t,n,r){pi(e,r,n,t.references,t.file);let i=Q([t.description,`- key: \`${t.key}\``]);if(t.properties===void 0){$(e,`${i}export type ${t.name} = ${t.type};`);return}let a=t.properties.map(e=>`${Q([e.description],` `)} ${e.name}${e.optional?`?`:``}: ${e.type};`);t.type!==void 0&&a.push(` [key: string]: ${t.type};`),$(e,`${i}export interface ${t.name} {\n${a.join(`
|
|
24
|
+
`)}\n}`)}function gi(e,t){let n=t.module(`${e.directory}/boundedContext.ts`),r=`${e.constantName}_BOUNDED_CONTEXT`;n.imports.add(Z,[`Hop`,`wait`]),$(n,`${Q([`The bounded context \`${e.name}\`.`,e.description])}export const ${r} = ${C(e.name)};`);let i=e.errors.map(e=>`${Q([`${e.status}: ${e.description??e.code}`],` `)} ${e.member}: ${C(e.code)},`);$(n,`${Q([`The domain error codes of \`${e.name}\`, each a problem's \`code\` with the status the Manifest gives it.`])}export const ${e.typeName}ErrorCodes = {\n${i.join(`
|
|
25
|
+
`)}\n} as const;`),$(n,`${Q([`A {@link ${e.typeName}ErrorCodes} value.`])}export type ${e.typeName}ErrorCode = (typeof ${e.typeName}ErrorCodes)[keyof typeof ${e.typeName}ErrorCodes];`);let a=e.subscriptions.length>0;a&&$(n,`${Q([`The subscriptions of \`${e.name}\` a \`handled\` hop names.`])}export type ${e.typeName}Subscription = ${fi(e.subscriptions.map(C))};`);let o=[` /** Until a command of \`${e.name}\` passed admission. */\n accepted: (): Hop => wait.accepted(${r}),`,` /** Until a command's events are appended to the log of \`${e.name}\`. */\n committed: (): Hop => wait.committed(${r}),`,` /** Until the snapshot of \`${e.name}\` holds the commit. */\n snapshot: (): Hop => wait.snapshot(${r}),`];a&&o.push(` /** Until a subscription of \`${e.name}\` handled the commit. */\n handled: (subscription: ${e.typeName}Subscription): Hop => wait.handled(subscription, ${r}),`),$(n,`${Q([`The hops of a wait chain (\`Wow-Wait\`) in \`${e.name}\`.`])}export const ${b(e.name)}Wait = {\n${o.join(`
|
|
26
|
+
`)}\n} as const;`)}function _i(e,t,n,r,i){let a=n.module(`${e.directory}/aggregate.ts`),o=e.typeName;$(a,`${Q([`The aggregate \`${e.context}.${e.name}\`.`,e.description])}export const ${o}Aggregate = {\n context: ${C(t.name)},\n name: ${C(e.name)},\n path: ${C(`/${t.name}/${e.name}`)},\n ownership: ${C(e.ownership)},\n snapshot: ${e.snapshot},\n} as const;`),$(a,`${Q([`The \`state.*\` paths of \`${e.name}\`'s snapshots a query filters, sorts and projects on.`])}export type ${o}StateField = ${fi(e.stateFields.map(C))};`);let s=e.events.map(e=>`EventView<${C(e.wireName)}, ${e.type}>`);a.imports.add(Z,s.length>0?[`EventView`,`SystemEvent`]:[`SystemEvent`]),$(a,`${Q([`The events of \`${e.name}\`, named as the server sends them: \`${e.context}.${e.name}.<Event>\`, and the system events every aggregate has.`])}export type ${o}Event = ${fi([...s,`SystemEvent`])};`),pi(a,i,r,e.events.map(e=>e.type))}function vi(e){let t=[e.byIdPath,e.unaddressedPath].filter(e=>e!==void 0).map(e=>`\`POST ${e.path}\``).join(`, `),n=e.creation===`REQUIRED`?`Creates the aggregate.`:e.creation===`ALLOWED`?`Creates the aggregate, or acts on the one that exists.`:void 0;return Q([e.description,`\`${e.name}\`${e.mounted?`, mounted (a transformer finds its aggregate)`:``}: ${t}.`,n,e.produces.length>0?`Produces ${e.produces.map(e=>`\`${e}\``).join(`, `)}.`:void 0],` `)}function yi(e,t,n){let r=e.bodyType===`unknown`?`object`:e.bodyType,i=e.bodyOptional?`body: ${r} = {}`:`body: ${r}`,a=n?`stream`:`send`,o=n?`Promise<CommandResultStream>`:`Promise<CommandResult>`,s=n?`${e.method}Stream`:e.method,c=n?Q([`\`${e.name}\`, answered as one result per hop of its wait (\`text/event-stream\`).`],` `):vi(e),l=e.byIdPath,u=e.unaddressedPath;return l&&u?`${c} ${s}(${i}, options?: CreateCommandOptions): ${o} {\n return this.gateway.${a}(options?.id === undefined ? ${t}.${u.member} : ${t}.${l.member}, body, options);\n }`:l?`${c} ${s}(id: string, ${i}, options?: CommandOptions): ${o} {\n return this.gateway.${a}(${t}.${l.member}, body, { ...options, id });\n }`:`${c} ${s}(${i}, options?: CommandOptions): ${o} {\n return this.gateway.${a}(${t}.${u.member}, body, options);\n }`}function bi(e,t,n,r){let i=t.module(`${e.directory}/commandClient.ts`),a=e.typeName,o=`${a}CommandPaths`,s=e.commands.filter(e=>e.byIdPath||e.unaddressedPath),c=s.flatMap(e=>[e.byIdPath,e.unaddressedPath].filter(e=>e!==void 0).map(e=>` ${e.member}: ${C(e.path)},`));$(i,`${Q([`The command routes of \`${e.context}.${e.name}\`.`])}export const ${o} = {\n${c.join(`
|
|
27
|
+
`)}\n} as const;`);let l=s.flatMap(e=>[yi(e,o,!1),yi(e,o,!0)]),u=[`CommandGateway`,`CommandResult`,`WowClientOptions`];s.length>0&&u.push(`CommandResultStream`),s.some(e=>e.byIdPath&&e.unaddressedPath)&&u.push(`CreateCommandOptions`),(s.some(e=>!(e.byIdPath&&e.unaddressedPath))||e.lifecycle.length>0)&&u.push(`CommandOptions`);let d=[];for(let t of e.lifecycle){u.push(`LifecycleCommands`),t.bodyType&&(t.bodyGenerated?d:u).push(t.bodyType);let e=t.bodyType?`id: string, body: ${t.bodyType}, options?: CommandOptions`:`id: string, options?: CommandOptions`;l.push(`${Q([t.description,`The lifecycle command \`${t.name}\`.`],` `)} ${t.method}(${e}): Promise<CommandResult> {\n return this.gateway.lifecycle(${a}Aggregate.path, id, LifecycleCommands.${t.member}, ${t.bodyType?`body`:`undefined`}, options);\n }`)}e.lifecycle.length>0&&i.imports.add(`./aggregate.js`,[`${a}Aggregate`]),i.imports.add(Z,[...new Set(u)].sort()),pi(i,r,n,[...s.map(e=>e.bodyType),...d]),$(i,`${Q([`Sends the commands of \`${e.context}.${e.name}\`; a command that did not succeed rejects with a \`WowProblemError\` holding its result.`])}export class ${a}CommandClient {\n readonly gateway: CommandGateway;\n\n /** @param options - How the service is reached */\n constructor(options?: WowClientOptions) {\n this.gateway = new CommandGateway(options);\n }\n\n${l.join(`
|
|
28
|
+
|
|
29
|
+
`)}\n}`)}function xi(e,t,n,r){let i=t.module(`${e.directory}/queryClient.ts`),a=e.typeName,o=e.stateType,s=[`StateClient`,`WowClientOptions`],c=[`${a}Aggregate`,`${a}Event`],l=` /** @param options - How the service is reached */\n constructor(options?: WowClientOptions) {\n super(${a}Aggregate, options);\n }`;e.queryModels.includes(`snapshot`)&&(s.push(`SnapshotQueryClient`),c.push(`${a}StateField`),$(i,`${Q([`Queries the snapshots of \`${e.context}.${e.name}\`: \`POST /${e.context}/${e.name}/snapshot/query\`.`])}export class ${a}SnapshotQueryClient extends SnapshotQueryClient<${o}, ${a}StateField> {\n${l}\n}`)),e.queryModels.includes(`events`)&&(s.push(`EventQueryClient`),$(i,`${Q([`Queries the event streams of \`${e.context}.${e.name}\`, one aggregate at a time: \`POST /${e.context}/${e.name}/events/query\`.`])}export class ${a}EventQueryClient extends EventQueryClient<${a}Event> {\n${l}\n}`)),$(i,`${Q([`Reads the states of \`${e.context}.${e.name}\`, at a version or a time, and their traces: \`GET /${e.context}/${e.name}/{id}/state\`.`])}export class ${a}StateClient extends StateClient<${o}, ${a}Event> {\n${l}\n}`),i.imports.add(Z,s.sort()),i.imports.add(`./aggregate.js`,c),pi(i,r,n,[o])}function Si(e){return{openAPI:e,components:e.components,endpoints:He(e.paths,e.components)}}var Ci=`.wow-generator.json`,wi=`.fetcher-generator.json`,Ti=class e{project;outputPath;outputDir;previous;legacyManifest;written=new Set;stale=new Set;constructor(e,t,n,r,i){this.project=e,this.outputPath=t,this.outputDir=n,this.previous=r,this.legacyManifest=i}static open(n,r,i){let a=n.getFileSystem(),o=r;r=(0,t.resolve)(a.getCurrentDirectory(),r);let c=(0,t.join)(r,wi),l=a.fileExistsSync(c)?c:void 0,u=(0,t.join)(r,Ci);!a.fileExistsSync(u)&&l&&(u=l);let d=new Map;if(a.fileExistsSync(u)){let e=Ei(u,a.readFileSync(u));for(let[n,i]of Object.entries(e.files)){let e=(0,t.resolve)(r,n);if(Ai(r,e),(0,t.isAbsolute)(n)||!n.endsWith(`.ts`)||typeof i!=`string`||!/^[a-f0-9]{64}$/.test(i))throw new s(`output`,`Invalid generated file entry in ${u}: ${n}`);d.set(e,i)}}let f=new Set([...i?.written??[],...d.keys()]);for(let e of n.getSourceFiles())f.has(e.getFilePath())&&e.forget();return new e(n,o,r,d,l)}get files(){return this.written}claim(e,t=this.outputPath){let n=R(t,e);Ai(t,n);let r=this.project.getSourceFile(n)??this.project.createSourceFile(n,``,{overwrite:!0}),i=r.getFilePath();return this.written.has(i)||(r.removeText(),this.written.add(i)),r}forgetStale(){for(let[e,t]of this.previous)!this.written.has(e)&&this.isUnchanged(e,t)&&this.stale.add(e);for(let e of this.project.getSourceFiles())this.stale.has(e.getFilePath())&&e.forget()}async commit(e){e?.throwIfAborted();let n=this.project.getFileSystem(),r=new Set([...this.written].map(e=>e.toLowerCase()));for(let e of this.stale)!this.written.has(e)&&r.has(e.toLowerCase())&&this.isUnchanged(e,this.previous.get(e))&&(await ki(`delete`,e,()=>n.delete(e)),this.stale.delete(e));let i=[...this.written].sort().map(e=>this.project.getSourceFileOrThrow(e));(await Promise.allSettled(i.map(e=>e.save()))).forEach((e,t)=>{if(e.status===`rejected`)throw Oi(`write`,i[t].getFilePath(),e.reason)}),e?.throwIfAborted();for(let e of this.stale)!this.written.has(e)&&this.isUnchanged(e,this.previous.get(e))&&await ki(`delete`,e,()=>n.delete(e));let a=(0,t.join)(this.outputDir,Ci),o=JSON.stringify({version:1,files:Object.fromEntries(i.map(e=>[(0,t.relative)(this.outputDir,e.getFilePath()).split(t.sep).join(`/`),Di(n.readFileSync(e.getFilePath()))]))},null,2)+`
|
|
30
|
+
`;await ki(`write`,a,async()=>{n.mkdirSync(this.outputDir),await n.writeFile(a,o)});let s=this.legacyManifest;s&&n.fileExistsSync(s)&&await ki(`delete`,s,()=>n.delete(s))}isUnchanged(e,t){let n=this.project.getFileSystem();return n.fileExistsSync(e)?(Ai(n.realpathSync(this.outputDir),n.realpathSync(e)),Di(n.readFileSync(e))===t):!1}};function Ei(e,t){let n=`delete it; without it this run cannot remove the stale files of the last run`,r;try{r=JSON.parse(t)}catch(t){throw new s(`output`,`Cannot parse the generation manifest ${e}: ${c(t)}. Resolve the merge conflict in it if it has one, or ${n}.`,{cause:t})}let i=r?.version;if(typeof i==`number`&&Number.isInteger(i)&&i>1)throw new s(`output`,`The generation manifest ${e} was written by a newer wow-generator (manifest version ${i}); this one reads version 1. Upgrade wow-generator.`);if(i!==1||!r.files||typeof r.files!=`object`||Array.isArray(r.files))throw new s(`output`,`Invalid generation manifest ${e}: expected "version": 1 and a "files" object. Restore it from version control, or ${n}.`);return r}function Di(t){if(!e.ts.sys.createSHA256Hash)throw Error(`SHA-256 hashing is unavailable in this environment.`);return e.ts.sys.createSHA256Hash(t)}function Oi(e,t,n){return n instanceof s?n:new s(`output`,`Cannot ${e} ${t}: ${c(n)}`,{cause:n})}async function ki(e,t,n){try{await n()}catch(n){throw Oi(e,t,n)}}function Ai(e,n){let r=n.split(`/`).join(t.sep),i=(0,t.resolve)(e),a=(0,t.resolve)(r),o=(0,t.relative)(i,a);if(o===``||o.startsWith(`..`)||(0,t.isAbsolute)(o))throw new s(`output`,`Path traversal detected: "${n}" resolves outside the output directory "${e}".`)}function ji(e){let{openAPI:t,components:n,endpoints:r}=e,i=[],a=new Map,o=new Set,c=t.tags??[],l=new Set(c.map(e=>e.name)),u=new Set(r.flatMap(e=>e.operation.tags??[]).filter(e=>!l.has(e))),d=new Map;for(let e of[...c,...[...u].map(e=>({name:e}))]){let t=nt(e);t&&d.set(e.name,{aggregate:t,commands:new Map,events:new Map})}let f=e=>(e.tags??[]).flatMap(e=>{let t=d.get(e);return t?(o.add(e),[t]):[]}),p=(e,t,n)=>{let r=a.get(e.key);r||(r={},a.set(e.key,r));let i=t in r?r[t]:e.schema[t];r[t]=i||n},m=(e,t)=>new s(`specification`,`Cannot read the Wow metadata of ${e.operationId}: ${t}. wow-generator reads documents from Wow ${Qe} or later.`),h=(e,t)=>{let n=st.exec(t)?.[1];n&&e.forEach(e=>{e.resourceName??=n})},g=e=>{let{operation:t,path:r}=e;if(t.operationId===`wow.command.send`)return;let a=rt(t.operationId);if(!a)return;let o=Ge(t),c=new Set;for(;o&&T(o)&&o.$ref!==`#/components/responses/wow.CommandOk`;){if(!o.$ref.startsWith(le))return;if(c.has(o.$ref))throw new s(`specification`,`Cyclic component reference: ${o.$ref}`);c.add(o.$ref),o=n?.responses?.[o.$ref.slice(le.length)]}if(!o||!T(o)||o.$ref!==`#/components/responses/wow.CommandOk`)return;let l=f(t);if(!t.requestBody)return;let u=Je(t,n??{}),d=(T(t.requestBody)?pe(t.requestBody,n??{}):t.requestBody)?.content?.[A]?.schema;if(!T(d)){l.length>0&&i.push(`Skipping command ${t.operationId} (${e.method.toUpperCase()} ${r}): its application/json request body is not a $ref to a component schema.`);return}let m=k(d,n??{});if(!m.schema)return;p(m,`title`,t.summary),p(m,`description`,t.description);let h={name:a,method:e.method,path:r,pathParameters:u,summary:t.summary,description:t.description,schema:m,operation:t};l.forEach(e=>{e.commands.set(a,h)})},ee=({operation:e,path:t})=>{if(!e.operationId?.endsWith(`.snapshot_state.single`))return;let r=f(e);h(r,t);let i=Ke(e,n);if(!T(i)){if(r.length>0)throw m(e,`its 200 application/json response is not a $ref to the state schema`);return}let a=k(i,n);r.forEach(e=>{e.state=a})},_=({operation:e})=>{if(!n||!e.operationId?.endsWith(`.event.list_query`))return;let t=f(e);if(t.length===0)return;let r=Ke(e,n);if(T(r))return;let i=r?.items;if(!T(i))throw m(e,`its 200 application/json response is not an array of a $ref to the event stream schema`);let a=Mi(O(i,n),[`properties`,`body`,`items`,`anyOf`]);if(!Array.isArray(a))throw m(e,`the event stream schema ${i.$ref} has no properties.body.items.anyOf listing the domain events`);let o=a.map((t,r)=>{let a=Mi(t,[`properties`,`name`,`const`]),o=Mi(t,[`properties`,`body`]);if(typeof a!=`string`||!T(o))throw m(e,`domain event ${r} of ${i.$ref} needs a properties.name.const and a properties.body that is a $ref to the event schema`);let s=k(o,n);return p(s,`title`,t.title),{title:t.title??a,name:a,schema:s}});t.forEach(e=>{o.forEach(t=>{e.events.set(t.name,t)})})},te=({operation:e,path:t})=>{if(!n||!e.operationId?.endsWith(`.snapshot.count`))return;let r=f(e);if(r.length===0)return;h(r,t);let i=e.requestBody?T(e.requestBody)?pe(e.requestBody,n):e.requestBody:void 0;if(!i)throw m(e,`it has no request body`);let a=i[ot],o;if(a!==void 0){if(!T(a))throw m(e,`${ot} must be a schema reference`);o=a}else{let t=i.content?.[A]?.schema,r=(T(t)?O(t,n):void 0)?.properties?.field;if(!T(r))throw m(e,`its request body has no ${ot}, and its condition schema has no field $ref to read the query fields from`);o=r}let s=k(o,n);r.forEach(e=>{e.fields=s})};for(let e of r)g(e),ee(e),_(e),te(e);let v=new Map;for(let[e,t]of d){if(!t.state||!t.fields){if(o.has(e)){let n=[t.state?void 0:`${e}${it}`,t.fields?void 0:`${e}${at}`].filter(Boolean);i.push(`Skipping aggregate ${e}: the document has no ${n.join(` or `)} operation, so it generates neither command nor query clients for it.`)}continue}let n=t.aggregate.contextAlias,r=v.get(n);r||(r=new Set,v.set(n,r)),r.add({...t,resourceName:t.resourceName??t.aggregate.aggregateName})}return{contextAlias:et(t),contexts:v,aggregateTags:o,schemaDocOverrides:a,warnings:i}}function Mi(e,t){let n=e;for(let e of t){if(typeof n!=`object`||!n)return;n=n[e]}return n}var Ni=Symbol(`project`),Pi=Symbol(`signal`),Fi=class{options;project;logger;signal;output;constructor(t){this.options=t,this.logger=t.logger??new u,this.signal=t[Pi],this.project=t[Ni]??Ii(t.tsConfigFilePath),this.project.manipulationSettings.set({indentationText:e.IndentationText.TwoSpaces,quoteKind:e.QuoteKind.Single,useTrailingCommas:!0}),this.logger.debug(`Project instance created with tsConfigFilePath: ${this.options.tsConfigFilePath}`)}async generate(){let{logger:e,signal:t,options:n}=this,r=0,i=t=>{for(let n of t)r++,e.warn(n)};e.debug(`Starting code generation from OpenAPI specification`),e.debug(`Work directory: ${process.cwd()}`),e.debug(`Input path: ${n.inputPath}`),e.debug(`Output directory: ${n.outputDir}`);let a={headers:n.headers,timeoutMs:n.timeoutMs,signal:t},o=await zr(n.configPath,e,a);i(o.warnings),t?.throwIfAborted(),e.debug(`Parsing the input document`);let c=await Pr(n.inputPath,a);if(t?.throwIfAborted(),Yr(c))return this.generateFromManifest(Xr(c,n.inputPath),o.origin,i,()=>r);let l=Fr(c,n.inputPath);e.debug(`OpenAPI specification parsed successfully`);let u=oe(l);if(u.length>0)throw new s(`specification`,`${n.inputPath} has ${u.length} $ref(s) that point at nothing: ${u.slice(0,10).map(({ref:e,location:t})=>`${e} (at ${t})`).join(`, `)}${u.length>10?`, …`:``}`);let d=Si(l);e.debug(`Resolving bounded context aggregates`);let f=ji(d);i(f.warnings),e.debug(`Resolved ${f.contexts.size} bounded context aggregates`);let p=Ti.open(this.project,n.outputDir,this.output);this.output=p,e.debug(`Analysing the document`);let m=Zt(d,f,o.config);i(m.warnings),e.debug(`Writing generated modules`);let h=new en(e=>p.claim(e));pr(m.model,{modules:h,outputDir:n.outputDir,types:sr(d.components),schemaDocs:n.schemaDocs??`summary`}),h.build(),e.debug(`Generated modules written`),p.forgetStale();let g=this.project.getDirectory(n.outputDir);return g?(e.debug(`Generating index files`),i(hr(g,e=>p.claim(`index.ts`,e))),e.debug(`Optimizing source files`),Dr(g.getDescendantSourceFiles().filter(e=>p.files.has(e.getFilePath())),e),e.debug(`Source files optimized successfully`)):e.debug(`Output directory not found.`),e.debug(`Saving project to disk`),await p.commit(t),e.debug(`Code generation completed successfully`),{files:[...p.files].sort(),configPath:o.origin,warnings:r}}async generateFromManifest(e,t,n,r){let{logger:i,signal:a,options:o}=this,s=Ti.open(this.project,o.outputDir,this.output);this.output=s,i.debug(`Analysing the Manifest`);let c=si(e);n(c.warnings);let l=new en(e=>s.claim(e));mi(c.model,l,o.outputDir),l.build(),s.forgetStale();let u=this.project.getDirectory(o.outputDir);return u&&(n(hr(u,e=>s.claim(`index.ts`,e))),Dr(u.getDescendantSourceFiles().filter(e=>s.files.has(e.getFilePath())),i)),await s.commit(a),i.debug(`Code generation from the Manifest completed successfully`),{files:[...s.files].sort(),configPath:t,warnings:r()}}};function Ii(t){try{return new e.Project({tsConfigFilePath:t,skipAddingFilesFromTsConfig:!0})}catch(e){throw new s(`configuration`,`Cannot read the TypeScript configuration ${t}: ${c(e)}`,{cause:e})}}Object.defineProperty(exports,"a",{enumerable:!0,get:function(){return d}}),Object.defineProperty(exports,"c",{enumerable:!0,get:function(){return a}}),Object.defineProperty(exports,"i",{enumerable:!0,get:function(){return u}}),Object.defineProperty(exports,"n",{enumerable:!0,get:function(){return Pi}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return o}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return Or}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return Fi}});
|
|
31
|
+
//# sourceMappingURL=codeGenerator-Ba5Cz8XW.cjs.map
|