@ahoo-wang/wow-generator 10.0.0-beta.1 → 10.0.0-beta.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.
Files changed (70) hide show
  1. package/README.md +2 -1
  2. package/README.zh-CN.md +1 -1
  3. package/dist/analysis/clientNames.d.cts +0 -9
  4. package/dist/analysis/clientNames.d.ts +0 -9
  5. package/dist/cli.cjs +1 -1
  6. package/dist/cli.js +2 -2
  7. package/dist/{codeGenerator-Cxlr_VOh.js → codeGenerator-CXowDsB9.js} +1233 -867
  8. package/dist/codeGenerator-CXowDsB9.js.map +1 -0
  9. package/dist/codeGenerator-q59QJpfT.cjs +38 -0
  10. package/dist/codeGenerator-q59QJpfT.cjs.map +1 -0
  11. package/dist/emitters/manifest/aggregate.d.cts +4 -0
  12. package/dist/emitters/manifest/aggregate.d.ts +4 -0
  13. package/dist/emitters/manifest/commandClient.d.cts +4 -0
  14. package/dist/emitters/manifest/commandClient.d.ts +4 -0
  15. package/dist/emitters/manifest/contextClient.d.cts +8 -0
  16. package/dist/emitters/manifest/contextClient.d.ts +8 -0
  17. package/dist/emitters/manifest/contract.d.cts +17 -0
  18. package/dist/emitters/manifest/contract.d.ts +17 -0
  19. package/dist/emitters/manifest/generatedModule.d.cts +19 -0
  20. package/dist/emitters/manifest/generatedModule.d.ts +19 -0
  21. package/dist/emitters/manifest/queryClient.d.cts +4 -0
  22. package/dist/emitters/manifest/queryClient.d.ts +4 -0
  23. package/dist/emitters/manifest/routing.d.cts +9 -0
  24. package/dist/emitters/manifest/routing.d.ts +9 -0
  25. package/dist/emitters/manifest/serviceRoutes.d.cts +11 -0
  26. package/dist/emitters/manifest/serviceRoutes.d.ts +11 -0
  27. package/dist/emitters/manifest/textNumbers.d.cts +24 -0
  28. package/dist/emitters/manifest/textNumbers.d.ts +24 -0
  29. package/dist/emitters/manifest/typeDeclarations.d.cts +4 -0
  30. package/dist/emitters/manifest/typeDeclarations.d.ts +4 -0
  31. package/dist/emitters/manifestClients.d.cts +1 -5
  32. package/dist/emitters/manifestClients.d.ts +1 -5
  33. package/dist/emitters/models.d.cts +1 -1
  34. package/dist/emitters/models.d.ts +1 -1
  35. package/dist/emitters/target.d.cts +1 -1
  36. package/dist/emitters/target.d.ts +1 -1
  37. package/dist/index.cjs +1 -1
  38. package/dist/index.js +1 -1
  39. package/dist/manifest/aggregates.d.cts +6 -0
  40. package/dist/manifest/aggregates.d.ts +6 -0
  41. package/dist/manifest/analyze.d.cts +1 -186
  42. package/dist/manifest/analyze.d.ts +1 -186
  43. package/dist/manifest/document.d.cts +4 -0
  44. package/dist/manifest/document.d.ts +4 -0
  45. package/dist/manifest/model.d.cts +180 -0
  46. package/dist/manifest/model.d.ts +180 -0
  47. package/dist/manifest/names.d.cts +30 -0
  48. package/dist/manifest/names.d.ts +30 -0
  49. package/dist/manifest/schemaTypes.d.cts +46 -0
  50. package/dist/manifest/schemaTypes.d.ts +46 -0
  51. package/dist/manifest/serviceRoutes.d.cts +45 -0
  52. package/dist/manifest/serviceRoutes.d.ts +45 -0
  53. package/dist/manifest/textNumbers.d.cts +108 -0
  54. package/dist/manifest/textNumbers.d.ts +108 -0
  55. package/dist/manifest/typeText.d.cts +11 -0
  56. package/dist/manifest/typeText.d.ts +11 -0
  57. package/dist/naming/naming.d.cts +9 -0
  58. package/dist/naming/naming.d.ts +9 -0
  59. package/dist/types/indexSignature.d.cts +18 -0
  60. package/dist/types/indexSignature.d.ts +18 -0
  61. package/dist/types/literalTypes.d.cts +11 -0
  62. package/dist/types/literalTypes.d.ts +11 -0
  63. package/dist/types/typeContext.d.cts +66 -0
  64. package/dist/types/typeContext.d.ts +66 -0
  65. package/dist/types/typeResolver.d.cts +2 -101
  66. package/dist/types/typeResolver.d.ts +2 -101
  67. package/package.json +6 -6
  68. package/dist/codeGenerator-CADTvm2G.cjs +0 -37
  69. package/dist/codeGenerator-CADTvm2G.cjs.map +0 -1
  70. package/dist/codeGenerator-Cxlr_VOh.js.map +0 -1
