@moccona/apicodegen 0.0.11 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -259,6 +259,15 @@ export async function getPetById({ petId }: { petId: number }) {
259
259
  - ✅ Cookie parameters: Request cookies
260
260
  - ✅ Body parameters: JSON and FormData
261
261
 
262
+ ### Response Formats
263
+ - ✅ `application/json` — parsed and typed
264
+ - ✅ SSE `text/event-stream` — raw response returned for application-layer handling
265
+ - ✅ Other text/binary types — returned unparsed
266
+
267
+ > For SSE endpoints:
268
+ > - **fetch** adapter: returns `Promise<Response>`. Use `EventSource`, `response.body.getReader()`, or another tool of your choice to parse events.
269
+ > - **axios** adapter: configures axios with `adapter: 'fetch'` + `responseType: 'stream'`, so `response.data` is a `ReadableStream` you can iterate directly.
270
+
262
271
  ### Request Body Formats
263
272
  - ✅ `application/json` - JSON data
264
273
  - ✅ `multipart/form-data` - File uploads
package/bin/cli.cjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let c=require("node:path");c=s(c,1);let l=require("commander"),u=require("fs-extra");u=s(u,1);let d=require("@moccona/logger"),f=require("undici"),p=require("typescript"),m=require("node:fs/promises"),h=require("prettier");var g={name:`@moccona/apicodegen`,version:`0.0.11`,description:``,type:`module`,engines:{node:`>=24`},bin:{apicodegen:`./bin/cli.cjs`},scripts:{dev:`tsdown --watch`,build:`tsdown`,test:`vitest --watch false`,prepublishOnly:`npm run build`,lint:`pnpm exec biome check src`,"lint:fix":`pnpm exec biome check --write src`,format:`pnpm exec biome format --write src`,debug:`node --inspect-brk=9229 bin/cli.cjs`,prepare:`husky`,typecheck:`tsc --noEmit`,version:`changeset version`,publish:`changeset publish`},exports:{"./package.json":`./package.json`,"./vite":{types:`./npm/vite/index.d.mts`,import:`./npm/vite/index.mjs`},"./*":{types:`./npm/*/index.d.mts`,import:`./npm/*/index.mjs`,require:`./npm/*/index.cjs`},".":{types:`./npm/index.d.mts`,import:`./npm/index.mjs`,require:`./npm/index.cjs`}},keywords:[`api-codegen`],repository:{type:`git`,url:`https://github.com/freemode1614/api-codegen`},author:`freemode`,license:`MIT`,publishConfig:{access:`public`},dependencies:{"@moccona/logger":`^0.0.2`,commander:`^13.1.0`,execa:`^9.5.2`,"fs-extra":`^11.3.0`,"openapi-types":`^12.1.3`,prettier:`^3.6.2`,undici:`^7.8.0`},devDependencies:{"@arethetypeswrong/core":`^0.18.2`,"@biomejs/biome":`^2.4.16`,"@changesets/cli":`^2.31.0`,"@types/fs-extra":`^11.0.4`,"@types/node":`^22.14.1`,axios:`^1.11.0`,"fast-glob":`^3.3.3`,husky:`^9.1.7`,"lint-staged":`^17.0.5`,prettier:`^3.6.2`,serve:`^14.2.4`,"serve-handler":`^6.1.7`,tsdown:`^0.22.1`,typescript:`^5.9.2`,vite:`^7.1.5`,"vite-tsconfig-paths":`^6.1.1`,vitest:`^3.2.4`},peerDependencies:{prettier:`^3`,typescript:`^5`,vite:`^7`},peerDependenciesMeta:{vite:{optional:!0}},"lint-staged":{"src/**/*":[`biome check --write`,`biome format --write`]},packageManager:`pnpm@10.9.0`};const _=e=>`\x1b[36m${e}\x1b[0m`,v={print(e){console.log(_(`
2
+ var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},s=(n,r,a)=>(a=n==null?{}:e(i(n)),o(r||!n||!n.__esModule?t(a,`default`,{value:n,enumerable:!0}):a,n));let c=require("node:path");c=s(c,1);let l=require("commander"),u=require("fs-extra");u=s(u,1);let d=require("@moccona/logger"),f=require("undici"),p=require("typescript"),m=require("node:fs/promises"),h=require("prettier");var g={name:`@moccona/apicodegen`,version:`0.1.1`,description:``,type:`module`,engines:{node:`>=24`},bin:{apicodegen:`./bin/cli.cjs`},scripts:{dev:`tsdown --watch`,build:`tsdown`,test:`vitest --watch false`,prepublishOnly:`npm run build`,lint:`pnpm exec biome check src`,"lint:fix":`pnpm exec biome check --write src`,format:`pnpm exec biome format --write src`,debug:`node --inspect-brk=9229 bin/cli.cjs`,prepare:`husky`,typecheck:`tsc --noEmit`,version:`changeset version`,publish:`changeset publish`},exports:{"./package.json":`./package.json`,"./vite":{types:`./npm/vite/index.d.mts`,import:`./npm/vite/index.mjs`},"./*":{types:`./npm/*/index.d.mts`,import:`./npm/*/index.mjs`,require:`./npm/*/index.cjs`},".":{types:`./npm/index.d.mts`,import:`./npm/index.mjs`,require:`./npm/index.cjs`}},keywords:[`api-codegen`],repository:{type:`git`,url:`https://github.com/freemode1614/api-codegen`},author:`freemode`,license:`MIT`,publishConfig:{access:`public`},dependencies:{"@moccona/logger":`^0.0.2`,commander:`^13.1.0`,execa:`^9.5.2`,"fs-extra":`^11.3.0`,"openapi-types":`^12.1.3`,prettier:`^3.6.2`,undici:`^7.8.0`},devDependencies:{"@arethetypeswrong/core":`^0.18.2`,"@biomejs/biome":`^2.4.16`,"@changesets/cli":`^2.31.0`,"@types/fs-extra":`^11.0.4`,"@types/node":`^22.14.1`,axios:`^1.11.0`,"fast-glob":`^3.3.3`,husky:`^9.1.7`,"lint-staged":`^17.0.5`,prettier:`^3.6.2`,serve:`^14.2.4`,"serve-handler":`^6.1.7`,tsdown:`^0.22.1`,typescript:`^5.9.2`,vite:`^7.1.5`,"vite-tsconfig-paths":`^6.1.1`,vitest:`^3.2.4`},peerDependencies:{prettier:`^3`,typescript:`^5`,vite:`^7`},peerDependenciesMeta:{vite:{optional:!0}},"lint-staged":{"src/**/*":[`biome check --write`,`biome format --write`]},packageManager:`pnpm@10.9.0`};const _=e=>`\x1b[36m${e}\x1b[0m`,v={print(e){console.log(_(`
3
3
 
4
4
  ▄▄▄ ██▓███ ██▓ ▄████▄ ▒█████ ▓█████▄ ▓█████ ▄████ ▓█████ ███▄ █
5
5
  ▒████▄ ▓██░ ██▒▓██▒▒██▀ ▀█ ▒██▒ ██▒▒██▀ ██▌▓█ ▀ ██▒ ▀█▒▓█ ▀ ██ ▀█ █
@@ -16,8 +16,8 @@ API Code Generator v${e}
16
16
  `))}},y={APICODEGEN_SPEC:`spec`,APICODEGEN_OUTPUT:`output`,APICODEGEN_BASE_URL:`baseURL`,APICODEGEN_ADAPTOR:`adaptor`,APICODEGEN_VERBOSE:`verbose`,APICODEGEN_WATCH:`watch`,APICODEGEN_TYPE_CHECK:`typeCheck`};function ee(){let e={};for(let[t,n]of Object.entries(y)){let r=process.env[t];if(r!==void 0)switch(n){case`verbose`:case`watch`:case`typeCheck`:e[n]=r===`true`||r===`1`;break;case`adaptor`:e[n]=r;break;default:e[n]=r}}return e}async function b(e){let t=c.default.extname(e).toLowerCase();try{if(t===`.json`||t===`.jsonc`){let t=await u.default.readFile(e,`utf-8`);return JSON.parse(t)}if(t===`.js`||t===`.cjs`||t===`.mjs`){let t=await import(e);return t.default||t}if(t===`.ts`){let t=await u.default.readFile(e,`utf-8`);try{return JSON.parse(t)}catch{let e=t.match(/export\s+default\s+(\{.+\})/s);if(e)return JSON.parse(e[1])}}let n=await u.default.readFile(e,`utf-8`);return JSON.parse(n)}catch(t){throw Error(`Failed to load config from ${e}: ${t}`)}}async function x(e){for(let t of[`apicodegen.config.json`,`apicodegen.config.js`,`apicodegen.config.mjs`,`.apicodegenrc`,`.apicodegenrc.json`,`.apicodegenrc.js`,`.apicodegenrc.mjs`]){let n=c.default.join(e,t);if(await u.default.pathExists(n))return n}let t=c.default.join(e,`package.json`);if(await u.default.pathExists(t))try{let n=JSON.parse(await u.default.readFile(t,`utf-8`));if(n.apicodegen&&typeof n.apicodegen==`string`)return c.default.resolve(e,n.apicodegen)}catch{}return null}function S(e,...t){let n={...e};for(let e of t)if(e)for(let[t,r]of Object.entries(e))r!==void 0&&(n[t]=r);return n}function C(e){if(!e.spec)throw Error(`Missing required field: spec (OpenAPI spec file path or URL)`);return!0}async function w(e={}){let t=e.cwd||process.cwd(),n=e.cliOptions||{},r=ee(),i={},a;if(e.configFile)a=c.default.resolve(t,e.configFile),i=await b(a);else{let e=await x(t);e&&(a=e,i=await b(e))}let o=c.default.join(t,`package.json`),s={};if(await u.default.pathExists(o))try{let e=JSON.parse(await u.default.readFile(o,`utf-8`));e.apicodegen&&typeof e.apicodegen==`object`&&(s=e.apicodegen)}catch{}let l=S({spec:``,output:`./output.ts`},r,s,i,n);C(l);let d=e.name||l.baseURL||l.spec;return{...l,configFilePath:a,name:d}}function te(e){return{docURL:e.spec,output:e.output,adaptor:e.adaptor,baseURL:e.baseURL,importClientSource:e.importClientSource,verbose:e.verbose,requestOptions:e.requestOptions}}const T={SPEC_NOT_FOUND:`E_SPEC_NOT_FOUND`,SPEC_FETCH_FAILED:`E_SPEC_FETCH_FAILED`,SPEC_PARSE_FAILED:`E_SPEC_PARSE_FAILED`,OUTPUT_DIR_MISSING:`E_OUTPUT_DIR_MISSING`,CONFIG_INVALID:`E_CONFIG_INVALID`,VALIDATION_FAILED:`E_VALIDATION_FAILED`,GENERATION_FAILED:`E_GENERATION_FAILED`,TYPE_CHECK_FAILED:`E_TYPE_CHECK_FAILED`};var E=class e extends Error{code;location;line;column;path;suggestions;cause;constructor(t){super(t.message),this.name=`ApicodegenError`,this.code=t.code,this.location=t.location,this.line=t.line,this.column=t.column,this.path=t.path,this.suggestions=t.suggestions||[],this.cause=t.cause,Error.captureStackTrace&&Error.captureStackTrace(this,e)}toString(e=!1){let t=[];if(t.push(`\x1b[1;31mError [${this.code}]\x1b[0m ${this.message}`),this.location&&t.push(` \x1b[36m→ Location:\x1b[0m ${this.location}`),this.path&&t.push(` \x1b[36m→ Path:\x1b[0m ${this.path}`),this.line!==void 0){let e=` \x1b[36m→ Line:\x1b[0m ${this.line}`;this.column!==void 0&&(e+=`, Column: ${this.column}`),t.push(e)}if(this.suggestions.length>0)for(let e of this.suggestions)t.push(` \x1b[32m→ Suggestion:\x1b[0m ${e}`);if(e&&this.cause&&(t.push(`\n \x1b[90mOriginal Error:\x1b[0m ${this.cause.message}`),this.stack)){let e=this.stack.split(`
17
17
  `).slice(1).join(`
18
18
  `);t.push(`\x1b[90m${e}\x1b[0m`)}return t.join(`
19
- `)}toJSON(){return{name:this.name,code:this.code,message:this.message,location:this.location,line:this.line,column:this.column,path:this.path,suggestions:this.suggestions,cause:this.cause?.message}}};const D={specNotFound(e,t){return new E({code:T.SPEC_NOT_FOUND,message:`OpenAPI spec file not found`,location:e,suggestions:[`Check if the file exists using 'ls -la'`,`Use --spec to provide the correct path`,`For remote specs, ensure the URL is accessible`],cause:t})},specFetchFailed(e,t,n){let r=t?`Failed to fetch OpenAPI spec (HTTP ${t})`:`Failed to fetch OpenAPI spec from URL`;return new E({code:T.SPEC_FETCH_FAILED,message:r,location:e,suggestions:[`Check if the URL is accessible in a browser`,`Download the spec file locally and use the local path`,`Verify CORS settings if fetching from a different origin`],cause:n})},specParseFailed(e,t,n,r){return new E({code:T.SPEC_PARSE_FAILED,message:`Failed to parse OpenAPI spec (invalid JSON or YAML)`,location:e,line:t,column:n,suggestions:[`Validate JSON syntax using jsonlint.com`,`For YAML specs, ensure proper indentation`,`Check for trailing commas or unquoted special characters`],cause:r})},outputDirMissing(e,t){return new E({code:T.OUTPUT_DIR_MISSING,message:`Output directory does not exist`,location:e,suggestions:[`Create the directory: mkdir -p $(dirname <output>)`,`Check if the path is correct`],cause:t})},configInvalid(e,t){return new E({code:T.CONFIG_INVALID,message:`Invalid configuration file`,location:e,suggestions:[`Validate JSON syntax in the config file`,`Check for required fields (spec, output)`],cause:t})},validationFailed(e,t,n){return new E({code:T.VALIDATION_FAILED,message:`OpenAPI spec validation failed`,location:e,path:t,suggestions:[`Check OpenAPI spec structure at the specified path`,`Ensure all required fields are present`,`Validate using swagger.io editor`],cause:n})},generationFailed(e){return new E({code:T.GENERATION_FAILED,message:`Code generation failed`,suggestions:[`Check for unsupported OpenAPI features`,`Ensure spec follows OpenAPI 2.0, 3.0, or 3.1 specification`,`Use --verbose for more details`],cause:e})},typeCheckFailed(e,t,n){return new E({code:T.TYPE_CHECK_FAILED,message:`TypeScript type check failed`,location:e,suggestions:[`Review type errors above`,`Check for schema inconsistencies`,`Update generated types or fix source schema`],cause:n})},missingRequiredField(e,t){return new E({code:T.VALIDATION_FAILED,message:`Missing required field: ${e}`,path:t,suggestions:[`Add the '${e}' field to your configuration`]})}};function ne(e,t){return e instanceof E?e:e instanceof Error?new E({code:t?.code||T.GENERATION_FAILED,message:t?.message||e.message,location:t?.location,suggestions:t?.suggestions,cause:e}):new E({code:t?.code||T.GENERATION_FAILED,message:String(e),suggestions:t?.suggestions})}function O(e){return e instanceof E}const k=e=>`\x1b[36m${e}\x1b[0m`,A=e=>`\x1b[32m${e}\x1b[0m`,j=e=>`\x1b[31m${e}\x1b[0m`,M=e=>`\x1b[34m${e}\x1b[0m`,N=e=>`\x1b[33m${e}\x1b[0m`,re=e=>`\x1b[35m${e}\x1b[0m`,P=e=>`\x1b[90m${e}\x1b[0m`,F=e=>`\x1b[1m${e}\x1b[0m`,I={success(e){console.log(`${A(`✓`)} ${e}`)},error(e,t=!1){if(O(e))console.error(`${j(`✗`)} ${e.toString(t)}`);else if(e instanceof Error){let n=`Error: ${e.message}`;console.error(`${j(`✗`)} ${n}${t&&e.stack?`\n${P(e.stack)}`:``}`)}else console.error(`${j(`✗`)} ${String(e)}`)},info(e){console.log(`${M(`ℹ`)} ${e}`)},warn(e){console.log(`${N(`⚠`)} ${e}`)},loading(e){console.log(`${N(`🔄`)} ${e}`)},watching(e){console.log(`${re(`⟳`)} ${e}`)},fileChange(e){console.log(`${N(`↓`)} ${e}`)},fileAdd(e){console.log(`${A(`+`)} ${e}`)},shutdown(){console.log(`\n${P(`👋 Shutting down...`)}`)},divider(e=50){console.log(`${F(k(`─`.repeat(e)))}`)},heading(e,t,n=50){console.log(`${F(k(`─`.repeat(n)))}`),console.log(`${F(k(e))}`),console.log(`${P(`Mode:`)} ${t||`unknown`}`),console.log(`${F(k(`─`.repeat(n)))}`)},item(e,t=`green`){let n=t===`green`?`✓`:t===`red`?`✗`:`⚠`;console.log(`${t===`green`?A(n):t===`red`?j(n):N(n)} ${e}`)},summary(e){let{succeeded:t,failed:n,endpoints:r,schemas:i,duration:a}=e,o=`API Code Gen - Complete (${t} succeeded${n>0?`, ${n} failed`:``}, ${r} endpoints, ${i} schemas, ${a}ms)`;console.log(n===0?`${A(`✓`)} ${o}`:`${N(`⚠`)} ${o}`)}};var L=class{};const R=new Set(`break.case.catch.class.const.continue.debugger.default.delete.do.else.enum.export.extends.false.finally.for.function.if.import.in.instanceof.new.null.return.super.switch.this.throw.true.try.typeof.var.void.while.with.as.implements.interface.let.package.private.protected.public.static.yield.abstract.any.async.await.constructor.declare.from.get.is.module.namespace.never.require.set.type.unknown.readonly.of.asserts.infer.keyof.boolean.number.string.symbol.object.undefined.bigint`.split(`.`));let z=function(e){return e.JSON=`application/json`,e.TEXT=`text`,e.IMAGE=`image`,e.AUDIO=`audio`,e.VIDEO=`video`,e}({}),B=function(e){return e.GET=`get`,e.PUT=`put`,e.POST=`post`,e.DELETE=`delete`,e.OPTIONS=`options`,e.HEAD=`head`,e.PATCH=`patch`,e.TRACE=`trace`,e}({});var V=class e{constructor(){if(new.target===e)throw Error(`Cannot instantiate abstract class`)}static ref2name(t,n){let r=t.replace(/^#/,``).split(`/`).filter(Boolean);if(!n)return r.slice(-1)[0];let i=n,a=``;for(let e of r){let t=e.replaceAll(`~1`,`/`);i=i[t],a=t}return i?i.$ref?e.ref2name(i.$ref,n):a:`unknown`}static pathToFnName(t,n,r=``){return e.normalize(e.camelCase(e.normalize(t)))+(n?e.capitalize(e.upperCamelCase(`using_${n}`)):``)}static normalize(e){return R.has(e)&&(e+=`_`),e.replace(/[/\-_{}():\s`,*<>$#.]/gm,`_`).replace(/^\d./gm,``).replaceAll(`...`,``)}static capitalize(e){return e=e.trim(),`${e.charAt(0).toUpperCase()}${e.slice(1)}`}static camelCase(t){t=t.trim();let n=t.split(`_`).filter(Boolean);for(;n[0]?.match(/^\d/);)n.shift();return n.map((t,n)=>n===0?t:e.capitalize(t)).join(``)}static upperCamelCase(t){return e.normalize(t).replaceAll(`...`,``).split(`_`).filter(Boolean).map(e.capitalize).join(``)}static async fetchDoc(e,t={}){let{body:n,statusCode:r}=await(0,f.request)(e,{method:`GET`,dispatcher:new f.Agent({connect:{rejectUnauthorized:!1}}),...t});if(r>=400)throw Error(`Failed to fetch OpenAPI documentation from ${e}: HTTP ${r}`);try{return n.json()}catch(t){throw Error(`Failed to parse JSON response from ${e}: ${t instanceof Error?t.message:String(t)}`)}}static getMediaType(e){return Object.values(z).find(t=>e.includes(t))}static isValidEnumType(t){return t.type!==`boolean`&&!e.isBooleanEnum(t)}static isBooleanEnum(e){return e.type===`boolean`||!!e.enum?.some(e=>typeof e==`boolean`)}static isSameEnum(e,t){return e.enum.length===t.enum.length&&e.enum.sort().every((e,n)=>e===t.enum.sort()[n])}static uniqueEnums(e){let t=new Map;for(let n of e){let e=t.get(n.name);if(e)for(let t of n.enum)e.add(t);else t.set(n.name,new Set(n.enum))}return Array.from(t.entries()).map(([e,t])=>({name:e,enum:Array.from(t)}))}static findSameSchema(t,n){return n.find(n=>e.isSameEnum(n,t))}static isRef(e){return typeof e==`object`&&!!e&&`$ref`in e&&typeof e.$ref==`string`}},H=class{enums=[];schemas={};parameters={};responses={};requestBodies={};apis={};docURL;baseURL;output;requestOptions;importClientSource;constructor(e,t){this.docURL=e.docURL,this.baseURL=e.baseURL??``,this.output=e.output??`.`,this.requestOptions=e.requestOptions??{},this.importClientSource=e.importClientSource??``;let{enums:n,schemas:r,requestBodies:i,responses:a,parameters:o,apis:s}=this.parse(t);this.enums=n,this.schemas=r,this.responses=a,this.parameters=o,this.requestBodies=i,this.apis=s}},U=class e{static toCode(e){if(e.length===0)return`// No api declaration found.`;let t=p.factory.createSourceFile(e,p.factory.createToken(p.SyntaxKind.EndOfFileToken),p.NodeFlags.None);return(0,p.createPrinter)().printFile(t)}static async write(e,t){let{mkdir:n}=await import(`node:fs/promises`),{dirname:r}=await import(`node:path`);try{await n(r(t),{recursive:!0}),await(0,m.writeFile)(t,e)}catch(e){throw new E({code:T.OUTPUT_DIR_MISSING,message:`Failed to write generated code to output file`,location:t,cause:e instanceof Error?e:Error(String(e)),suggestions:[`Verify the output directory path is writable`,`Check that the parent directory exists or can be created`]})}}static toUrlTemplate(e,t,n=``){let r=t.filter(e=>e.in===`query`);if(r.length>0){let t=r.map((e,t)=>`${t===0?`?`:`&`}${encodeURIComponent(e.name)}={${V.normalize(e.name)}}`).join(``);e+=t}let i=e.replaceAll(`{`,"${").split(`$`).filter(Boolean);return i.length===1?p.factory.createNoSubstitutionTemplateLiteral(n+e):p.factory.createTemplateExpression(p.factory.createTemplateHead(n+i[0]),i.slice(1).map((e,t)=>{let n=/^{(.+)}(.+)?/gm.exec(e),r=t===i.length-2;if(!n)throw Error(`Invalid path segment: ${e}`);return p.factory.createTemplateSpan(p.factory.createIdentifier(V.normalize(n[1])),r?p.factory.createTemplateTail(n[2]||``):p.factory.createTemplateMiddle(n[2]))}))}static addComments(e,t){if(!Array.isArray(t)||t.filter(Boolean).length===0)return;let n=t.map(e=>e.tag===`returns`?`* @returns {${e.type}} ${e.comment??``}`:e.tag===`param`?e.comment?`* @param ${e.paramName} - ${e.comment}`:`* @param ${e.paramName}`:e.tag?`* @${e.tag} ${e.comment??``}`:`* ${e.comment}`).join(`
19
+ `)}toJSON(){return{name:this.name,code:this.code,message:this.message,location:this.location,line:this.line,column:this.column,path:this.path,suggestions:this.suggestions,cause:this.cause?.message}}};const D={specNotFound(e,t){return new E({code:T.SPEC_NOT_FOUND,message:`OpenAPI spec file not found`,location:e,suggestions:[`Check if the file exists using 'ls -la'`,`Use --spec to provide the correct path`,`For remote specs, ensure the URL is accessible`],cause:t})},specFetchFailed(e,t,n){let r=t?`Failed to fetch OpenAPI spec (HTTP ${t})`:`Failed to fetch OpenAPI spec from URL`;return new E({code:T.SPEC_FETCH_FAILED,message:r,location:e,suggestions:[`Check if the URL is accessible in a browser`,`Download the spec file locally and use the local path`,`Verify CORS settings if fetching from a different origin`],cause:n})},specParseFailed(e,t,n,r){return new E({code:T.SPEC_PARSE_FAILED,message:`Failed to parse OpenAPI spec (invalid JSON or YAML)`,location:e,line:t,column:n,suggestions:[`Validate JSON syntax using jsonlint.com`,`For YAML specs, ensure proper indentation`,`Check for trailing commas or unquoted special characters`],cause:r})},outputDirMissing(e,t){return new E({code:T.OUTPUT_DIR_MISSING,message:`Output directory does not exist`,location:e,suggestions:[`Create the directory: mkdir -p $(dirname <output>)`,`Check if the path is correct`],cause:t})},configInvalid(e,t){return new E({code:T.CONFIG_INVALID,message:`Invalid configuration file`,location:e,suggestions:[`Validate JSON syntax in the config file`,`Check for required fields (spec, output)`],cause:t})},validationFailed(e,t,n){return new E({code:T.VALIDATION_FAILED,message:`OpenAPI spec validation failed`,location:e,path:t,suggestions:[`Check OpenAPI spec structure at the specified path`,`Ensure all required fields are present`,`Validate using swagger.io editor`],cause:n})},generationFailed(e){return new E({code:T.GENERATION_FAILED,message:`Code generation failed`,suggestions:[`Check for unsupported OpenAPI features`,`Ensure spec follows OpenAPI 2.0, 3.0, or 3.1 specification`,`Use --verbose for more details`],cause:e})},typeCheckFailed(e,t,n){return new E({code:T.TYPE_CHECK_FAILED,message:`TypeScript type check failed`,location:e,suggestions:[`Review type errors above`,`Check for schema inconsistencies`,`Update generated types or fix source schema`],cause:n})},missingRequiredField(e,t){return new E({code:T.VALIDATION_FAILED,message:`Missing required field: ${e}`,path:t,suggestions:[`Add the '${e}' field to your configuration`]})}};function ne(e,t){return e instanceof E?e:e instanceof Error?new E({code:t?.code||T.GENERATION_FAILED,message:t?.message||e.message,location:t?.location,suggestions:t?.suggestions,cause:e}):new E({code:t?.code||T.GENERATION_FAILED,message:String(e),suggestions:t?.suggestions})}function O(e){return e instanceof E}const k=e=>`\x1b[36m${e}\x1b[0m`,A=e=>`\x1b[32m${e}\x1b[0m`,j=e=>`\x1b[31m${e}\x1b[0m`,M=e=>`\x1b[34m${e}\x1b[0m`,N=e=>`\x1b[33m${e}\x1b[0m`,re=e=>`\x1b[35m${e}\x1b[0m`,P=e=>`\x1b[90m${e}\x1b[0m`,F=e=>`\x1b[1m${e}\x1b[0m`,I={success(e){console.log(`${A(`✓`)} ${e}`)},error(e,t=!1){if(O(e))console.error(`${j(`✗`)} ${e.toString(t)}`);else if(e instanceof Error){let n=`Error: ${e.message}`;console.error(`${j(`✗`)} ${n}${t&&e.stack?`\n${P(e.stack)}`:``}`)}else console.error(`${j(`✗`)} ${String(e)}`)},info(e){console.log(`${M(`ℹ`)} ${e}`)},warn(e){console.log(`${N(`⚠`)} ${e}`)},loading(e){console.log(`${N(`🔄`)} ${e}`)},watching(e){console.log(`${re(`⟳`)} ${e}`)},fileChange(e){console.log(`${N(`↓`)} ${e}`)},fileAdd(e){console.log(`${A(`+`)} ${e}`)},shutdown(){console.log(`\n${P(`👋 Shutting down...`)}`)},divider(e=50){console.log(`${F(k(`─`.repeat(e)))}`)},heading(e,t,n=50){console.log(`${F(k(`─`.repeat(n)))}`),console.log(`${F(k(e))}`),console.log(`${P(`Mode:`)} ${t||`unknown`}`),console.log(`${F(k(`─`.repeat(n)))}`)},item(e,t=`green`){let n=t===`green`?`✓`:t===`red`?`✗`:`⚠`;console.log(`${t===`green`?A(n):t===`red`?j(n):N(n)} ${e}`)},summary(e){let{succeeded:t,failed:n,endpoints:r,schemas:i,duration:a}=e,o=`API Code Gen - Complete (${t} succeeded${n>0?`, ${n} failed`:``}, ${r} endpoints, ${i} schemas, ${a}ms)`;console.log(n===0?`${A(`✓`)} ${o}`:`${N(`⚠`)} ${o}`)}};var L=class{};const R=new Set(`break.case.catch.class.const.continue.debugger.default.delete.do.else.enum.export.extends.false.finally.for.function.if.import.in.instanceof.new.null.return.super.switch.this.throw.true.try.typeof.var.void.while.with.as.implements.interface.let.package.private.protected.public.static.yield.abstract.any.async.await.constructor.declare.from.get.is.module.namespace.never.require.set.type.unknown.readonly.of.asserts.infer.keyof.boolean.number.string.symbol.object.undefined.bigint`.split(`.`));let z=function(e){return e.JSON=`application/json`,e.EVENT_STREAM=`text/event-stream`,e.TEXT=`text`,e.IMAGE=`image`,e.AUDIO=`audio`,e.VIDEO=`video`,e}({}),B=function(e){return e.GET=`get`,e.PUT=`put`,e.POST=`post`,e.DELETE=`delete`,e.OPTIONS=`options`,e.HEAD=`head`,e.PATCH=`patch`,e.TRACE=`trace`,e}({});var V=class e{constructor(){if(new.target===e)throw Error(`Cannot instantiate abstract class`)}static ref2name(t,n){let r=t.replace(/^#/,``).split(`/`).filter(Boolean);if(!n)return r.slice(-1)[0];let i=n,a=``;for(let e of r){let t=e.replaceAll(`~1`,`/`);i=i[t],a=t}return i?i.$ref?e.ref2name(i.$ref,n):a:`unknown`}static pathToFnName(t,n,r=``){return e.normalize(e.camelCase(e.normalize(t)))+(n?e.capitalize(e.upperCamelCase(`using_${n}`)):``)}static normalize(e){return R.has(e)&&(e+=`_`),e.replace(/[/\-_{}():\s`,*<>$#.]/gm,`_`).replace(/^\d./gm,``).replaceAll(`...`,``)}static capitalize(e){return e=e.trim(),`${e.charAt(0).toUpperCase()}${e.slice(1)}`}static camelCase(t){t=t.trim();let n=t.split(`_`).filter(Boolean);for(;n[0]?.match(/^\d/);)n.shift();return n.map((t,n)=>n===0?t:e.capitalize(t)).join(``)}static upperCamelCase(t){return e.normalize(t).replaceAll(`...`,``).split(`_`).filter(Boolean).map(e.capitalize).join(``)}static async fetchDoc(e,t={}){let{body:n,statusCode:r}=await(0,f.request)(e,{method:`GET`,dispatcher:new f.Agent({connect:{rejectUnauthorized:!1}}),...t});if(r>=400)throw Error(`Failed to fetch OpenAPI documentation from ${e}: HTTP ${r}`);try{return n.json()}catch(t){throw Error(`Failed to parse JSON response from ${e}: ${t instanceof Error?t.message:String(t)}`)}}static getMediaType(e){return Object.values(z).find(t=>e.includes(t))}static isValidEnumType(t){return t.type!==`boolean`&&!e.isBooleanEnum(t)}static isBooleanEnum(e){return e.type===`boolean`||!!e.enum?.some(e=>typeof e==`boolean`)}static isSameEnum(e,t){return e.enum.length===t.enum.length&&e.enum.sort().every((e,n)=>e===t.enum.sort()[n])}static uniqueEnums(e){let t=new Map;for(let n of e){let e=t.get(n.name);if(e)for(let t of n.enum)e.add(t);else t.set(n.name,new Set(n.enum))}return Array.from(t.entries()).map(([e,t])=>({name:e,enum:Array.from(t)}))}static findSameSchema(t,n){return n.find(n=>e.isSameEnum(n,t))}static isRef(e){return typeof e==`object`&&!!e&&`$ref`in e&&typeof e.$ref==`string`}},H=class{enums=[];schemas={};parameters={};responses={};requestBodies={};apis={};docURL;baseURL;output;requestOptions;importClientSource;constructor(e,t){this.docURL=e.docURL,this.baseURL=e.baseURL??``,this.output=e.output??`.`,this.requestOptions=e.requestOptions??{},this.importClientSource=e.importClientSource??``;let{enums:n,schemas:r,requestBodies:i,responses:a,parameters:o,apis:s}=this.parse(t);this.enums=n,this.schemas=r,this.responses=a,this.parameters=o,this.requestBodies=i,this.apis=s}},U=class e{static toCode(e){if(e.length===0)return`// No api declaration found.`;let t=p.factory.createSourceFile(e,p.factory.createToken(p.SyntaxKind.EndOfFileToken),p.NodeFlags.None);return(0,p.createPrinter)().printFile(t)}static async write(e,t){let{mkdir:n}=await import(`node:fs/promises`),{dirname:r}=await import(`node:path`);try{await n(r(t),{recursive:!0}),await(0,m.writeFile)(t,e)}catch(e){throw new E({code:T.OUTPUT_DIR_MISSING,message:`Failed to write generated code to output file`,location:t,cause:e instanceof Error?e:Error(String(e)),suggestions:[`Verify the output directory path is writable`,`Check that the parent directory exists or can be created`]})}}static toUrlTemplate(e,t,n=``){let r=t.filter(e=>e.in===`query`);if(r.length>0){let t=r.map((e,t)=>`${t===0?`?`:`&`}${encodeURIComponent(e.name)}={${V.normalize(e.name)}}`).join(``);e+=t}let i=e.replaceAll(`{`,"${").split(`$`).filter(Boolean);return i.length===1?p.factory.createNoSubstitutionTemplateLiteral(n+e):p.factory.createTemplateExpression(p.factory.createTemplateHead(n+i[0]),i.slice(1).map((e,t)=>{let n=/^{(.+)}(.+)?/gm.exec(e),r=t===i.length-2;if(!n)throw Error(`Invalid path segment: ${e}`);return p.factory.createTemplateSpan(p.factory.createIdentifier(V.normalize(n[1])),r?p.factory.createTemplateTail(n[2]||``):p.factory.createTemplateMiddle(n[2]))}))}static addComments(e,t){if(!Array.isArray(t)||t.filter(Boolean).length===0)return;let n=t.map(e=>e.tag===`returns`?`* @returns {${e.type}} ${e.comment??``}`:e.tag===`param`?e.comment?`* @param ${e.paramName} - ${e.comment}`:`* @param ${e.paramName}`:e.tag?`* @${e.tag} ${e.comment??``}`:`* ${e.comment}`).join(`
20
20
  `).trim()+`
21
- `;(0,p.addSyntheticLeadingComment)(e,p.SyntaxKind.MultiLineCommentTrivia,n,!0)}static isBinarySchema(t){if(t.type===`array`){let n=t;return e.isBinarySchema(n.items)}let n=t;return n.format===`blob`||n.format===`binary`||n.type===`file`}static schemaToTypeString(t){if(t.type===`array`){let n=t;return n.items?`${e.schemaToTypeString(n.items)}[]`:`unknown`}let n=t;return t.type===`string`?`string`:t.type===`number`||t.type===`integer`?`number`:t.type===`boolean`?`boolean`:t.type===`object`||t.properties?`object`:n.format===`binary`||n.type===`file`||n.format===`blob`?`Blob`:n.ref?n.ref:`unknown`}static generateParamTags(t,n){let r=[];for(let n of t){let t=V.normalize(n.name),i=`unknown`;n.schema&&(i=e.schemaToTypeString(n.schema));let a=n.required===!1;r.push({tag:`param`,paramName:t,type:`${i}${a?` | undefined`:``}`,comment:n.description??``})}if(n?.schema&&`properties`in n.schema){let t=n.schema.properties,i=n.schema.required,a=Array.isArray(i)?i:[];for(let[n,i]of Object.entries(t??{})){let t=`req.${n}`,o=e.schemaToTypeString(i),s=!a.includes(n);r.push({tag:`param`,paramName:t,type:`${o}${s?` | undefined`:``}`,comment:i.description??``})}}return r}static toRequestBodyTypeNode(t){return p.factory.createParameterDeclaration(void 0,void 0,p.factory.createIdentifier(`req`),void 0,e.toTypeNode(t))}static toTypeNode(t){let{type:n,ref:r}=t;if(r){let e=V.ref2name(r);return p.factory.createTypeReferenceNode(p.factory.createIdentifier(e===`unknown`?e:V.upperCamelCase(e)))}switch(n){case`array`:{let{items:n}=t;return p.factory.createArrayTypeNode(e.toTypeNode(n))}case`object`:{let n=Object.keys(t.properties??{}).length;if(!t.properties||n===0)return p.factory.createTypeReferenceNode(p.factory.createIdentifier(`Record`),[p.factory.createToken(p.SyntaxKind.StringKeyword),p.factory.createToken(p.SyntaxKind.UnknownKeyword)]);let r=Object.keys(t.properties);return p.factory.createTypeLiteralNode(r.map(n=>{let r=t.properties[n];return p.factory.createPropertySignature(void 0,p.factory.createStringLiteral(n),t.required||t.ref||e.isBinarySchema(t)?void 0:p.factory.createToken(p.SyntaxKind.QuestionToken),e.toTypeNode(r))}))}case`integer`:case`number`:return t.enum?p.factory.createUnionTypeNode(t.enum.map(e=>p.factory.createLiteralTypeNode(p.factory.createNumericLiteral(e)))):p.factory.createToken(p.SyntaxKind.NumberKeyword);case`boolean`:return p.factory.createToken(p.SyntaxKind.BooleanKeyword);case`file`:return p.factory.createTypeReferenceNode(p.factory.createIdentifier(`Blob`));default:{let{format:n,oneOf:r,allOf:i,anyOf:a,type:o,enum:s}=t;switch(n){case`number`:return p.factory.createToken(p.SyntaxKind.NumberKeyword);case`string`:return p.factory.createToken(p.SyntaxKind.StringKeyword);case`boolean`:return p.factory.createToken(p.SyntaxKind.BooleanKeyword);case`blob`:case`binary`:return p.factory.createTypeReferenceNode(p.factory.createIdentifier(`Blob`));default:}if(s)return p.factory.createUnionTypeNode(s.map(e=>p.factory.createLiteralTypeNode(p.factory.createStringLiteral(e))));if(o===`string`)return p.factory.createToken(p.SyntaxKind.StringKeyword);if(r)return p.factory.createUnionTypeNode(r.map(t=>e.toTypeNode(t)));if(a)return p.factory.createUnionTypeNode(a.map(t=>e.toTypeNode(t)));if(i)return p.factory.createIntersectionTypeNode(i.map(t=>e.toTypeNode(t)));if(o&&typeof o==`string`)return p.factory.createTypeReferenceNode(o!==`unknown`&&o!==`null`?p.factory.createIdentifier(V.upperCamelCase(o)):o)}}return p.factory.createToken(p.SyntaxKind.UnknownKeyword)}static toDeclarationNodes(t){let n=[],r=[],i=[];for(let a of t)if(a.ref){let e=V.ref2name(a.ref);i.push(p.factory.createParameterDeclaration(void 0,void 0,p.factory.createIdentifier(V.normalize(e)),void 0,p.factory.createTypeReferenceNode(p.factory.createIdentifier(V.upperCamelCase(V.normalize(e)))),void 0))}else{let{name:t,schema:i,required:o}=a;n.push(p.factory.createBindingElement(void 0,void 0,p.factory.createIdentifier(V.normalize(t)))),r.push(p.factory.createPropertySignature([],p.factory.createIdentifier(V.normalize(t)),o?void 0:p.factory.createToken(p.SyntaxKind.QuestionToken),i?e.toTypeNode(i):p.factory.createToken(p.SyntaxKind.UnknownKeyword)))}return n.length>0?[p.factory.createParameterDeclaration(void 0,void 0,p.factory.createObjectBindingPattern(n),void 0,p.factory.createTypeLiteralNode(r),void 0),...i]:i}static toFormDataStatement(t,n){let r=[],i=p.factory.createVariableStatement(void 0,p.factory.createVariableDeclarationList([p.factory.createVariableDeclaration(p.factory.createIdentifier(`fd`),void 0,void 0,p.factory.createNewExpression(p.factory.createIdentifier(`FormData`),void 0,[]))],p.NodeFlags.Const));return r.push(i),t.forEach(e=>{r.push(p.factory.createExpressionStatement(p.factory.createBinaryExpression(p.factory.createIdentifier(e.name),p.factory.createToken(p.SyntaxKind.AmpersandAmpersandToken),p.factory.createCallExpression(p.factory.createPropertyAccessExpression(p.factory.createIdentifier(`fd`),p.factory.createIdentifier(`append`)),void 0,[p.factory.createStringLiteral(e.name),p.factory.createIdentifier(e.name)]))))}),n&&n.type===`object`&&n.properties&&Object.keys(n.properties).length!==0&&Object.keys(n.properties).forEach(t=>{let i=n.properties[t];i.type===`array`&&e.isBinarySchema(i)?r.push(p.factory.createForOfStatement(void 0,p.factory.createVariableDeclarationList([p.factory.createVariableDeclaration(`file`)],p.NodeFlags.Const),p.factory.createElementAccessExpression(p.factory.createIdentifier(`req`),p.factory.createStringLiteral(t)),p.factory.createBlock([p.factory.createExpressionStatement(p.factory.createCallExpression(p.factory.createPropertyAccessExpression(p.factory.createIdentifier(`fd`),p.factory.createIdentifier(`append`)),[],[p.factory.createStringLiteral(t),p.factory.createIdentifier(`file`),p.factory.createPropertyAccessExpression(p.factory.createAsExpression(p.factory.createIdentifier(`file`),p.factory.createTypeReferenceNode(p.factory.createIdentifier(`File`),void 0)),p.factory.createIdentifier(`name`))]))]))):i.required?r.push(p.factory.createExpressionStatement(p.factory.createCallExpression(p.factory.createPropertyAccessExpression(p.factory.createIdentifier(`fd`),p.factory.createIdentifier(`append`)),void 0,[p.factory.createStringLiteral(t),i.type===`string`||e.isBinarySchema(i)||i.isRef?p.factory.createElementAccessExpression(p.factory.createIdentifier(`req`),p.factory.createStringLiteral(t)):i.type===`array`||i.type===`object`?p.factory.createCallExpression(p.factory.createPropertyAccessExpression(p.factory.createIdentifier(`JSON`),p.factory.createIdentifier(`stringify`)),void 0,[p.factory.createElementAccessExpression(p.factory.createIdentifier(`req`),p.factory.createStringLiteral(t))]):p.factory.createCallExpression(p.factory.createIdentifier(`String`),void 0,[p.factory.createElementAccessExpression(p.factory.createIdentifier(`req`),p.factory.createStringLiteral(t))])]))):r.push(p.factory.createExpressionStatement(p.factory.createBinaryExpression(p.factory.createElementAccessExpression(p.factory.createIdentifier(`req`),p.factory.createStringLiteral(t)),p.factory.createToken(p.SyntaxKind.AmpersandAmpersandToken),p.factory.createCallExpression(p.factory.createPropertyAccessExpression(p.factory.createIdentifier(`fd`),p.factory.createIdentifier(`append`)),void 0,[p.factory.createStringLiteral(t),i.type===`string`||e.isBinarySchema(i)||i.isRef?p.factory.createElementAccessExpression(p.factory.createIdentifier(`req`),p.factory.createStringLiteral(t)):i.type===`array`||i.type===`object`?p.factory.createCallExpression(p.factory.createPropertyAccessExpression(p.factory.createIdentifier(`JSON`),p.factory.createIdentifier(`stringify`)),void 0,[p.factory.createElementAccessExpression(p.factory.createIdentifier(`req`),p.factory.createStringLiteral(t))]):p.factory.createCallExpression(p.factory.createIdentifier(`String`),void 0,[p.factory.createElementAccessExpression(p.factory.createIdentifier(`req`),p.factory.createStringLiteral(t))])]))))}),r}static bodyBlock(t,n,r,i,a,o){let s=i&&[`multipart/form-data`,`application/x-www-form-urlencoded`].includes(i.type),c=a?.type===`application/json`,l=i?.schema&&i.schema.type===`array`&&e.isBinarySchema(i.schema),u=r.filter(t=>t.in===`formData`||t.schema&&e.isBinarySchema(t.schema)),d=r.filter(e=>!u.includes(e)),f=i?.schema&&`properties`in i.schema&&Object.values(i.schema?.properties??{}).some(t=>e.isBinarySchema(t)),m=r.some(t=>t?.schema&&e.isBinarySchema(t.schema)),h=!!s&&(l||m||f||u.length>0);return p.factory.createBlock([...h?e.toFormDataStatement(u,i?.schema):[],...o.client(t,n,d,i,a,o,h,c)])}static schemaToStatemets(t,n,r){let i=[],{apis:a,schemas:o={},enums:s}=t,c=[];for(let e of s)c.push(V.upperCamelCase(e.name)),i.push(p.factory.createEnumDeclaration([p.factory.createToken(p.SyntaxKind.ExportKeyword)],p.factory.createIdentifier(V.upperCamelCase(e.name)),e.enum.map(e=>p.factory.createEnumMember(p.factory.createStringLiteral(typeof e==`string`?e:`${e}_`),typeof e==`string`?p.factory.createStringLiteral(e):p.factory.createNumericLiteral(e)))));for(let t in o)if(Object.hasOwn(o,t)&&!c.includes(V.upperCamelCase(t))){let n=o[t];i.push(p.factory.createTypeAliasDeclaration([p.factory.createModifier(p.SyntaxKind.ExportKeyword)],p.factory.createIdentifier(V.upperCamelCase(t)),void 0,e.toTypeNode(n)))}for(let t in a){let o=a[t];for(let a of o){let{method:o,operationId:s,requestBody:c=[],responses:l=[],summary:u,deprecated:d,description:f}=a,{parameters:m=[]}=a;m=m.filter(e=>e.in!==`cookie`),c.length===0&&c.push({type:`application/json`});let h=c.length>1;for(let a of c){let c=p.factory.createFunctionDeclaration([p.factory.createModifier(p.SyntaxKind.ExportKeyword),p.factory.createModifier(p.SyntaxKind.AsyncKeyword)],void 0,V.pathToFnName(t,o,s)+(h?V.capitalize(a.type.split(`/`)[1]):``),void 0,[...m.length>0?e.toDeclarationNodes(m):[],...a?.schema?[e.toRequestBodyTypeNode(a.schema)]:[]].filter(Boolean),void 0,e.bodyBlock(r.baseURL+t,o,m,a,l[0],n)),g=[f,u].filter(Boolean).join(`. `);e.addComments(c,[g&&{comment:g},d&&{tag:`deprecated`},...e.generateParamTags(m,a)].filter(Boolean)),i.push(c)}}}return i}static async prettier(e){return await(0,h.format)(e,{parser:`typescript`})}static async genCode(t,n,r){let{importClientSource:i}=n,a=e.schemaToStatemets(t,r,{baseURL:n.baseURL??``}),o=e.toCode(a);return i&&(o=i+`
21
+ `;(0,p.addSyntheticLeadingComment)(e,p.SyntaxKind.MultiLineCommentTrivia,n,!0)}static isBinarySchema(t){if(t.type===`array`){let n=t;return e.isBinarySchema(n.items)}let n=t;return n.format===`blob`||n.format===`binary`||n.type===`file`}static schemaToTypeString(t){if(t.type===`array`){let n=t;return n.items?`${e.schemaToTypeString(n.items)}[]`:`unknown`}let n=t;return t.type===`string`?`string`:t.type===`number`||t.type===`integer`?`number`:t.type===`boolean`?`boolean`:t.type===`object`||t.properties?`object`:n.format===`binary`||n.type===`file`||n.format===`blob`?`Blob`:n.ref?n.ref:`unknown`}static generateParamTags(t,n){let r=[];for(let n of t){let t=V.normalize(n.name),i=`unknown`;n.schema&&(i=e.schemaToTypeString(n.schema));let a=n.required===!1;r.push({tag:`param`,paramName:t,type:`${i}${a?` | undefined`:``}`,comment:n.description??``})}if(n?.schema&&`properties`in n.schema){let t=n.schema.properties,i=n.schema.required,a=Array.isArray(i)?i:[];for(let[n,i]of Object.entries(t??{})){let t=`req.${n}`,o=e.schemaToTypeString(i),s=!a.includes(n);r.push({tag:`param`,paramName:t,type:`${o}${s?` | undefined`:``}`,comment:i.description??``})}}return r}static toRequestBodyTypeNode(t){return p.factory.createParameterDeclaration(void 0,void 0,p.factory.createIdentifier(`req`),void 0,e.toTypeNode(t))}static toTypeNode(t){let{type:n,ref:r}=t;if(r){let e=V.ref2name(r);return p.factory.createTypeReferenceNode(p.factory.createIdentifier(e===`unknown`?e:V.upperCamelCase(e)))}switch(n){case`array`:{let{items:n}=t;return p.factory.createArrayTypeNode(e.toTypeNode(n))}case`object`:{let n=Object.keys(t.properties??{}).length;if(!t.properties||n===0)return p.factory.createTypeReferenceNode(p.factory.createIdentifier(`Record`),[p.factory.createToken(p.SyntaxKind.StringKeyword),p.factory.createToken(p.SyntaxKind.UnknownKeyword)]);let r=Object.keys(t.properties);return p.factory.createTypeLiteralNode(r.map(n=>{let r=t.properties[n];return p.factory.createPropertySignature(void 0,p.factory.createStringLiteral(n),t.required||t.ref||e.isBinarySchema(t)?void 0:p.factory.createToken(p.SyntaxKind.QuestionToken),e.toTypeNode(r))}))}case`integer`:case`number`:return t.enum?p.factory.createUnionTypeNode(t.enum.map(e=>p.factory.createLiteralTypeNode(p.factory.createNumericLiteral(e)))):p.factory.createToken(p.SyntaxKind.NumberKeyword);case`boolean`:return p.factory.createToken(p.SyntaxKind.BooleanKeyword);case`file`:return p.factory.createTypeReferenceNode(p.factory.createIdentifier(`Blob`));default:{let{format:n,oneOf:r,allOf:i,anyOf:a,type:o,enum:s}=t;switch(n){case`number`:return p.factory.createToken(p.SyntaxKind.NumberKeyword);case`string`:return p.factory.createToken(p.SyntaxKind.StringKeyword);case`boolean`:return p.factory.createToken(p.SyntaxKind.BooleanKeyword);case`blob`:case`binary`:return p.factory.createTypeReferenceNode(p.factory.createIdentifier(`Blob`));default:}if(s)return p.factory.createUnionTypeNode(s.map(e=>p.factory.createLiteralTypeNode(p.factory.createStringLiteral(e))));if(o===`string`)return p.factory.createToken(p.SyntaxKind.StringKeyword);if(r)return p.factory.createUnionTypeNode(r.map(t=>e.toTypeNode(t)));if(a)return p.factory.createUnionTypeNode(a.map(t=>e.toTypeNode(t)));if(i)return p.factory.createIntersectionTypeNode(i.map(t=>e.toTypeNode(t)));if(o&&typeof o==`string`)return p.factory.createTypeReferenceNode(o!==`unknown`&&o!==`null`?p.factory.createIdentifier(V.upperCamelCase(o)):o)}}return p.factory.createToken(p.SyntaxKind.UnknownKeyword)}static toDeclarationNodes(t){let n=[],r=[],i=[];for(let a of t)if(a.ref){let e=V.ref2name(a.ref);i.push(p.factory.createParameterDeclaration(void 0,void 0,p.factory.createIdentifier(V.normalize(e)),void 0,p.factory.createTypeReferenceNode(p.factory.createIdentifier(V.upperCamelCase(V.normalize(e)))),void 0))}else{let{name:t,schema:i,required:o}=a;n.push(p.factory.createBindingElement(void 0,void 0,p.factory.createIdentifier(V.normalize(t)))),r.push(p.factory.createPropertySignature([],p.factory.createIdentifier(V.normalize(t)),o?void 0:p.factory.createToken(p.SyntaxKind.QuestionToken),i?e.toTypeNode(i):p.factory.createToken(p.SyntaxKind.UnknownKeyword)))}return n.length>0?[p.factory.createParameterDeclaration(void 0,void 0,p.factory.createObjectBindingPattern(n),void 0,p.factory.createTypeLiteralNode(r),void 0),...i]:i}static toFormDataStatement(t,n){let r=[],i=p.factory.createVariableStatement(void 0,p.factory.createVariableDeclarationList([p.factory.createVariableDeclaration(p.factory.createIdentifier(`fd`),void 0,void 0,p.factory.createNewExpression(p.factory.createIdentifier(`FormData`),void 0,[]))],p.NodeFlags.Const));return r.push(i),t.forEach(e=>{r.push(p.factory.createExpressionStatement(p.factory.createBinaryExpression(p.factory.createIdentifier(e.name),p.factory.createToken(p.SyntaxKind.AmpersandAmpersandToken),p.factory.createCallExpression(p.factory.createPropertyAccessExpression(p.factory.createIdentifier(`fd`),p.factory.createIdentifier(`append`)),void 0,[p.factory.createStringLiteral(e.name),p.factory.createIdentifier(e.name)]))))}),n&&n.type===`object`&&n.properties&&Object.keys(n.properties).length!==0&&Object.keys(n.properties).forEach(t=>{let i=n.properties[t];i.type===`array`&&e.isBinarySchema(i)?r.push(p.factory.createForOfStatement(void 0,p.factory.createVariableDeclarationList([p.factory.createVariableDeclaration(`file`)],p.NodeFlags.Const),p.factory.createElementAccessExpression(p.factory.createIdentifier(`req`),p.factory.createStringLiteral(t)),p.factory.createBlock([p.factory.createExpressionStatement(p.factory.createCallExpression(p.factory.createPropertyAccessExpression(p.factory.createIdentifier(`fd`),p.factory.createIdentifier(`append`)),[],[p.factory.createStringLiteral(t),p.factory.createIdentifier(`file`),p.factory.createPropertyAccessExpression(p.factory.createAsExpression(p.factory.createIdentifier(`file`),p.factory.createTypeReferenceNode(p.factory.createIdentifier(`File`),void 0)),p.factory.createIdentifier(`name`))]))]))):i.required?r.push(p.factory.createExpressionStatement(p.factory.createCallExpression(p.factory.createPropertyAccessExpression(p.factory.createIdentifier(`fd`),p.factory.createIdentifier(`append`)),void 0,[p.factory.createStringLiteral(t),i.type===`string`||e.isBinarySchema(i)||i.isRef?p.factory.createElementAccessExpression(p.factory.createIdentifier(`req`),p.factory.createStringLiteral(t)):i.type===`array`||i.type===`object`?p.factory.createCallExpression(p.factory.createPropertyAccessExpression(p.factory.createIdentifier(`JSON`),p.factory.createIdentifier(`stringify`)),void 0,[p.factory.createElementAccessExpression(p.factory.createIdentifier(`req`),p.factory.createStringLiteral(t))]):p.factory.createCallExpression(p.factory.createIdentifier(`String`),void 0,[p.factory.createElementAccessExpression(p.factory.createIdentifier(`req`),p.factory.createStringLiteral(t))])]))):r.push(p.factory.createExpressionStatement(p.factory.createBinaryExpression(p.factory.createElementAccessExpression(p.factory.createIdentifier(`req`),p.factory.createStringLiteral(t)),p.factory.createToken(p.SyntaxKind.AmpersandAmpersandToken),p.factory.createCallExpression(p.factory.createPropertyAccessExpression(p.factory.createIdentifier(`fd`),p.factory.createIdentifier(`append`)),void 0,[p.factory.createStringLiteral(t),i.type===`string`||e.isBinarySchema(i)||i.isRef?p.factory.createElementAccessExpression(p.factory.createIdentifier(`req`),p.factory.createStringLiteral(t)):i.type===`array`||i.type===`object`?p.factory.createCallExpression(p.factory.createPropertyAccessExpression(p.factory.createIdentifier(`JSON`),p.factory.createIdentifier(`stringify`)),void 0,[p.factory.createElementAccessExpression(p.factory.createIdentifier(`req`),p.factory.createStringLiteral(t))]):p.factory.createCallExpression(p.factory.createIdentifier(`String`),void 0,[p.factory.createElementAccessExpression(p.factory.createIdentifier(`req`),p.factory.createStringLiteral(t))])]))))}),r}static bodyBlock(t,n,r,i,a,o){let s=i&&[`multipart/form-data`,`application/x-www-form-urlencoded`].includes(i.type),c=a?.type===`application/json`,l=a?.type===`text/event-stream`,u=i?.schema&&i.schema.type===`array`&&e.isBinarySchema(i.schema),d=r.filter(t=>t.in===`formData`||t.schema&&e.isBinarySchema(t.schema)),f=r.filter(e=>!d.includes(e)),m=i?.schema&&`properties`in i.schema&&Object.values(i.schema?.properties??{}).some(t=>e.isBinarySchema(t)),h=r.some(t=>t?.schema&&e.isBinarySchema(t.schema)),g=!!s&&(u||h||m||d.length>0);return p.factory.createBlock([...g?e.toFormDataStatement(d,i?.schema):[],...o.client(t,n,f,i,a,o,g,c,l)])}static schemaToStatemets(t,n,r){let i=[],{apis:a,schemas:o={},enums:s}=t,c=[];for(let e of s)c.push(V.upperCamelCase(e.name)),i.push(p.factory.createEnumDeclaration([p.factory.createToken(p.SyntaxKind.ExportKeyword)],p.factory.createIdentifier(V.upperCamelCase(e.name)),e.enum.map(e=>p.factory.createEnumMember(p.factory.createStringLiteral(typeof e==`string`?e:`${e}_`),typeof e==`string`?p.factory.createStringLiteral(e):p.factory.createNumericLiteral(e)))));for(let t in o)if(Object.hasOwn(o,t)&&!c.includes(V.upperCamelCase(t))){let n=o[t];i.push(p.factory.createTypeAliasDeclaration([p.factory.createModifier(p.SyntaxKind.ExportKeyword)],p.factory.createIdentifier(V.upperCamelCase(t)),void 0,e.toTypeNode(n)))}for(let t in a){let o=a[t];for(let a of o){let{method:o,operationId:s,requestBody:c=[],responses:l=[],summary:u,deprecated:d,description:f}=a,{parameters:m=[]}=a;m=m.filter(e=>e.in!==`cookie`),c.length===0&&c.push({type:`application/json`});let h=c.length>1;for(let a of c){let c=p.factory.createFunctionDeclaration([p.factory.createModifier(p.SyntaxKind.ExportKeyword),p.factory.createModifier(p.SyntaxKind.AsyncKeyword)],void 0,V.pathToFnName(t,o,s)+(h?V.capitalize(a.type.split(`/`)[1]):``),void 0,[...m.length>0?e.toDeclarationNodes(m):[],...a?.schema?[e.toRequestBodyTypeNode(a.schema)]:[]].filter(Boolean),void 0,e.bodyBlock(r.baseURL+t,o,m,a,l[0],n)),g=[f,u].filter(Boolean).join(`. `);e.addComments(c,[g&&{comment:g},d&&{tag:`deprecated`},...e.generateParamTags(m,a)].filter(Boolean)),i.push(c)}}}return i}static async prettier(e){return await(0,h.format)(e,{parser:`typescript`})}static async genCode(t,n,r){let{importClientSource:i}=n,a=e.schemaToStatemets(t,r,{baseURL:n.baseURL??``}),o=e.toCode(a);return i&&(o=i+`
22
22
 
23
- `+o),await e.prettier(o)}},W=class extends L{methodFieldName=`method`;bodyFieldName=`data`;headersFieldName=`headers`;queryFieldName=`params`;name=`axios`;client(e,t,n,r,i,a,o){let s=[],c=n.filter(e=>!e.in||e.in===`body`),l=n.filter(e=>e.in===`header`);return s.push(p.factory.createReturnStatement(p.factory.createCallExpression(p.factory.createIdentifier(a.name),i?.schema?[U.toTypeNode(i.schema)]:void 0,[U.toUrlTemplate(e,n),p.factory.createObjectLiteralExpression([p.factory.createPropertyAssignment(p.factory.createIdentifier(a.methodFieldName),p.factory.createStringLiteral(t.toUpperCase()))].concat(l.length>0?p.factory.createPropertyAssignment(p.factory.createIdentifier(a.headersFieldName),p.factory.createObjectLiteralExpression(l.map(e=>p.factory.createPropertyAssignment(p.factory.createStringLiteral(e.name),p.factory.createCallExpression(p.factory.createIdentifier(`encodeURIComponent`),void 0,[p.factory.createCallExpression(p.factory.createIdentifier(`String`),void 0,[p.factory.createIdentifier(V.normalize(e.name))])]))))):[],o||c.length>0||r?.schema?p.factory.createPropertyAssignment(p.factory.createIdentifier(a.bodyFieldName),o?p.factory.createIdentifier(`fd`):(c.length>0||r?.schema&&U.isBinarySchema(r.schema),p.factory.createIdentifier(`req`))):[]),!0)]))),s}},G=class extends L{methodFieldName=`method`;bodyFieldName=`body`;headersFieldName=`headers`;queryFieldName=``;name=`fetch`;client(e,t,n,r,i,a,o,s){let c=[],l=n.filter(e=>!e.in||e.in===`body`),u=n.filter(e=>e.in===`header`),d=()=>p.factory.createObjectLiteralExpression([p.factory.createPropertyAssignment(p.factory.createIdentifier(a.methodFieldName),p.factory.createStringLiteral(t.toUpperCase()))].concat(u.length>0?p.factory.createPropertyAssignment(p.factory.createIdentifier(a.headersFieldName),p.factory.createObjectLiteralExpression(u.map(e=>p.factory.createPropertyAssignment(p.factory.createStringLiteral(e.name),p.factory.createCallExpression(p.factory.createIdentifier(`encodeURIComponent`),void 0,[p.factory.createCallExpression(p.factory.createIdentifier(`String`),void 0,[p.factory.createIdentifier(V.normalize(e.name))])]))))):[],o||l.length>0||r?.schema?p.factory.createPropertyAssignment(p.factory.createIdentifier(a.bodyFieldName),o?p.factory.createIdentifier(`fd`):l.length>0||r?.schema&&!U.isBinarySchema(r.schema)?p.factory.createCallExpression(p.factory.createPropertyAccessExpression(p.factory.createIdentifier(`JSON`),p.factory.createIdentifier(`stringify`)),[],[r?p.factory.createIdentifier(`req`):p.factory.createObjectLiteralExpression(l.map(e=>p.factory.createShorthandPropertyAssignment(p.factory.createIdentifier(e.name))),!0)]):p.factory.createIdentifier(`req`)):[]),!0);return c.push(p.factory.createReturnStatement(s?p.factory.createCallExpression(p.factory.createPropertyAccessExpression(p.factory.createCallExpression(p.factory.createIdentifier(a.name),void 0,[U.toUrlTemplate(e,n),d()]),p.factory.createIdentifier(`then`)),void 0,[p.factory.createArrowFunction([p.factory.createModifier(p.SyntaxKind.AsyncKeyword)],[],[p.factory.createParameterDeclaration(void 0,void 0,p.factory.createIdentifier(`response`))],void 0,p.factory.createToken(p.SyntaxKind.EqualsGreaterThanToken),i?.schema?p.factory.createAsExpression(p.factory.createParenthesizedExpression(p.factory.createAwaitExpression(p.factory.createCallExpression(p.factory.createPropertyAccessExpression(p.factory.createIdentifier(`response`),p.factory.createIdentifier(`json`)),void 0,[]))),i?.schema?U.toTypeNode(i.schema):p.factory.createToken(p.SyntaxKind.UnknownKeyword)):p.factory.createParenthesizedExpression(p.factory.createAwaitExpression(p.factory.createCallExpression(p.factory.createPropertyAccessExpression(p.factory.createIdentifier(`response`),p.factory.createIdentifier(`json`)),void 0,[]))))]):p.factory.createCallExpression(p.factory.createIdentifier(a.name),void 0,[U.toUrlTemplate(e,n),d()]))),c}},K=class{resolvePathRef(e){let t=V.ref2name(e,this.doc);return this.doc.paths?.[t]}isOpenAPIArraySchema(e){return typeof e==`object`&&!!e&&e.type===`array`}getSchemaByRef(e,t=!1,n=[],r=``){let i=``;if(V.isRef(e)){if(i=this.formatRefName(V.ref2name(e.$ref)),t)return{type:r+i};let n=this.getSchemaContainer()?.[V.ref2name(e.$ref,this.doc)];if(!n)return{type:`unknown`};e=n}return this.toBaseSchema(e,n,``,r+i)}formatRefName(e){return V.capitalize(e)}getParameterByRef(e,t=[],n=``){if(V.isRef(e)){let t=this.getParameterContainer()?.[V.ref2name(e.$ref,this.doc)];if(!t)return{name:`unknown`,in:`query`};e=t}let{name:r,required:i,deprecated:a,description:o,schema:s}=e;if(s&&!V.isRef(s)&&s.enum){let c=V.upperCamelCase(V.normalize(n))+V.upperCamelCase(V.normalize(r)),l={name:c,enum:[...new Set(s.enum)]},u=V.findSameSchema(l,t);return!u&&V.isValidEnumType(s)&&t.push(l),{name:r,required:i,description:o,deprecated:a,in:e.in,schema:{type:u?.name??c}}}return{name:r,required:i,description:o,deprecated:a,in:e.in,schema:e.schema?this.getSchemaByRef(e.schema,!1,t,n+V.capitalize(r)):void 0}}getResponseByRef(e){if(V.isRef(e)){let t=this.getResponseContainer()?.[V.ref2name(e.$ref,this.doc)];if(!t)return[];e=t}let{content:t={}}=e;return Object.keys(t).map(e=>({type:e,schema:t[e].schema?this.getSchemaByRef(t[e].schema,!0):void 0}))}getRequestBodyByRef(e,t=[]){if(V.isRef(e)){let t=this.getRequestBodyContainer()?.[V.ref2name(e.$ref,this.doc)];if(!t)return[];e=t}let{content:n={}}=e;return Object.keys(n).map(e=>({type:e,schema:n[e].schema?this.getSchemaByRef(n[e].schema,!1,t):void 0}))}toBaseSchema(e,t=[],n=``,r=``){if(!e)return{type:`unknown`};if(V.isRef(e))return this.getSchemaByRef(e,!0);if(this.isOpenAPIArraySchema(e)){let{type:i,description:a,items:o,required:s}=e,c=o?this.toBaseSchema(o,t,n,r):{type:`unknown`};return{type:i,required:!!s,description:a,items:c}}let{required:i=[],allOf:a,anyOf:o,description:s,deprecated:c,enum:l,format:u,oneOf:d,properties:f={}}=e,{type:p}=e;if(l&&p!==`boolean`){let a={name:V.upperCamelCase(V.normalize(r))+V.upperCamelCase(V.normalize(n)),enum:[...new Set(l)]},o=V.findSameSchema(a,t);return!o&&V.isValidEnumType(e)&&t.push(a),{type:o?o.name:V.isBooleanEnum(e)?`boolean`:a.name,required:i,description:s,deprecated:c}}return p===void 0&&Object.keys(f).length>0&&(p=`object`),{type:p,required:i,description:s,deprecated:c,enum:l,format:u,allOf:a?.map(e=>V.isRef(e)?{...e,ref:e.$ref,type:V.capitalize(V.ref2name(e.$ref,this.doc))}:this.toBaseSchema(e,t)),anyOf:o?.map(e=>V.isRef(e)?{...e,ref:e.$ref,type:V.capitalize(V.ref2name(e.$ref,this.doc))}:this.toBaseSchema(e,t)),oneOf:d?.map(e=>V.isRef(e)?{...e,ref:e.$ref,type:V.capitalize(V.ref2name(e.$ref,this.doc))}:this.toBaseSchema(e,t)),properties:Object.keys(f).reduce((e,n)=>{let i=f[n];return{...e,[n]:V.isRef(i)?{type:V.capitalize(V.ref2name(i.$ref,this.doc)),isRef:!0}:this.toBaseSchema(i,t,n,r)}},{})}}init(){let{paths:e={}}=this.doc,t=[],n=this.getSchemaContainer()??{},r=this.getParameterContainer()??{},i=this.getResponseContainer()??{},a=this.getRequestBodyContainer()??{},o=Object.keys(n).reduce((e,r)=>{let i=n[r];return{...e,[r]:this.getSchemaByRef(i,!1,t,r)}},{}),s=Object.keys(r).reduce((e,n)=>{let i=r[n];return{...e,[n]:this.getParameterByRef(i,t,n)}},{}),c=Object.keys(i).reduce((e,t)=>{let n=i[t];return{...e,[t]:this.getResponseByRef(n)}},{}),l=Object.keys(a).reduce((e,n)=>{let r=a[n];return{...e,[n]:this.getRequestBodyByRef(r,t)}},{}),u=Object.keys(e).reduce((n,r)=>{let i=e[r]??{};if(i.$ref){let e=this.resolvePathRef(i.$ref);e&&(i=e)}let{parameters:a=[],description:o,summary:s}=i,c=[];return Object.values(B).forEach(e=>{let n=i[e];if(n){let{deprecated:r,operationId:i,responses:l,summary:u,description:d,requestBody:f={content:{}}}=n,p=l?{...l}:{},{parameters:m=[]}=n,h=[...a,...m].map(e=>this.getParameterByRef(e,t)),g=this.getRequestBodyByRef(f,t),_=[...new Set(h.map(e=>e.name))];Object.keys(p).length===0&&(p[200]={description:`Successful response`});let v=Object.keys(p);for(let t of v)if(t in p){let n=p[t],a=this.getResponseByRef(n);c.push({method:e,operationId:i,summary:u??s,description:d??o,deprecated:r,parameters:_.map(e=>h.find(t=>t.name===e)).filter(e=>e!==void 0),responses:a,requestBody:g});break}}}),{...n,[r]:c}},{});return{enums:V.uniqueEnums(t),schemas:o,responses:c,parameters:s,requestBodies:l,apis:u}}},q=class extends K{doc;version=`v2`;constructor(e){super(),this.doc=e}getSchemaContainer(){return this.doc.definitions}getParameterContainer(){return this.doc.parameters}getResponseContainer(){return this.doc.responses}getRequestBodyContainer(){}getParameterByRef(e,t=[],n=``){if(V.isRef(e)){let t=V.ref2name(e.$ref,this.doc),n=this.doc.parameters?.[t];if(!n)throw Error(`Parameter reference not found: ${e.$ref}`);e=n}let r=e,{name:i,required:a,description:o,type:s,items:c,enum:l,properties:u,schema:d}=r;if(l){let e=V.upperCamelCase(V.normalize(n))+V.upperCamelCase(V.normalize(i)),s={name:e,enum:[...new Set(l)]},c=V.findSameSchema(s,t);return!c&&V.isValidEnumType({type:e,enum:l})&&t.push(s),{name:i,required:a,description:o,in:r.in,schema:{type:c?.name??e}}}return c?{name:i,required:a,description:o,in:r.in,schema:{type:s,items:c}}:d&&V.isRef(d)?{name:i,required:a,description:o,in:r.in,schema:{type:V.capitalize(V.ref2name(d.$ref))}}:{name:i,required:a,description:o,in:r.in,schema:{type:s,properties:u}}}getResponseByRef(e){V.isRef(e)&&(e=this.doc.responses[V.ref2name(e.$ref,this.doc)]);let{schema:t}=e;return[{type:`application/json`,schema:t?this.getSchemaByRef(t,!0):void 0}]}init(){let{paths:e={}}=this.doc,t=[],n=this.getSchemaContainer()??{},r=this.getParameterContainer()??{},i=this.getResponseContainer()??{},a=Object.keys(n).reduce((e,r)=>{let i=n[r];return{...e,[r]:this.getSchemaByRef(i,!1,t,r)}},{}),o=Object.keys(r).reduce((e,n)=>{let i=r[n];return{...e,[n]:this.getParameterByRef(i,t,n)}},{}),s=Object.keys(i).reduce((e,t)=>{let n=i[t];return{...e,[t]:this.getResponseByRef(n)}},{}),c={};for(let n of Object.keys(e)){let r=e[n]??{};if(r.$ref){let e=this.resolvePathRef(r.$ref);e&&(r=e)}let{parameters:i=[]}=r,a=[];Object.values(B).forEach(e=>{let n=r[e];if(!n)return;let{deprecated:o,operationId:s,summary:c,description:l,responses:u}=n,{parameters:d=[]}=n,f=[...i,...d].map(e=>this.getParameterByRef(e,t)),p=[...new Set(f.map(e=>e.name))],m=u?{...u}:{};Object.keys(m).length===0&&(m[200]={description:`Successful response`});let h=f.filter(e=>e.in===`body`||e.in===`formData`),g=f.filter(e=>e.in!==`body`&&e.in!==`formData`),_=Object.keys(m);for(let t of _)if(t in m){let n=m[t],r=this.getResponseByRef(n),i=h.length===1&&h[0].in===`body`&&h[0].name===`body`;a.push({method:e,operationId:s,summary:c,deprecated:o,description:l,parameters:p.map(e=>g.find(t=>t.name===e)).filter(e=>e!==void 0),responses:r,requestBody:h.length>0?i?[{type:`application/json`,schema:h[0].schema}]:[{type:`application/json`,schema:{type:`object`,properties:h.reduce((e,t)=>({...e,[t.name]:{type:t.schema?.type??`unknown`,required:t.schema?.required,items:t.schema?.items,description:t.schema?.description}}),{})}}]:void 0});break}}),c[n]=a}return{enums:V.uniqueEnums(t),schemas:a,responses:s,parameters:o,requestBodies:{},apis:c}}},J=class extends K{doc;version=`v3`;constructor(e){super(),this.doc=e}getSchemaContainer(){return this.doc.components?.schemas}getParameterContainer(){return this.doc.components?.parameters}getResponseContainer(){return this.doc.components?.responses}getRequestBodyContainer(){return this.doc.components?.requestBodies}},Y=class extends K{doc;version=`v3_1`;constructor(e){super(),this.doc=e}formatRefName(e){return V.upperCamelCase(e)}getSchemaContainer(){return this.doc.components?.schemas}getParameterContainer(){return this.doc.components?.parameters}getResponseContainer(){return this.doc.components?.responses}getRequestBodyContainer(){return this.doc.components?.requestBodies}};const X=(0,d.createScopedLogger)(`OpenAPI`);function ie(e){switch((e.openapi||e.swagger).slice(0,3)){case`3.1`:return`v3_1`;case`3.0`:return`v3`;case`2.0`:return`v2`;default:return`unknown`}}var ae=class extends H{parse(e){let t=ie(e);switch(X.debug(`openapi version ${t}`),t){case`v2`:return new q(e).init();case`v3`:return new J(e).init();case`v3_1`:return new Y(e).init();default:throw Error(`Not a valid OpenAPI version: ${t}`)}}};function oe(e){switch(e){case`axios`:return new W;default:return new G}}async function Z(e){let t=Date.now(),{verbose:n}=e;n?X.setLevel(`debug`):X.setLevel(`info`),X.info(`Fetch document from ${e.docURL}`);let{enums:r,schemas:i,parameters:a,responses:o,requestBodies:s,apis:c}=new ae(e,await V.fetchDoc(e.docURL,e.requestOptions)),l=oe(e.adaptor??`fetch`),u=await U.genCode({enums:r,schemas:i,parameters:a,responses:o,requestBodies:s,apis:c},e,l);e.output&&await U.write(u,e.output);let d=Date.now()-t;return{code:u,stats:{endpoints:Object.keys(c).length,schemas:Object.keys(i).length,duration:d}}}const Q=g.version;async function se(e){let t=async()=>{try{let{endpoints:t,schemas:n,duration:r}=(await Z(e)).stats;I.success(`Regenerated ${e.output} (${t} endpoints, ${n} schemas) ${r}ms`)}catch(e){I.error(e,!0)}},n=e.docURL,r=c.default.dirname(c.default.isAbsolute(n)?n:c.default.resolve(process.cwd(),n));return u.default.watch(r,{persistent:!0},async(e,n)=>{n&&(e===`change`||e===`rename`)&&(I.fileChange(n),await t())})}function ce(e,t){return e.startsWith(`http://`)||e.startsWith(`https://`)?e:e.startsWith(`/`)||e.match(/^[A-Za-z]:/)?`file://${e}`:t?new URL(e,t).href:c.default.resolve(process.cwd(),e)}async function le(e){if(e.startsWith(`http://`)||e.startsWith(`https://`))return;let t=e.replace(/^file:\/\//,``),n=c.default.isAbsolute(t)?t:c.default.resolve(process.cwd(),t);if(!await u.default.pathExists(n))throw D.specNotFound(n)}function ue(e){return e.startsWith(`http://`)||e.startsWith(`https://`)}const $=(0,l.createCommand)(`apicodegen`);$.name(`apicodegen`).version(Q).description(`API code generation from OpenAPI specifications`).argument(`[spec]`,`URL or path to OpenAPI documentation`).option(`-s, --spec <path>`,`OpenAPI spec file path or URL`).option(`-o, --output <path>`,`Output file path`).option(`-a, --adaptor <type>`,`HTTP client adaptor (fetch|axios)`,`fetch`).option(`-b, --baseURL <url>`,`Base URL for API endpoints`).option(`-c, --config <path>`,`Path to config file`).option(`-w, --watch`,`Watch for file changes and regenerate`).option(`-v, --verbose`,`Enable verbose logging`).option(`--importClientSource <path>`,`Custom client import source path`).action(async(e,t)=>{if(v.print(Q),!e&&!t.spec){I.info(`Usage: apicodegen [options] [spec]`),I.info(`Run 'apicodegen --help' for full options.`);return}let n={};t.spec&&(n.spec=t.spec),t.output&&(n.output=t.output),t.adaptor&&(n.adaptor=t.adaptor),t.baseURL&&(n.baseURL=t.baseURL),t.verbose&&(n.verbose=t.verbose),t.watch&&(n.watch=t.watch),t.importClientSource&&(n.importClientSource=t.importClientSource),t.config&&(n.configFile=t.config),e&&(n.spec=e);try{let e=await w({cwd:process.cwd(),cliOptions:n});await le(e.spec);let t=ce(e.spec,e.baseURL),r={...te(e),docURL:t};if(e.watch){I.watching(`Watching for changes...`);let e=[];if(!t.startsWith(`http`)){let n=t.replace(/^file:\/\//,``),r=c.default.dirname(n);e.push(`${r}/**/*.json`,`${r}/**/*.yaml`,`${r}/**/*.yml`)}let n=await se(r),i=async()=>{I.shutdown(),n&&await n.close(),process.exit(0)};process.on(`SIGINT`,i),process.on(`SIGTERM`,i)}else{ue(t)&&I.loading(`Fetching spec from ${t}...`);let{endpoints:n,schemas:i,duration:a}=(await Z(r)).stats;I.success(`Generated ${e.output} (${n} endpoints, ${i} schemas) ${a}ms`)}}catch(e){if(O(e))I.error(e,t.verbose);else{let n=ne(e,{code:T.GENERATION_FAILED,message:`An unexpected error occurred`});I.error(n,t.verbose)}process.exit(1)}}),$.parse();
23
+ `+o),await e.prettier(o)}},W=class extends L{methodFieldName=`method`;bodyFieldName=`data`;headersFieldName=`headers`;queryFieldName=`params`;name=`axios`;client(e,t,n,r,i,a,o,s,c){let l=[],u=n.filter(e=>!e.in||e.in===`body`),d=n.filter(e=>e.in===`header`),f=(e=[])=>p.factory.createObjectLiteralExpression([p.factory.createPropertyAssignment(p.factory.createIdentifier(a.methodFieldName),p.factory.createStringLiteral(t.toUpperCase()))].concat(d.length>0?p.factory.createPropertyAssignment(p.factory.createIdentifier(a.headersFieldName),p.factory.createObjectLiteralExpression(d.map(e=>p.factory.createPropertyAssignment(p.factory.createStringLiteral(e.name),p.factory.createCallExpression(p.factory.createIdentifier(`encodeURIComponent`),void 0,[p.factory.createCallExpression(p.factory.createIdentifier(`String`),void 0,[p.factory.createIdentifier(V.normalize(e.name))])]))))):[],o||u.length>0||r?.schema?p.factory.createPropertyAssignment(p.factory.createIdentifier(a.bodyFieldName),o?p.factory.createIdentifier(`fd`):(u.length>0||r?.schema&&U.isBinarySchema(r.schema),p.factory.createIdentifier(`req`))):[],e),!0);return c?(l.push(p.factory.createReturnStatement(p.factory.createCallExpression(p.factory.createIdentifier(a.name),void 0,[U.toUrlTemplate(e,n),f([p.factory.createPropertyAssignment(p.factory.createIdentifier(`adapter`),p.factory.createStringLiteral(`fetch`)),p.factory.createPropertyAssignment(p.factory.createIdentifier(`responseType`),p.factory.createStringLiteral(`stream`))])]))),l):(l.push(p.factory.createReturnStatement(p.factory.createCallExpression(p.factory.createIdentifier(a.name),i?.schema?[U.toTypeNode(i.schema)]:void 0,[U.toUrlTemplate(e,n),f()]))),l)}},G=class extends L{methodFieldName=`method`;bodyFieldName=`body`;headersFieldName=`headers`;queryFieldName=``;name=`fetch`;client(e,t,n,r,i,a,o,s,c){let l=[],u=n.filter(e=>!e.in||e.in===`body`),d=n.filter(e=>e.in===`header`),f=()=>p.factory.createObjectLiteralExpression([p.factory.createPropertyAssignment(p.factory.createIdentifier(a.methodFieldName),p.factory.createStringLiteral(t.toUpperCase()))].concat(d.length>0?p.factory.createPropertyAssignment(p.factory.createIdentifier(a.headersFieldName),p.factory.createObjectLiteralExpression(d.map(e=>p.factory.createPropertyAssignment(p.factory.createStringLiteral(e.name),p.factory.createCallExpression(p.factory.createIdentifier(`encodeURIComponent`),void 0,[p.factory.createCallExpression(p.factory.createIdentifier(`String`),void 0,[p.factory.createIdentifier(V.normalize(e.name))])]))))):[],o||u.length>0||r?.schema?p.factory.createPropertyAssignment(p.factory.createIdentifier(a.bodyFieldName),o?p.factory.createIdentifier(`fd`):u.length>0||r?.schema&&!U.isBinarySchema(r.schema)?p.factory.createCallExpression(p.factory.createPropertyAccessExpression(p.factory.createIdentifier(`JSON`),p.factory.createIdentifier(`stringify`)),[],[r?p.factory.createIdentifier(`req`):p.factory.createObjectLiteralExpression(u.map(e=>p.factory.createShorthandPropertyAssignment(p.factory.createIdentifier(e.name))),!0)]):p.factory.createIdentifier(`req`)):[]),!0);return c?(l.push(p.factory.createReturnStatement(p.factory.createCallExpression(p.factory.createIdentifier(a.name),void 0,[U.toUrlTemplate(e,n),f()]))),l):(l.push(p.factory.createReturnStatement(s?p.factory.createCallExpression(p.factory.createPropertyAccessExpression(p.factory.createCallExpression(p.factory.createIdentifier(a.name),void 0,[U.toUrlTemplate(e,n),f()]),p.factory.createIdentifier(`then`)),void 0,[p.factory.createArrowFunction([p.factory.createModifier(p.SyntaxKind.AsyncKeyword)],[],[p.factory.createParameterDeclaration(void 0,void 0,p.factory.createIdentifier(`response`))],void 0,p.factory.createToken(p.SyntaxKind.EqualsGreaterThanToken),i?.schema?p.factory.createAsExpression(p.factory.createParenthesizedExpression(p.factory.createAwaitExpression(p.factory.createCallExpression(p.factory.createPropertyAccessExpression(p.factory.createIdentifier(`response`),p.factory.createIdentifier(`json`)),void 0,[]))),i?.schema?U.toTypeNode(i.schema):p.factory.createToken(p.SyntaxKind.UnknownKeyword)):p.factory.createParenthesizedExpression(p.factory.createAwaitExpression(p.factory.createCallExpression(p.factory.createPropertyAccessExpression(p.factory.createIdentifier(`response`),p.factory.createIdentifier(`json`)),void 0,[]))))]):p.factory.createCallExpression(p.factory.createIdentifier(a.name),void 0,[U.toUrlTemplate(e,n),f()]))),l)}},K=class{resolvePathRef(e){let t=V.ref2name(e,this.doc);return this.doc.paths?.[t]}isOpenAPIArraySchema(e){return typeof e==`object`&&!!e&&e.type===`array`}getSchemaByRef(e,t=!1,n=[],r=``){let i=``;if(V.isRef(e)){if(i=this.formatRefName(V.ref2name(e.$ref)),t)return{type:r+i};let n=this.getSchemaContainer()?.[V.ref2name(e.$ref,this.doc)];if(!n)return{type:`unknown`};e=n}return this.toBaseSchema(e,n,``,r+i)}formatRefName(e){return V.capitalize(e)}getParameterByRef(e,t=[],n=``){if(V.isRef(e)){let t=this.getParameterContainer()?.[V.ref2name(e.$ref,this.doc)];if(!t)return{name:`unknown`,in:`query`};e=t}let{name:r,required:i,deprecated:a,description:o,schema:s}=e;if(s&&!V.isRef(s)&&s.enum){let c=V.upperCamelCase(V.normalize(n))+V.upperCamelCase(V.normalize(r)),l={name:c,enum:[...new Set(s.enum)]},u=V.findSameSchema(l,t);return!u&&V.isValidEnumType(s)&&t.push(l),{name:r,required:i,description:o,deprecated:a,in:e.in,schema:{type:u?.name??c}}}return{name:r,required:i,description:o,deprecated:a,in:e.in,schema:e.schema?this.getSchemaByRef(e.schema,!1,t,n+V.capitalize(r)):void 0}}getResponseByRef(e){if(V.isRef(e)){let t=this.getResponseContainer()?.[V.ref2name(e.$ref,this.doc)];if(!t)return[];e=t}let{content:t={}}=e;return Object.keys(t).map(e=>({type:e,schema:t[e].schema?this.getSchemaByRef(t[e].schema,!0):void 0}))}getRequestBodyByRef(e,t=[]){if(V.isRef(e)){let t=this.getRequestBodyContainer()?.[V.ref2name(e.$ref,this.doc)];if(!t)return[];e=t}let{content:n={}}=e;return Object.keys(n).map(e=>({type:e,schema:n[e].schema?this.getSchemaByRef(n[e].schema,!1,t):void 0}))}toBaseSchema(e,t=[],n=``,r=``){if(!e)return{type:`unknown`};if(V.isRef(e))return this.getSchemaByRef(e,!0);if(this.isOpenAPIArraySchema(e)){let{type:i,description:a,items:o,required:s}=e,c=o?this.toBaseSchema(o,t,n,r):{type:`unknown`};return{type:i,required:!!s,description:a,items:c}}let{required:i=[],allOf:a,anyOf:o,description:s,deprecated:c,enum:l,format:u,oneOf:d,properties:f={}}=e,{type:p}=e;if(l&&p!==`boolean`){let a={name:V.upperCamelCase(V.normalize(r))+V.upperCamelCase(V.normalize(n)),enum:[...new Set(l)]},o=V.findSameSchema(a,t);return!o&&V.isValidEnumType(e)&&t.push(a),{type:o?o.name:V.isBooleanEnum(e)?`boolean`:a.name,required:i,description:s,deprecated:c}}return p===void 0&&Object.keys(f).length>0&&(p=`object`),{type:p,required:i,description:s,deprecated:c,enum:l,format:u,allOf:a?.map(e=>V.isRef(e)?{...e,ref:e.$ref,type:V.capitalize(V.ref2name(e.$ref,this.doc))}:this.toBaseSchema(e,t)),anyOf:o?.map(e=>V.isRef(e)?{...e,ref:e.$ref,type:V.capitalize(V.ref2name(e.$ref,this.doc))}:this.toBaseSchema(e,t)),oneOf:d?.map(e=>V.isRef(e)?{...e,ref:e.$ref,type:V.capitalize(V.ref2name(e.$ref,this.doc))}:this.toBaseSchema(e,t)),properties:Object.keys(f).reduce((e,n)=>{let i=f[n];return{...e,[n]:V.isRef(i)?{type:V.capitalize(V.ref2name(i.$ref,this.doc)),isRef:!0}:this.toBaseSchema(i,t,n,r)}},{})}}init(){let{paths:e={}}=this.doc,t=[],n=this.getSchemaContainer()??{},r=this.getParameterContainer()??{},i=this.getResponseContainer()??{},a=this.getRequestBodyContainer()??{},o=Object.keys(n).reduce((e,r)=>{let i=n[r];return{...e,[r]:this.getSchemaByRef(i,!1,t,r)}},{}),s=Object.keys(r).reduce((e,n)=>{let i=r[n];return{...e,[n]:this.getParameterByRef(i,t,n)}},{}),c=Object.keys(i).reduce((e,t)=>{let n=i[t];return{...e,[t]:this.getResponseByRef(n)}},{}),l=Object.keys(a).reduce((e,n)=>{let r=a[n];return{...e,[n]:this.getRequestBodyByRef(r,t)}},{}),u=Object.keys(e).reduce((n,r)=>{let i=e[r]??{};if(i.$ref){let e=this.resolvePathRef(i.$ref);e&&(i=e)}let{parameters:a=[],description:o,summary:s}=i,c=[];return Object.values(B).forEach(e=>{let n=i[e];if(n){let{deprecated:r,operationId:i,responses:l,summary:u,description:d,requestBody:f={content:{}}}=n,p=l?{...l}:{},{parameters:m=[]}=n,h=[...a,...m].map(e=>this.getParameterByRef(e,t)),g=this.getRequestBodyByRef(f,t),_=[...new Set(h.map(e=>e.name))];Object.keys(p).length===0&&(p[200]={description:`Successful response`});let v=Object.keys(p);for(let t of v)if(t in p){let n=p[t],a=this.getResponseByRef(n);c.push({method:e,operationId:i,summary:u??s,description:d??o,deprecated:r,parameters:_.map(e=>h.find(t=>t.name===e)).filter(e=>e!==void 0),responses:a,requestBody:g});break}}}),{...n,[r]:c}},{});return{enums:V.uniqueEnums(t),schemas:o,responses:c,parameters:s,requestBodies:l,apis:u}}},q=class extends K{doc;version=`v2`;constructor(e){super(),this.doc=e}getSchemaContainer(){return this.doc.definitions}getParameterContainer(){return this.doc.parameters}getResponseContainer(){return this.doc.responses}getRequestBodyContainer(){}getParameterByRef(e,t=[],n=``){if(V.isRef(e)){let t=V.ref2name(e.$ref,this.doc),n=this.doc.parameters?.[t];if(!n)throw Error(`Parameter reference not found: ${e.$ref}`);e=n}let r=e,{name:i,required:a,description:o,type:s,items:c,enum:l,properties:u,schema:d}=r;if(l){let e=V.upperCamelCase(V.normalize(n))+V.upperCamelCase(V.normalize(i)),s={name:e,enum:[...new Set(l)]},c=V.findSameSchema(s,t);return!c&&V.isValidEnumType({type:e,enum:l})&&t.push(s),{name:i,required:a,description:o,in:r.in,schema:{type:c?.name??e}}}return c?{name:i,required:a,description:o,in:r.in,schema:{type:s,items:c}}:d&&V.isRef(d)?{name:i,required:a,description:o,in:r.in,schema:{type:V.capitalize(V.ref2name(d.$ref))}}:{name:i,required:a,description:o,in:r.in,schema:{type:s,properties:u}}}getResponseByRef(e){V.isRef(e)&&(e=this.doc.responses[V.ref2name(e.$ref,this.doc)]);let{schema:t}=e;return[{type:`application/json`,schema:t?this.getSchemaByRef(t,!0):void 0}]}init(){let{paths:e={}}=this.doc,t=[],n=this.getSchemaContainer()??{},r=this.getParameterContainer()??{},i=this.getResponseContainer()??{},a=Object.keys(n).reduce((e,r)=>{let i=n[r];return{...e,[r]:this.getSchemaByRef(i,!1,t,r)}},{}),o=Object.keys(r).reduce((e,n)=>{let i=r[n];return{...e,[n]:this.getParameterByRef(i,t,n)}},{}),s=Object.keys(i).reduce((e,t)=>{let n=i[t];return{...e,[t]:this.getResponseByRef(n)}},{}),c={};for(let n of Object.keys(e)){let r=e[n]??{};if(r.$ref){let e=this.resolvePathRef(r.$ref);e&&(r=e)}let{parameters:i=[]}=r,a=[];Object.values(B).forEach(e=>{let n=r[e];if(!n)return;let{deprecated:o,operationId:s,summary:c,description:l,responses:u}=n,{parameters:d=[]}=n,f=[...i,...d].map(e=>this.getParameterByRef(e,t)),p=[...new Set(f.map(e=>e.name))],m=u?{...u}:{};Object.keys(m).length===0&&(m[200]={description:`Successful response`});let h=f.filter(e=>e.in===`body`||e.in===`formData`),g=f.filter(e=>e.in!==`body`&&e.in!==`formData`),_=Object.keys(m);for(let t of _)if(t in m){let n=m[t],r=this.getResponseByRef(n),i=h.length===1&&h[0].in===`body`&&h[0].name===`body`;a.push({method:e,operationId:s,summary:c,deprecated:o,description:l,parameters:p.map(e=>g.find(t=>t.name===e)).filter(e=>e!==void 0),responses:r,requestBody:h.length>0?i?[{type:`application/json`,schema:h[0].schema}]:[{type:`application/json`,schema:{type:`object`,properties:h.reduce((e,t)=>({...e,[t.name]:{type:t.schema?.type??`unknown`,required:t.schema?.required,items:t.schema?.items,description:t.schema?.description}}),{})}}]:void 0});break}}),c[n]=a}return{enums:V.uniqueEnums(t),schemas:a,responses:s,parameters:o,requestBodies:{},apis:c}}},J=class extends K{doc;version=`v3`;constructor(e){super(),this.doc=e}getSchemaContainer(){return this.doc.components?.schemas}getParameterContainer(){return this.doc.components?.parameters}getResponseContainer(){return this.doc.components?.responses}getRequestBodyContainer(){return this.doc.components?.requestBodies}},Y=class extends K{doc;version=`v3_1`;constructor(e){super(),this.doc=e}formatRefName(e){return V.upperCamelCase(e)}getSchemaContainer(){return this.doc.components?.schemas}getParameterContainer(){return this.doc.components?.parameters}getResponseContainer(){return this.doc.components?.responses}getRequestBodyContainer(){return this.doc.components?.requestBodies}};const X=(0,d.createScopedLogger)(`OpenAPI`);function ie(e){switch((e.openapi||e.swagger).slice(0,3)){case`3.1`:return`v3_1`;case`3.0`:return`v3`;case`2.0`:return`v2`;default:return`unknown`}}var ae=class extends H{parse(e){let t=ie(e);switch(X.debug(`openapi version ${t}`),t){case`v2`:return new q(e).init();case`v3`:return new J(e).init();case`v3_1`:return new Y(e).init();default:throw Error(`Not a valid OpenAPI version: ${t}`)}}};function oe(e){switch(e){case`axios`:return new W;default:return new G}}async function Z(e){let t=Date.now(),{verbose:n}=e;n?X.setLevel(`debug`):X.setLevel(`info`),X.info(`Fetch document from ${e.docURL}`);let{enums:r,schemas:i,parameters:a,responses:o,requestBodies:s,apis:c}=new ae(e,await V.fetchDoc(e.docURL,e.requestOptions)),l=oe(e.adaptor??`fetch`),u=await U.genCode({enums:r,schemas:i,parameters:a,responses:o,requestBodies:s,apis:c},e,l);e.output&&await U.write(u,e.output);let d=Date.now()-t;return{code:u,stats:{endpoints:Object.keys(c).length,schemas:Object.keys(i).length,duration:d}}}const Q=g.version;async function se(e){let t=async()=>{try{let{endpoints:t,schemas:n,duration:r}=(await Z(e)).stats;I.success(`Regenerated ${e.output} (${t} endpoints, ${n} schemas) ${r}ms`)}catch(e){I.error(e,!0)}},n=e.docURL,r=c.default.dirname(c.default.isAbsolute(n)?n:c.default.resolve(process.cwd(),n));return u.default.watch(r,{persistent:!0},async(e,n)=>{n&&(e===`change`||e===`rename`)&&(I.fileChange(n),await t())})}function ce(e,t){return e.startsWith(`http://`)||e.startsWith(`https://`)?e:e.startsWith(`/`)||e.match(/^[A-Za-z]:/)?`file://${e}`:t?new URL(e,t).href:c.default.resolve(process.cwd(),e)}async function le(e){if(e.startsWith(`http://`)||e.startsWith(`https://`))return;let t=e.replace(/^file:\/\//,``),n=c.default.isAbsolute(t)?t:c.default.resolve(process.cwd(),t);if(!await u.default.pathExists(n))throw D.specNotFound(n)}function ue(e){return e.startsWith(`http://`)||e.startsWith(`https://`)}const $=(0,l.createCommand)(`apicodegen`);$.name(`apicodegen`).version(Q).description(`API code generation from OpenAPI specifications`).argument(`[spec]`,`URL or path to OpenAPI documentation`).option(`-s, --spec <path>`,`OpenAPI spec file path or URL`).option(`-o, --output <path>`,`Output file path`).option(`-a, --adaptor <type>`,`HTTP client adaptor (fetch|axios)`,`fetch`).option(`-b, --baseURL <url>`,`Base URL for API endpoints`).option(`-c, --config <path>`,`Path to config file`).option(`-w, --watch`,`Watch for file changes and regenerate`).option(`-v, --verbose`,`Enable verbose logging`).option(`--importClientSource <path>`,`Custom client import source path`).action(async(e,t)=>{if(v.print(Q),!e&&!t.spec){I.info(`Usage: apicodegen [options] [spec]`),I.info(`Run 'apicodegen --help' for full options.`);return}let n={};t.spec&&(n.spec=t.spec),t.output&&(n.output=t.output),t.adaptor&&(n.adaptor=t.adaptor),t.baseURL&&(n.baseURL=t.baseURL),t.verbose&&(n.verbose=t.verbose),t.watch&&(n.watch=t.watch),t.importClientSource&&(n.importClientSource=t.importClientSource),t.config&&(n.configFile=t.config),e&&(n.spec=e);try{let e=await w({cwd:process.cwd(),cliOptions:n});await le(e.spec);let t=ce(e.spec,e.baseURL),r={...te(e),docURL:t};if(e.watch){I.watching(`Watching for changes...`);let e=[];if(!t.startsWith(`http`)){let n=t.replace(/^file:\/\//,``),r=c.default.dirname(n);e.push(`${r}/**/*.json`,`${r}/**/*.yaml`,`${r}/**/*.yml`)}let n=await se(r),i=async()=>{I.shutdown(),n&&await n.close(),process.exit(0)};process.on(`SIGINT`,i),process.on(`SIGTERM`,i)}else{ue(t)&&I.loading(`Fetching spec from ${t}...`);let{endpoints:n,schemas:i,duration:a}=(await Z(r)).stats;I.success(`Generated ${e.output} (${n} endpoints, ${i} schemas) ${a}ms`)}}catch(e){if(O(e))I.error(e,t.verbose);else{let n=ne(e,{code:T.GENERATION_FAILED,message:`An unexpected error occurred`});I.error(n,t.verbose)}process.exit(1)}}),$.parse();
package/npm/index.cjs CHANGED
@@ -157,6 +157,7 @@ let ParameterIn = /* @__PURE__ */ function(ParameterIn) {
157
157
  }({});
158
158
  let MediaTypes = /* @__PURE__ */ function(MediaTypes) {
159
159
  MediaTypes["JSON"] = "application/json";
160
+ MediaTypes["EVENT_STREAM"] = "text/event-stream";
160
161
  MediaTypes["TEXT"] = "text";
161
162
  MediaTypes["IMAGE"] = "image";
162
163
  MediaTypes["AUDIO"] = "audio";
@@ -902,13 +903,14 @@ var Generator = class Generator {
902
903
  static bodyBlock(uri, method, parameters, requestBody, response, adapter) {
903
904
  const isFormDataRequest = requestBody && ["multipart/form-data", "application/x-www-form-urlencoded"].includes(requestBody.type);
904
905
  const shouldParseResponseToJSON = "application/json" === response?.type;
906
+ const isEventStream = response?.type === "text/event-stream";
905
907
  const isRequestBodyBinary = requestBody?.schema && requestBody.schema.type === "array" && Generator.isBinarySchema(requestBody.schema);
906
908
  const parametersShouldPutInFormData = parameters.filter((p) => p.in === "formData" || p.schema && Generator.isBinarySchema(p.schema));
907
909
  const parametersShouldNotPutInFormData = parameters.filter((p) => !parametersShouldPutInFormData.includes(p));
908
910
  const isRequestBodyContainsBinary = requestBody?.schema && "properties" in requestBody.schema && Object.values(requestBody.schema?.properties ?? {}).some((p) => Generator.isBinarySchema(p));
909
911
  const hasBinaryInParameters = parameters.some((p) => p?.schema && Generator.isBinarySchema(p.schema));
910
912
  const shouldPutParametersOrBodyInFormData = !!isFormDataRequest && (isRequestBodyBinary || hasBinaryInParameters || isRequestBodyContainsBinary || parametersShouldPutInFormData.length > 0);
911
- return typescript.factory.createBlock([...shouldPutParametersOrBodyInFormData ? Generator.toFormDataStatement(parametersShouldPutInFormData, requestBody?.schema) : [], ...adapter.client(uri, method, parametersShouldNotPutInFormData, requestBody, response, adapter, shouldPutParametersOrBodyInFormData, shouldParseResponseToJSON)]);
913
+ return typescript.factory.createBlock([...shouldPutParametersOrBodyInFormData ? Generator.toFormDataStatement(parametersShouldPutInFormData, requestBody?.schema) : [], ...adapter.client(uri, method, parametersShouldNotPutInFormData, requestBody, response, adapter, shouldPutParametersOrBodyInFormData, shouldParseResponseToJSON, isEventStream)]);
912
914
  }
913
915
  static schemaToStatemets(parsedDoc, adaptor, options) {
914
916
  const statements = [];
@@ -985,13 +987,19 @@ var AxiosAdapter = class extends Adapter {
985
987
  */
986
988
  name = "axios";
987
989
  /**
988
- * Method that should generate and return the client-specific configuration statements.
989
- *
990
- * @returns {Statement[]} An array of TypeScript statements that define the client configuration.
991
- *
992
- * @throws {Error} Indicates that the method is not yet implemented and needs to be filled in.
990
+ * Generates client code for making API requests using Axios.
991
+ * @param uri - The API endpoint URI
992
+ * @param method - The HTTP method (GET, POST, etc.)
993
+ * @param parameters - Array of parameters to include in the request
994
+ * @param requestBody - The request body media type definition
995
+ * @param response - The response media type definition
996
+ * @param adapter - The adapter instance
997
+ * @param shouldUseFormData - Flag to use FormData for the request body
998
+ * @param shouldUseJSONResponse - Unused by AxiosAdapter; present to align with the abstract signature so positional args bind correctly
999
+ * @param isEventStream - Flag indicating a text/event-stream response; when true the raw AxiosResponse is returned without JSON parsing
1000
+ * @return - An array of generated TypeScript statements
993
1001
  */
994
- client(uri, method, parameters, requestBody, response, adapter, shouldUseFormData) {
1002
+ client(uri, method, parameters, requestBody, response, adapter, shouldUseFormData, _shouldUseJSONResponse, isEventStream) {
995
1003
  const statements = [];
996
1004
  const inBody = parameters.filter((p) => !p.in || p.in === "body");
997
1005
  const inHeader = parameters.filter((p) => p.in === "header");
@@ -1000,9 +1008,13 @@ var AxiosAdapter = class extends Adapter {
1000
1008
  * including method, headers, and body.
1001
1009
  * @returns - The constructed fetch options object
1002
1010
  */
1003
- const toLiterlExpression = () => {
1004
- return typescript.factory.createObjectLiteralExpression([typescript.factory.createPropertyAssignment(typescript.factory.createIdentifier(adapter.methodFieldName), typescript.factory.createStringLiteral(method.toUpperCase()))].concat(inHeader.length > 0 ? typescript.factory.createPropertyAssignment(typescript.factory.createIdentifier(adapter.headersFieldName), typescript.factory.createObjectLiteralExpression(inHeader.map((p) => typescript.factory.createPropertyAssignment(typescript.factory.createStringLiteral(p.name), typescript.factory.createCallExpression(typescript.factory.createIdentifier("encodeURIComponent"), void 0, [typescript.factory.createCallExpression(typescript.factory.createIdentifier("String"), void 0, [typescript.factory.createIdentifier(Base.normalize(p.name))])]))))) : []).concat(shouldUseFormData || inBody.length > 0 || requestBody?.schema ? typescript.factory.createPropertyAssignment(typescript.factory.createIdentifier(adapter.bodyFieldName), shouldUseFormData ? typescript.factory.createIdentifier("fd") : inBody.length > 0 || requestBody?.schema && !Generator.isBinarySchema(requestBody.schema) ? typescript.factory.createIdentifier("req") : typescript.factory.createIdentifier("req")) : []), true);
1011
+ const toLiterlExpression = (extraProperties = []) => {
1012
+ return typescript.factory.createObjectLiteralExpression([typescript.factory.createPropertyAssignment(typescript.factory.createIdentifier(adapter.methodFieldName), typescript.factory.createStringLiteral(method.toUpperCase()))].concat(inHeader.length > 0 ? typescript.factory.createPropertyAssignment(typescript.factory.createIdentifier(adapter.headersFieldName), typescript.factory.createObjectLiteralExpression(inHeader.map((p) => typescript.factory.createPropertyAssignment(typescript.factory.createStringLiteral(p.name), typescript.factory.createCallExpression(typescript.factory.createIdentifier("encodeURIComponent"), void 0, [typescript.factory.createCallExpression(typescript.factory.createIdentifier("String"), void 0, [typescript.factory.createIdentifier(Base.normalize(p.name))])]))))) : []).concat(shouldUseFormData || inBody.length > 0 || requestBody?.schema ? typescript.factory.createPropertyAssignment(typescript.factory.createIdentifier(adapter.bodyFieldName), shouldUseFormData ? typescript.factory.createIdentifier("fd") : inBody.length > 0 || requestBody?.schema && !Generator.isBinarySchema(requestBody.schema) ? typescript.factory.createIdentifier("req") : typescript.factory.createIdentifier("req")) : []).concat(extraProperties), true);
1005
1013
  };
1014
+ if (isEventStream) {
1015
+ statements.push(typescript.factory.createReturnStatement(typescript.factory.createCallExpression(typescript.factory.createIdentifier(adapter.name), void 0, [Generator.toUrlTemplate(uri, parameters), toLiterlExpression([typescript.factory.createPropertyAssignment(typescript.factory.createIdentifier("adapter"), typescript.factory.createStringLiteral("fetch")), typescript.factory.createPropertyAssignment(typescript.factory.createIdentifier("responseType"), typescript.factory.createStringLiteral("stream"))])])));
1016
+ return statements;
1017
+ }
1006
1018
  statements.push(typescript.factory.createReturnStatement(typescript.factory.createCallExpression(typescript.factory.createIdentifier(adapter.name), response?.schema ? [Generator.toTypeNode(response.schema)] : void 0, [Generator.toUrlTemplate(uri, parameters), toLiterlExpression()])));
1007
1019
  return statements;
1008
1020
  }
@@ -1029,9 +1041,10 @@ var FetchAdapter = class extends Adapter {
1029
1041
  * @param adapter - The adapter instance
1030
1042
  * @param shouldUseFormData - Flag to use FormData for the request body
1031
1043
  * @param shouldUseJSONResponse - Flag to use JSON parsing for the response
1044
+ * @param isEventStream - Flag indicating a text/event-stream response; when true the raw Response is returned unparsed
1032
1045
  * @return - An array of generated TypeScript statements
1033
1046
  */
1034
- client(uri, method, parameters, requestBody, response, adapter, shouldUseFormData, shouldUseJSONResponse) {
1047
+ client(uri, method, parameters, requestBody, response, adapter, shouldUseFormData, shouldUseJSONResponse, isEventStream) {
1035
1048
  const statements = [];
1036
1049
  const inBody = parameters.filter((p) => !p.in || p.in === "body");
1037
1050
  const inHeader = parameters.filter((p) => p.in === "header");
@@ -1043,6 +1056,10 @@ var FetchAdapter = class extends Adapter {
1043
1056
  const toLiterlExpression = () => {
1044
1057
  return typescript.factory.createObjectLiteralExpression([typescript.factory.createPropertyAssignment(typescript.factory.createIdentifier(adapter.methodFieldName), typescript.factory.createStringLiteral(method.toUpperCase()))].concat(inHeader.length > 0 ? typescript.factory.createPropertyAssignment(typescript.factory.createIdentifier(adapter.headersFieldName), typescript.factory.createObjectLiteralExpression(inHeader.map((p) => typescript.factory.createPropertyAssignment(typescript.factory.createStringLiteral(p.name), typescript.factory.createCallExpression(typescript.factory.createIdentifier("encodeURIComponent"), void 0, [typescript.factory.createCallExpression(typescript.factory.createIdentifier("String"), void 0, [typescript.factory.createIdentifier(Base.normalize(p.name))])]))))) : []).concat(shouldUseFormData || inBody.length > 0 || requestBody?.schema ? typescript.factory.createPropertyAssignment(typescript.factory.createIdentifier(adapter.bodyFieldName), shouldUseFormData ? typescript.factory.createIdentifier("fd") : inBody.length > 0 || requestBody?.schema && !Generator.isBinarySchema(requestBody.schema) ? typescript.factory.createCallExpression(typescript.factory.createPropertyAccessExpression(typescript.factory.createIdentifier("JSON"), typescript.factory.createIdentifier("stringify")), [], [requestBody ? typescript.factory.createIdentifier("req") : typescript.factory.createObjectLiteralExpression(inBody.map((b) => typescript.factory.createShorthandPropertyAssignment(typescript.factory.createIdentifier(b.name))), true)]) : typescript.factory.createIdentifier("req")) : []), true);
1045
1058
  };
1059
+ if (isEventStream) {
1060
+ statements.push(typescript.factory.createReturnStatement(typescript.factory.createCallExpression(typescript.factory.createIdentifier(adapter.name), void 0, [Generator.toUrlTemplate(uri, parameters), toLiterlExpression()])));
1061
+ return statements;
1062
+ }
1046
1063
  statements.push(typescript.factory.createReturnStatement(shouldUseJSONResponse ? typescript.factory.createCallExpression(typescript.factory.createPropertyAccessExpression(typescript.factory.createCallExpression(typescript.factory.createIdentifier(adapter.name), void 0, [Generator.toUrlTemplate(uri, parameters), toLiterlExpression()]), typescript.factory.createIdentifier("then")), void 0, [typescript.factory.createArrowFunction([typescript.factory.createModifier(typescript.SyntaxKind.AsyncKeyword)], [], [typescript.factory.createParameterDeclaration(void 0, void 0, typescript.factory.createIdentifier("response"))], void 0, typescript.factory.createToken(typescript.SyntaxKind.EqualsGreaterThanToken), response?.schema ? typescript.factory.createAsExpression(typescript.factory.createParenthesizedExpression(typescript.factory.createAwaitExpression(typescript.factory.createCallExpression(typescript.factory.createPropertyAccessExpression(typescript.factory.createIdentifier("response"), typescript.factory.createIdentifier("json")), void 0, []))), response?.schema ? Generator.toTypeNode(response.schema) : typescript.factory.createToken(typescript.SyntaxKind.UnknownKeyword)) : typescript.factory.createParenthesizedExpression(typescript.factory.createAwaitExpression(typescript.factory.createCallExpression(typescript.factory.createPropertyAccessExpression(typescript.factory.createIdentifier("response"), typescript.factory.createIdentifier("json")), void 0, []))))]) : typescript.factory.createCallExpression(typescript.factory.createIdentifier(adapter.name), void 0, [Generator.toUrlTemplate(uri, parameters), toLiterlExpression()])));
1047
1064
  return statements;
1048
1065
  }
@@ -1843,15 +1860,57 @@ async function codeGen(initOptions) {
1843
1860
  const PLUGIN_NAME = "api-code-gen";
1844
1861
  const pluginLogger = (0, _moccona_logger.createScopedLogger)("api-code-gen");
1845
1862
  /**
1863
+ * Find the nearest tsconfig.json or jsconfig.json by searching upward.
1864
+ * Bounded by process.cwd() — the Vite project root — to avoid picking up
1865
+ * unrelated configs outside the project.
1866
+ */
1867
+ async function findNearestTsConfig(filePath) {
1868
+ let dir = node_path.default.dirname(node_path.default.resolve(filePath));
1869
+ const rootDir = process.cwd();
1870
+ const fsRoot = node_path.default.parse(dir).root;
1871
+ while (true) {
1872
+ for (const name of ["tsconfig.json", "jsconfig.json"]) {
1873
+ const configPath = node_path.default.join(dir, name);
1874
+ if (await fs_extra.default.pathExists(configPath)) return configPath;
1875
+ }
1876
+ if (dir === rootDir || dir === fsRoot) break;
1877
+ dir = node_path.default.dirname(dir);
1878
+ }
1879
+ return null;
1880
+ }
1881
+ /**
1846
1882
  * Run TypeScript type checking on generated file
1847
1883
  */
1848
1884
  async function runTypeCheck(filePath) {
1849
1885
  const { execaCommand } = await import("execa");
1850
1886
  const errors = [];
1887
+ const resolvedPath = node_path.default.resolve(filePath);
1888
+ const tsconfigPath = await findNearestTsConfig(resolvedPath);
1889
+ if (!tsconfigPath) {
1890
+ try {
1891
+ await execaCommand(`npx tsc ${resolvedPath} --noEmit`, { shell: true });
1892
+ } catch (error) {
1893
+ if (error instanceof Error) errors.push(error.message);
1894
+ }
1895
+ return errors;
1896
+ }
1897
+ const outputDir = node_path.default.dirname(resolvedPath);
1898
+ const tempConfigName = `.${node_path.default.basename(resolvedPath).replace(/\.ts$/i, "")}.${Date.now()}.apicodegen.json`;
1899
+ const tempConfigPath = node_path.default.join(outputDir, tempConfigName);
1900
+ const tempConfig = {
1901
+ extends: node_path.default.relative(outputDir, tsconfigPath),
1902
+ compilerOptions: { noEmit: true },
1903
+ include: [node_path.default.basename(resolvedPath)]
1904
+ };
1851
1905
  try {
1852
- await execaCommand(`npx tsc ${filePath} --noEmit`, { shell: true });
1906
+ await fs_extra.default.writeJson(tempConfigPath, tempConfig);
1907
+ await execaCommand(`npx tsc --project "${tempConfigPath}" --noEmit`, { shell: true });
1853
1908
  } catch (error) {
1854
1909
  if (error instanceof Error) errors.push(error.message);
1910
+ } finally {
1911
+ try {
1912
+ await fs_extra.default.remove(tempConfigPath);
1913
+ } catch {}
1855
1914
  }
1856
1915
  return errors;
1857
1916
  }