@@ -0,0 +1,38 @@
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(x(e)||`_`);return p.has(t)?`${t}_`:t}function _(e){return/^\p{Lu}[\p{L}\p{N}$]*$/u.test(e)&&m(e)}function v(e){return h((Array.isArray(e)?e:[e]).map(e=>_(e)?e:b(e)).join(``)||`_`)}function y(e){return e.split(f)}function ee(e){return Array.isArray(e)?e.flatMap(e=>te(y(e))):te(y(e))}function te(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 b(e){return e===``||e.length===0?``:ee(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 x(e){let t=b(e);return t.charAt(0).toLowerCase()+t.slice(1)}function S(e){return e===``||Array.isArray(e)&&e.length===0?``:ee(e).filter(e=>e.length>0).map(e=>e.toUpperCase()).join(`_`)}function C(e){return/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(e)?e:w(e)}function ne(e){return/^\d+$/.test(e)?`NUM_${e}`:S(e)||e}function w(e){return`'${JSON.stringify(e).slice(1,-1).replace(/\\"/g,`"`).replace(/'/g,`\\'`)}'`}function re(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 ie(e,t){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)?t:t?`${e.replace(/\/+$/,``)}/${t.replace(/^\/+/,``)}`:e}var ae=`types.ts`;function oe(e){return ie(e.path,ae)}function T(e){return!!(e&&typeof e==`object`&&`$ref`in e)}function se(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 ce(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/`)&&se(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/`,le=`${E}parameters/`,ue=`${E}requestBodies/`,de=`${E}responses/`,fe=`${E}schemas/`;function pe(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,fe)}function me(e,t){return D(e,t.responses,de)}function he(e,t){return D(e,t.requestBodies,ue)}function ge(e,t){return D(e,t.parameters,le)}var _e=new Intl.Collator(`en-US`);function k(e,t){return _e.compare(e,t)}var ve=`application/json`,ye=`text/event-stream`;function be(e){return e.split(`;`)[0].trim().toLowerCase()}function xe(e){let t=be(e);return t===`application/json`||/^application\/[^/]+\+json$/.test(t)}function Se(e){let t=be(e);return t.startsWith(`text/`)&&t!==`text/event-stream`}function A(e,t,n=e=>be(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 Ce(e,t){if(t&&!T(t))return A(t.content,e)?.schema}function we(e){if(e&&!T(e))return A(e.content,ve,xe)?.schema}function Te(e){return Ce(ye,e)}function Ee(e){return Ce(`*/*`,e)}function De(e){return!e||T(e)?!1:Object.keys(e.content??{}).some(Se)}function j(e){return Array.isArray(e.enum)&&e.enum.length>0}var Oe=`x-enum-text`;function ke(e){return e[Oe]}function Ae(e){return e.type===`object`&&!!e.properties}function je(e){return e.type===`array`&&!!e.items}function Me(e){return Array.isArray(e.anyOf)&&e.anyOf.length>0}function Ne(e){return Array.isArray(e.oneOf)&&e.oneOf.length>0}function Pe(e){return Array.isArray(e.allOf)&&e.allOf.length>0}function M(e){return Me(e)||Ne(e)||Pe(e)}function Fe(e){return e.includes(`|`)||e.includes(`&`)?`(${e})[]`:`${e}[]`}function Ie(e){return e.type===`object`&&!e.properties&&e.additionalProperties!==void 0}var Le=`x-map-key-schema`;function Re(e){return e[Le]}function ze(e){return e.readOnly===!0}function Be(e){if(Array.isArray(e))return e.map(e=>Be(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 Ve(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 He(e,t){return e.operation.operationId&&t.operation.operationId?k(e.operation.operationId,t.operation.operationId):e.path&&t.path?k(e.path,t.path):e.method&&t.method?k(e.method,t.method):0}function Ue(e,t,n){let r=new Map;for(let i of[...e,...t]){let e=T(i)?n&&ge(i,n):i,t=e?`${e.in}:${e.name}`:i.$ref;r.set(t,i)}return[...r.values()]}function We(e,t){let n=[];for(let[r,i]of Object.entries(e))Ge(i).forEach(e=>{n.push({method:e.method,operation:i.parameters?.length?{...e.operation,parameters:Ue(i.parameters,e.operation.parameters??[],t)}:e.operation,path:r})});return n.sort(He)}function Ge(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 Ke(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 qe(e,t){let n=Ke(e),r=n?e.responses[n]:void 0;return t&&T(r)?me(r,t):r}function Je(e,t){return(e.parameters??[]).map(e=>T(e)?ge(e,t):e).filter(e=>e!==void 0)}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=`x-fetcher-method`;function Ze(e,t){let n=t??e[`x-fetcher-method`];if(n!==void 0){if(typeof n!=`string`||!Qe(n))throw new s(`specification`,`${Xe} of ${e.operationId??`an operation`} is ${JSON.stringify(n)}, which is not a valid method name.`);return n}if(!e.operationId)return;let r=x(e.operationId.split(`.`).pop())||`_`;return/^\p{N}/u.test(r)?`_${r}`:r}function Qe(e){return m(e)||/^[a-z]+$/.test(e)}function N(e){if(!e)return{name:``,path:`/`};let t=e.split(`.`),n=-1;for(let e=0;e<t.length;e++)if(t[e]&&/^[A-Z]/.test(t[e])){n=e;break}let r=t.slice(0,n),i=r.length>0?`/${r.join(`/`)}`:`/`;return{name:v(t.slice(n)),path:i}}function $e(e,t){if(!e.$ref.startsWith(`#/components/schemas/`))throw new s(`specification`,`Unsupported schema reference: ${e.$ref}. Bundle or inline external schemas before generation.`);return t&&O(e,t),N(pe(e))}var et=[`httpRequest`,`attributes`];function tt(e,t,n){return new nt(e,t,n).clients()}var nt=class{document;config;warnings;constructor(e,t,n){this.document=e,this.config=t,this.warnings=n}clients(){let e=this.tags(),t=this.groupOperations(),n=new Map;return[...t.keys()].sort().map(r=>{let i=N(r),a=i;for(let e=2;n.has(it(a));e++)a={...i,name:`${i.name}${e}`};return a!==i&&this.warnings.push(`Tags ${n.get(it(i))} and ${r} both name the API client ${i.name}ApiClient; ${r} generates ${a.name}ApiClient.`),n.set(it(a),r),this.client(e.get(r),a,[...t.get(r)])})}client(e,t,n){let r=`${t.name}ApiClient`,i=ie(t.path,rt(r)),a=new Map;return{tagName:e.name,className:r,file:i,description:e.description,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(et),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=Ze(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=Je(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:re(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)?.includes(t)??!1}body(e,t){if(!e.requestBody)return;let n=T(e.requestBody)?he(e.requestBody,this.document.components):e.requestBody;if(!n)return;let r=n.required===!0,i=n.content??{},a=A(i,ve,xe),o=re(`body`,t);return a?.schema?{name:o,required:r,content:{kind:`json`,schema:a.schema,optionalFields:Ve(a.schema,this.document.components)}}:A(i,`multipart/form-data`)?{name:o,required:r,content:{kind:`formData`}}:A(i,`application/x-www-form-urlencoded`)?{name:o,required:r,content:{kind:`urlEncoded`}}:Object.keys(i).some(Se)?{name:o,required:r,content:{kind:`text`}}:{name:o,required:r,content:{kind:`binary`}}}returns(e){let t=qe(e,this.document.components);if(!t)return{kind:`response`};let n=we(t),r=n||Ee(t);if(r)return{kind:`json`,schema:r,wildcard:!n};let i=Te(t);if(i){if(T(i)){let e=O(i,this.document.components);if(je(e)&&T(e.items)){let t=$e(e.items,this.document.components);return{kind:`eventStream`,items:e.items,serverSentEvent:t.name.includes(`ServerSentEvent`)}}}return{kind:`eventStream`,serverSentEvent:!1}}return De(t)?{kind:`text`}:{kind:`response`}}groupOperations(){let e=new Map;for(let t of this.document.endpoints){let n=`${t.method.toUpperCase()} ${t.path}`,r=t.operation.tags??[];if(r.length===0)this.warnings.push(`Skipping ${n}: it has no tag, and the tag names its API client.`);else if(!t.operation.operationId)this.warnings.push(`Skipping ${n}: it has no operationId, and the operationId names its method.`);else for(let n of r)e.has(n)||e.set(n,new Set),e.get(n).add(t)}return e}tags(){let e=new Map;for(let{operation:t}of this.document.endpoints)t.tags?.forEach(t=>{e.has(t)||e.set(t,{name:t,description:``})});return this.document.openAPI.tags?.forEach(t=>e.set(t.name,t)),e}};function rt(e){return`${e.charAt(0).toLowerCase()}${e.slice(1)}.ts`}function it(e){return`${e.path}/${e.name}`.toLowerCase()}function at(e){let t=e.components?.schemas;if(!t)return[];let n=Object.keys(t);return ot(n),n.map(e=>{let n=t[e],r=N(e);return{key:e,info:r,file:oe(r),schema:n}})}function ot(e){let t=new Map;for(let n of e){let e=N(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 st(e,t){let n=[];return{model:{models:at(e),apiClients:tt(e,t,n)},warnings:n}}var ct=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})}))}},lt=class{sourceFile;imports=new ct;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&&ft(n,e)&&t.push(dt),t.push(e),n=e;return t.length>0&&this.sourceFile.addStatements(t),this.sourceFile}},ut=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 lt(t),this.modules.set(n,r)),r}build(){for(let e of this.modules.values())e.build();this.modules.clear()}},dt=e=>{e.blankLineIfLastNot()};function ft(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 pt(e,t){return{name:`[key: string]`,type:e,docs:t}}var mt=`@`;function P(e,t,n){return e.imports.add(t,n)}function ht(e,n,r){return r.path.startsWith(mt)?r.path:F(e.directoryPath,(0,t.join)(n,r.path,ae))}function F(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 gt(e,t=`
2
+ `){if(!Array.isArray(e))return;let n=e.filter(e=>typeof e==`string`&&e.length>0).map(_t);return n.length>0?n.join(t):void 0}function _t(e){return e.replace(/\*\//g,`*\\/`)}function I(e,t){let n=gt(t);n&&(e.docs=[...e.docs??[],n])}function vt(e,t,n=!1){e=xt(e);let r=[e.title,e.description];return t&&r.push(`- key: ${t}`),n&&St(r,e),e.format&&r.push(e.format===`int64`?`- format: int64 (a value beyond Number.MAX_SAFE_INTEGER loses precision)`:`- format: ${e.format}`),Ct(r,e,`default`),Ct(r,e,`example`),Tt(r,e),Et(r,e),Dt(r,e),r}function yt(e,t,n){I(e,vt(t,n))}function bt(e,t,n,r=!1){let i=vt(t,n,!0);r&&wt(i,`schema`,t),I(e,i)}function xt(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 St(e,t){let n=t.required??[];(n.length||Object.keys(t.properties??{}).length)&&e.push(`- required: ${n.length?n.join(`, `):`(none)`}`)}function Ct(e,t,n){let r=t[n];r&&(typeof r==`object`?wt(e,n,r):e.push(`- ${n}: \`${r}\``))}function wt(e,t,n){e.push(`- ${t}: `),e.push("```json"),e.push(JSON.stringify(n,null,2)),e.push("```")}function Tt(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 Et(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 Dt(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 Ot(e,t){return e===void 0?!1:typeof e==`string`||typeof t==`string`?e===t:e.primitive===t.primitive}function L(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?L(r,t,n):void 0}if(!(e.nullable||Array.isArray(e.type))){if(Pe(e)&&e.type===void 0){let r=e.allOf.map(e=>L(e,t,n)),[i]=r;return i!==void 0&&r.every(e=>Ot(e,i))?i:void 0}if(!(M(e)||e.const!==void 0||e.type===void 0))return e.type===`object`?`object`:e.type===`array`?`array`:{primitive:Be(e.type)}}}function kt(e,t,n){let r=L(t,n);if(typeof r!=`object`)return!1;let i=L(e,n);return i===void 0||typeof i==`string`||i.primitive!==r.primitive}function At(e,t){let n=e.additionalProperties;return typeof n==`object`&&Object.values(e.properties??{}).some(e=>kt(e,n,t))}function jt(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 R(t){if(typeof t==`string`)return new e.CodeBlockWriter({useSingleQuote:!0}).quote(t).toString();if(Array.isArray(t))return`[${t.map(e=>R(e)).join(`, `)}]`;if(typeof t==`object`&&t){let e=Object.entries(t).map(([e,t])=>`${C(e)}: ${R(t)}`);return e.length?`{ ${e.join(`; `)}; readonly [globalThis.Symbol.iterator]?: never }`:`globalThis.Record<string, never>`}return JSON.stringify(t)??`never`}function Mt(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 Nt=[`Array`,`Blob`,`Exclude`,`FormData`,`Partial`,`Promise`,`ReadonlyArray`,`Record`,`Response`,`Symbol`,`URLSearchParams`],Pt=new Set([`string`,`number`,`boolean`]),Ft=new Set([`$comment`,`$schema`,`default`,`deprecated`,`description`,`example`,`examples`,`externalDocs`,`readOnly`,`title`,`writeOnly`,`xml`]);function It(e){return e.nullable!==!0||j(e)||!M(e)?!1:[e.allOf,e.oneOf,e.anyOf].every(e=>e===void 0||e.every(T))}var Lt=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([...Nt,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=(ze(t)?`readonly `:``)+C(e);if(!T(t)){let e=gt(vt(t),`
3
+ * `);if(e)return`
4
+ /**
5
+ * ${e}
6
+ */
7
+ ${r}: ${n}
8
+ `}return`${r}: ${n}`})}objectType(e){let t=[];Ae(e)&&t.push(...this.propertyDefinitions(e));for(let n of e.required??[])Object.hasOwn(e.properties??{},n)||t.push(`${C(n)}: ${this.requiredAdditionalPropertyType(e)}`);let n=Ie(e)&&Re(e)?this.mapType(e):At(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=Re(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(It(e))return`(${this.type({...e,nullable:!1})}) | null`;if(M(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(!jt(e.const,e))return`never`;let t=R(e.const),n=this.type({...e,const:void 0});return n===`any`?t:`(${t}) & (${n})`}if(e.nullable&&e.type&&!j(e))return`(${this.type({...e,nullable:!1})}) | null`;if(j(e)){let t=e.enum.filter(t=>jt(t,e)).map(e=>R(e)).join(` | `)||`never`,n=this.type({...e,enum:void 0});return n===`any`||Pt.has(n)?t:`(${t}) & (${n})`}return Ie(e)&&!e.required?.length?this.mapType(e):e.type===`array`?Fe(this.type(e.items??{})):e.type===`object`?this.objectType(e):e.type?Be(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-`)&&!Ft.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`||Ft.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=pe(n),o=Object.entries(i.mapping??{}).filter(([,e])=>e===n.$ref||e===a).map(([e])=>e),s=(o.length>0?o:[a]).map(e=>w(e)).join(` | `);return`(${r} & { ${C(i.propertyName)}: ${s} })`}};function z(e,t){let n=new Lt(e);return{text:t(n),imports:n.imports()}}function Rt(e,t){return z(t,t=>t.type(e))}function zt(e,t){return z(t,t=>t.additionalProperties(e))}function Bt(e,t){return z(t,t=>t.additionalPropertyType(e))}function Vt(e,t){return z(t,t=>t.requiredAdditionalPropertyType(e))}function Ht(e,t){return z(t,t=>t.mapValueType(e))}var Ut=`@ahoo-wang/fetcher`,Wt=[`ContentTypeValues`,`ResultExtractors`],Gt=`@ahoo-wang/fetcher-decorator`,Kt=[`ApiMetadata`,`ApiMetadataCapable`,`ParameterRequest`,`api`,`get`,`post`,`put`,`patch`,`del`,`request`,`attribute`,`path`,`query`,`header`,`body`,`autoGeneratedError`],qt={type:`Promise<Response>`,metadata:`{resultExtractor: ResultExtractors.Response }`},Jt={type:`Promise<string>`,metadata:`{resultExtractor: ResultExtractors.Text }`},Yt=`{
10
+ headers: { Accept: ContentTypeValues.TEXT_EVENT_STREAM },
11
+ resultExtractor: JsonEventStreamResultExtractor,
12
+ }`;function Xt(e){P(e,Ut,Wt)}function Zt(e){P(e,Gt,Kt)}function Qt(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 $t(t){t.implements=[...[t.implements??[]].flat(),`ApiMetadataCapable`],t.ctors??=[],t.ctors.push({parameters:[{name:`apiMetadata`,type:`ApiMetadata`,hasQuestionToken:!0,scope:e.Scope.Public,isReadonly:!0}]})}function en(e){return e===`delete`?`del`:e}var tn=`@ahoo-wang/fetcher-eventstream`;function nn(e){P(e,tn,[`JsonEventStreamResultExtractor`,`JsonServerSentEventStream`])}function rn(e,t){let n=t.modules.module(e.file);Xt(n),Zt(n),nn(n);let r=Qt(e.className,n);I(r,[e.description]),$t(r);let i=an(e.className,n,t);for(let t of e.methods)(r.methods??=[]).push(on(t,i))}function an(e,t,n){let r={context:n.types,owner:{name:e},specifierOf:e=>ht(t,n.outputDir,e),imports:t.imports};return{module:t,resolveType(e){let n=Rt(e,r);return t.imports.apply(n.imports),n.text}}}function on(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:[w(i.parameterName)]}]});e.body&&(e.body.required?n:r).push({name:e.body.name,type:sn(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=cn(e.returns,t),o=w(e.path),s={name:e.name,decorators:[{name:en(e.httpMethod),arguments:a.metadata?[o,a.metadata]:[o]}],parameters:i,returnType:a.type,statements:[`throw autoGeneratedError(${i.map(e=>e.name).join(`,`)});`]};return I(s,[...e.docs]),s}function sn(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:(P(t.module,Ut,[`PartialBy`]),`PartialBy<${e}, ${r.map(w).join(` | `)}>`)}case`formData`:return`FormData`;case`urlEncoded`:return`URLSearchParams`;case`text`:return`string`;case`binary`:return`BodyInit`}}function cn(e,t){switch(e.kind){case`json`:{let n=t.resolveType(e.schema);return e.wildcard&&n===`string`?Jt:{type:`Promise<${n}>`}}case`eventStream`:{if(!e.items)return{type:`Promise<JsonServerSentEventStream<any>>`,metadata:Yt};let n=t.resolveType(e.items);return{type:`Promise<JsonServerSentEventStream<${e.serverSentEvent?`${n}['data']`:n}>>`,metadata:Yt}}case`text`:return Jt;case`response`:return qt}}function ln(e){return Mt(e,{ofKey:e=>N(e),ofReference:$e})}function un(e,t){new fn(e,t.modules.module(e.file),t).write()}function dn(e){let t=new Set,n=new Map;for(let r of e){let e=ne(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,C(a))}return n}var fn=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=>ht(t,n.outputDir,e),imports:t.imports}}write(){let e=this.process();e&&bt(e,this.model.schema,this.model.key,this.target.schemaDocs===`full`)}process(){let{schema:e}=this.model;return T(e)?this.processTypeAlias(e):j(e)?this.processEnum(e):e.const!==void 0||e.nullable&&e.type||M(e)&&(e.type||e.properties||e.required)?this.processTypeAlias(e):Ae(e)?this.processInterface(e):Ie(e)&&typeof e.additionalProperties==`object`&&!Re(e)&&!e.required?.length?this.processIndexSignature(e):je(e)?this.processArray(e):M(e)?this.processComposition(e):this.processTypeAlias(e)}scope;emit(e){return this.module.imports.apply(e.imports),e.text}resolveType(e){return this.emit(Rt(e,this.scope))}processEnum(t){let n=ke(t);if(n){let t=dn(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:R(n[e])}))})}let r=[...new Set(t.enum.filter(e=>typeof e==`string`))],i=dn(r);return M(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:R(e)}))})}addPropertyToInterface(e,t,n){let r={name:C(t),type:this.resolveType(n),isReadonly:ze(n)};(e.properties??=[]).push(r),yt(r,n)}processInterface(t){if(At(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:C(e),type:this.emit(Vt(t,this.scope))});return this.emit(zt(t,this.scope))&&n.push(pt(this.emit(Bt(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:Fe(n),isExported:!0})}processIndexSignature(t){return this.module.add({kind:e.StructureKind.Interface,name:this.modelInfo.name,isExported:!0,properties:[pt(this.emit(Ht(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})}};function pn(e,t){e.models.forEach(e=>un(e,t)),e.apiClients.forEach(e=>rn(e,t))}function mn(e,t){let n=[];return hn(e,t,n),n}function hn(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:_n(t)})}for(let i of e.getDirectories()){let e=hn(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:gn(i,r,t,n)}function gn(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])=>k(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 _n(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 vn(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 yn(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())&&!vn(t)){let e=t.getSymbol();e&&i.add(e.compilerSymbol)}}),n.map(e=>bn(e,e=>{let t=e.getSymbol();return!!t&&!i.has(t.compilerSymbol)}))}function bn(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 xn(e){let t=e.flatMap(yn);for(let e of t)e()}var Sn=new Set([2300,2304,2308,2315,2393,2395,2440,2451,2456,2503,2552,2749]);function Cn(t){let n=[];for(let r of t)for(let t of r.getPreEmitDiagnostics()){if(!Sn.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(`
13
+ `)}`)}var wn=`// Code generated by wow-generator. DO NOT EDIT.
14
+
15
+ `,Tn={indentSize:2,tabSize:2,convertTabsToSpaces:!0,semicolons:`insert`,insertSpaceAfterOpeningAndBeforeClosingNonemptyBraces:!0};function En(e,t){e.forEach((n,r)=>{t.debug(`Optimizing file [${n.getFilePath()}] - ${r+1}/${e.length}`),n.formatText(Tn),n.organizeImports(Tn)}),xn(e),Cn(e);for(let t of e)t.insertText(0,wn)}var Dn=3e4;function On(e){return/^https?:\/\//i.test(e)}function kn(e,t={}){return On(e)?An(e,t):Mn(e)}async function An(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`:jn(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 jn(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 Mn(e){return new Promise((t,n)=>{(0,r.readFile)(e,`utf-8`,(e,r)=>{e?n(e):t(r)})})}async function Nn(e,t){let n;try{n=await kn(e,t)}catch(t){throw new s(`input`,`Cannot read the OpenAPI document ${e}: ${c(t)}`,{cause:t})}try{return Fn(n)}catch(t){throw new s(`input`,`Cannot parse the OpenAPI document ${e}: ${c(t)}`,{cause:t})}}function Pn(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 Fn(e){switch(In(e)){case`json`:return JSON.parse(e);case`yaml`:return(0,n.parse)(e)}}function In(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`)}async function Ln(e,t,n){if(e!==void 0)return{...await Bn({path:e,explicit:!0},t,n),origin:Vn(e)};let r=await Bn({path:a,explicit:!1},t,n);return r===void 0?(t.debug(`No configuration file found, generating with defaults`),{config:{},warnings:[]}):{...r,origin:Vn(a)}}var Rn=[`apiClients`],zn=[`ignorePathParameters`,`methodNames`];async function Bn(e,t,n){let r=Vn(e.path);t.debug(`Reading configuration: ${r}`);let i;try{i=await kn(e.path,n)}catch(n){if(!e.explicit&&Hn(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=Fn(i)}catch(e){throw new s(`configuration`,`Cannot parse configuration ${r}: ${c(e)}`,{cause:e})}let o=Wn(a,r);return t.debug(`Configuration loaded from ${r}: ${Kn(o.config)}`),o}function Vn(e){return On(e)||(0,t.isAbsolute)(e)?e:(0,t.resolve)(e)}function Hn(e){return typeof e==`object`&&!!e&&e.code===`ENOENT`}function B(e){return e===null?`null`:Array.isArray(e)?`an array`:`a ${typeof e}`}function V(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Un(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 Wn(e,t){if(!V(e))throw new s(`configuration`,`Configuration ${t} must be a JSON or YAML object, found ${B(e)}`);let n=[];return Un(n,t,`configuration`,e,Rn),Gn(e.apiClients,t,n),{config:e,warnings:n}}function Gn(e,t,n){if(e!==void 0){if(!V(e))throw new s(`configuration`,`apiClients in ${t} must be an object keyed by tag name, found ${B(e)}`);for(let[r,i]of Object.entries(e)){if(!V(i))throw new s(`configuration`,`apiClients["${r}"] in ${t} must be an object, found ${B(i)}`);Un(n,t,`apiClients["${r}"]`,i,zn);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 ${B(e)}`);let{methodNames:a}=i;if(a!==void 0){if(!V(a))throw new s(`configuration`,`apiClients["${r}"].methodNames in ${t} must be an object mapping operationIds to method names, found ${B(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 Kn(e){let t=Object.keys(e.apiClients??{});return`apiClients=${t.length?t.join(`, `):`none`}`}var qn=new Set,Jn=`#/$defs/`;function H(e){return e.startsWith(Jn)?e.slice(8):void 0}function Yn(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 U(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Xn(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=(n.requires??[]).filter(e=>!qn.has(e));if(r.length>0)throw new s(`input`,`${t} requires ${r.join(`, `)}, which this wow-generator does not understand: generate with a newer one.`);let i=[];if(n.contexts.forEach((e,t)=>{!U(e)||typeof e.name!=`string`?i.push(`contexts[${t}] has no name`):(e.aggregates??[]).forEach((t,n)=>{let r=`${e.name}.aggregates[${n}]`;!U(t)||typeof t.name!=`string`?i.push(`${r} has no name`):!U(t.state)||typeof t.state.schema!=`string`?i.push(`${e.name}.${t.name} has no state schema`):((t.commands??[]).forEach(n=>{(typeof n?.name!=`string`||typeof n.schema!=`string`)&&i.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`)&&i.push(`an event of ${e.name}.${t.name} has no name or schema`)}))})}),n.$defs!==void 0&&!U(n.$defs)&&i.push(`$defs is not an object`),i.length>0)throw new s(`specification`,`${t} is not a Manifest wow-generator can read: ${i.join(`; `)}.`);return n}function W(e){let t=e.type;return typeof t==`string`?[t]:Array.isArray(t)?t.filter(e=>typeof e==`string`):[]}var Zn=[`Omit`,`Promise`,`Record`],Qn=[`CommandClient`,`CommandOptions`,`CommandResult`,`CommandResultStream`,`CommittedEvent`,`CreateCommandOptions`,`EventQueryClient`,`Hop`,`LifecycleCommands`,`MANIFEST_FORMAT`,`NoAccess`,`OwnStateClient`,`RequestOptions`,`RoutingManifest`,`ServiceRoutes`,`SnapshotQueryClient`,`StateClient`,`SystemEvent`,`WowClientOptions`],$n=[`Client`,`Contract`,`ErrorCode`,`Manifest`,`Routes`,`Subscription`],er=[`Access`,`Aggregate`,`CommandClient`,`Event`,`EventQueryClient`,`SnapshotQueryClient`,`StateClient`,`StateField`];function tr(e){return v(b(e.name))}function nr(e){return v(b(e.name))}function rr(e){let t=new Set([...Zn,...Qn]);for(let n of e.contexts){let e=tr(n);for(let n of $n)t.add(`${e}${n}`);for(let e of n.aggregates??[]){let n=nr(e);for(let e of er)t.add(`${n}${e}`)}}return t}function ir(){return new Set([`body`,`query`,`options`])}function ar(e,t){return e.in===`path`?re(e.name,t):e.name}var or={string:`string`,integer:`string`,boolean:`boolean`};function sr(e){return(e.access??[]).map(e=>({name:e.name,type:or[e.type]??`string | number | boolean`,multiple:e.multiple??!1,integer:e.type===`integer`}))}var cr={"wow.lifecycle.TransferOwner":`TransferOwner`,"wow.lifecycle.TransferSpace":`TransferSpace`},lr=new Set([`wow.lifecycle.DeleteAggregate`,`wow.lifecycle.RestoreAggregate`,`wow.lifecycle.TransferOwner`,`wow.lifecycle.TransferSpace`]);function ur(e,t,n){if(t===void 0)return!0;let r=e.resolve(t);return!Array.isArray(r.required)||r.required.every(e=>e===n)}function dr(e,t,n){if(t===void 0)return!1;let r=e.resolve(t).properties,i=U(r)?r[n]:void 0;return U(i)&&i.readOnly===!0}function fr(e){return(e.commands??[]).filter(e=>e.system!==!0&&e.internal!==!0)}function pr(e){return(e.commands??[]).filter(e=>e.system===!0&&e.name.startsWith(`wow.lifecycle.`))}function mr(e,t){return[t.state.schema,...fr(t).map(e=>e.schema),...(t.events??[]).map(e=>e.schema)].map(H).filter(e=>e!==void 0).concat(hr(e,t))}function hr(e,t){return pr(t).map(e=>e.name).filter(t=>cr[t]!==void 0&&e.schemaOf(t))}function gr(e){return(e.routes??[]).map(e=>({method:e.method,path:e.path}))}function _r(e,t,n){let r=H(t);return r===void 0?`unknown`:e.refType(r,n)}function vr(e,t,n,r){let i=`${n.name}.${r.name}`,a=nr(r),o=r.idSource??`assigned`,s=o===`owner`,c=new Set(hr(e,r)),l=pr(r).filter(e=>lr.has(e.name)).map(t=>{let n=t.name,r=n.split(`.`).pop(),a=e.schemaOf(n)?.description,o=g(x(r)),l=s&&(t.routes??[]).some(e=>!e.path.includes(`{id}`));return{name:n,member:S(r),method:o,routes:gr(t),...l?{ownMethod:`${o}Own`}:{},...c.has(n)?{bodyType:e.refType(n,i),bodyGenerated:!0}:cr[n]?{bodyType:cr[n]}:{},...typeof a==`string`?{description:a}:{}}}),u=new Set(l.flatMap(e=>[e.method,e.ownMethod??e.method])),d=fr(r).map(n=>{let r=g(x(n.name));(u.has(r)||r===`gateway`)&&(r=`${r}Command`),u.add(r);let a=(n.routes??[]).filter(e=>e.method===`POST`),o=a.find(e=>e.path.includes(`{id}`)),c=a.find(e=>!e.path.includes(`{id}`)),l;s&&o&&c&&!(n.mounted??!1)&&(l=`${r}Own`,u.has(l)&&(l=`${l}Command`),u.add(l));let d=H(n.schema),f=d===void 0?void 0:e.schemaOf(d),p=n.idProperty,m=p!==void 0&&dr(e,f,p);return{name:n.name,method:r,routes:gr(n),...o?{byIdPath:{path:o.path}}:{},...c?{unaddressedPath:{path:c.path}}:{},...l===void 0?{}:{ownMethod:l},bodyType:_r(e,n.schema,`${i}.${n.name}`),bodyOptional:ur(e,f,m?p:void 0),...p===void 0?{}:{idProperty:p},...m?{idComputed:m}:{},creation:n.creation??`none`,mounted:n.mounted??!1,produces:n.produces??[],...n.description?{description:n.description}:{},...t.marks({$ref:n.schema},n.schema)===void 0?{}:{bodyNumbers:!0}}}),f=t.marks({$ref:r.state.schema},r.state.schema),p=Object.fromEntries((r.events??[]).flatMap(e=>{let i=t.marks({$ref:e.schema},e.schema);return i===void 0?[]:[[yr(n,r,e.name),i]]})),m=Object.fromEntries(fr(r).flatMap(e=>{let n=t.marks({$ref:e.schema},e.schema);return n===void 0?[]:[[e.name,n]]})),h=sr(r),_=Object.fromEntries(h.filter(e=>e.integer).map(e=>[e.name,!e.multiple||{members:{"*":!0}}])),v={...f===void 0?{}:{state:f},...Object.keys(p).length===0?{}:{events:p},...Object.keys(m).length===0?{}:{commands:m},...Object.keys(_).length===0?{}:{access:{members:_}}},y=H(r.state.schema),ee=y===void 0?void 0:e.schemaOf(y);return{context:n.name,name:r.name,...r.description?{description:r.description}:{},typeName:a,directory:`${n.name}/${r.name}`,ownership:r.ownership??`owner`,idSource:o,snapshot:r.snapshot?.enabled??!0,stateType:_r(e,r.state.schema,`${i} state`),stateFields:ee===void 0?[]:e.fields({$ref:r.state.schema},`state`),commands:d,events:(r.events??[]).map(t=>({name:t.name,wireName:yr(n,r,t.name),revision:t.revision??1,type:_r(e,t.schema,`${i}.${t.name}`)})),lifecycle:l,queryModels:(r.queries??[]).map(e=>e.model),access:h,...Object.keys(v).length===0?{}:{textNumbers:v}}}function yr(e,t,n){return n.includes(`.`)?n:`${e.name}.${t.name}.${n}`}var br=new Set([`int64`,`bigint`,`decimal`]),G=class{path;detail;constructor(e,t){this.path=e,this.detail=t}},xr=class{defs;constantOf;shapes=new Map;reading=new Set;lazy=new Map;setAside=[];variants=new Map;constructor(e,t){this.defs=e,this.constantOf=t}marks(e,t){let n=this.shape(e,t);return this.settle(),this.toMarks(n)}settle(){for(let{where:e,name:t,index:n,shape:r}of this.setAside.splice(0))if(this.exact(r,new Set))throw new s(`specification`,`The alternatives of ${e} are told apart by their \`${t}\`, but alternative ${n+1} has none and holds exact numbers no reader could choose by it. Give it a \`${t}\` too, or take it out of the union.`)}declarations(){let e=new Map;for(;e.size<this.lazy.size;)for(let[t,n]of[...this.lazy]){if(e.has(t))continue;let r=this.variants.get(t);e.set(t,{key:r?.key??t,...r===void 0?{}:{beside:!0},...n,marks:this.toMarks(r?.shape??this.shapes.get(t))})}return[...e.values()].sort((e,t)=>e.name<t.name?-1:+(e.name>t.name))}shape(e,t){if(!U(e))return;if(typeof e.$ref==`string`){let t=H(e.$ref);return t===void 0?void 0:this.shapeOf(t)}let n=[],r=W(e).find(e=>e===`number`||e===`integer`);if(r!==void 0){let t=typeof e.format==`string`?e.format:``;n.push({number:{exact:br.has(t),format:t||r}})}let i={};if(U(e.properties))for(let[n,r]of Object.entries(e.properties)){let e=this.shape(r,`${t}.${n}`);e!==void 0&&(i[n]=e)}let a=K([this.shape(e.items,`${t}.*`),this.shape(e.additionalProperties,`${t}.*`)]);a!==void 0&&(i[`*`]=a),Object.keys(i).length>0&&n.push({members:i});for(let r of[`oneOf`,`anyOf`]){let i=e[r];Array.isArray(i)&&n.push(this.either(i,t))}return Array.isArray(e.allOf)&&n.push(...e.allOf.map(e=>this.shape(e,t))),K(n)}shapeOf(e){if(this.reading.has(e))return{ref:e};if(this.shapes.has(e))return this.shapes.get(e);let t=this.defs[e];if(!U(t))return;this.reading.add(e);let n=this.shape(t,e);return this.reading.delete(e),this.shapes.set(e,n),n}either(e,t){let n=e.map(e=>this.shape(e,t));try{return n.reduce((e,t)=>this.merge(e,t,``),void 0)}catch(r){if(!(r instanceof G))throw r;let i=this.discriminant(e);if(i===void 0)throw new s(`specification`,`The alternatives of ${t} disagree at ${r.path||`their root`}: ${r.detail}, and no member with a constant value tells them apart. Give the alternatives a discriminator (@JsonTypeInfo with @JsonSubTypes), or the same number format.`);let a={},o;return e.forEach((e,r)=>{let s=this.constant(e,i),c=n[r];s===void 0?(c!==void 0&&this.setAside.push({where:t,name:i,index:r,shape:{...c,number:void 0}}),o=this.merge(o,c,``)):c!==void 0&&(a[s]=c)}),K([o?.number?{number:o.number}:void 0,{by:{name:i,cases:a}}])}}discriminant(e){let t=e.map(e=>this.properties(e,new Set)).filter(e=>Object.keys(e).length>0);if(!(t.length<2))return Object.keys(t[0]).sort().find(e=>{let n=t.map(t=>Cr(t[e]));return n.every(e=>e!==void 0)&&new Set(n).size===n.length})}constant(e,t){return Cr(this.properties(e,new Set)[t])}properties(e,t){if(!U(e))return{};if(typeof e.$ref==`string`){let n=H(e.$ref);return n===void 0||t.has(n)?{}:this.properties(this.defs[n],new Set([...t,n]))}return Object.assign({},...(Array.isArray(e.allOf)?e.allOf:[]).map(e=>this.properties(e,t)),U(e.properties)?e.properties:{})}merge(e,t,n){if(e===void 0)return t;if(t===void 0||e.ref!==void 0&&e.ref===t.ref&&e.beside===void 0&&t.beside===void 0)return e;if(e.ref!==void 0||t.ref!==void 0)return this.merge(this.expand(e),this.expand(t),n);if(e.by!==void 0||t.by!==void 0)throw new G(n,`one is an object told apart by a member, another is not`);let r=e.number??t.number;if(e.number&&t.number&&e.number.exact!==t.number.exact){let[r,i]=e.number.exact?[e.number,t.number]:[t.number,e.number];throw new G(n,`one is \`${r.format}\`, read as its exact text, another \`${i.format}\`, read as a number`)}e.number?.exact&&(r=e.number);let i={...e.members};for(let[e,r]of Object.entries(t.members??{}))i[e]=this.merge(i[e],r,n===``?e:`${n}.${e}`);return{...r===void 0?{}:{number:r},...Object.keys(i).length===0?{}:{members:i}}}expand(e){if(e.ref===void 0)return e;if(this.shapes.has(e.ref))return K([this.shapes.get(e.ref),e.beside]);throw new G(``,`one is \`${e.ref}\`, a recursive type not yet read, another is not`)}toMarks(e){if(e===void 0)return;if(e.ref!==void 0){let t=e.ref,n=this.exact(e.beside,new Set);if(!n&&!this.exact({ref:t},new Set))return;let r=n?`${t} ${JSON.stringify(e.beside)}`:t,i=this.lazy.get(r);if(i===void 0){if(i=this.constantOf(t),n){let n=[...this.variants.values()].filter(e=>e.key===t).length;i={...i,name:`${i.name}${n+2}`},this.variants.set(r,{key:t,shape:K([this.shapes.get(t),e.beside])})}this.lazy.set(r,i)}return{lazy:i}}let t;if(e.by!==void 0){let n=Sr(e.by.cases,e=>this.toMarks(e));t=n===void 0?void 0:{by:e.by.name,cases:n}}else if(e.members!==void 0){let n=Sr(e.members,e=>this.toMarks(e));t=n===void 0?void 0:{members:n}}return e.number?.exact?t===void 0||{or:t}:t}exact(e,t){return e===void 0?!1:e.ref===void 0?e.number?.exact===!0||Object.values(e.members??{}).some(e=>this.exact(e,t))||Object.values(e.by?.cases??{}).some(e=>this.exact(e,t)):this.exact(e.beside,t)?!0:!t.has(e.ref)&&(t.add(e.ref),this.exact(this.shapes.get(e.ref),t))}};function K(e){return e.reduce((e,t)=>{if(e===void 0)return t;if(t===void 0)return e;if(e.ref!==void 0||t.ref!==void 0){let[n,r]=e.ref===void 0?[t,e]:[e,t];return{ref:n.ref,beside:K([n.beside,r])}}let n=e.number?.exact||t.number===void 0?e.number??t.number:t.number,r={...e.members};for(let[e,n]of Object.entries(t.members??{}))r[e]=K([r[e],n]);let i=e.by??t.by;return{...n===void 0?{}:{number:n},...i===void 0?Object.keys(r).length===0?{}:{members:r}:{by:{name:i.name,cases:Object.fromEntries(Object.entries(i.cases).map(([e,t])=>[e,K([t,{members:r}])]))}}}},void 0)}function Sr(e,t){let n=Object.entries(e).flatMap(([e,n])=>{let r=t(n);return r===void 0?[]:[[e,r]]});return n.length===0?void 0:Object.fromEntries(n)}function Cr(e){if(U(e))return typeof e.const==`string`?e.const:Array.isArray(e.enum)&&e.enum.length===1&&typeof e.enum[0]==`string`?e.enum[0]:void 0}function wr(e){let t=0;for(let n=0;n<e.length;n++){let r=e[n];if(r===`'`)for(n++;n<e.length&&e[n]!==`'`;n++)e[n]===`\\`&&n++;else if(`({[<`.includes(r))t++;else if(`)}]`.includes(r)||r===`>`&&e[n-1]!==`=`)t--;else if(t===0&&(r===`|`||r===`&`)&&e[n-1]===` `&&e[n+1]===` `)return!0}return!1}function Tr(e,t){let n=[...new Set(e)];return n.length===1?n[0]:n.map(e=>wr(e)?`(${e})`:e).join(t)}function Er(e){return typeof e==`string`?w(e):JSON.stringify(e)}var Dr=4,Or=class{defs;names=new Map;warnings=[];constructor(e){this.defs=e}inlined(e){return e.includes(`(`)}name(e,t){let n=new Set(e);for(let e=0;n.size>0;e++){let r=new Map;for(let t of n.keys()){let n=t.split(`.`),i=n[n.length-1].split(`$`),a=v([...n.slice(Math.max(0,n.length-1-e),n.length-1),...i].map(e=>/^[a-z]/.test(e)?b(e):e));r.set(a,[...r.get(a)??[],t])}let i=new Set([...t,...this.names.values()]);for(let[t,a]of r){let r=a.filter(t=>t.split(`.`).length-1<=e),o=a.length===1&&!i.has(t)?a:r;for(let e of o){let r=t;for(let e=2;i.has(r);e++)r=`${t}${e}`;i.add(r),this.names.set(e,r),n.delete(e)}}}}schemaOf(e){let t=this.defs[e];return U(t)?t:void 0}resolve(e,t=new Set){let n=e.$ref;if(typeof n!=`string`)return e;let r=H(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(U(e))for(let[n,r]of Object.entries(e))if(n===`$ref`&&typeof r==`string`){let e=H(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(!U(e))return`unknown`;if(typeof e.$ref==`string`){let n=H(e.$ref);return n===void 0?`unknown`:this.refType(n,t)}if(`const`in e)return Er(e.const);if(Array.isArray(e.enum))return e.enum.length===0?`never`:Tr(e.enum.map(Er),` | `);for(let[n,r]of[[`oneOf`,` | `],[`anyOf`,` | `],[`allOf`,` & `]]){let i=e[n];if(Array.isArray(i)&&i.length>0)return Tr(i.map(e=>this.type(e,t)),r)}let n=W(e);return n.length===0?U(e.properties)?this.objectType(e,t):`unknown`:Tr(n.map(n=>this.primitive(n,e,t)),` | `)}primitive(e,t,n){switch(e){case`string`:return`string`;case`integer`:case`number`:return typeof t.format==`string`&&br.has(t.format)?`string`:`number`;case`boolean`:return`boolean`;case`null`:return`null`;case`array`:{let e=t.items===void 0?`unknown`:this.type(t.items,n);return wr(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(!U(e.properties))return[];let n=new Set(Array.isArray(e.required)?e.required:[]);return Object.entries(e.properties).map(([e,r])=>{let i=U(r)?r.description:void 0;return{name:C(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=W(e);return U(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`?H(e.$ref):void 0;if(a!==void 0&&r.has(a))return[];let o=a===void 0?r:new Set([...r,a]);if(!U(i.properties))return[];let s=[];for(let[e,r]of Object.entries(i.properties)){let i=`${t}.${e}`;s.push(i),n<Dr&&U(r)&&(W(this.resolve(r)).includes(`array`)||s.push(...this.fields(r,i,n+1,o)))}return s}};function kr(e,t,n,r){let i=`${n.name} route ${r.name}`,a=ir();return{name:r.name,method:r.route.method,path:r.route.path,...r.description?{description:r.description}:{},deprecated:r.deprecated===!0,parameters:(r.parameters??[]).map(t=>({name:t.name,identifier:ar(t,a),location:t.in===`path`?`path`:`query`,type:e.type(t.schema,`${i} ${t.name}`),required:t.required})),...r.request===void 0?{}:{requestType:e.type(r.request,`${i} body`)},...r.response===void 0?{}:{responseType:Ar(e.type(r.response,`${i} answer`),r.responseOptional===!0)},...jr(t.marks(r.request,`${i} body`),t.marks(r.response,`${i} answer`))}}function Ar(e,t){return t?`${e} | undefined`:e}function jr(e,t){return e===void 0&&t===void 0?{}:{textNumbers:{...e===void 0?{}:{request:e},...t===void 0?{}:{response:t}}}}function Mr(e){let t=new Or(e.$defs??{}),n=e.contexts,r=new Map;for(let e of n){let n=[...(e.aggregates??[]).flatMap(e=>mr(t,e)),...(e.routes??[]).flatMap(e=>[...t.references(e.request),...t.references(e.response)])];for(let i of t.closure(n).sort(k))r.has(i)||r.set(i,e.name)}let i=[...r.keys()].filter(e=>t.schemaOf(e)&&!t.inlined(e));t.name([...i].sort(k),rr(e));let a=i.map(e=>Nr(t,e,`${r.get(e)}/types.ts`)).sort((e,t)=>k(e.file,t.file)||k(e.name,t.name)),o=new xr(e.$defs??{},e=>({name:`${x(t.names.get(e)??e)}Numbers`,file:`${r.get(e)}/textNumbers.ts`})),s=n.map(e=>Pr(t,o,e)).map(e=>({...e,textNumbers:o.declarations().filter(t=>t.file===`${e.directory}/textNumbers.ts`)}));return{model:{...e.service?.name?{service:e.service.name}:{},types:a,contexts:s},warnings:[...new Set(t.warnings)]}}function Nr(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(k)};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 Pr(e,t,n){return{name:n.name,...n.description?{description:n.description}:{},typeName:tr(n),constantName:S(n.name),directory:n.name,errors:(n.errors??[]).map(e=>({code:e.code,status:e.status,...e.description?{description:e.description}:{}})),subscriptions:[...new Set((n.subscriptions??[]).map(e=>e.name))].sort(k),aggregates:(n.aggregates??[]).map(r=>vr(e,t,n,r)),routes:(n.routes??[]).map(r=>kr(e,t,n,r))}}var q=`@ahoo-wang/wow-client`,Fr=`@ahoo-wang/wow-client/routes`;function J(e,t=``){let n=e.filter(e=>typeof e==`string`&&e!==``).flatMap(e=>_t(e).split(`
16
+ `));return n.length===0?``:n.length===1?`${t}/** ${n[0]} */\n`:`${t}/**\n${n.map(e=>`${t} * ${e}`.trimEnd()).join(`
17
+ `)}\n${t} */\n`}function Y(e,t){e.add(`\n${t}`)}function X(e){return e.length===0?`never`:e.join(` | `)}function Z(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(F(e.directoryPath,(0,i.join)(t,n)),r)}function Ir(e,t){let n=e.aggregates.map(t=>`${e.name}.${t.name}.`),r=t===void 0?`${e.name}.`:`${e.name}.${t.name}.`;return e.errors.filter(e=>t===void 0?!n.some(t=>e.code.startsWith(t)):e.code.startsWith(r)).map(e=>({member:S((e.code.startsWith(r)?e.code.slice(r.length):e.code).split(/[^A-Za-z0-9]+/))||`ERROR`,error:e}))}function Lr(e,t){return e.length===0?``:`${t}Errors: {\n${e.map(({member:e,error:n})=>`${J([`${n.status}: ${n.description??n.code}`],`${t} `)}${t} ${e}: ${w(n.code)},`).join(`
18
+ `)}\n${t}},\n`}function Rr(e,t,n){let r=t.module(`${e.directory}/contract.ts`),a=`${e.typeName}Contract`;r.imports.add(q,[`Hop`,`wait`]);for(let t of e.aggregates)r.imports.add(F(r.directoryPath,(0,i.join)(n,t.directory,`aggregate.ts`)),[`${t.typeName}Aggregate`]);let o=e.aggregates.map(e=>` ${e.typeName}: ${e.typeName}Aggregate,\n`);Y(r,`${J([`The bounded context \`${e.name}\`: its name, its error codes and its aggregates, as the Kotlin \`${a}\` names them. A problem's \`code\` is one of its \`Errors\`, or of an aggregate's.`,e.description])}export const ${a} = {\n NAME: ${w(e.name)},\n${Lr(Ir(e),` `)}${o.join(``)}} as const;`),Y(r,`${J([`An error code of \`${e.name}\`, of the context or of one of its aggregates.`])}export type ${e.typeName}ErrorCode = ${X(e.errors.map(e=>w(e.code)))};`);let s=e.subscriptions.length>0;s&&Y(r,`${J([`The subscriptions of \`${e.name}\` a \`handled\` hop names.`])}export type ${e.typeName}Subscription = ${X(e.subscriptions.map(w))};`);let c=`${a}.NAME`,l=[` /** Until a command of \`${e.name}\` passed admission. */\n accepted: (): Hop => wait.accepted(${c}),`,` /** Until a command's events are appended to the log of \`${e.name}\`. */\n committed: (): Hop => wait.committed(${c}),`,` /** Until the snapshot of \`${e.name}\` holds the commit. */\n snapshot: (): Hop => wait.snapshot(${c}),`,` /** Until the store the snapshot queries of \`${e.name}\` read holds the commit. */\n queryable: (): Hop => wait.queryable(${c}),`];s&&l.push(` /** Until a subscription of \`${e.name}\` handled the commit. */\n handled: (subscription: ${e.typeName}Subscription): Hop => wait.handled(subscription, ${c}),`),Y(r,`${J([`The hops of a wait chain (\`Wow-Wait\`) in \`${e.name}\`.`])}export const ${x(e.name)}Wait = {\n${l.join(`
19
+ `)}\n} as const;`)}function Q(e,t){if(e===!0)return`true`;if(`members`in e)return zr(e.members,t);if(`lazy`in e){let n=F(t.module.directoryPath,(0,i.join)(t.outputDir,e.lazy.file));return n!==`./${(0,i.basename)(t.module.sourceFile.getFilePath(),`.ts`)}.js`&&t.module.imports.add(n,[e.lazy.name]),`() => ${e.lazy.name}`}return`or`in e?(t.module.imports.add(t.client,[`textNumberOr`]),`textNumberOr(${Q(e.or,t)})`):(t.module.imports.add(t.client,[`textNumbersBy`]),`textNumbersBy(${w(e.by)}, ${zr(e.cases,t)})`)}function zr(e,t){return`{ ${Object.entries(e).map(([e,n])=>`${C(e)}: ${Q(n,t)}`).join(`, `)} }`}function Br(e,t){let n=e.textNumbers;return n===void 0?``:` textNumbers: {\n${[`state`,`events`,`commands`,`access`].flatMap(e=>{let r=n[e];return r===void 0?[]:e===`state`||e===`access`?[` ${e}: ${Q(r,t)},`]:[` ${e}: {\n${Object.entries(r).map(([e,n])=>` ${C(e)}: ${Q(n,t)},`).join(`
20
+ `)}\n },`]}).join(`
21
+ `)}\n },\n`}function Vr(e,t){let n=e.routes.flatMap(n=>{let r=n.textNumbers;if(r===void 0)return[];let i=[`request`,`response`].flatMap(e=>r[e]===void 0?[]:[`${e}: ${Q(r[e],t)}`]);return[`${w(`${e.name}.${n.name}`)}: { ${i.join(`, `)} }`]});return n.length===0?``:`, textNumbers: { ${n.join(`, `)} }`}function Hr(e,t,n,r){if(e.textNumbers.length===0)return;let i=t.module(`${e.directory}/textNumbers.ts`);i.imports.add(r,[`TextNumbers`]);let a={module:i,outputDir:n,client:r};for(let t of e.textNumbers)i.add(`\n/** The exact numbers of \`${t.key}\`${t.beside?" with what an `allOf` says beside it":``}, a recursive type: its own marks, and others', read them lazily. */\nexport const ${t.name}: TextNumbers = ${Q(t.marks,a)};`)}function Ur(e,t,n,r,i){let a=n.module(`${e.directory}/aggregate.ts`),o=e.typeName;Y(a,`${J([`The aggregate \`${e.context}.${e.name}\`.`,e.description])}export const ${o}Aggregate = {\n context: ${w(t.name)},\n name: ${w(e.name)},\n path: ${w(`/${t.name}/${e.name}`)},\n ownership: ${w(e.ownership)},\n${e.idSource===`assigned`?``:` idSource: ${w(e.idSource)},\n`} snapshot: ${e.snapshot},\n${Br(e,{module:a,outputDir:i,client:q})}${Lr(Ir(t,e),` `)}} as const;`),Y(a,`${J([`The \`state.*\` paths of \`${e.name}\`'s snapshots a query filters, sorts and projects on.`])}export type ${o}StateField = ${X(e.stateFields.map(w))};`),Wr(e,a);let s=e.events.map(e=>`CommittedEvent<${w(e.wireName)}, ${e.type}>`);a.imports.add(q,s.length>0?[`CommittedEvent`,`SystemEvent`]:[`SystemEvent`]),Y(a,`${J([`The events of \`${e.name}\`, named as the server sends them, \`${e.context}.${e.name}.<Event>\` at its current revision (the \`events\` query upgrades older records), and the system events every aggregate has.`])}export type ${o}Event = ${X([...s,`SystemEvent`])};`),Z(a,i,r,e.events.map(e=>e.type))}function Wr(e,t){let n=e.typeName,r=`\`${e.context}.${e.name}\``;if(e.access.length===0){t.imports.add(q,[`NoAccess`]),Y(t,`${J([`The access attributes of ${r}: it declares none.`])}export type ${n}Access = NoAccess;`);return}let i=e.access.map(e=>{let t=e.type.includes(`|`)?`(${e.type})`:e.type,n=e.multiple?`readonly ${t}[]`:`${e.type} | null`;return` readonly ${C(e.name)}?: ${n};`});Y(t,`${J([`The access attributes of ${r} (\`@Access\`) by name, as its records carry them: a single one's value or null, a multiple one's values. A record written before an attribute was declared lacks it.`])}export type ${n}Access = {\n${i.join(`
22
+ `)}\n};`)}function Gr(e,t){let n=(t===void 0?[e.byIdPath,e.unaddressedPath]:[t?e.unaddressedPath:e.byIdPath]).filter(e=>e!==void 0).map(e=>`\`POST ${e.path}\``).join(`, `),r=e.creation===`required`?`Creates the aggregate.`:e.creation===`allowed`?`Creates the aggregate, or acts on the one that exists.`:void 0;return J([e.description,`\`${e.name}\`${e.mounted?`, mounted (a transformer finds its aggregate)`:``}${t===!0?`, to the caller's own aggregate, whose id is the caller's owner`:``}: ${n}.`,t===!1?"By id, for a caller with no owner; `"+e.ownMethod+"` sends it to the caller's own.":void 0,e.idProperty===void 0?void 0:`Its body names its aggregate: \`${e.idProperty}\`${e.idComputed?`, which the service computes from the fields given`:``}.`,r,e.produces.length>0?`Produces ${e.produces.map(e=>`\`${e}\``).join(`, `)}.`:void 0],` `)}function $(e,t,n,r){let i=e.bodyType===`unknown`?`object`:e.bodyType,a=e.idComputed?`Omit<${i}, ${w(e.idProperty)}>`:i,o=e.bodyOptional?`body: ${a} = {}`:`body: ${a}`,s=n?`stream`:`wait`,c=n?`Promise<CommandResultStream>`:`Promise<CommandResult>`,l=r===!0?e.ownMethod:e.method,u=n?`${l}Stream`:l,d=n?J([`\`${e.name}\`${r===!0?` to the caller's own aggregate`:``}, answered as one result per hop of its wait (\`text/event-stream\`).`],` `):Gr(e,r),f=w(`${t.context}.${t.name}.${e.name}`),p=e=>`{ ...options, command: ${f}, body${e} }`,m=r===void 0?e.byIdPath:!r,h=r===void 0?e.unaddressedPath:r,g=m&&h?`CreateCommandOptions`:`CommandOptions`,_=m&&!h?`id: string, `:``,v=p(m&&!h?`, id`:``);return n?`${d} ${u}(${_}${o}, options?: ${g}): ${c} {\n return this.client.${s}(${v});\n }`:Kr(d,u,`${_}${o}`,g,v)}function Kr(e,t,n,r,i){return`${e} ${t}(${n?`${n}, `:``}options?: ${r}): Promise<CommandResult> {\n return this.client.wait(${i});\n }`}function qr(e,t,n,r,a){let o=n.module(`${e.directory}/commandClient.ts`),s=e.typeName,c=e.commands.filter(e=>e.byIdPath||e.unaddressedPath),l=c.flatMap(t=>t.ownMethod===void 0?[$(t,e,!1),$(t,e,!0)]:[!1,!0].flatMap(n=>[$(t,e,!1,n),$(t,e,!0,n)])),u=[`CommandClient`,`CommandResult`,`WowClientOptions`];c.length>0&&u.push(`CommandResultStream`);let d=e=>e.byIdPath!==void 0&&e.unaddressedPath!==void 0&&e.ownMethod===void 0;c.some(d)&&u.push(`CreateCommandOptions`),(c.some(e=>!d(e))||e.lifecycle.length>0)&&u.push(`CommandOptions`);let f=[];for(let t of e.lifecycle){u.push(`LifecycleCommands`),t.bodyType&&(t.bodyGenerated?f:u).push(t.bodyType);let n=t.bodyType?`body: ${t.bodyType}`:``,r=n=>`{ ...options, command: LifecycleCommands.${t.member}, type: { context: ${w(e.context)}, name: ${w(e.name)} }${n?`, id`:``}${t.bodyType?`, body`:``} }`;l.push(Kr(J([t.description,`The lifecycle command \`${t.name}\`.`,t.ownMethod===void 0?void 0:`By id, for a caller with no owner; \`${t.ownMethod}\` sends it to the caller's own.`],` `),t.method,n?`id: string, ${n}`:`id: string`,`CommandOptions`,r(!0))),t.ownMethod!==void 0&&l.push(Kr(J([t.description,`The lifecycle command \`${t.name}\`, to the caller's own aggregate, whose id is the caller's owner.`],` `),t.ownMethod,n,`CommandOptions`,r(!1)))}let p=c.filter(e=>e.bodyNumbers);p.length>0&&o.imports.add(`./aggregate.js`,[`${s}Aggregate`]);let m=p.length?`, bodyNumbers: {\n${p.map(t=>` ${w(`${e.context}.${e.name}.${t.name}`)}: ${s}Aggregate.textNumbers.commands${C(t.name)===t.name?`.${t.name}`:`[${w(t.name)}]`},`).join(`
23
+ `)}\n }`:``,h=`${t.typeName}Manifest`;o.imports.add(F(o.directoryPath,(0,i.join)(a,t.directory,`manifest.ts`)),[h]),o.imports.add(q,[...new Set(u)].sort()),Z(o,a,r,[...c.map(e=>e.bodyType),...f]),Y(o,`${J([`Sends the commands of \`${e.context}.${e.name}\` by its service's routes (\`${h}\`). Each method answers the result its wait plan ends with, as \`CommandClient.wait\` does: the server's default plan unless the options give one, \`{ wait: WaitPlan.ACCEPTED }\` to answer once it is accepted. A rejected command rejects with a \`CommandRejectedError\`; anything else that did not succeed with a \`WowProblemError\`.`])}export class ${s}CommandClient {\n readonly client: CommandClient;\n\n /** @param options - How the service is reached */\n constructor(options?: WowClientOptions) {\n this.client = new CommandClient(options, { manifest: ${h}${m} });\n }\n\n${l.join(`
24
+
25
+ `)}\n}`)}function Jr(e,t,n){let r=t.module(`${e.directory}/client.ts`),a=`${e.typeName}Client`;r.imports.add(q,[`CommandClient`,`WowClientOptions`]),r.imports.add(`./manifest.js`,[`${e.typeName}Manifest`]);let o=[],s=[];for(let t of e.aggregates){let e=t.typeName,a=e=>F(r.directoryPath,(0,i.join)(n,t.directory,e)),c=[[`commands`,`${e}CommandClient`]];t.queryModels.includes(`snapshot`)&&c.push([`snapshots`,`${e}SnapshotQueryClient`]),t.queryModels.includes(`events`)&&c.push([`events`,`${e}EventQueryClient`]),c.push([`state`,`${e}StateClient`]),r.imports.add(a(`commandClient.ts`),[`${e}CommandClient`]),r.imports.add(a(`queryClient.ts`),c.slice(1).map(([,e])=>e));let l=C(x(t.name));o.push(`${J([`The clients of \`${t.context}.${t.name}\`.`],` `)} readonly ${l}: {\n${c.map(([e,t])=>` readonly ${e}: ${t};`).join(`
26
+ `)}\n };`),s.push(` this.${l} = {\n${c.map(([e,t])=>` ${e}: new ${t}(options),`).join(`
27
+ `)}\n };`)}e.routes.length>0&&(r.imports.add(`./routes.js`,[`${e.typeName}Routes`]),o.push(`${J([`The service routes of \`${e.name}\`.`],` `)} readonly routes: ${e.typeName}Routes;`),s.push(` this.routes = new ${e.typeName}Routes(options);`)),Y(r,`${J([e.routes.length===0?`The clients of \`${e.name}\`: its command client, and per aggregate its command, query and state clients.`:`The clients of \`${e.name}\`: its command client, per aggregate its command, query and state clients, and its service routes.`])}export class ${a} {\n /** Sends any command of the service, by its Manifest's routes: \`send\`, \`wait\` and \`stream\`. */\n readonly commands: CommandClient;\n\n${o.join(`
28
+
29
+ `)}\n\n /** @param options - How the service is reached */\n constructor(options?: WowClientOptions) {\n this.commands = new CommandClient(options, { manifest: ${e.typeName}Manifest });\n${s.join(`
30
+ `)}\n }\n}`)}function Yr(e,t,n,r){let i=t.module(`${e.directory}/queryClient.ts`),a=e.typeName,o=e.stateType,s=e.idSource===`owner`,c=s?`OwnStateClient`:`StateClient`,l=[c,`WowClientOptions`],u=[`${a}Access`,`${a}Aggregate`,`${a}Event`],d=` /** @param options - How the service is reached */\n constructor(options?: WowClientOptions) {\n super(${a}Aggregate, options);\n }`;e.queryModels.includes(`snapshot`)&&(l.push(`SnapshotQueryClient`),u.push(`${a}StateField`),Y(i,`${J([`Queries the snapshots of \`${e.context}.${e.name}\`: \`POST /${e.context}/${e.name}/snapshot/query\`.`])}export class ${a}SnapshotQueryClient extends SnapshotQueryClient<${o}, ${a}StateField, ${a}Access> {\n${d}\n}`)),e.queryModels.includes(`events`)&&(l.push(`EventQueryClient`),Y(i,`${J([`Queries the event streams of \`${e.context}.${e.name}\`, one record per commit: \`POST /${e.context}/${e.name}/events/query\`.`])}export class ${a}EventQueryClient extends EventQueryClient<${a}Event, ${a}Access> {\n${d}\n}`)),Y(i,`${J([s?`Reads the states of \`${e.context}.${e.name}\`, at a version or a time, and their traces: the caller's own by no id (\`readOwn\`, \`getOwn\`, \`findOwn\`, \`traceOwn\`: \`GET /${e.context}/${e.name}/state\`), and by id for a caller with no owner (\`GET /${e.context}/${e.name}/{id}/state\`).`:`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 ${c}<${o}, ${a}Event, ${a}Access> {\n${d}\n}`),i.imports.add(q,l.sort()),i.imports.add(`./aggregate.js`,u),Z(i,r,n,[o])}function Xr(e,t){let n=t.module(`${e.directory}/manifest.ts`),r=`${e.typeName}Manifest`;n.imports.add(q,[`MANIFEST_FORMAT`,`RoutingManifest`]);let i=(e,t,n)=>` { name: ${w(e)}, routes: ${Zr(t)}${n===void 0?``:`, idProperty: ${w(n)}`} },`,a=e.aggregates.map(e=>{let t=[...e.commands.filter(e=>e.routes.length>0).map(e=>i(e.name,e.routes,e.idProperty)),...e.lifecycle.map(e=>i(e.name,e.routes))];return` {\n name: ${w(e.name)},\n commands: [\n${t.join(`
31
+ `)}\n ],\n },`}),o=e.routes.map(e=>` { name: ${w(e.name)}, route: { method: ${w(e.method)}, path: ${w(e.path)} } },`),s=o.length===0?``:` routes: [\n${o.join(`
32
+ `)}\n ],\n`;Y(n,`${J([o.length===0?`The routes of \`${e.name}\`'s commands, as its Manifest lists them: what its command clients send by, with no Manifest fetched and no schema.`:`The routes of \`${e.name}\`'s commands and service routes, as its Manifest lists them: what its clients send by, with no Manifest fetched and no schema.`])}export const ${r}: RoutingManifest = {\n format: MANIFEST_FORMAT,\n contexts: [\n {\n name: ${w(e.name)},\n aggregates: [\n${a.join(`
33
+ `)}\n ],\n${s} },\n ],\n};`)}function Zr(e){return`[${e.map(e=>`{ method: ${w(e.method)}, path: ${w(e.path)} }`).join(`, `)}]`}function Qr(e,t,n,r){if(e.routes.length===0)return;let i=t.module(`${e.directory}/routes.ts`),a=`${e.typeName}Routes`;i.imports.add(q,[`RequestOptions`,`WowClientOptions`]),i.imports.add(Fr,[`ServiceRoutes`]),i.imports.add(`./manifest.js`,[`${e.typeName}Manifest`]),Z(i,r,n,e.routes.flatMap(e=>[e.requestType,e.responseType,...e.parameters.map(e=>e.type)].filter(e=>e!==void 0).flatMap(e=>e.match(/[A-Za-z_$][A-Za-z0-9_$]*/g)??[])));let o=e.routes.map(t=>$r(e,t));Y(i,`${J([`The service routes of \`${e.name}\`: routes whose handler is the service's own code, each called by its Manifest's name.`])}export class ${a} {\n /** Calls any route of the service by its name. */\n readonly routes: ServiceRoutes;\n\n /** @param options - How the service is reached */\n constructor(options?: WowClientOptions) {\n this.routes = new ServiceRoutes(options, { manifest: ${e.typeName}Manifest${Vr(e,{module:i,outputDir:r,client:q})} });\n }\n\n${o.join(`
34
+
35
+ `)}\n}`)}function $r(e,t){let n=t.parameters.filter(e=>e.location===`path`),r=t.parameters.filter(e=>e.location===`query`),i=n.map(e=>`${e.identifier}: ${e.type}`);if(t.requestType!==void 0&&i.push(`body: ${t.requestType}`),r.length>0){let e=r.map(e=>`readonly ${C(e.name)}${e.required?``:`?`}: ${e.type}`).join(`; `),t=r.some(e=>e.required);i.push(`query${t?``:`?`}: { ${e} }`)}i.push(`options?: RequestOptions`);let a=t.responseType??`void`,o=[...n.length===0?[]:[`path: { ${n.map(e=>e.identifier===e.name?e.name:`${C(e.name)}: ${e.identifier}`).join(`, `)} }`],...t.requestType===void 0?[]:[`body`],...r.length===0?[]:[`query`]];return`${J([t.description,`\`${t.method} ${t.path}\``,t.deprecated?`@deprecated The service deprecates this route.`:void 0],` `)} ${C(t.name)}(${i.join(`, `)}): Promise<${a}> {\n return this.routes.call(${w(e.name)}, ${w(t.name)}, { ${o.join(`, `)} }, options) as Promise<${a}>;\n }`}function ei(e,t,n,r){Z(e,r,n,t.references,t.file);let i=J([t.description,`- key: \`${t.key}\``]);if(t.properties===void 0){Y(e,`${i}export type ${t.name} = ${t.type};`);return}let a=t.properties.map(e=>`${J([e.description],` `)} ${e.name}${e.optional?`?`:``}: ${e.type};`);t.type!==void 0&&a.push(` [key: string]: ${t.type};`),Y(e,`${i}export interface ${t.name} {\n${a.join(`
36
+ `)}\n}`)}function ti(e,t,n){let r=new Map(e.types.map(e=>[e.name,e.file]));for(let i of e.types)ei(t.module(i.file),i,r,n);for(let i of e.contexts){Rr(i,t,n);for(let e of i.aggregates)Ur(e,i,t,r,n),qr(e,i,t,r,n),Yr(e,t,r,n);Xr(i,t),Hr(i,t,n,q),Qr(i,t,r,n),Jr(i,t,n)}}function ni(e){return{openAPI:e,components:e.components,endpoints:We(e.paths,e.components)}}var ri=`.wow-generator.json`,ii=class e{project;outputPath;outputDir;previous;written=new Set;stale=new Set;constructor(e,t,n,r){this.project=e,this.outputPath=t,this.outputDir=n,this.previous=r}static open(n,r,i){let a=n.getFileSystem(),o=r;r=(0,t.resolve)(a.getCurrentDirectory(),r);let c=(0,t.join)(r,ri),l=new Map;if(a.fileExistsSync(c)){let e=ai(c,a.readFileSync(c));for(let[n,i]of Object.entries(e.files)){let e=(0,t.resolve)(r,n);if(li(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 ${c}: ${n}`);l.set(e,i)}}let u=new Set([...i?.written??[],...l.keys()]);for(let e of n.getSourceFiles())u.has(e.getFilePath())&&e.forget();return new e(n,o,r,l)}get files(){return this.written}claim(e,t=this.outputPath){let n=ie(t,e);li(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 ci(`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 si(`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 ci(`delete`,e,()=>n.delete(e));let a=(0,t.join)(this.outputDir,ri),o=JSON.stringify({version:1,files:Object.fromEntries(i.map(e=>[(0,t.relative)(this.outputDir,e.getFilePath()).split(t.sep).join(`/`),oi(n.readFileSync(e.getFilePath()))]))},null,2)+`
37
+ `;await ci(`write`,a,async()=>{n.mkdirSync(this.outputDir),await n.writeFile(a,o)})}isUnchanged(e,t){let n=this.project.getFileSystem();return n.fileExistsSync(e)?(li(n.realpathSync(this.outputDir),n.realpathSync(e)),oi(n.readFileSync(e))===t):!1}};function ai(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 oi(t){if(!e.ts.sys.createSHA256Hash)throw Error(`SHA-256 hashing is unavailable in this environment.`);return e.ts.sys.createSHA256Hash(t)}function si(e,t,n){return n instanceof s?n:new s(`output`,`Cannot ${e} ${t}: ${c(n)}`,{cause:n})}async function ci(e,t,n){try{await n()}catch(n){throw si(e,t,n)}}function li(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}".`)}var ui=Symbol(`project`),di=Symbol(`signal`),fi=class{options;project;logger;signal;output;constructor(t){this.options=t,this.logger=t.logger??new u,this.signal=t[di],this.project=t[ui]??pi(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`),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 Ln(n.configPath,e,a);i(o.warnings),t?.throwIfAborted(),e.debug(`Parsing the input document`);let c=await Nn(n.inputPath,a);if(t?.throwIfAborted(),Yn(c))return this.generateFromManifest(Xn(c,n.inputPath),o.origin,i,()=>r);let l=Pn(c,n.inputPath);e.debug(`OpenAPI specification parsed successfully`);let u=ce(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=ni(l),f=ii.open(this.project,n.outputDir,this.output);this.output=f,e.debug(`Analysing the document`);let p=st(d,o.config);i(p.warnings),e.debug(`Writing generated modules`);let m=new ut(e=>f.claim(e));pn(p.model,{modules:m,outputDir:n.outputDir,types:ln(d.components),schemaDocs:n.schemaDocs??`summary`}),m.build(),e.debug(`Generated modules written`),f.forgetStale();let h=this.project.getDirectory(n.outputDir);return h?(e.debug(`Generating index files`),i(mn(h,e=>f.claim(`index.ts`,e))),e.debug(`Optimizing source files`),En(h.getDescendantSourceFiles().filter(e=>f.files.has(e.getFilePath())),e),e.debug(`Source files optimized successfully`)):e.debug(`Output directory not found.`),e.debug(`Saving project to disk`),await f.commit(t),e.debug(`Code generation completed successfully`),{files:[...f.files].sort(),configPath:o.origin,warnings:r}}async generateFromManifest(e,t,n,r){let{logger:i,signal:a,options:o}=this,s=ii.open(this.project,o.outputDir,this.output);this.output=s,i.debug(`Analysing the Manifest`);let c=Mr(e);n(c.warnings);let l=new ut(e=>s.claim(e));ti(c.model,l,o.outputDir),l.build(),s.forgetStale();let u=this.project.getDirectory(o.outputDir);return u&&(n(mn(u,e=>s.claim(`index.ts`,e))),En(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 pi(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 di}}),Object.defineProperty(exports,"o",{enumerable:!0,get:function(){return o}}),Object.defineProperty(exports,"r",{enumerable:!0,get:function(){return Dn}}),Object.defineProperty(exports,"s",{enumerable:!0,get:function(){return s}}),Object.defineProperty(exports,"t",{enumerable:!0,get:function(){return fi}});
38
+ //# sourceMappingURL=codeGenerator-q59QJpfT.cjs.map