@blimu/codegen 0.2.0 → 0.2.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.
@@ -4,7 +4,7 @@ export type ClientOption = FetchClientConfig & {
4
4
  {{~#each IR.securitySchemes~}}
5
5
  {{~#if (eq this.type "http")~}}
6
6
  {{~#if (eq this.scheme "bearer")~}}
7
- {{camel this.key}}?: string;
7
+ {{camel this.key}}?: string | (() => string | undefined | Promise<string | undefined>);
8
8
  {{~else if (eq this.scheme "basic")~}}
9
9
  {{camel this.key}}?: { username: string; password: string };
10
10
  {{~/if~}}
@@ -12,8 +12,6 @@ export type ClientOption = FetchClientConfig & {
12
12
  {{camel this.key}}?: string;
13
13
  {{~/if~}}
14
14
  {{~/each~}}
15
- // Generic accessToken support (alias for bearer auth)
16
- accessToken?: string | (() => string | undefined | Promise<string | undefined>);
17
15
  };
18
16
 
19
17
  // Re-export FetchError for backward compatibility
@@ -23,35 +21,34 @@ export class CoreClient extends FetchClient {
23
21
  constructor(cfg: ClientOption = {}) {
24
22
  // Build auth strategies from OpenAPI security schemes
25
23
  const authStrategies: AuthStrategy[] = [];
24
+
25
+ // Extract auth and security scheme properties to avoid passing them to FetchClient
26
+ const {
27
+ auth: _existingAuth{{~#each IR.securitySchemes~}},
28
+ {{camel this.key}}{{~/each~}},
29
+ ...restCfg
30
+ } = cfg;
26
31
 
27
32
  {{~#each IR.securitySchemes~}}
28
33
  {{~#if (eq this.type "http")~}}
29
34
  {{~#if (eq this.scheme "bearer")~}}
30
35
  if (cfg.{{camel this.key}}) {
31
36
  const {{camel this.key}}Value = cfg.{{camel this.key}};
32
- authStrategies.push({
33
- type: "bearer",
34
- token: () => {{camel this.key}}Value,
35
- });
36
- }
37
- {{~/if~}}
38
- {{~/if~}}
39
- {{~/each~}}
40
- // Support accessToken as an alias for bearer auth (only if no bearer auth was already added)
41
- if (!authStrategies.some((s: any) => s.type === "bearer") && cfg.accessToken) {
42
- const accessTokenValue = cfg.accessToken;
43
- if (typeof accessTokenValue === "string") {
37
+ if (typeof {{camel this.key}}Value === "string") {
44
38
  authStrategies.push({
45
39
  type: "bearer",
46
- token: () => accessTokenValue,
40
+ token: () => {{camel this.key}}Value,
47
41
  });
48
- } else if (typeof accessTokenValue === "function") {
42
+ } else if (typeof {{camel this.key}}Value === "function") {
49
43
  authStrategies.push({
50
44
  type: "bearer",
51
- token: accessTokenValue as () => string | undefined | Promise<string | undefined>,
45
+ token: {{camel this.key}}Value as () => string | undefined | Promise<string | undefined>,
52
46
  });
53
47
  }
54
48
  }
49
+ {{~/if~}}
50
+ {{~/if~}}
51
+ {{~/each~}}
55
52
 
56
53
  {{~#each IR.securitySchemes~}}
57
54
  {{~#if (eq this.type "http")~}}
@@ -99,13 +96,6 @@ export class CoreClient extends FetchClient {
99
96
  {{~/if~}}
100
97
  {{~/each~}}
101
98
 
102
- // Extract accessToken, auth, and security scheme properties to avoid passing them to FetchClient
103
- const {
104
- accessToken,
105
- auth: _existingAuth{{~#each IR.securitySchemes~}},
106
- {{camel this.key}}{{~/each~}},
107
- ...restCfg
108
- } = cfg;
109
99
 
110
100
  // Build final auth config (merge existing with new strategies)
111
101
  const finalAuthStrategies = [
@@ -39,7 +39,7 @@
39
39
  }
40
40
  },
41
41
  "scripts": {
42
- "build": "tsup src/index.ts src/services/*.ts src/schema.ts src/schema.zod.ts src/client.ts src/utils.ts --format cjs,esm --dts --no-splitting",
42
+ "build": "tsup",
43
43
  "typecheck": "tsc -p tsconfig.json --noEmit",
44
44
  "lint": "eslint .",
45
45
  "format": "eslint --fix . && prettier --write .",
@@ -2,7 +2,6 @@
2
2
  // Use these schemas for runtime validation in forms, API requests, etc.
3
3
 
4
4
  import { z } from 'zod';
5
- import * as Schema from './schema';
6
5
 
7
6
  {{! Simple types: generate as regular Zod schema exports (not in namespace) }}
8
7
  {{#each IR.modelDefs}}
@@ -54,7 +53,7 @@ export const {{this.name}}Schema = z.object({
54
53
  /**
55
54
  * Zod schema for {{this.name}}
56
55
  */
57
- export const {{this.name}}Schema = Schema.{{this.schema.ref}}Schema;
56
+ export const {{this.name}}Schema = {{zodSchema this.schema}};
58
57
 
59
58
  {{~else if (eq this.schema.kind "oneOf")~}}
60
59
  /**
@@ -1,26 +1,27 @@
1
1
  {
2
- "rootDir": "./src",
3
2
  "compilerOptions": {
4
- "module": "commonjs",
5
- "moduleResolution": "node",
3
+ "rootDir": "./src",
4
+ "module": "ES2022",
5
+ "moduleResolution": "Bundler",
6
+ "target": "ES2022",
6
7
  "esModuleInterop": true,
7
8
  "isolatedModules": true,
8
9
  "declaration": true,
10
+ "declarationMap": true,
9
11
  "removeComments": true,
10
12
  "allowSyntheticDefaultImports": true,
11
- "target": "ES2023",
12
13
  "sourceMap": true,
13
14
  "outDir": "./dist",
14
15
  "baseUrl": "./src",
15
16
  "incremental": true,
16
17
  "tsBuildInfoFile": "./dist/tsconfig.tsbuildinfo",
17
18
  "skipLibCheck": true,
18
- "strictNullChecks": true,
19
19
  "forceConsistentCasingInFileNames": true,
20
- "noImplicitAny": false,
21
- "strictBindCallApply": false,
22
- "noFallthroughCasesInSwitch": false,
23
- "useDefineForClassFields": false
20
+ "strict": true,
21
+ "noFallthroughCasesInSwitch": true,
22
+ "noUnusedLocals": true,
23
+ "noUnusedParameters": true,
24
+ "useDefineForClassFields": true
24
25
  },
25
26
  "include": ["src/**/*"],
26
27
  "exclude": ["node_modules", "dist"]
@@ -0,0 +1,15 @@
1
+ import { defineConfig } from "tsup";
2
+
3
+ export default defineConfig({
4
+ entry: ["src/**/*.ts"],
5
+ format: ["cjs", "esm"],
6
+ dts: true,
7
+ splitting: false,
8
+ sourcemap: true,
9
+ clean: true,
10
+ outDir: "dist",
11
+ tsconfig: "./tsconfig.json",
12
+ // External dependencies should not be bundled
13
+ // This ensures proper type resolution and smaller bundle sizes
14
+ external: [],
15
+ });
package/dist/index.d.mts CHANGED
@@ -298,6 +298,7 @@ declare class TypeScriptGeneratorService implements Generator<TypeScriptClient>
298
298
  private generateZodSchema;
299
299
  private generatePackageJson;
300
300
  private generateTsConfig;
301
+ private generateTsupConfig;
301
302
  private generateReadme;
302
303
  private generatePrettierConfig;
303
304
  }
package/dist/index.d.ts CHANGED
@@ -298,6 +298,7 @@ declare class TypeScriptGeneratorService implements Generator<TypeScriptClient>
298
298
  private generateZodSchema;
299
299
  private generatePackageJson;
300
300
  private generateTsConfig;
301
+ private generateTsupConfig;
301
302
  private generateReadme;
302
303
  private generatePrettierConfig;
303
304
  }
package/dist/index.js CHANGED
@@ -1,7 +1,22 @@
1
- "use strict";var Je=Object.create;var W=Object.defineProperty;var Ke=Object.getOwnPropertyDescriptor;var Qe=Object.getOwnPropertyNames;var Ye=Object.getPrototypeOf,Xe=Object.prototype.hasOwnProperty;var f=(o,e)=>W(o,"name",{value:e,configurable:!0});var et=(o,e)=>{for(var t in e)W(o,t,{get:e[t],enumerable:!0})},me=(o,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Qe(e))!Xe.call(o,s)&&s!==t&&W(o,s,{get:()=>e[s],enumerable:!(r=Ke(e,s))||r.enumerable});return o};var O=(o,e,t)=>(t=o!=null?Je(Ye(o)):{},me(e||!o||!o.__esModule?W(t,"default",{value:o,enumerable:!0}):t,o)),tt=o=>me(W({},"__esModule",{value:!0}),o);var yt={};et(yt,{ClientSchema:()=>ge,ConfigModule:()=>D,ConfigSchema:()=>G,ConfigService:()=>v,GeneratorModule:()=>J,GeneratorService:()=>R,IRSchemaKind:()=>l,OpenApiModule:()=>B,OpenApiService:()=>x,PredefinedTypeSchema:()=>de,TYPESCRIPT_TEMPLATE_NAMES:()=>oe,TypeScriptClientSchema:()=>he,defineConfig:()=>st,generate:()=>ht,loadConfig:()=>gt,loadMjsConfig:()=>z});module.exports=tt(yt);var m=require("zod"),de=m.z.object({type:m.z.string().min(1,"Type name is required"),package:m.z.string().min(1,"Package name is required"),importPath:m.z.string().optional()}),oe=["client.ts.hbs","index.ts.hbs","package.json.hbs","README.md.hbs","schema.ts.hbs","schema.zod.ts.hbs","service.ts.hbs","tsconfig.json.hbs","utils.ts.hbs"],rt=m.z.object({type:m.z.string().min(1,"Type is required"),outDir:m.z.string().min(1,"OutDir is required"),name:m.z.string().min(1,"Name is required"),includeTags:m.z.array(m.z.string()).optional(),excludeTags:m.z.array(m.z.string()).optional(),operationIdParser:m.z.custom().optional(),preCommand:m.z.array(m.z.string()).optional(),postCommand:m.z.array(m.z.string()).optional(),defaultBaseURL:m.z.string().optional(),exclude:m.z.array(m.z.string()).optional()}),he=rt.extend({type:m.z.literal("typescript"),packageName:m.z.string().min(1,"PackageName is required"),moduleName:m.z.string().optional(),includeQueryKeys:m.z.boolean().optional(),predefinedTypes:m.z.array(de).optional(),dependencies:m.z.record(m.z.string(),m.z.string()).optional(),devDependencies:m.z.record(m.z.string(),m.z.string()).optional(),formatCode:m.z.boolean().optional(),templates:m.z.record(m.z.string(),m.z.string()).refine(o=>Object.keys(o).every(e=>oe.includes(e)),{message:`Template names must be one of: ${oe.join(", ")}`}).optional()}),ge=m.z.discriminatedUnion("type",[he]),G=m.z.object({spec:m.z.string().min(1,"Spec is required"),name:m.z.string().optional(),clients:m.z.array(ge).min(1,"At least one client is required")});var X=require("@nestjs/common"),be=O(require("fs")),w=O(require("path"));var ye=require("url"),Y=O(require("path"));async function z(o){try{let e=Y.isAbsolute(o)?o:Y.resolve(o),r=await import((0,ye.pathToFileURL)(e).href),s=r.default||r;if(!s)throw new Error(`Config file must export a default export or named export: ${o}`);return G.parse(s)}catch(e){throw e instanceof Error?new Error(`Failed to load MJS config from ${o}: ${e.message}`):e}}f(z,"loadMjsConfig");function nt(o,e,t,r){var s=arguments.length,n=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,e,t,r);else for(var i=o.length-1;i>=0;i--)(a=o[i])&&(n=(s<3?a(n):s>3?a(e,t,n):a(e,t))||n);return s>3&&n&&Object.defineProperty(e,t,n),n}f(nt,"_ts_decorate");var v=class o{static{f(this,"ConfigService")}logger=new X.Logger(o.name);DEFAULT_CONFIG_FILE="chunkflow-codegen.config.mjs";async findDefaultConfig(){let e=process.cwd(),t=w.parse(e).root;for(;e!==t;){let r=w.join(e,this.DEFAULT_CONFIG_FILE);try{return await be.promises.access(r),r}catch{}e=w.dirname(e)}return null}async load(e){try{let t=await z(e);return this.normalizePaths(t,e)}catch(t){throw t instanceof Error?new Error(`Failed to load config from ${e}: ${t.message}`):t}}normalizePaths(e,t){let r=w.dirname(w.resolve(t)),s=e.spec;this.isUrl(s)||w.isAbsolute(s)||(s=w.resolve(r,s));let n=e.clients.map(a=>{let i=a.outDir;return w.isAbsolute(i)||(i=w.resolve(r,i)),{...a,outDir:i}});return{...e,spec:s,clients:n}}isUrl(e){try{let t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}getPreCommand(e){return e.preCommand||[]}getPostCommand(e){return e.postCommand||[]}shouldExcludeFile(e,t){if(!e.exclude||e.exclude.length===0)return!1;let r;try{r=w.relative(e.outDir,t)}catch{return!1}r=w.posix.normalize(r),r==="."&&(r="");for(let s of e.exclude){let n=w.posix.normalize(s);if(r===n||n!==""&&r.startsWith(n+"/"))return!0}return!1}};v=nt([(0,X.Injectable)()],v);var Se=require("@nestjs/common");function ot(o,e,t,r){var s=arguments.length,n=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,e,t,r);else for(var i=o.length-1;i>=0;i--)(a=o[i])&&(n=(s<3?a(n):s>3?a(e,t,n):a(e,t))||n);return s>3&&n&&Object.defineProperty(e,t,n),n}f(ot,"_ts_decorate");var D=class{static{f(this,"ConfigModule")}};D=ot([(0,Se.Module)({providers:[v],exports:[v]})],D);function st(o){return G.parse(o)}f(st,"defineConfig");var l=(function(o){return o.Unknown="unknown",o.String="string",o.Number="number",o.Integer="integer",o.Boolean="boolean",o.Null="null",o.Array="array",o.Object="object",o.Enum="enum",o.Ref="ref",o.OneOf="oneOf",o.AnyOf="anyOf",o.AllOf="allOf",o.Not="not",o})({});var te=require("@nestjs/common");var Pe=require("@nestjs/common");var ve=require("@nestjs/common");function we(o){let e=o.openapi;return typeof e!="string"?"unknown":e.startsWith("3.1")?"3.1":e.startsWith("3.0")?"3.0":"unknown"}f(we,"detectOpenAPIVersion");function Te(o){return o==="3.0"||o==="3.1"}f(Te,"isSupportedVersion");function se(o,e){if(!(!e||typeof e!="object")){if("$ref"in e&&e.$ref){let t=e.$ref;if(t.startsWith("#/components/schemas/")){let r=t.replace("#/components/schemas/","");if(o.components?.schemas?.[r]){let s=o.components.schemas[r];return"$ref"in s?se(o,s):s}}return}return e}}f(se,"getSchemaFromRef");function Oe(o){return o?"nullable"in o&&o.nullable===!0?!0:"type"in o&&Array.isArray(o.type)?o.type.includes("null"):!1:!1}f(Oe,"isSchemaNullable");function ae(o){if(!(!o||!("type"in o)))return o.type}f(ae,"getSchemaType");function at(o,e,t,r){var s=arguments.length,n=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,e,t,r);else for(var i=o.length-1;i>=0;i--)(a=o[i])&&(n=(s<3?a(n):s>3?a(e,t,n):a(e,t))||n);return s>3&&n&&Object.defineProperty(e,t,n),n}f(at,"_ts_decorate");var P=class{static{f(this,"SchemaConverterService")}schemaRefToIR(e,t){if(!t)return{kind:l.Unknown,nullable:!1};if("$ref"in t&&t.$ref){let c=t.$ref;if(c.startsWith("#/components/schemas/")){let u=c.replace("#/components/schemas/","");return{kind:l.Ref,ref:u,nullable:!1}}let p=c.split("/");if(p.length>0){let u=p[p.length-1];if(u)return{kind:l.Ref,ref:u,nullable:!1}}return{kind:l.Unknown,nullable:!1}}let r=se(e,t);if(!r)return{kind:l.Unknown,nullable:!1};let s=Oe(r),n;if(r.discriminator&&(n={propertyName:r.discriminator.propertyName,mapping:r.discriminator.mapping}),r.oneOf&&r.oneOf.length>0){let c=r.oneOf.map(p=>this.schemaRefToIR(e,p));return{kind:l.OneOf,oneOf:c,nullable:s,discriminator:n}}if(r.anyOf&&r.anyOf.length>0){let c=r.anyOf.map(p=>this.schemaRefToIR(e,p));return{kind:l.AnyOf,anyOf:c,nullable:s,discriminator:n}}if(r.allOf&&r.allOf.length>0){let c=r.allOf.map(p=>this.schemaRefToIR(e,p));return{kind:l.AllOf,allOf:c,nullable:s,discriminator:n}}if(r.not){let c=this.schemaRefToIR(e,r.not);return{kind:l.Not,not:c,nullable:s,discriminator:n}}if(r.enum&&r.enum.length>0){let c=r.enum.map(u=>String(u)),p=this.inferEnumBaseKind(r);return{kind:l.Enum,enumValues:c,enumRaw:r.enum,enumBase:p,nullable:s,discriminator:n}}let a=ae(r),i=Array.isArray(a)?a.filter(c=>c!=="null")[0]:a;if(i)switch(i){case"string":return{kind:l.String,nullable:s,format:r.format,discriminator:n};case"integer":return{kind:l.Integer,nullable:s,discriminator:n};case"number":return{kind:l.Number,nullable:s,discriminator:n};case"boolean":return{kind:l.Boolean,nullable:s,discriminator:n};case"array":let c=r,p=this.schemaRefToIR(e,c.items);return{kind:l.Array,items:p,nullable:s,discriminator:n};case"object":let u=[];if(r.properties){let h=Object.keys(r.properties).sort();for(let b of h){let q=r.properties[b],F=this.schemaRefToIR(e,q),_=r.required?.includes(b)||!1;u.push({name:b,type:F,required:_,annotations:this.extractAnnotations(q)})}}let y;return r.additionalProperties&&typeof r.additionalProperties=="object"&&(y=this.schemaRefToIR(e,r.additionalProperties)),{kind:l.Object,properties:u,additionalProperties:y,nullable:s,discriminator:n}}return{kind:l.Unknown,nullable:s,discriminator:n}}extractAnnotations(e){if(!e||"$ref"in e)return{};let t=e;return{title:t.title,description:t.description,deprecated:t.deprecated,readOnly:t.readOnly,writeOnly:t.writeOnly,default:t.default,examples:t.example?Array.isArray(t.example)?t.example:[t.example]:void 0}}inferEnumBaseKind(e){let t=ae(e);if(t){let r=Array.isArray(t)?t.filter(s=>s!=="null")[0]:t;if(r)switch(r){case"string":return l.String;case"integer":return l.Integer;case"number":return l.Number;case"boolean":return l.Boolean}}if(e.enum&&e.enum.length>0){let r=e.enum[0];if(typeof r=="string")return l.String;if(typeof r=="number")return Number.isInteger(r)?l.Integer:l.Number;if(typeof r=="boolean")return l.Boolean}return l.Unknown}};P=at([(0,ve.Injectable)()],P);function k(o){if(o=o.trim(),o==="")return"";let e=o.split(/[^A-Za-z0-9]+/).filter(r=>r!==""),t=[];for(let r of e){let s=ce(r);t.push(...s)}return t.filter(r=>r!=="").map(r=>r.charAt(0).toUpperCase()+r.slice(1).toLowerCase()).join("")}f(k,"toPascalCase");function $(o){let e=k(o);return e===""?"":e.charAt(0).toLowerCase()+e.slice(1)}f($,"toCamelCase");function L(o){if(o=o.trim(),o==="")return"";let e=o.split(/[^A-Za-z0-9]+/).filter(r=>r!==""),t=[];for(let r of e){let s=ce(r);t.push(...s)}return t.filter(r=>r!=="").map(r=>r.toLowerCase()).join("_")}f(L,"toSnakeCase");function ke(o){if(o=o.trim(),o==="")return"";let e=o.split(/[^A-Za-z0-9]+/).filter(r=>r!==""),t=[];for(let r of e){let s=ce(r);t.push(...s)}return t.filter(r=>r!=="").map(r=>r.toLowerCase()).join("-")}f(ke,"toKebabCase");function ce(o){if(o==="")return[];let e=[],t="",r=Array.from(o);for(let s=0;s<r.length;s++){let n=r[s],a=!1;s>0&&ie(n)&&(ie(r[s-1])?s<r.length-1&&!ie(r[s+1])&&(a=!0):a=!0),a&&t.length>0&&(e.push(t),t=""),t+=n}return t.length>0&&e.push(t),e}f(ce,"splitCamelCase");function ie(o){return o>="A"&&o<="Z"}f(ie,"isUppercase");function it(o,e,t,r){var s=arguments.length,n=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,e,t,r);else for(var i=o.length-1;i>=0;i--)(a=o[i])&&(n=(s<3?a(n):s>3?a(e,t,n):a(e,t))||n);return s>3&&n&&Object.defineProperty(e,t,n),n}f(it,"_ts_decorate");function xe(o,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,e)}f(xe,"_ts_metadata");var j=class{static{f(this,"IrBuilderService")}schemaConverter;constructor(e){this.schemaConverter=e}buildIR(e){let t=this.collectTags(e),r=this.collectSecuritySchemes(e),s=this.buildStructuredModels(e),n={};for(let i of t)n[i]=!0;let a=this.buildIRFromDoc(e,n);return a.securitySchemes=r,a.modelDefs=[...s,...a.modelDefs],a.openApiDocument=e,a}filterIR(e,t){let r=this.compileTagFilters(t.includeTags||[]),s=this.compileTagFilters(t.excludeTags||[]),n=[];for(let i of e.services){let c=[];for(let p of i.operations)this.shouldIncludeOperation(p.originalTags,r,s)&&c.push(p);c.length>0&&n.push({...i,operations:c})}let a={services:n,models:e.models,securitySchemes:e.securitySchemes,modelDefs:e.modelDefs,openApiDocument:e.openApiDocument};return a.modelDefs=this.filterUnusedModelDefs(a,e.modelDefs),a}detectStreamingContentType(e){let t=e.toLowerCase().split(";")[0].trim();return t==="text/event-stream"?{isStreaming:!0,format:"sse"}:t==="application/x-ndjson"||t==="application/x-jsonlines"||t==="application/jsonl"?{isStreaming:!0,format:"ndjson"}:t.includes("stream")||t.includes("chunked")?{isStreaming:!0,format:"chunked"}:{isStreaming:!1}}collectTags(e){let t=new Set;if(t.add("misc"),e.paths)for(let[r,s]of Object.entries(e.paths)){if(!s)continue;let n=[s.get,s.post,s.put,s.patch,s.delete,s.options,s.head,s.trace];for(let a of n)if(!(!a||!a.tags))for(let i of a.tags)t.add(i)}return Array.from(t).sort()}compileTagFilters(e){return e.map(t=>{try{return new RegExp(t)}catch(r){throw new Error(`Invalid tag filter pattern "${t}": ${r instanceof Error?r.message:String(r)}`)}})}shouldIncludeOperation(e,t,r){let s=t.length===0;if(t.length>0)for(let n of e){for(let a of t)if(a.test(n)){s=!0;break}if(s)break}if(!s)return!1;if(r.length>0){for(let n of e)for(let a of r)if(a.test(n))return!1}return!0}buildIRFromDoc(e,t){let r={};r.misc={tag:"misc",operations:[]};let s=[],n=new Set;if(e.components?.schemas)for(let c of Object.keys(e.components.schemas))n.add(c);let a=f((c,p,u,y)=>{r[c]||(r[c]={tag:c,operations:[]});let h=p.operationId||"",{pathParams:b,queryParams:q}=this.collectParams(e,p),{requestBody:F,extractedTypes:_}=this.extractRequestBodyWithTypes(e,p,c,h,u,n);s.push(..._);let{response:E,extractedTypes:U}=this.extractResponseWithTypes(e,p,c,h,u,n);s.push(...U);let K=p.tags&&p.tags.length>0?[...p.tags]:["misc"];r[c].operations.push({operationID:h,method:u,path:y,tag:c,originalTags:K,summary:p.summary||"",description:p.description||"",deprecated:p.deprecated||!1,pathParams:b,queryParams:q,requestBody:F,response:E})},"addOp");if(e.paths)for(let[c,p]of Object.entries(e.paths)){if(!p)continue;let u=[{op:p.get,method:"GET"},{op:p.post,method:"POST"},{op:p.put,method:"PUT"},{op:p.patch,method:"PATCH"},{op:p.delete,method:"DELETE"},{op:p.options,method:"OPTIONS"},{op:p.head,method:"HEAD"},{op:p.trace,method:"TRACE"}];for(let{op:y,method:h}of u){if(!y)continue;let b=this.firstAllowedTag(y.tags||[],t);b&&a(b,y,h,c)}}let i=Object.values(r);for(let c of i)c.operations.sort((p,u)=>p.path===u.path?p.method.localeCompare(u.method):p.path.localeCompare(u.path));return i.sort((c,p)=>c.tag.localeCompare(p.tag)),{services:i,models:[],securitySchemes:[],modelDefs:s}}deriveMethodName(e,t,r){if(e){let n=e.indexOf("Controller_"),a=n>=0?e.substring(n+11):e;return $(a)}let s=r.includes("{")&&r.includes("}");switch(t){case"GET":return s?"get":"list";case"POST":return"create";case"PUT":case"PATCH":return"update";case"DELETE":return"delete";default:return t.toLowerCase()}}firstAllowedTag(e,t){for(let r of e)if(t[r])return r;return e.length===0&&t.misc?"misc":""}collectSecuritySchemes(e){if(!e.components?.securitySchemes)return[];let t=Object.keys(e.components.securitySchemes).sort(),r=[];for(let s of t){let n=e.components.securitySchemes[s];if(!n||"$ref"in n)continue;let a={key:s,type:n.type};switch(n.type){case"http":a.scheme=n.scheme,a.bearerFormat=n.bearerFormat;break;case"apiKey":a.in=n.in,a.name=n.name;break;case"oauth2":case"openIdConnect":break}r.push(a)}return r}collectParams(e,t){let r=[],s=[];if(t.parameters)for(let n of t.parameters){if(!n||"$ref"in n)continue;let a=n,i=this.schemaConverter.schemaRefToIR(e,a.schema),c={name:a.name,required:a.required||!1,schema:i,description:a.description||""};a.in==="path"?r.push(c):a.in==="query"&&s.push(c)}return r.sort((n,a)=>n.name.localeCompare(a.name)),s.sort((n,a)=>n.name.localeCompare(a.name)),{pathParams:r,queryParams:s}}findMatchingComponentSchema(e,t){if(!t||!e.components?.schemas)return null;if("$ref"in t&&t.$ref){let s=t.$ref;if(s.startsWith("#/components/schemas/")){let n=s.replace("#/components/schemas/","");if(e.components.schemas[n])return n}}let r=this.schemaConverter.schemaRefToIR(e,t);for(let[s,n]of Object.entries(e.components.schemas)){let a=this.schemaConverter.schemaRefToIR(e,n);if(this.compareSchemas(r,a))return s}return null}compareSchemas(e,t){if(e.kind!==t.kind)return!1;if(e.kind===l.Ref&&t.kind===l.Ref)return e.ref===t.ref;if(e.kind===l.Object&&t.kind===l.Object){let r=e.properties||[],s=t.properties||[];if(r.length!==s.length)return!1;let n=new Map(r.map(i=>[i.name,{type:i.type,required:i.required}])),a=new Map(s.map(i=>[i.name,{type:i.type,required:i.required}]));if(n.size!==a.size)return!1;for(let[i,c]of n){let p=a.get(i);if(!p||c.required!==p.required||!this.compareSchemas(c.type,p.type))return!1}return!0}return e.kind===l.Array&&t.kind===l.Array?!e.items||!t.items?e.items===t.items:this.compareSchemas(e.items,t.items):!0}extractModelNameFromSchema(e){return e.kind===l.Ref&&e.ref?e.ref:e.kind===l.Array&&e.items&&e.items.kind===l.Ref&&e.items.ref?e.items.ref:null}generateTypeName(e,t,r,s,n,a){let i=this.extractModelNameFromSchema(e);if(i)return i;let c=this.deriveMethodName(r,s,n);return`${k(t)}${k(c)}${a}`}extractRequestBodyWithTypes(e,t,r,s,n,a){let i=[];if(!t.requestBody||"$ref"in t.requestBody)return{requestBody:null,extractedTypes:[]};let c=t.requestBody;if(c.content?.["application/json"]){let u=c.content["application/json"],y=this.schemaConverter.schemaRefToIR(e,u.schema),h=this.findMatchingComponentSchema(e,u.schema);if(h)return{requestBody:{contentType:"application/json",typeTS:"",schema:{kind:l.Ref,ref:h,nullable:!1},required:c.required||!1},extractedTypes:[]};let b=this.generateTypeName(y,r,s,n,t.path,"RequestBody");return y.kind===l.Object&&!a.has(b)?(a.add(b),i.push({name:b,schema:y,annotations:this.schemaConverter.extractAnnotations(u.schema)}),{requestBody:{contentType:"application/json",typeTS:"",schema:{kind:l.Ref,ref:b,nullable:!1},required:c.required||!1},extractedTypes:i}):{requestBody:{contentType:"application/json",typeTS:"",schema:y,required:c.required||!1},extractedTypes:[]}}return{requestBody:this.extractRequestBody(e,t),extractedTypes:[]}}extractRequestBody(e,t){if(!t.requestBody||"$ref"in t.requestBody)return null;let r=t.requestBody;if(r.content?.["application/json"]){let s=r.content["application/json"];return{contentType:"application/json",typeTS:"",schema:this.schemaConverter.schemaRefToIR(e,s.schema),required:r.required||!1}}if(r.content?.["application/x-www-form-urlencoded"]){let s=r.content["application/x-www-form-urlencoded"];return{contentType:"application/x-www-form-urlencoded",typeTS:"",schema:this.schemaConverter.schemaRefToIR(e,s.schema),required:r.required||!1}}if(r.content?.["multipart/form-data"])return{contentType:"multipart/form-data",typeTS:"",schema:{kind:"unknown",nullable:!1},required:r.required||!1};if(r.content){let s=Object.keys(r.content)[0],n=r.content[s];return{contentType:s,typeTS:"",schema:this.schemaConverter.schemaRefToIR(e,n.schema),required:r.required||!1}}return null}extractResponseWithTypes(e,t,r,s,n,a){let i=[];if(!t.responses)return{response:{typeTS:"unknown",schema:{kind:l.Unknown,nullable:!1},description:"",isStreaming:!1,contentType:""},extractedTypes:[]};let c=["200","201"];for(let u of c){let y=t.responses[u];if(y&&!("$ref"in y)){let h=y;if(h.content){for(let[E,U]of Object.entries(h.content)){let K=this.detectStreamingContentType(E),V=this.schemaConverter.schemaRefToIR(e,U.schema);if(K.isStreaming)return{response:{typeTS:"",schema:V,description:h.description||"",isStreaming:!0,contentType:E,streamingFormat:K.format},extractedTypes:[]};if(E==="application/json"){let ue=this.findMatchingComponentSchema(e,U.schema);if(ue)return{response:{typeTS:"",schema:{kind:l.Ref,ref:ue,nullable:!1},description:h.description||"",isStreaming:!1,contentType:E},extractedTypes:[]};let Q=this.generateTypeName(V,r,s,n,t.path,"Response");return V.kind===l.Object&&!a.has(Q)?(a.add(Q),i.push({name:Q,schema:V,annotations:this.schemaConverter.extractAnnotations(U.schema)}),{response:{typeTS:"",schema:{kind:l.Ref,ref:Q,nullable:!1},description:h.description||"",isStreaming:!1,contentType:E},extractedTypes:i}):{response:{typeTS:"",schema:V,description:h.description||"",isStreaming:!1,contentType:E},extractedTypes:[]}}}let b=Object.keys(h.content)[0],q=h.content[b],F=this.schemaConverter.schemaRefToIR(e,q.schema),_=this.detectStreamingContentType(b);return{response:{typeTS:"",schema:F,description:h.description||"",isStreaming:_.isStreaming,contentType:b,streamingFormat:_.format},extractedTypes:[]}}return{response:{typeTS:"void",schema:{kind:l.Unknown,nullable:!1},description:h.description||"",isStreaming:!1,contentType:""},extractedTypes:[]}}}return{response:this.extractResponse(e,t),extractedTypes:[]}}extractResponse(e,t){if(!t.responses)return{typeTS:"unknown",schema:{kind:l.Unknown,nullable:!1},description:"",isStreaming:!1,contentType:""};let r=["200","201"];for(let s of r){let n=t.responses[s];if(n&&!("$ref"in n)){let a=n;if(a.content){for(let[u,y]of Object.entries(a.content)){let h=this.detectStreamingContentType(u);if(h.isStreaming)return{typeTS:"",schema:this.schemaConverter.schemaRefToIR(e,y.schema),description:a.description||"",isStreaming:!0,contentType:u,streamingFormat:h.format}}if(a.content["application/json"]){let u=a.content["application/json"];return{typeTS:"",schema:this.schemaConverter.schemaRefToIR(e,u.schema),description:a.description||"",isStreaming:!1,contentType:"application/json"}}let i=Object.keys(a.content)[0],c=a.content[i],p=this.detectStreamingContentType(i);return{typeTS:"",schema:this.schemaConverter.schemaRefToIR(e,c.schema),description:a.description||"",isStreaming:p.isStreaming,contentType:i,streamingFormat:p.format}}return{typeTS:"void",schema:{kind:l.Unknown,nullable:!1},description:a.description||"",isStreaming:!1,contentType:""}}}for(let[s,n]of Object.entries(t.responses))if(s.length===3&&s[0]==="2"&&n&&!("$ref"in n)){let a=n;if(s==="204")return{typeTS:"void",schema:{kind:l.Unknown,nullable:!1},description:a.description||"",isStreaming:!1,contentType:""};if(a.content){for(let[u,y]of Object.entries(a.content)){let h=this.detectStreamingContentType(u);if(h.isStreaming)return{typeTS:"",schema:this.schemaConverter.schemaRefToIR(e,y.schema),description:a.description||"",isStreaming:!0,contentType:u,streamingFormat:h.format}}if(a.content["application/json"]){let u=a.content["application/json"];return{typeTS:"",schema:this.schemaConverter.schemaRefToIR(e,u.schema),description:a.description||"",isStreaming:!1,contentType:"application/json"}}let i=Object.keys(a.content)[0],c=a.content[i],p=this.detectStreamingContentType(i);return{typeTS:"",schema:this.schemaConverter.schemaRefToIR(e,c.schema),description:a.description||"",isStreaming:p.isStreaming,contentType:i,streamingFormat:p.format}}}return{typeTS:"unknown",schema:{kind:l.Unknown,nullable:!1},description:"",isStreaming:!1,contentType:""}}buildStructuredModels(e){let t=[];if(!e.components?.schemas)return t;let r=Object.keys(e.components.schemas).sort(),s=new Set;for(let n of r)s.add(n);for(let n of r){let a=e.components.schemas[n],i=this.schemaConverter.schemaRefToIR(e,a);t.push({name:n,schema:i,annotations:this.schemaConverter.extractAnnotations(a)})}return t}filterUnusedModelDefs(e,t){let r=new Map;for(let i of t)r.set(i.name,i);let s=new Set,n=new Set,a=f(i=>{if(i.kind==="ref"&&i.ref){let c=i.ref;if(s.add(c),!n.has(c)){n.add(c);let p=r.get(c);p&&a(p.schema)}}if(i.items&&a(i.items),i.additionalProperties&&a(i.additionalProperties),i.oneOf)for(let c of i.oneOf)a(c);if(i.anyOf)for(let c of i.anyOf)a(c);if(i.allOf)for(let c of i.allOf)a(c);if(i.not&&a(i.not),i.properties)for(let c of i.properties)a(c.type)},"collectRefs");for(let i of e.services)for(let c of i.operations){for(let p of c.pathParams)a(p.schema);for(let p of c.queryParams)a(p.schema);c.requestBody&&a(c.requestBody.schema),a(c.response.schema)}return t.filter(i=>s.has(i.name))}};j=it([(0,Pe.Injectable)(),xe("design:type",Function),xe("design:paramtypes",[typeof P>"u"?Object:P])],j);var ee=require("@nestjs/common"),I=O(require("@apidevtools/swagger-parser")),fe=O(require("fs")),le=O(require("path"));function ct(o,e,t,r){var s=arguments.length,n=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,e,t,r);else for(var i=o.length-1;i>=0;i--)(a=o[i])&&(n=(s<3?a(n):s>3?a(e,t,n):a(e,t))||n);return s>3&&n&&Object.defineProperty(e,t,n),n}f(ct,"_ts_decorate");var x=class o{static{f(this,"OpenApiService")}logger=new ee.Logger(o.name);async loadDocument(e){try{let t=null;try{t=new URL(e)}catch{}let r;if(t&&(t.protocol==="http:"||t.protocol==="https:")){this.logger.debug(`Loading OpenAPI spec from URL: ${e}`);let n=await fetch(e,{signal:AbortSignal.timeout(1e4)});if(!n.ok)throw new Error(`Failed to fetch OpenAPI spec: HTTP ${n.status} ${n.statusText}`);let a=await n.text(),i;try{i=JSON.parse(a)}catch{throw new Error("OpenAPI spec is not valid JSON")}try{let c=await I.default.parse(i);r=await I.default.bundle(c)}catch(c){this.logger.debug(`Bundle failed: ${c instanceof Error?c.message:String(c)}`),this.logger.debug("Attempting dereference directly");try{let p=await I.default.parse(i);r=await I.default.dereference(p)}catch(p){throw p}}}else{let n=le.resolve(e);if(!fe.existsSync(n))throw new Error(`OpenAPI spec file not found: ${n}`);this.logger.debug(`Loading OpenAPI spec from file: ${n}`);try{r=await I.default.bundle(n)}catch(a){this.logger.debug(`Bundle failed: ${a instanceof Error?a.message:String(a)}`),this.logger.debug("Attempting dereference directly"),r=await I.default.dereference(n)}}let s=we(r);if(!Te(s))throw new Error(`Unsupported OpenAPI version: ${r.openapi}. Only versions 3.0.x and 3.1.0 are supported.`);return this.logger.log(`Detected OpenAPI version: ${s} (${r.openapi})`),r}catch(t){throw t instanceof Error?new Error(`Failed to load OpenAPI document from ${e}: ${t.message}`):t}}async validateDocument(e){try{let t=null;try{t=new URL(e)}catch{}if(t&&(t.protocol==="http:"||t.protocol==="https:"))await I.default.validate(e);else{let r=le.resolve(e);if(!fe.existsSync(r))throw new Error(`OpenAPI spec file not found: ${r}`);await I.default.validate(r)}}catch(t){throw t instanceof Error?new Error(`Invalid OpenAPI document: ${t.message}`):t}}};x=ct([(0,ee.Injectable)()],x);function ft(o,e,t,r){var s=arguments.length,n=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,e,t,r);else for(var i=o.length-1;i>=0;i--)(a=o[i])&&(n=(s<3?a(n):s>3?a(e,t,n):a(e,t))||n);return s>3&&n&&Object.defineProperty(e,t,n),n}f(ft,"_ts_decorate");function je(o,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,e)}f(je,"_ts_metadata");var R=class o{static{f(this,"GeneratorService")}irBuilder;openApiService;logger=new te.Logger(o.name);generators=new Map;constructor(e,t){this.irBuilder=e,this.openApiService=t}register(e){this.generators.set(e.getType(),e),this.logger.debug(`Registered generator: ${e.getType()}`)}getGenerator(e){return this.generators.get(e)}getAvailableTypes(){return Array.from(this.generators.keys())}async generate(e,t){let r=this.getGenerator(t.type);if(!r)throw new Error(`Unsupported client type: ${t.type}`);let s=await this.openApiService.loadDocument(e),n=this.irBuilder.buildIR(s),a=this.irBuilder.filterIR(n,t);await r.generate(t,a)}};R=ft([(0,te.Injectable)(),je("design:type",Function),je("design:paramtypes",[typeof j>"u"?Object:j,typeof x>"u"?Object:x])],R);var Le=require("@nestjs/common");var Re=require("@nestjs/common");function lt(o,e,t,r){var s=arguments.length,n=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,e,t,r);else for(var i=o.length-1;i>=0;i--)(a=o[i])&&(n=(s<3?a(n):s>3?a(e,t,n):a(e,t))||n);return s>3&&n&&Object.defineProperty(e,t,n),n}f(lt,"_ts_decorate");var B=class{static{f(this,"OpenApiModule")}};B=lt([(0,Re.Module)({providers:[x],exports:[x]})],B);var ne=require("@nestjs/common"),S=O(require("fs")),T=O(require("path")),d=O(require("handlebars"));var g=O(require("handlebars"));function Ce(){g.registerHelper("pascal",o=>k(o)),g.registerHelper("camel",o=>$(o)),g.registerHelper("kebab",o=>ke(o)),g.registerHelper("snake",o=>L(o)),g.registerHelper("serviceName",o=>k(o)+"Service"),g.registerHelper("serviceProp",o=>$(o)),g.registerHelper("fileBase",o=>L(o).toLowerCase()),g.registerHelper("eq",(o,e)=>o===e),g.registerHelper("ne",(o,e)=>o!==e),g.registerHelper("gt",(o,e)=>o>e),g.registerHelper("lt",(o,e)=>o<e),g.registerHelper("sub",(o,e)=>o-e),g.registerHelper("len",o=>Array.isArray(o)?o.length:0),g.registerHelper("or",function(...o){let e=o[o.length-1];return e&&e.fn?o.slice(0,-1).some(t=>t)?e.fn(this):e.inverse(this):o.slice(0,-1).some(t=>t)}),g.registerHelper("and",function(...o){let e=o[o.length-1];return e&&e.fn?o.slice(0,-1).every(t=>t)?e.fn(this):e.inverse(this):o.slice(0,-1).every(t=>t)}),g.registerHelper("replace",(o,e,t)=>typeof o!="string"?o:o.replace(new RegExp(e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),t)),g.registerHelper("index",(o,e)=>o?.[e]),g.registerHelper("getServiceName",o=>{let e=o.split(".");return e.length>1?e[1]:o}),g.registerHelper("groupByNamespace",o=>{let e={};for(let t of o){let r=t.tag.split(".");if(r.length===1)e[""]||(e[""]=[]),e[""].push(t);else{let s=r[0];e[s]||(e[s]=[]),e[s].push(t)}}return e}),g.registerHelper("getRootServices",o=>o.filter(e=>!e.tag.includes("."))),g.registerHelper("dict",()=>({})),g.registerHelper("setVar",(o,e,t)=>(t&&t.data&&t.data.root&&(t.data.root[`_${o}`]=e),"")),g.registerHelper("getVar",(o,e)=>e&&e.data&&e.data.root&&e.data.root[`_${o}`]||!1),g.registerHelper("set",(o,e,t)=>(o&&typeof o=="object"&&(o[e]=t),"")),g.registerHelper("hasKey",(o,e)=>o&&typeof o=="object"&&e in o),g.registerHelper("lookup",(o,e)=>o&&typeof o=="object"?o[e]:void 0),g.registerHelper("reMatch",(o,e)=>{try{return new RegExp(o).test(e)}catch{return!1}})}f(Ce,"registerCommonHandlebarsHelpers");function pt(o){return o.replace(/&quot;/g,'"').replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&#x60;/g,"`").replace(/&#96;/g,"`").replace(/&amp;/g,"&")}f(pt,"decodeHtmlEntities");function C(o,e,t,r=!1){let s;switch(o.kind){case l.String:o.format==="binary"?s="Blob":s="string";break;case l.Number:case l.Integer:s="number";break;case l.Boolean:s="boolean";break;case l.Null:s="null";break;case l.Ref:o.ref?e?.some(n=>n.type===o.ref)||r&&t&&t.find(a=>a.name===o.ref)?s=o.ref:s="Schema."+o.ref:s="unknown";break;case l.Array:if(o.items){let n=C(o.items,e,t);n.includes(" | ")||n.includes(" & ")?s=`Array<(${n})>`:s=`Array<${n}>`}else s="Array<unknown>";break;case l.OneOf:o.oneOf?s=o.oneOf.map(a=>C(a,e,t)).join(" | "):s="unknown";break;case l.AnyOf:o.anyOf?s=o.anyOf.map(a=>C(a,e,t)).join(" | "):s="unknown";break;case l.AllOf:o.allOf?s=o.allOf.map(a=>C(a,e,t)).join(" & "):s="unknown";break;case l.Enum:if(o.enumValues&&o.enumValues.length>0){let n=[];switch(o.enumBase){case l.Number:case l.Integer:for(let a of o.enumValues)n.push(a);break;case l.Boolean:for(let a of o.enumValues)a==="true"||a==="false"?n.push(a):n.push(`"${a}"`);break;default:for(let a of o.enumValues)n.push(`"${a}"`)}s=n.join(" | ")}else s="unknown";break;case l.Object:if(!o.properties||o.properties.length===0)s="Record<string, unknown>";else{let n=[];for(let a of o.properties){let i=C(a.type,e,t,r);a.required?n.push(`${a.name}: ${i}`):n.push(`${a.name}?: ${i}`)}s="{ "+n.join("; ")+" }"}break;default:s="unknown"}return o.nullable&&s!=="null"&&(s+=" | null"),pt(s)}f(C,"schemaToTSType");function M(o){let e=o.path,t=e.includes("{")&&e.includes("}");if(o.operationID)return $(o.operationID);switch(o.method){case"GET":return t?"get":"list";case"POST":return"create";case"PUT":case"PATCH":return"update";case"DELETE":return"delete";default:return o.method.toLowerCase()}}f(M,"deriveMethodName");async function $e(o,e){if(o.operationIdParser)try{let r=await o.operationIdParser(e.operationID,e.method,e.path);if(r)return $(r)}catch{}let t=ut(e.operationID);return t?$(t):M(e)}f($e,"resolveMethodName");function ut(o){if(!o)return"";let e=o.indexOf("Controller_");return e>=0?o.substring(e+11):o}f(ut,"defaultParseOperationID");function Ie(o){let e=o.path,t="`";for(let r=0;r<e.length;r++){if(e[r]==="{"){let s=r+1;for(;s<e.length&&e[s]!=="}";)s++;if(s<e.length){let n=e.substring(r+1,s);t+=`\${encodeURIComponent(${n})}`,r=s;continue}}t+=e[r]}return t+="`",t}f(Ie,"buildPathTemplate");function Ae(o){let t=o.path.split("/"),r=[];for(let n of t)n!==""&&(n.startsWith("{")&&n.endsWith("}")||r.push(n));return`'${r.join("/")}'`}f(Ae,"buildQueryKeyBase");function re(o){let e=[],t=new Map;for(let s=0;s<o.pathParams.length;s++)t.set(o.pathParams[s].name,s);let r=o.path;for(let s=0;s<r.length;s++)if(r[s]==="{"){let n=s+1;for(;n<r.length&&r[n]!=="}";)n++;if(n<r.length){let a=r.substring(s+1,n),i=t.get(a);i!==void 0&&e.push(o.pathParams[i]),s=n;continue}}return e}f(re,"orderPathParams");function He(o,e,t,r=!1){return C(o,t,e,r)}f(He,"schemaToTSTypeWithSimpleTypes");function pe(o,e,t,r,s=!1){let n=[];for(let a of re(o))n.push(`${a.name}: ${He(a.schema,t,r,s)}`);if(o.queryParams.length>0){let a=k(o.tag)+k(e)+"Query";n.push(`query?: Schema.${a}`)}if(o.requestBody){let a=o.requestBody.required===!0?"":"?";n.push(`body${a}: ${He(o.requestBody.schema,t,r,s)}`)}return n.push('init?: Omit<RequestInit, "method" | "body">'),n}f(pe,"buildMethodSignature");function qe(o,e){if(!e||e.length===0)return[];let t=new Set,r=f(n=>{let a=o.find(i=>i.name===n);return a?a.schema:null},"resolveRef"),s=f(n=>{if(n.kind==="ref"&&n.ref)if(e.some(i=>i.type===n.ref))t.add(n.ref);else{let i=r(n.ref);i&&s(i)}else if(n.kind==="array"&&n.items)s(n.items);else if(n.kind==="object"&&n.properties)for(let a of n.properties)s(a.type);else if(n.kind==="oneOf"&&n.oneOf)for(let a of n.oneOf)s(a);else if(n.kind==="anyOf"&&n.anyOf)for(let a of n.anyOf)s(a);else if(n.kind==="allOf"&&n.allOf)for(let a of n.allOf)s(a)},"checkSchema");for(let n of o)s(n.schema);return e.filter(n=>t.has(n.type))}f(qe,"collectPredefinedTypesUsedInSchema");function Ee(o,e,t){if(!e||e.length===0)return[];let r=new Set,s=f(a=>{if(!t)return null;let i=t.find(c=>c.name===a);return i?i.schema:null},"resolveRef"),n=f(a=>{if(a.kind==="ref"&&a.ref)if(e.some(c=>c.type===a.ref))r.add(a.ref);else{let c=s(a.ref);c&&n(c)}else if(a.kind==="array"&&a.items)n(a.items);else if(a.kind==="object"&&a.properties)for(let i of a.properties)n(i.type);else if(a.kind==="oneOf"&&a.oneOf)for(let i of a.oneOf)n(i);else if(a.kind==="anyOf"&&a.anyOf)for(let i of a.anyOf)n(i);else if(a.kind==="allOf"&&a.allOf)for(let i of a.allOf)n(i)},"checkSchema");for(let a of o.operations)for(let i of a.pathParams)n(i.schema);return e.filter(a=>r.has(a.type))}f(Ee,"collectPredefinedTypesUsedInService");function Ne(o){let e=[];for(let t of re(o))e.push(t.name);return o.queryParams.length>0&&e.push("query"),o.requestBody&&e.push("body"),e}f(Ne,"queryKeyArgs");function Z(o){let e=!1;for(let t of o)if(!(t>="a"&&t<="z"||t>="A"&&t<="Z"||t>="0"&&t<="9"||t==="_"||t==="$")){e=!0;break}return o.length>0&&o[0]>="0"&&o[0]<="9"&&(e=!0),e?`"${o}"`:o}f(Z,"quoteTSPropertyName");function Fe(o){return o.response.isStreaming===!0}f(Fe,"isStreamingOperation");function De(o){let e=o.response.schema;return e.kind===l.Array&&e.items?C(e.items):o.response.streamingFormat==="sse"?"string":C(e)}f(De,"getStreamingItemType");function A(o,e="",t,r=!1){let s=e+" ",n;switch(o.kind){case l.String:n="z.string()",o.format==="date"||o.format==="date-time"?n+=".datetime()":o.format==="email"?n+=".email()":o.format==="uri"||o.format==="url"?n+=".url()":o.format==="uuid"&&(n+=".uuid()");break;case l.Number:n="z.number()";break;case l.Integer:n="z.number().int()";break;case l.Boolean:n="z.boolean()";break;case l.Null:n="z.null()";break;case l.Ref:o.ref?n=r?`${o.ref}Schema`:`Schema.${o.ref}Schema`:n="z.unknown()";break;case l.Array:o.items?n=`z.array(${A(o.items,s,t,r)})`:n="z.array(z.unknown())";break;case l.Object:if(!o.properties||o.properties.length===0)o.additionalProperties?n=`z.record(z.string(), ${A(o.additionalProperties,s,t,r)})`:n="z.record(z.string(), z.unknown())";else{let a=[];for(let c of o.properties){let p=A(c.type,s,t,r),u=Z(c.name);c.required?a.push(`${s}${u}: ${p}`):a.push(`${s}${u}: ${p}.optional()`)}let i=`z.object({
1
+ "use strict";var Ye=Object.create;var W=Object.defineProperty;var Xe=Object.getOwnPropertyDescriptor;var et=Object.getOwnPropertyNames;var tt=Object.getPrototypeOf,rt=Object.prototype.hasOwnProperty;var f=(o,e)=>W(o,"name",{value:e,configurable:!0});var nt=(o,e)=>{for(var t in e)W(o,t,{get:e[t],enumerable:!0})},me=(o,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of et(e))!rt.call(o,s)&&s!==t&&W(o,s,{get:()=>e[s],enumerable:!(r=Xe(e,s))||r.enumerable});return o};var O=(o,e,t)=>(t=o!=null?Ye(tt(o)):{},me(e||!o||!o.__esModule?W(t,"default",{value:o,enumerable:!0}):t,o)),ot=o=>me(W({},"__esModule",{value:!0}),o);var vt={};nt(vt,{ClientSchema:()=>ge,ConfigModule:()=>D,ConfigSchema:()=>G,ConfigService:()=>v,GeneratorModule:()=>J,GeneratorService:()=>C,IRSchemaKind:()=>l,OpenApiModule:()=>B,OpenApiService:()=>x,PredefinedTypeSchema:()=>de,TYPESCRIPT_TEMPLATE_NAMES:()=>oe,TypeScriptClientSchema:()=>he,defineConfig:()=>ct,generate:()=>wt,loadConfig:()=>Ot,loadMjsConfig:()=>M});module.exports=ot(vt);var d=require("zod"),de=d.z.object({type:d.z.string().min(1,"Type name is required"),package:d.z.string().min(1,"Package name is required"),importPath:d.z.string().optional()}),oe=["client.ts.hbs","index.ts.hbs","package.json.hbs","README.md.hbs","schema.ts.hbs","schema.zod.ts.hbs","service.ts.hbs","tsconfig.json.hbs","utils.ts.hbs"],st=d.z.object({type:d.z.string().min(1,"Type is required"),outDir:d.z.string().min(1,"OutDir is required"),name:d.z.string().min(1,"Name is required"),includeTags:d.z.array(d.z.string()).optional(),excludeTags:d.z.array(d.z.string()).optional(),operationIdParser:d.z.custom().optional(),preCommand:d.z.array(d.z.string()).optional(),postCommand:d.z.array(d.z.string()).optional(),defaultBaseURL:d.z.string().optional(),exclude:d.z.array(d.z.string()).optional()}),he=st.extend({type:d.z.literal("typescript"),packageName:d.z.string().min(1,"PackageName is required"),moduleName:d.z.string().optional(),includeQueryKeys:d.z.boolean().optional(),predefinedTypes:d.z.array(de).optional(),dependencies:d.z.record(d.z.string(),d.z.string()).optional(),devDependencies:d.z.record(d.z.string(),d.z.string()).optional(),formatCode:d.z.boolean().optional(),templates:d.z.record(d.z.string(),d.z.string()).refine(o=>Object.keys(o).every(e=>oe.includes(e)),{message:`Template names must be one of: ${oe.join(", ")}`}).optional()}),ge=d.z.discriminatedUnion("type",[he]),G=d.z.object({spec:d.z.string().min(1,"Spec is required"),name:d.z.string().optional(),clients:d.z.array(ge).min(1,"At least one client is required")});var X=require("@nestjs/common"),be=O(require("fs")),S=O(require("path"));var ye=require("url"),Y=O(require("path"));async function M(o){try{let e=Y.isAbsolute(o)?o:Y.resolve(o),r=await import((0,ye.pathToFileURL)(e).href),s=r.default||r;if(!s)throw new Error(`Config file must export a default export or named export: ${o}`);return G.parse(s)}catch(e){throw e instanceof Error?new Error(`Failed to load MJS config from ${o}: ${e.message}`):e}}f(M,"loadMjsConfig");function at(o,e,t,r){var s=arguments.length,n=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,e,t,r);else for(var i=o.length-1;i>=0;i--)(a=o[i])&&(n=(s<3?a(n):s>3?a(e,t,n):a(e,t))||n);return s>3&&n&&Object.defineProperty(e,t,n),n}f(at,"_ts_decorate");var v=class o{static{f(this,"ConfigService")}logger=new X.Logger(o.name);DEFAULT_CONFIG_FILE="chunkflow-codegen.config.mjs";async findDefaultConfig(){let e=process.cwd(),t=S.parse(e).root;for(;e!==t;){let r=S.join(e,this.DEFAULT_CONFIG_FILE);try{return await be.promises.access(r),r}catch{}e=S.dirname(e)}return null}async load(e){try{let t=await M(e);return this.normalizePaths(t,e)}catch(t){throw t instanceof Error?new Error(`Failed to load config from ${e}: ${t.message}`):t}}normalizePaths(e,t){let r=S.dirname(S.resolve(t)),s=e.spec;this.isUrl(s)||S.isAbsolute(s)||(s=S.resolve(r,s));let n=e.clients.map(a=>{let i=a.outDir;return S.isAbsolute(i)||(i=S.resolve(r,i)),{...a,outDir:i}});return{...e,spec:s,clients:n}}isUrl(e){try{let t=new URL(e);return t.protocol==="http:"||t.protocol==="https:"}catch{return!1}}getPreCommand(e){return e.preCommand||[]}getPostCommand(e){return e.postCommand||[]}shouldExcludeFile(e,t){if(!e.exclude||e.exclude.length===0)return!1;let r;try{r=S.relative(e.outDir,t)}catch{return!1}r=S.posix.normalize(r),r==="."&&(r="");for(let s of e.exclude){let n=S.posix.normalize(s);if(r===n||n!==""&&r.startsWith(n+"/"))return!0}return!1}};v=at([(0,X.Injectable)()],v);var we=require("@nestjs/common");function it(o,e,t,r){var s=arguments.length,n=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,e,t,r);else for(var i=o.length-1;i>=0;i--)(a=o[i])&&(n=(s<3?a(n):s>3?a(e,t,n):a(e,t))||n);return s>3&&n&&Object.defineProperty(e,t,n),n}f(it,"_ts_decorate");var D=class{static{f(this,"ConfigModule")}};D=it([(0,we.Module)({providers:[v],exports:[v]})],D);function ct(o){return G.parse(o)}f(ct,"defineConfig");var l=(function(o){return o.Unknown="unknown",o.String="string",o.Number="number",o.Integer="integer",o.Boolean="boolean",o.Null="null",o.Array="array",o.Object="object",o.Enum="enum",o.Ref="ref",o.OneOf="oneOf",o.AnyOf="anyOf",o.AllOf="allOf",o.Not="not",o})({});var te=require("@nestjs/common");var Pe=require("@nestjs/common");var ve=require("@nestjs/common");function Se(o){let e=o.openapi;return typeof e!="string"?"unknown":e.startsWith("3.1")?"3.1":e.startsWith("3.0")?"3.0":"unknown"}f(Se,"detectOpenAPIVersion");function Te(o){return o==="3.0"||o==="3.1"}f(Te,"isSupportedVersion");function se(o,e){if(!(!e||typeof e!="object")){if("$ref"in e&&e.$ref){let t=e.$ref;if(t.startsWith("#/components/schemas/")){let r=t.replace("#/components/schemas/","");if(o.components?.schemas?.[r]){let s=o.components.schemas[r];return"$ref"in s?se(o,s):s}}return}return e}}f(se,"getSchemaFromRef");function Oe(o){return o?"nullable"in o&&o.nullable===!0?!0:"type"in o&&Array.isArray(o.type)?o.type.includes("null"):!1:!1}f(Oe,"isSchemaNullable");function ae(o){if(!(!o||!("type"in o)))return o.type}f(ae,"getSchemaType");function ft(o,e,t,r){var s=arguments.length,n=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,e,t,r);else for(var i=o.length-1;i>=0;i--)(a=o[i])&&(n=(s<3?a(n):s>3?a(e,t,n):a(e,t))||n);return s>3&&n&&Object.defineProperty(e,t,n),n}f(ft,"_ts_decorate");var P=class{static{f(this,"SchemaConverterService")}schemaRefToIR(e,t){if(!t)return{kind:l.Unknown,nullable:!1};if("$ref"in t&&t.$ref){let c=t.$ref;if(c.startsWith("#/components/schemas/")){let u=c.replace("#/components/schemas/","");return{kind:l.Ref,ref:u,nullable:!1}}let p=c.split("/");if(p.length>0){let u=p[p.length-1];if(u)return{kind:l.Ref,ref:u,nullable:!1}}return{kind:l.Unknown,nullable:!1}}let r=se(e,t);if(!r)return{kind:l.Unknown,nullable:!1};let s=Oe(r),n;if(r.discriminator&&(n={propertyName:r.discriminator.propertyName,mapping:r.discriminator.mapping}),r.oneOf&&r.oneOf.length>0){let c=r.oneOf.map(p=>this.schemaRefToIR(e,p));return{kind:l.OneOf,oneOf:c,nullable:s,discriminator:n}}if(r.anyOf&&r.anyOf.length>0){let c=r.anyOf.map(p=>this.schemaRefToIR(e,p));return{kind:l.AnyOf,anyOf:c,nullable:s,discriminator:n}}if(r.allOf&&r.allOf.length>0){let c=r.allOf.map(p=>this.schemaRefToIR(e,p));return{kind:l.AllOf,allOf:c,nullable:s,discriminator:n}}if(r.not){let c=this.schemaRefToIR(e,r.not);return{kind:l.Not,not:c,nullable:s,discriminator:n}}if(r.enum&&r.enum.length>0){let c=r.enum.map(u=>String(u)),p=this.inferEnumBaseKind(r);return{kind:l.Enum,enumValues:c,enumRaw:r.enum,enumBase:p,nullable:s,discriminator:n}}let a=ae(r),i=Array.isArray(a)?a.filter(c=>c!=="null")[0]:a;if(i)switch(i){case"string":return{kind:l.String,nullable:s,format:r.format,discriminator:n};case"integer":return{kind:l.Integer,nullable:s,discriminator:n};case"number":return{kind:l.Number,nullable:s,discriminator:n};case"boolean":return{kind:l.Boolean,nullable:s,discriminator:n};case"array":let c=r,p=this.schemaRefToIR(e,c.items);return{kind:l.Array,items:p,nullable:s,discriminator:n};case"object":let u=[];if(r.properties){let m=Object.keys(r.properties).sort();for(let b of m){let q=r.properties[b],N=this.schemaRefToIR(e,q),_=r.required?.includes(b)||!1;u.push({name:b,type:N,required:_,annotations:this.extractAnnotations(q)})}}let y;return r.additionalProperties&&typeof r.additionalProperties=="object"&&(y=this.schemaRefToIR(e,r.additionalProperties)),{kind:l.Object,properties:u,additionalProperties:y,nullable:s,discriminator:n}}return{kind:l.Unknown,nullable:s,discriminator:n}}extractAnnotations(e){if(!e||"$ref"in e)return{};let t=e;return{title:t.title,description:t.description,deprecated:t.deprecated,readOnly:t.readOnly,writeOnly:t.writeOnly,default:t.default,examples:t.example?Array.isArray(t.example)?t.example:[t.example]:void 0}}inferEnumBaseKind(e){let t=ae(e);if(t){let r=Array.isArray(t)?t.filter(s=>s!=="null")[0]:t;if(r)switch(r){case"string":return l.String;case"integer":return l.Integer;case"number":return l.Number;case"boolean":return l.Boolean}}if(e.enum&&e.enum.length>0){let r=e.enum[0];if(typeof r=="string")return l.String;if(typeof r=="number")return Number.isInteger(r)?l.Integer:l.Number;if(typeof r=="boolean")return l.Boolean}return l.Unknown}};P=ft([(0,ve.Injectable)()],P);function k(o){if(o=o.trim(),o==="")return"";let e=o.split(/[^A-Za-z0-9]+/).filter(r=>r!==""),t=[];for(let r of e){let s=ce(r);t.push(...s)}return t.filter(r=>r!=="").map(r=>r.charAt(0).toUpperCase()+r.slice(1).toLowerCase()).join("")}f(k,"toPascalCase");function $(o){let e=k(o);return e===""?"":e.charAt(0).toLowerCase()+e.slice(1)}f($,"toCamelCase");function L(o){if(o=o.trim(),o==="")return"";let e=o.split(/[^A-Za-z0-9]+/).filter(r=>r!==""),t=[];for(let r of e){let s=ce(r);t.push(...s)}return t.filter(r=>r!=="").map(r=>r.toLowerCase()).join("_")}f(L,"toSnakeCase");function ke(o){if(o=o.trim(),o==="")return"";let e=o.split(/[^A-Za-z0-9]+/).filter(r=>r!==""),t=[];for(let r of e){let s=ce(r);t.push(...s)}return t.filter(r=>r!=="").map(r=>r.toLowerCase()).join("-")}f(ke,"toKebabCase");function ce(o){if(o==="")return[];let e=[],t="",r=Array.from(o);for(let s=0;s<r.length;s++){let n=r[s],a=!1;s>0&&ie(n)&&(ie(r[s-1])?s<r.length-1&&!ie(r[s+1])&&(a=!0):a=!0),a&&t.length>0&&(e.push(t),t=""),t+=n}return t.length>0&&e.push(t),e}f(ce,"splitCamelCase");function ie(o){return o>="A"&&o<="Z"}f(ie,"isUppercase");function lt(o,e,t,r){var s=arguments.length,n=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,e,t,r);else for(var i=o.length-1;i>=0;i--)(a=o[i])&&(n=(s<3?a(n):s>3?a(e,t,n):a(e,t))||n);return s>3&&n&&Object.defineProperty(e,t,n),n}f(lt,"_ts_decorate");function xe(o,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,e)}f(xe,"_ts_metadata");var j=class{static{f(this,"IrBuilderService")}schemaConverter;constructor(e){this.schemaConverter=e}buildIR(e){let t=this.collectTags(e),r=this.collectSecuritySchemes(e),s=this.buildStructuredModels(e),n={};for(let i of t)n[i]=!0;let a=this.buildIRFromDoc(e,n);return a.securitySchemes=r,a.modelDefs=[...s,...a.modelDefs],a.openApiDocument=e,a}filterIR(e,t){let r=this.compileTagFilters(t.includeTags||[]),s=this.compileTagFilters(t.excludeTags||[]),n=[];for(let i of e.services){let c=[];for(let p of i.operations)this.shouldIncludeOperation(p.originalTags,r,s)&&c.push(p);c.length>0&&n.push({...i,operations:c})}let a={services:n,models:e.models,securitySchemes:e.securitySchemes,modelDefs:e.modelDefs,openApiDocument:e.openApiDocument};return a.modelDefs=this.filterUnusedModelDefs(a,e.modelDefs),a}detectStreamingContentType(e){let t=e.toLowerCase().split(";")[0].trim();return t==="text/event-stream"?{isStreaming:!0,format:"sse"}:t==="application/x-ndjson"||t==="application/x-jsonlines"||t==="application/jsonl"?{isStreaming:!0,format:"ndjson"}:t.includes("stream")||t.includes("chunked")?{isStreaming:!0,format:"chunked"}:{isStreaming:!1}}collectTags(e){let t=new Set;if(t.add("misc"),e.paths)for(let[r,s]of Object.entries(e.paths)){if(!s)continue;let n=[s.get,s.post,s.put,s.patch,s.delete,s.options,s.head,s.trace];for(let a of n)if(!(!a||!a.tags))for(let i of a.tags)t.add(i)}return Array.from(t).sort()}compileTagFilters(e){return e.map(t=>{try{return new RegExp(t)}catch(r){throw new Error(`Invalid tag filter pattern "${t}": ${r instanceof Error?r.message:String(r)}`)}})}shouldIncludeOperation(e,t,r){let s=t.length===0;if(t.length>0)for(let n of e){for(let a of t)if(a.test(n)){s=!0;break}if(s)break}if(!s)return!1;if(r.length>0){for(let n of e)for(let a of r)if(a.test(n))return!1}return!0}buildIRFromDoc(e,t){let r={};r.misc={tag:"misc",operations:[]};let s=[],n=new Set;if(e.components?.schemas)for(let c of Object.keys(e.components.schemas))n.add(c);let a=f((c,p,u,y)=>{r[c]||(r[c]={tag:c,operations:[]});let m=p.operationId||"",{pathParams:b,queryParams:q}=this.collectParams(e,p),{requestBody:N,extractedTypes:_}=this.extractRequestBodyWithTypes(e,p,c,m,u,n);s.push(..._);let{response:E,extractedTypes:U}=this.extractResponseWithTypes(e,p,c,m,u,n);s.push(...U);let K=p.tags&&p.tags.length>0?[...p.tags]:["misc"];r[c].operations.push({operationID:m,method:u,path:y,tag:c,originalTags:K,summary:p.summary||"",description:p.description||"",deprecated:p.deprecated||!1,pathParams:b,queryParams:q,requestBody:N,response:E})},"addOp");if(e.paths)for(let[c,p]of Object.entries(e.paths)){if(!p)continue;let u=[{op:p.get,method:"GET"},{op:p.post,method:"POST"},{op:p.put,method:"PUT"},{op:p.patch,method:"PATCH"},{op:p.delete,method:"DELETE"},{op:p.options,method:"OPTIONS"},{op:p.head,method:"HEAD"},{op:p.trace,method:"TRACE"}];for(let{op:y,method:m}of u){if(!y)continue;let b=this.firstAllowedTag(y.tags||[],t);b&&a(b,y,m,c)}}let i=Object.values(r);for(let c of i)c.operations.sort((p,u)=>p.path===u.path?p.method.localeCompare(u.method):p.path.localeCompare(u.path));return i.sort((c,p)=>c.tag.localeCompare(p.tag)),{services:i,models:[],securitySchemes:[],modelDefs:s}}deriveMethodName(e,t,r){if(e){let n=e.indexOf("Controller_"),a=n>=0?e.substring(n+11):e;return $(a)}let s=r.includes("{")&&r.includes("}");switch(t){case"GET":return s?"get":"list";case"POST":return"create";case"PUT":case"PATCH":return"update";case"DELETE":return"delete";default:return t.toLowerCase()}}firstAllowedTag(e,t){for(let r of e)if(t[r])return r;return e.length===0&&t.misc?"misc":""}collectSecuritySchemes(e){if(!e.components?.securitySchemes)return[];let t=Object.keys(e.components.securitySchemes).sort(),r=[];for(let s of t){let n=e.components.securitySchemes[s];if(!n||"$ref"in n)continue;let a={key:s,type:n.type};switch(n.type){case"http":a.scheme=n.scheme,a.bearerFormat=n.bearerFormat;break;case"apiKey":a.in=n.in,a.name=n.name;break;case"oauth2":case"openIdConnect":break}r.push(a)}return r}collectParams(e,t){let r=[],s=[];if(t.parameters)for(let n of t.parameters){if(!n||"$ref"in n)continue;let a=n,i=this.schemaConverter.schemaRefToIR(e,a.schema),c={name:a.name,required:a.required||!1,schema:i,description:a.description||""};a.in==="path"?r.push(c):a.in==="query"&&s.push(c)}return r.sort((n,a)=>n.name.localeCompare(a.name)),s.sort((n,a)=>n.name.localeCompare(a.name)),{pathParams:r,queryParams:s}}findMatchingComponentSchema(e,t){if(!t||!e.components?.schemas)return null;if("$ref"in t&&t.$ref){let s=t.$ref;if(s.startsWith("#/components/schemas/")){let n=s.replace("#/components/schemas/","");if(e.components.schemas[n])return n}}let r=this.schemaConverter.schemaRefToIR(e,t);for(let[s,n]of Object.entries(e.components.schemas)){let a=this.schemaConverter.schemaRefToIR(e,n);if(this.compareSchemas(r,a))return s}return null}compareSchemas(e,t){if(e.kind!==t.kind)return!1;if(e.kind===l.Ref&&t.kind===l.Ref)return e.ref===t.ref;if(e.kind===l.Object&&t.kind===l.Object){let r=e.properties||[],s=t.properties||[];if(r.length!==s.length)return!1;let n=new Map(r.map(i=>[i.name,{type:i.type,required:i.required}])),a=new Map(s.map(i=>[i.name,{type:i.type,required:i.required}]));if(n.size!==a.size)return!1;for(let[i,c]of n){let p=a.get(i);if(!p||c.required!==p.required||!this.compareSchemas(c.type,p.type))return!1}return!0}return e.kind===l.Array&&t.kind===l.Array?!e.items||!t.items?e.items===t.items:this.compareSchemas(e.items,t.items):!0}extractModelNameFromSchema(e){return e.kind===l.Ref&&e.ref?e.ref:e.kind===l.Array&&e.items&&e.items.kind===l.Ref&&e.items.ref?e.items.ref:null}generateTypeName(e,t,r,s,n,a){let i=this.extractModelNameFromSchema(e);if(i)return i;let c=this.deriveMethodName(r,s,n);return`${k(t)}${k(c)}${a}`}extractRequestBodyWithTypes(e,t,r,s,n,a){let i=[];if(!t.requestBody||"$ref"in t.requestBody)return{requestBody:null,extractedTypes:[]};let c=t.requestBody;if(c.content?.["application/json"]){let u=c.content["application/json"],y=this.schemaConverter.schemaRefToIR(e,u.schema),m=this.findMatchingComponentSchema(e,u.schema);if(m)return{requestBody:{contentType:"application/json",typeTS:"",schema:{kind:l.Ref,ref:m,nullable:!1},required:c.required||!1},extractedTypes:[]};let b=this.generateTypeName(y,r,s,n,t.path,"RequestBody");return y.kind===l.Object&&!a.has(b)?(a.add(b),i.push({name:b,schema:y,annotations:this.schemaConverter.extractAnnotations(u.schema)}),{requestBody:{contentType:"application/json",typeTS:"",schema:{kind:l.Ref,ref:b,nullable:!1},required:c.required||!1},extractedTypes:i}):{requestBody:{contentType:"application/json",typeTS:"",schema:y,required:c.required||!1},extractedTypes:[]}}return{requestBody:this.extractRequestBody(e,t),extractedTypes:[]}}extractRequestBody(e,t){if(!t.requestBody||"$ref"in t.requestBody)return null;let r=t.requestBody;if(r.content?.["application/json"]){let s=r.content["application/json"];return{contentType:"application/json",typeTS:"",schema:this.schemaConverter.schemaRefToIR(e,s.schema),required:r.required||!1}}if(r.content?.["application/x-www-form-urlencoded"]){let s=r.content["application/x-www-form-urlencoded"];return{contentType:"application/x-www-form-urlencoded",typeTS:"",schema:this.schemaConverter.schemaRefToIR(e,s.schema),required:r.required||!1}}if(r.content?.["multipart/form-data"])return{contentType:"multipart/form-data",typeTS:"",schema:{kind:"unknown",nullable:!1},required:r.required||!1};if(r.content){let s=Object.keys(r.content)[0],n=r.content[s];return{contentType:s,typeTS:"",schema:this.schemaConverter.schemaRefToIR(e,n.schema),required:r.required||!1}}return null}extractResponseWithTypes(e,t,r,s,n,a){let i=[];if(!t.responses)return{response:{typeTS:"unknown",schema:{kind:l.Unknown,nullable:!1},description:"",isStreaming:!1,contentType:""},extractedTypes:[]};let c=["200","201"];for(let u of c){let y=t.responses[u];if(y&&!("$ref"in y)){let m=y;if(m.content){for(let[E,U]of Object.entries(m.content)){let K=this.detectStreamingContentType(E),V=this.schemaConverter.schemaRefToIR(e,U.schema);if(K.isStreaming)return{response:{typeTS:"",schema:V,description:m.description||"",isStreaming:!0,contentType:E,streamingFormat:K.format},extractedTypes:[]};if(E==="application/json"){let ue=this.findMatchingComponentSchema(e,U.schema);if(ue)return{response:{typeTS:"",schema:{kind:l.Ref,ref:ue,nullable:!1},description:m.description||"",isStreaming:!1,contentType:E},extractedTypes:[]};let Q=this.generateTypeName(V,r,s,n,t.path,"Response");return V.kind===l.Object&&!a.has(Q)?(a.add(Q),i.push({name:Q,schema:V,annotations:this.schemaConverter.extractAnnotations(U.schema)}),{response:{typeTS:"",schema:{kind:l.Ref,ref:Q,nullable:!1},description:m.description||"",isStreaming:!1,contentType:E},extractedTypes:i}):{response:{typeTS:"",schema:V,description:m.description||"",isStreaming:!1,contentType:E},extractedTypes:[]}}}let b=Object.keys(m.content)[0],q=m.content[b],N=this.schemaConverter.schemaRefToIR(e,q.schema),_=this.detectStreamingContentType(b);return{response:{typeTS:"",schema:N,description:m.description||"",isStreaming:_.isStreaming,contentType:b,streamingFormat:_.format},extractedTypes:[]}}return{response:{typeTS:"void",schema:{kind:l.Unknown,nullable:!1},description:m.description||"",isStreaming:!1,contentType:""},extractedTypes:[]}}}return{response:this.extractResponse(e,t),extractedTypes:[]}}extractResponse(e,t){if(!t.responses)return{typeTS:"unknown",schema:{kind:l.Unknown,nullable:!1},description:"",isStreaming:!1,contentType:""};let r=["200","201"];for(let s of r){let n=t.responses[s];if(n&&!("$ref"in n)){let a=n;if(a.content){for(let[u,y]of Object.entries(a.content)){let m=this.detectStreamingContentType(u);if(m.isStreaming)return{typeTS:"",schema:this.schemaConverter.schemaRefToIR(e,y.schema),description:a.description||"",isStreaming:!0,contentType:u,streamingFormat:m.format}}if(a.content["application/json"]){let u=a.content["application/json"];return{typeTS:"",schema:this.schemaConverter.schemaRefToIR(e,u.schema),description:a.description||"",isStreaming:!1,contentType:"application/json"}}let i=Object.keys(a.content)[0],c=a.content[i],p=this.detectStreamingContentType(i);return{typeTS:"",schema:this.schemaConverter.schemaRefToIR(e,c.schema),description:a.description||"",isStreaming:p.isStreaming,contentType:i,streamingFormat:p.format}}return{typeTS:"void",schema:{kind:l.Unknown,nullable:!1},description:a.description||"",isStreaming:!1,contentType:""}}}for(let[s,n]of Object.entries(t.responses))if(s.length===3&&s[0]==="2"&&n&&!("$ref"in n)){let a=n;if(s==="204")return{typeTS:"void",schema:{kind:l.Unknown,nullable:!1},description:a.description||"",isStreaming:!1,contentType:""};if(a.content){for(let[u,y]of Object.entries(a.content)){let m=this.detectStreamingContentType(u);if(m.isStreaming)return{typeTS:"",schema:this.schemaConverter.schemaRefToIR(e,y.schema),description:a.description||"",isStreaming:!0,contentType:u,streamingFormat:m.format}}if(a.content["application/json"]){let u=a.content["application/json"];return{typeTS:"",schema:this.schemaConverter.schemaRefToIR(e,u.schema),description:a.description||"",isStreaming:!1,contentType:"application/json"}}let i=Object.keys(a.content)[0],c=a.content[i],p=this.detectStreamingContentType(i);return{typeTS:"",schema:this.schemaConverter.schemaRefToIR(e,c.schema),description:a.description||"",isStreaming:p.isStreaming,contentType:i,streamingFormat:p.format}}}return{typeTS:"unknown",schema:{kind:l.Unknown,nullable:!1},description:"",isStreaming:!1,contentType:""}}buildStructuredModels(e){let t=[];if(!e.components?.schemas)return t;let r=Object.keys(e.components.schemas).sort(),s=new Set;for(let n of r)s.add(n);for(let n of r){let a=e.components.schemas[n],i=this.schemaConverter.schemaRefToIR(e,a);t.push({name:n,schema:i,annotations:this.schemaConverter.extractAnnotations(a)})}return t}filterUnusedModelDefs(e,t){let r=new Map;for(let i of t)r.set(i.name,i);let s=new Set,n=new Set,a=f(i=>{if(i.kind==="ref"&&i.ref){let c=i.ref;if(s.add(c),!n.has(c)){n.add(c);let p=r.get(c);p&&a(p.schema)}}if(i.items&&a(i.items),i.additionalProperties&&a(i.additionalProperties),i.oneOf)for(let c of i.oneOf)a(c);if(i.anyOf)for(let c of i.anyOf)a(c);if(i.allOf)for(let c of i.allOf)a(c);if(i.not&&a(i.not),i.properties)for(let c of i.properties)a(c.type)},"collectRefs");for(let i of e.services)for(let c of i.operations){for(let p of c.pathParams)a(p.schema);for(let p of c.queryParams)a(p.schema);c.requestBody&&a(c.requestBody.schema),a(c.response.schema)}return t.filter(i=>s.has(i.name))}};j=lt([(0,Pe.Injectable)(),xe("design:type",Function),xe("design:paramtypes",[typeof P>"u"?Object:P])],j);var ee=require("@nestjs/common"),I=O(require("@apidevtools/swagger-parser")),fe=O(require("fs")),le=O(require("path"));function pt(o,e,t,r){var s=arguments.length,n=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,e,t,r);else for(var i=o.length-1;i>=0;i--)(a=o[i])&&(n=(s<3?a(n):s>3?a(e,t,n):a(e,t))||n);return s>3&&n&&Object.defineProperty(e,t,n),n}f(pt,"_ts_decorate");var x=class o{static{f(this,"OpenApiService")}logger=new ee.Logger(o.name);async loadDocument(e){try{let t=null;try{t=new URL(e)}catch{}let r;if(t&&(t.protocol==="http:"||t.protocol==="https:")){this.logger.debug(`Loading OpenAPI spec from URL: ${e}`);let n=await fetch(e,{signal:AbortSignal.timeout(1e4)});if(!n.ok)throw new Error(`Failed to fetch OpenAPI spec: HTTP ${n.status} ${n.statusText}`);let a=await n.text(),i;try{i=JSON.parse(a)}catch{throw new Error("OpenAPI spec is not valid JSON")}try{let c=await I.default.parse(i);r=await I.default.bundle(c)}catch(c){this.logger.debug(`Bundle failed: ${c instanceof Error?c.message:String(c)}`),this.logger.debug("Attempting dereference directly");try{let p=await I.default.parse(i);r=await I.default.dereference(p)}catch(p){throw p}}}else{let n=le.resolve(e);if(!fe.existsSync(n))throw new Error(`OpenAPI spec file not found: ${n}`);this.logger.debug(`Loading OpenAPI spec from file: ${n}`);try{r=await I.default.bundle(n)}catch(a){this.logger.debug(`Bundle failed: ${a instanceof Error?a.message:String(a)}`),this.logger.debug("Attempting dereference directly"),r=await I.default.dereference(n)}}let s=Se(r);if(!Te(s))throw new Error(`Unsupported OpenAPI version: ${r.openapi}. Only versions 3.0.x and 3.1.0 are supported.`);return this.logger.log(`Detected OpenAPI version: ${s} (${r.openapi})`),r}catch(t){throw t instanceof Error?new Error(`Failed to load OpenAPI document from ${e}: ${t.message}`):t}}async validateDocument(e){try{let t=null;try{t=new URL(e)}catch{}if(t&&(t.protocol==="http:"||t.protocol==="https:"))await I.default.validate(e);else{let r=le.resolve(e);if(!fe.existsSync(r))throw new Error(`OpenAPI spec file not found: ${r}`);await I.default.validate(r)}}catch(t){throw t instanceof Error?new Error(`Invalid OpenAPI document: ${t.message}`):t}}};x=pt([(0,ee.Injectable)()],x);function ut(o,e,t,r){var s=arguments.length,n=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,e,t,r);else for(var i=o.length-1;i>=0;i--)(a=o[i])&&(n=(s<3?a(n):s>3?a(e,t,n):a(e,t))||n);return s>3&&n&&Object.defineProperty(e,t,n),n}f(ut,"_ts_decorate");function je(o,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,e)}f(je,"_ts_metadata");var C=class o{static{f(this,"GeneratorService")}irBuilder;openApiService;logger=new te.Logger(o.name);generators=new Map;constructor(e,t){this.irBuilder=e,this.openApiService=t}register(e){this.generators.set(e.getType(),e),this.logger.debug(`Registered generator: ${e.getType()}`)}getGenerator(e){return this.generators.get(e)}getAvailableTypes(){return Array.from(this.generators.keys())}async generate(e,t){let r=this.getGenerator(t.type);if(!r)throw new Error(`Unsupported client type: ${t.type}`);let s=await this.openApiService.loadDocument(e),n=this.irBuilder.buildIR(s),a=this.irBuilder.filterIR(n,t);await r.generate(t,a)}};C=ut([(0,te.Injectable)(),je("design:type",Function),je("design:paramtypes",[typeof j>"u"?Object:j,typeof x>"u"?Object:x])],C);var Le=require("@nestjs/common");var Ce=require("@nestjs/common");function mt(o,e,t,r){var s=arguments.length,n=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,e,t,r);else for(var i=o.length-1;i>=0;i--)(a=o[i])&&(n=(s<3?a(n):s>3?a(e,t,n):a(e,t))||n);return s>3&&n&&Object.defineProperty(e,t,n),n}f(mt,"_ts_decorate");var B=class{static{f(this,"OpenApiModule")}};B=mt([(0,Ce.Module)({providers:[x],exports:[x]})],B);var ne=require("@nestjs/common"),w=O(require("fs")),T=O(require("path")),h=O(require("handlebars"));var g=O(require("handlebars"));function Re(){g.registerHelper("pascal",o=>k(o)),g.registerHelper("camel",o=>$(o)),g.registerHelper("kebab",o=>ke(o)),g.registerHelper("snake",o=>L(o)),g.registerHelper("serviceName",o=>k(o)+"Service"),g.registerHelper("serviceProp",o=>$(o)),g.registerHelper("fileBase",o=>L(o).toLowerCase()),g.registerHelper("eq",(o,e)=>o===e),g.registerHelper("ne",(o,e)=>o!==e),g.registerHelper("gt",(o,e)=>o>e),g.registerHelper("lt",(o,e)=>o<e),g.registerHelper("sub",(o,e)=>o-e),g.registerHelper("len",o=>Array.isArray(o)?o.length:0),g.registerHelper("or",function(...o){let e=o[o.length-1];return e&&e.fn?o.slice(0,-1).some(t=>t)?e.fn(this):e.inverse(this):o.slice(0,-1).some(t=>t)}),g.registerHelper("and",function(...o){let e=o[o.length-1];return e&&e.fn?o.slice(0,-1).every(t=>t)?e.fn(this):e.inverse(this):o.slice(0,-1).every(t=>t)}),g.registerHelper("replace",(o,e,t)=>typeof o!="string"?o:o.replace(new RegExp(e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),t)),g.registerHelper("index",(o,e)=>o?.[e]),g.registerHelper("getServiceName",o=>{let e=o.split(".");return e.length>1?e[1]:o}),g.registerHelper("groupByNamespace",o=>{let e={};for(let t of o){let r=t.tag.split(".");if(r.length===1)e[""]||(e[""]=[]),e[""].push(t);else{let s=r[0];e[s]||(e[s]=[]),e[s].push(t)}}return e}),g.registerHelper("getRootServices",o=>o.filter(e=>!e.tag.includes("."))),g.registerHelper("dict",()=>({})),g.registerHelper("setVar",(o,e,t)=>(t&&t.data&&t.data.root&&(t.data.root[`_${o}`]=e),"")),g.registerHelper("getVar",(o,e)=>e&&e.data&&e.data.root&&e.data.root[`_${o}`]||!1),g.registerHelper("set",(o,e,t)=>(o&&typeof o=="object"&&(o[e]=t),"")),g.registerHelper("hasKey",(o,e)=>o&&typeof o=="object"&&e in o),g.registerHelper("lookup",(o,e)=>o&&typeof o=="object"?o[e]:void 0),g.registerHelper("reMatch",(o,e)=>{try{return new RegExp(o).test(e)}catch{return!1}})}f(Re,"registerCommonHandlebarsHelpers");function dt(o){return o.replace(/&quot;/g,'"').replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&#x60;/g,"`").replace(/&#96;/g,"`").replace(/&amp;/g,"&")}f(dt,"decodeHtmlEntities");function R(o,e,t,r=!1){let s;switch(o.kind){case l.String:o.format==="binary"?s="Blob":s="string";break;case l.Number:case l.Integer:s="number";break;case l.Boolean:s="boolean";break;case l.Null:s="null";break;case l.Ref:o.ref?e?.some(n=>n.type===o.ref)||r&&t&&t.find(a=>a.name===o.ref)?s=o.ref:s="Schema."+o.ref:s="unknown";break;case l.Array:if(o.items){let n=R(o.items,e,t);n.includes(" | ")||n.includes(" & ")?s=`Array<(${n})>`:s=`Array<${n}>`}else s="Array<unknown>";break;case l.OneOf:o.oneOf?s=o.oneOf.map(a=>R(a,e,t)).join(" | "):s="unknown";break;case l.AnyOf:o.anyOf?s=o.anyOf.map(a=>R(a,e,t)).join(" | "):s="unknown";break;case l.AllOf:o.allOf?s=o.allOf.map(a=>R(a,e,t)).join(" & "):s="unknown";break;case l.Enum:if(o.enumValues&&o.enumValues.length>0){let n=[];switch(o.enumBase){case l.Number:case l.Integer:for(let a of o.enumValues)n.push(a);break;case l.Boolean:for(let a of o.enumValues)a==="true"||a==="false"?n.push(a):n.push(`"${a}"`);break;default:for(let a of o.enumValues)n.push(`"${a}"`)}s=n.join(" | ")}else s="unknown";break;case l.Object:if(!o.properties||o.properties.length===0)s="Record<string, unknown>";else{let n=[];for(let a of o.properties){let i=R(a.type,e,t,r);a.required?n.push(`${a.name}: ${i}`):n.push(`${a.name}?: ${i}`)}s="{ "+n.join("; ")+" }"}break;default:s="unknown"}return o.nullable&&s!=="null"&&(s+=" | null"),dt(s)}f(R,"schemaToTSType");function z(o){let e=o.path,t=e.includes("{")&&e.includes("}");if(o.operationID)return $(o.operationID);switch(o.method){case"GET":return t?"get":"list";case"POST":return"create";case"PUT":case"PATCH":return"update";case"DELETE":return"delete";default:return o.method.toLowerCase()}}f(z,"deriveMethodName");async function $e(o,e){if(o.operationIdParser)try{let r=await o.operationIdParser(e.operationID,e.method,e.path);if(r)return $(r)}catch{}let t=ht(e.operationID);return t?$(t):z(e)}f($e,"resolveMethodName");function ht(o){if(!o)return"";let e=o.indexOf("Controller_");return e>=0?o.substring(e+11):o}f(ht,"defaultParseOperationID");function Ie(o){let e=o.path,t="`";for(let r=0;r<e.length;r++){if(e[r]==="{"){let s=r+1;for(;s<e.length&&e[s]!=="}";)s++;if(s<e.length){let n=e.substring(r+1,s);t+=`\${encodeURIComponent(${n})}`,r=s;continue}}t+=e[r]}return t+="`",t}f(Ie,"buildPathTemplate");function Ae(o){let t=o.path.split("/"),r=[];for(let n of t)n!==""&&(n.startsWith("{")&&n.endsWith("}")||r.push(n));return`'${r.join("/")}'`}f(Ae,"buildQueryKeyBase");function re(o){let e=[],t=new Map;for(let s=0;s<o.pathParams.length;s++)t.set(o.pathParams[s].name,s);let r=o.path;for(let s=0;s<r.length;s++)if(r[s]==="{"){let n=s+1;for(;n<r.length&&r[n]!=="}";)n++;if(n<r.length){let a=r.substring(s+1,n),i=t.get(a);i!==void 0&&e.push(o.pathParams[i]),s=n;continue}}return e}f(re,"orderPathParams");function He(o,e,t,r=!1){return R(o,t,e,r)}f(He,"schemaToTSTypeWithSimpleTypes");function pe(o,e,t,r,s=!1){let n=[];for(let a of re(o))n.push(`${a.name}: ${He(a.schema,t,r,s)}`);if(o.queryParams.length>0){let a=k(o.tag)+k(e)+"Query";n.push(`query?: Schema.${a}`)}if(o.requestBody){let a=o.requestBody.required===!0?"":"?";n.push(`body${a}: ${He(o.requestBody.schema,t,r,s)}`)}return n.push('init?: Omit<RequestInit, "method" | "body">'),n}f(pe,"buildMethodSignature");function qe(o,e){if(!e||e.length===0)return[];let t=new Set,r=f(n=>{let a=o.find(i=>i.name===n);return a?a.schema:null},"resolveRef"),s=f(n=>{if(n.kind==="ref"&&n.ref)if(e.some(i=>i.type===n.ref))t.add(n.ref);else{let i=r(n.ref);i&&s(i)}else if(n.kind==="array"&&n.items)s(n.items);else if(n.kind==="object"&&n.properties)for(let a of n.properties)s(a.type);else if(n.kind==="oneOf"&&n.oneOf)for(let a of n.oneOf)s(a);else if(n.kind==="anyOf"&&n.anyOf)for(let a of n.anyOf)s(a);else if(n.kind==="allOf"&&n.allOf)for(let a of n.allOf)s(a)},"checkSchema");for(let n of o)s(n.schema);return e.filter(n=>t.has(n.type))}f(qe,"collectPredefinedTypesUsedInSchema");function Ee(o,e,t){if(!e||e.length===0)return[];let r=new Set,s=f(a=>{if(!t)return null;let i=t.find(c=>c.name===a);return i?i.schema:null},"resolveRef"),n=f(a=>{if(a.kind==="ref"&&a.ref)if(e.some(c=>c.type===a.ref))r.add(a.ref);else{let c=s(a.ref);c&&n(c)}else if(a.kind==="array"&&a.items)n(a.items);else if(a.kind==="object"&&a.properties)for(let i of a.properties)n(i.type);else if(a.kind==="oneOf"&&a.oneOf)for(let i of a.oneOf)n(i);else if(a.kind==="anyOf"&&a.anyOf)for(let i of a.anyOf)n(i);else if(a.kind==="allOf"&&a.allOf)for(let i of a.allOf)n(i)},"checkSchema");for(let a of o.operations)for(let i of a.pathParams)n(i.schema);return e.filter(a=>r.has(a.type))}f(Ee,"collectPredefinedTypesUsedInService");function Fe(o){let e=[];for(let t of re(o))e.push(t.name);return o.queryParams.length>0&&e.push("query"),o.requestBody&&e.push("body"),e}f(Fe,"queryKeyArgs");function Z(o){let e=!1;for(let t of o)if(!(t>="a"&&t<="z"||t>="A"&&t<="Z"||t>="0"&&t<="9"||t==="_"||t==="$")){e=!0;break}return o.length>0&&o[0]>="0"&&o[0]<="9"&&(e=!0),e?`"${o}"`:o}f(Z,"quoteTSPropertyName");function Ne(o){return o.response.isStreaming===!0}f(Ne,"isStreamingOperation");function De(o){let e=o.response.schema;return e.kind===l.Array&&e.items?R(e.items):o.response.streamingFormat==="sse"?"string":R(e)}f(De,"getStreamingItemType");function A(o,e="",t,r=!1){let s=e+" ",n;switch(o.kind){case l.String:n="z.string()",o.format==="date"||o.format==="date-time"?n+=".datetime()":o.format==="email"?n+=".email()":o.format==="uri"||o.format==="url"?n+=".url()":o.format==="uuid"&&(n+=".uuid()");break;case l.Number:n="z.number()";break;case l.Integer:n="z.number().int()";break;case l.Boolean:n="z.boolean()";break;case l.Null:n="z.null()";break;case l.Ref:o.ref?n=r?`${o.ref}Schema`:`Schema.${o.ref}Schema`:n="z.unknown()";break;case l.Array:o.items?n=`z.array(${A(o.items,s,t,r)})`:n="z.array(z.unknown())";break;case l.Object:if(!o.properties||o.properties.length===0)o.additionalProperties?n=`z.record(z.string(), ${A(o.additionalProperties,s,t,r)})`:n="z.record(z.string(), z.unknown())";else{let a=[];for(let c of o.properties){let p=A(c.type,s,t,r),u=Z(c.name);c.required?a.push(`${s}${u}: ${p}`):a.push(`${s}${u}: ${p}.optional()`)}let i=`z.object({
2
2
  ${a.join(`,
3
3
  `)}
4
- ${e}})`;if(o.additionalProperties){let c=A(o.additionalProperties,s,t,r);n=`${i}.catchall(${c})`}else n=i}break;case l.Enum:o.enumValues&&o.enumValues.length>0?n=`z.enum([${o.enumValues.map(i=>i==="true"||i==="false"||/^-?[0-9]+(\.[0-9]+)?$/.test(i)?i:JSON.stringify(i)).join(", ")}])`:n="z.string()";break;case l.OneOf:o.oneOf&&o.oneOf.length>0?n=`z.union([${o.oneOf.map(i=>A(i,s,t,r)).join(", ")}])`:n="z.unknown()";break;case l.AnyOf:o.anyOf&&o.anyOf.length>0?n=`z.union([${o.anyOf.map(i=>A(i,s,t,r)).join(", ")}])`:n="z.unknown()";break;case l.AllOf:if(o.allOf&&o.allOf.length>0){let a=o.allOf.map(i=>A(i,s,t,r));n=a.join(".and(")+")".repeat(a.length-1)}else n="z.unknown()";break;default:n="z.unknown()"}return o.nullable&&n!=="z.null()"&&(n=`${n}.nullable()`),n}f(A,"schemaToZodSchema");var _e=require("child_process"),ze=require("util"),Me=O(require("path")),Ue=O(require("fs"));var Be=(0,ze.promisify)(_e.exec);async function Ve(o,e){let t=e||console;try{try{await Be("npx --yes prettier --version",{cwd:o,maxBuffer:10*1024*1024})}catch{t.warn?.("Prettier is not available. Skipping code formatting. Install prettier to enable formatting.");return}let r=Me.join(o,"src");if(!Ue.existsSync(r)){t.warn?.(`Source directory not found at ${r}. Skipping formatting.`);return}t.debug?.(`Formatting TypeScript files in ${r}...`);let{stdout:s,stderr:n}=await Be('npx --yes prettier --write "src/**/*.{ts,tsx}"',{cwd:o,maxBuffer:10*1024*1024});s&&t.debug?.(s),n&&!n.includes("warning")&&t.warn?.(n),t.debug?.("Code formatting completed successfully.")}catch(r){let s=r instanceof Error?r.message:String(r);t.warn?.(`Failed to format code with Prettier: ${s}. Generated code will not be formatted.`)}}f(Ve,"formatWithPrettier");function mt(o,e,t,r){var s=arguments.length,n=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,e,t,r);else for(var i=o.length-1;i>=0;i--)(a=o[i])&&(n=(s<3?a(n):s>3?a(e,t,n):a(e,t))||n);return s>3&&n&&Object.defineProperty(e,t,n),n}f(mt,"_ts_decorate");function We(o,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,e)}f(We,"_ts_metadata");var H=class o{static{f(this,"TypeScriptGeneratorService")}configService;logger=new ne.Logger(o.name);constructor(e){this.configService=e}getType(){return"typescript"}async generate(e,t){if(!e.defaultBaseURL&&t.openApiDocument?.servers){let i=t.openApiDocument.servers;Array.isArray(i)&&i.length>0&&(e.defaultBaseURL=i[0].url||"")}let r=T.join(e.outDir,"src"),s=T.join(r,"services");await S.promises.mkdir(s,{recursive:!0});let n=await this.preprocessIR(e,t);this.registerHandlebarsHelpers(e),await this.generateClient(e,n,r),await this.generateIndex(e,n,r),await this.generateUtils(e,n,r),await this.generateServices(e,n,s),await this.generateSchema(e,n,r),await this.generateZodSchema(e,n,r),await this.generatePackageJson(e),await this.generateTsConfig(e),await this.generateReadme(e,n),e.formatCode!==!1?(await this.generatePrettierConfig(e),this.logger.debug("Formatting generated TypeScript files with Prettier..."),await Ve(e.outDir,this.logger)):this.logger.debug("Code formatting is disabled for this client.")}async preprocessIR(e,t){let r=await Promise.all(t.services.map(async s=>({...s,operations:await Promise.all(s.operations.map(async n=>{let a=await $e(e,n);return{...n,_resolvedMethodName:a}}))})));return{...t,services:r}}registerHandlebarsHelpers(e){Ce(),d.registerHelper("methodName",t=>t._resolvedMethodName||M(t)),d.registerHelper("queryTypeName",t=>{let r=t._resolvedMethodName||M(t);return k(t.tag)+k(r)+"Query"}),d.registerHelper("pathTemplate",t=>{let r=Ie(t);return new d.SafeString(r)}),d.registerHelper("queryKeyBase",t=>{let r=Ae(t);return new d.SafeString(r)}),d.registerHelper("pathParamsInOrder",t=>re(t)),d.registerHelper("methodSignature",(t,r)=>{let s=t._resolvedMethodName||M(t),n=r?.data?.root?.IR?.modelDefs||[],a=r?.data?.root?.PredefinedTypes||[],i=r?.data?.root?.isSameFile||!1;return pe(t,s,n,a,i).map(p=>new d.SafeString(p))}),d.registerHelper("methodSignatureNoInit",(t,r)=>{let s=t._resolvedMethodName||M(t),n=r?.data?.root?.IR?.modelDefs||[],a=r?.data?.root?.PredefinedTypes||[],i=r?.data?.root?.isSameFile||!1;return pe(t,s,n,a,i).slice(0,-1)}),d.registerHelper("queryKeyArgs",t=>Ne(t).map(s=>new d.SafeString(s))),d.registerHelper("tsType",(t,r)=>{if(t&&typeof t=="object"&&"kind"in t){let s=r?.data?.root?.PredefinedTypes||[],n=r?.data?.root?.IR?.modelDefs||[],a=r?.data?.root?.isSameFile||!1;return C(t,s,n,a)}return"unknown"}),d.registerHelper("stripSchemaNs",t=>t.replace(/^Schema\./,"")),d.registerHelper("tsTypeStripNs",(t,r)=>{let s=r?.data?.root?.PredefinedTypes||[],n=r?.data?.root?.IR?.modelDefs||[],a=r?.data?.root?.isSameFile||!1;if(t&&typeof t=="object"&&"kind"in t){let c=C(t,s,n,a).replace(/Schema\./g,"");return new d.SafeString(c)}if(typeof t=="string"){if(t.startsWith("Schema.")){let i=t.replace(/^Schema\./,"");return s.find(p=>p.type===i)?new d.SafeString(i):new d.SafeString(i)}return new d.SafeString(t)}return"unknown"}),d.registerHelper("isPredefinedType",(t,r)=>(r?.data?.root?.PredefinedTypes||[]).some(n=>n.type===t)),d.registerHelper("getPredefinedType",(t,r)=>(r?.data?.root?.PredefinedTypes||[]).find(n=>n.type===t)),d.registerHelper("groupByPackage",t=>{let r={};for(let s of t||[])r[s.package]||(r[s.package]={package:s.package,types:[]}),r[s.package].types.push(s.type);return Object.values(r)}),d.registerHelper("getServicePredefinedTypes",(t,r)=>{let s=r?.data?.root?.PredefinedTypes||[],n=r?.data?.root?.IR?.modelDefs||[];return Ee(t,s,n)}),d.registerHelper("getSchemaPredefinedTypes",t=>{let r=t?.data?.root?.PredefinedTypes||[],s=t?.data?.root?.IR?.modelDefs||[];return qe(s,r)}),d.registerHelper("joinTypes",t=>t.join(", ")),d.registerHelper("uniquePackages",t=>{let r=new Set;for(let s of t||[])s.package&&r.add(s.package);return Array.from(r)}),d.registerHelper("isPredefinedPackage",(t,r)=>r?r.some(s=>s.package===t):!1),d.registerHelper("getAllDependencies",t=>{let r={"@blimu/fetch":"^0.2.0",zod:"^4.3.5"};if(t.predefinedTypes)for(let s of t.predefinedTypes)s.package&&!r[s.package]&&(r[s.package]=t.dependencies?.[s.package]||"*");if(t.dependencies)for(let[s,n]of Object.entries(t.dependencies))s!=="zod"&&!r[s]&&(r[s]=n);return r}),d.registerHelper("decodeHtml",t=>{if(typeof t!="string")return t;let r=t.replace(/&amp;#x60;/g,"&#x60;").replace(/&amp;#96;/g,"&#96;").replace(/&amp;quot;/g,"&quot;").replace(/&amp;lt;/g,"&lt;").replace(/&amp;gt;/g,"&gt;");return r=r.replace(/&quot;/g,'"').replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&#x60;/g,"`").replace(/&#96;/g,"`").replace(/&amp;/g,"&"),new d.SafeString(r)}),d.registerHelper("quotePropName",t=>Z(t)),d.registerHelper("zodSchema",(t,r)=>{if(t&&typeof t=="object"&&"kind"in t){let s=r?.data?.root?.IR?.modelDefs||[],n=r?.data?.root?._templateName==="schema.zod.ts.hbs";return new d.SafeString(A(t,"",s,n))}return"z.unknown()"}),d.registerHelper("isStreaming",t=>Fe(t)),d.registerHelper("streamingItemType",t=>new d.SafeString(De(t)))}async renderTemplate(e,t,r,s){let n=s.templates?.[e];if(n){this.logger.debug(`Using template override for ${e}: ${n}`);try{await S.promises.access(n,S.constants.R_OK);let h=await S.promises.readFile(n,"utf-8"),b=d.compile(h),q={...t,_templateName:e},F=b(q);await S.promises.writeFile(r,F,"utf-8");return}catch(h){let b=h instanceof Error?h.message:String(h);throw this.logger.error(`Template override file not found or not readable: ${n}. Error: ${b}`),new Error(`Template override file not found or not readable: ${n}`)}}let a=[T.join(__dirname,"generator/typescript/templates",e),T.join(__dirname,"templates",e),T.join(__dirname,"../typescript/templates",e),T.join(process.cwd(),"src/generator/typescript/templates",e)],i=null;for(let h of a)try{await S.promises.access(h),i=h,this.logger.debug(`Found template at: ${i}`);break}catch{this.logger.debug(`Template not found at: ${h}`)}if(!i)throw this.logger.error(`Template not found: ${e}`),this.logger.error(`Checked paths: ${a.join(", ")}`),this.logger.error(`__dirname: ${__dirname}`),new Error(`Template not found: ${e}`);let c=await S.promises.readFile(i,"utf-8"),p=d.compile(c),u={...t,_templateName:e},y=p(u);await S.promises.writeFile(r,y,"utf-8")}async generateClient(e,t,r){let s=T.join(r,"client.ts");if(!this.configService.shouldExcludeFile(e,s))try{await this.renderTemplate("client.ts.hbs",{Client:e,IR:t},s,e)}catch(n){let a=n instanceof Error?n.message:String(n);this.logger.warn(`Template client.ts.hbs not found: ${a}, using placeholder`),await S.promises.writeFile(s,"// Generated client - template rendering to be implemented","utf-8")}}async generateIndex(e,t,r){let s=T.join(r,"index.ts");if(!this.configService.shouldExcludeFile(e,s))try{await this.renderTemplate("index.ts.hbs",{Client:e,IR:t},s,e)}catch{this.logger.warn("Template index.ts.hbs not found, using placeholder"),await S.promises.writeFile(s,"// Generated index - template rendering to be implemented","utf-8")}}async generateUtils(e,t,r){let s=T.join(r,"utils.ts");if(!this.configService.shouldExcludeFile(e,s))try{await this.renderTemplate("utils.ts.hbs",{Client:e,IR:t},s,e)}catch{this.logger.warn("Template utils.ts.hbs not found, using placeholder"),await S.promises.writeFile(s,"// Generated utils - template rendering to be implemented","utf-8")}}async generateServices(e,t,r){for(let s of t.services){let n=T.join(r,`${L(s.tag).toLowerCase()}.ts`);if(!this.configService.shouldExcludeFile(e,n))try{await this.renderTemplate("service.ts.hbs",{Client:e,Service:s,IR:t,PredefinedTypes:e.predefinedTypes||[],isSameFile:!1},n,e)}catch{this.logger.warn("Template service.ts.hbs not found, using placeholder");let i=`// Generated service ${s.tag} - template rendering to be implemented`;await S.promises.writeFile(n,i,"utf-8")}}}async generateSchema(e,t,r){let s=T.join(r,"schema.ts");if(!this.configService.shouldExcludeFile(e,s))try{await this.renderTemplate("schema.ts.hbs",{Client:e,IR:t,PredefinedTypes:e.predefinedTypes||[],isSameFile:!0},s,e)}catch(n){let a=n instanceof Error?n.message:String(n);this.logger.warn(`Template schema.ts.hbs error: ${a}, using placeholder`),await S.promises.writeFile(s,"// Generated schema - template rendering to be implemented","utf-8")}}async generateZodSchema(e,t,r){let s=T.join(r,"schema.zod.ts");if(!this.configService.shouldExcludeFile(e,s))try{await this.renderTemplate("schema.zod.ts.hbs",{Client:e,IR:t},s,e)}catch(n){let a=n instanceof Error?n.message:String(n);this.logger.warn(`Template schema.zod.ts.hbs error: ${a}, using placeholder`),await S.promises.writeFile(s,"// Generated Zod schemas - template rendering to be implemented","utf-8")}}async generatePackageJson(e){let t=T.join(e.outDir,"package.json");if(!this.configService.shouldExcludeFile(e,t))try{await this.renderTemplate("package.json.hbs",{Client:e},t,e)}catch{this.logger.warn("Template package.json.hbs not found, using fallback");let s=JSON.stringify({name:e.packageName,version:"0.0.1",main:"dist/index.js",types:"dist/index.d.ts"},null,2);await S.promises.writeFile(t,s,"utf-8")}}async generateTsConfig(e){let t=T.join(e.outDir,"tsconfig.json");if(!this.configService.shouldExcludeFile(e,t))try{await this.renderTemplate("tsconfig.json.hbs",{Client:e},t,e)}catch{this.logger.warn("Template tsconfig.json.hbs not found, using fallback");let s=JSON.stringify({compilerOptions:{target:"ES2020",module:"commonjs",lib:["ES2020"],declaration:!0,outDir:"./dist",rootDir:"./src",strict:!0,esModuleInterop:!0,skipLibCheck:!0,forceConsistentCasingInFileNames:!0},include:["src/**/*"]},null,2);await S.promises.writeFile(t,s,"utf-8")}}async generateReadme(e,t){let r=T.join(e.outDir,"README.md");if(!this.configService.shouldExcludeFile(e,r))try{await this.renderTemplate("README.md.hbs",{Client:e,IR:t},r,e)}catch{this.logger.warn("Template README.md.hbs not found, using fallback");let n=`# ${e.name}
4
+ ${e}})`;if(o.additionalProperties){let c=A(o.additionalProperties,s,t,r);n=`${i}.catchall(${c})`}else n=i}break;case l.Enum:o.enumValues&&o.enumValues.length>0?n=`z.enum([${o.enumValues.map(i=>i==="true"||i==="false"||/^-?[0-9]+(\.[0-9]+)?$/.test(i)?i:JSON.stringify(i)).join(", ")}])`:n="z.string()";break;case l.OneOf:o.oneOf&&o.oneOf.length>0?n=`z.union([${o.oneOf.map(i=>A(i,s,t,r)).join(", ")}])`:n="z.unknown()";break;case l.AnyOf:o.anyOf&&o.anyOf.length>0?n=`z.union([${o.anyOf.map(i=>A(i,s,t,r)).join(", ")}])`:n="z.unknown()";break;case l.AllOf:if(o.allOf&&o.allOf.length>0){let a=o.allOf.map(i=>A(i,s,t,r));n=a.join(".and(")+")".repeat(a.length-1)}else n="z.unknown()";break;default:n="z.unknown()"}return o.nullable&&n!=="z.null()"&&(n=`${n}.nullable()`),n}f(A,"schemaToZodSchema");var _e=require("child_process"),Me=require("util"),ze=O(require("path")),Ue=O(require("fs"));var Be=(0,Me.promisify)(_e.exec);async function Ve(o,e){let t=e||console;try{try{await Be("npx --yes prettier --version",{cwd:o,maxBuffer:10*1024*1024})}catch{t.warn?.("Prettier is not available. Skipping code formatting. Install prettier to enable formatting.");return}let r=ze.join(o,"src");if(!Ue.existsSync(r)){t.warn?.(`Source directory not found at ${r}. Skipping formatting.`);return}let{stdout:s,stderr:n}=await Be('npx --yes prettier --write --loglevel=error "src/**/*.{ts,tsx}"',{cwd:o,maxBuffer:10*1024*1024});n&&!n.includes("warning")&&t.warn?.(n)}catch(r){let s=r instanceof Error?r.message:String(r);t.warn?.(`Failed to format code with Prettier: ${s}. Generated code will not be formatted.`)}}f(Ve,"formatWithPrettier");function gt(o,e,t,r){var s=arguments.length,n=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,e,t,r);else for(var i=o.length-1;i>=0;i--)(a=o[i])&&(n=(s<3?a(n):s>3?a(e,t,n):a(e,t))||n);return s>3&&n&&Object.defineProperty(e,t,n),n}f(gt,"_ts_decorate");function We(o,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,e)}f(We,"_ts_metadata");var H=class o{static{f(this,"TypeScriptGeneratorService")}configService;logger=new ne.Logger(o.name);constructor(e){this.configService=e}getType(){return"typescript"}async generate(e,t){if(!e.defaultBaseURL&&t.openApiDocument?.servers){let i=t.openApiDocument.servers;Array.isArray(i)&&i.length>0&&(e.defaultBaseURL=i[0].url||"")}let r=T.join(e.outDir,"src"),s=T.join(r,"services");await w.promises.mkdir(s,{recursive:!0});let n=await this.preprocessIR(e,t);this.registerHandlebarsHelpers(e),await this.generateClient(e,n,r),await this.generateIndex(e,n,r),await this.generateUtils(e,n,r),await this.generateServices(e,n,s),await this.generateSchema(e,n,r),await this.generateZodSchema(e,n,r),await this.generatePackageJson(e),await this.generateTsConfig(e),await this.generateTsupConfig(e),await this.generateReadme(e,n),e.formatCode!==!1?(await this.generatePrettierConfig(e),this.logger.debug("Formatting generated TypeScript files with Prettier..."),await Ve(e.outDir,this.logger)):this.logger.debug("Code formatting is disabled for this client.")}async preprocessIR(e,t){let r=await Promise.all(t.services.map(async s=>({...s,operations:await Promise.all(s.operations.map(async n=>{let a=await $e(e,n);return{...n,_resolvedMethodName:a}}))})));return{...t,services:r}}registerHandlebarsHelpers(e){Re(),h.registerHelper("methodName",t=>t._resolvedMethodName||z(t)),h.registerHelper("queryTypeName",t=>{let r=t._resolvedMethodName||z(t);return k(t.tag)+k(r)+"Query"}),h.registerHelper("pathTemplate",t=>{let r=Ie(t);return new h.SafeString(r)}),h.registerHelper("queryKeyBase",t=>{let r=Ae(t);return new h.SafeString(r)}),h.registerHelper("pathParamsInOrder",t=>re(t)),h.registerHelper("methodSignature",(t,r)=>{let s=t._resolvedMethodName||z(t),n=r?.data?.root?.IR?.modelDefs||[],a=r?.data?.root?.PredefinedTypes||[],i=r?.data?.root?.isSameFile||!1;return pe(t,s,n,a,i).map(p=>new h.SafeString(p))}),h.registerHelper("methodSignatureNoInit",(t,r)=>{let s=t._resolvedMethodName||z(t),n=r?.data?.root?.IR?.modelDefs||[],a=r?.data?.root?.PredefinedTypes||[],i=r?.data?.root?.isSameFile||!1;return pe(t,s,n,a,i).slice(0,-1)}),h.registerHelper("queryKeyArgs",t=>Fe(t).map(s=>new h.SafeString(s))),h.registerHelper("tsType",(t,r)=>{if(t&&typeof t=="object"&&"kind"in t){let s=r?.data?.root?.PredefinedTypes||[],n=r?.data?.root?.IR?.modelDefs||[],a=r?.data?.root?.isSameFile||!1;return R(t,s,n,a)}return"unknown"}),h.registerHelper("stripSchemaNs",t=>t.replace(/^Schema\./,"")),h.registerHelper("tsTypeStripNs",(t,r)=>{let s=r?.data?.root?.PredefinedTypes||[],n=r?.data?.root?.IR?.modelDefs||[],a=r?.data?.root?.isSameFile||!1;if(t&&typeof t=="object"&&"kind"in t){let c=R(t,s,n,a).replace(/Schema\./g,"");return new h.SafeString(c)}if(typeof t=="string"){if(t.startsWith("Schema.")){let i=t.replace(/^Schema\./,"");return s.find(p=>p.type===i)?new h.SafeString(i):new h.SafeString(i)}return new h.SafeString(t)}return"unknown"}),h.registerHelper("isPredefinedType",(t,r)=>(r?.data?.root?.PredefinedTypes||[]).some(n=>n.type===t)),h.registerHelper("getPredefinedType",(t,r)=>(r?.data?.root?.PredefinedTypes||[]).find(n=>n.type===t)),h.registerHelper("groupByPackage",t=>{let r={};for(let s of t||[])r[s.package]||(r[s.package]={package:s.package,types:[]}),r[s.package].types.push(s.type);return Object.values(r)}),h.registerHelper("getServicePredefinedTypes",(t,r)=>{let s=r?.data?.root?.PredefinedTypes||[],n=r?.data?.root?.IR?.modelDefs||[];return Ee(t,s,n)}),h.registerHelper("getSchemaPredefinedTypes",t=>{let r=t?.data?.root?.PredefinedTypes||[],s=t?.data?.root?.IR?.modelDefs||[];return qe(s,r)}),h.registerHelper("joinTypes",t=>t.join(", ")),h.registerHelper("uniquePackages",t=>{let r=new Set;for(let s of t||[])s.package&&r.add(s.package);return Array.from(r)}),h.registerHelper("isPredefinedPackage",(t,r)=>r?r.some(s=>s.package===t):!1),h.registerHelper("getAllDependencies",t=>{let r={"@blimu/fetch":"^0.2.0",zod:"^4.3.5"};if(t.predefinedTypes)for(let s of t.predefinedTypes)s.package&&!r[s.package]&&(r[s.package]=t.dependencies?.[s.package]||"*");if(t.dependencies)for(let[s,n]of Object.entries(t.dependencies))s!=="zod"&&!r[s]&&(r[s]=n);return r}),h.registerHelper("decodeHtml",t=>{if(typeof t!="string")return t;let r=t.replace(/&amp;#x60;/g,"&#x60;").replace(/&amp;#96;/g,"&#96;").replace(/&amp;quot;/g,"&quot;").replace(/&amp;lt;/g,"&lt;").replace(/&amp;gt;/g,"&gt;");return r=r.replace(/&quot;/g,'"').replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&#x60;/g,"`").replace(/&#96;/g,"`").replace(/&amp;/g,"&"),new h.SafeString(r)}),h.registerHelper("quotePropName",t=>Z(t)),h.registerHelper("zodSchema",(t,r)=>{if(t&&typeof t=="object"&&"kind"in t){let s=r?.data?.root?.IR?.modelDefs||[],n=r?.data?.root?._templateName==="schema.zod.ts.hbs";return new h.SafeString(A(t,"",s,n))}return"z.unknown()"}),h.registerHelper("isStreaming",t=>Ne(t)),h.registerHelper("streamingItemType",t=>new h.SafeString(De(t)))}async renderTemplate(e,t,r,s){let n=s.templates?.[e];if(n){this.logger.debug(`Using template override for ${e}: ${n}`);try{await w.promises.access(n,w.constants.R_OK);let m=await w.promises.readFile(n,"utf-8"),b=h.compile(m),q={...t,_templateName:e},N=b(q);await w.promises.writeFile(r,N,"utf-8");return}catch(m){let b=m instanceof Error?m.message:String(m);throw this.logger.error(`Template override file not found or not readable: ${n}. Error: ${b}`),new Error(`Template override file not found or not readable: ${n}`)}}let a=[T.join(__dirname,"generator/typescript/templates",e),T.join(__dirname,"templates",e),T.join(__dirname,"../typescript/templates",e),T.join(process.cwd(),"src/generator/typescript/templates",e)],i=null;for(let m of a)try{await w.promises.access(m),i=m,this.logger.debug(`Found template at: ${i}`);break}catch{this.logger.debug(`Template not found at: ${m}`)}if(!i)throw this.logger.error(`Template not found: ${e}`),this.logger.error(`Checked paths: ${a.join(", ")}`),this.logger.error(`__dirname: ${__dirname}`),new Error(`Template not found: ${e}`);let c=await w.promises.readFile(i,"utf-8"),p=h.compile(c),u={...t,_templateName:e},y=p(u);await w.promises.writeFile(r,y,"utf-8")}async generateClient(e,t,r){let s=T.join(r,"client.ts");if(!this.configService.shouldExcludeFile(e,s))try{await this.renderTemplate("client.ts.hbs",{Client:e,IR:t},s,e)}catch(n){let a=n instanceof Error?n.message:String(n);this.logger.warn(`Template client.ts.hbs not found: ${a}, using placeholder`),await w.promises.writeFile(s,"// Generated client - template rendering to be implemented","utf-8")}}async generateIndex(e,t,r){let s=T.join(r,"index.ts");if(!this.configService.shouldExcludeFile(e,s))try{await this.renderTemplate("index.ts.hbs",{Client:e,IR:t},s,e)}catch{this.logger.warn("Template index.ts.hbs not found, using placeholder"),await w.promises.writeFile(s,"// Generated index - template rendering to be implemented","utf-8")}}async generateUtils(e,t,r){let s=T.join(r,"utils.ts");if(!this.configService.shouldExcludeFile(e,s))try{await this.renderTemplate("utils.ts.hbs",{Client:e,IR:t},s,e)}catch{this.logger.warn("Template utils.ts.hbs not found, using placeholder"),await w.promises.writeFile(s,"// Generated utils - template rendering to be implemented","utf-8")}}async generateServices(e,t,r){for(let s of t.services){let n=T.join(r,`${L(s.tag).toLowerCase()}.ts`);if(!this.configService.shouldExcludeFile(e,n))try{await this.renderTemplate("service.ts.hbs",{Client:e,Service:s,IR:t,PredefinedTypes:e.predefinedTypes||[],isSameFile:!1},n,e)}catch{this.logger.warn("Template service.ts.hbs not found, using placeholder");let i=`// Generated service ${s.tag} - template rendering to be implemented`;await w.promises.writeFile(n,i,"utf-8")}}}async generateSchema(e,t,r){let s=T.join(r,"schema.ts");if(!this.configService.shouldExcludeFile(e,s))try{await this.renderTemplate("schema.ts.hbs",{Client:e,IR:t,PredefinedTypes:e.predefinedTypes||[],isSameFile:!0},s,e)}catch(n){let a=n instanceof Error?n.message:String(n);this.logger.warn(`Template schema.ts.hbs error: ${a}, using placeholder`),await w.promises.writeFile(s,"// Generated schema - template rendering to be implemented","utf-8")}}async generateZodSchema(e,t,r){let s=T.join(r,"schema.zod.ts");if(!this.configService.shouldExcludeFile(e,s))try{await this.renderTemplate("schema.zod.ts.hbs",{Client:e,IR:t},s,e)}catch(n){let a=n instanceof Error?n.message:String(n);this.logger.warn(`Template schema.zod.ts.hbs error: ${a}, using placeholder`),await w.promises.writeFile(s,"// Generated Zod schemas - template rendering to be implemented","utf-8")}}async generatePackageJson(e){let t=T.join(e.outDir,"package.json");if(!this.configService.shouldExcludeFile(e,t))try{await this.renderTemplate("package.json.hbs",{Client:e},t,e)}catch{this.logger.warn("Template package.json.hbs not found, using fallback");let s=JSON.stringify({name:e.packageName,version:"0.0.1",main:"dist/index.js",types:"dist/index.d.ts"},null,2);await w.promises.writeFile(t,s,"utf-8")}}async generateTsConfig(e){let t=T.join(e.outDir,"tsconfig.json");if(!this.configService.shouldExcludeFile(e,t))try{await this.renderTemplate("tsconfig.json.hbs",{Client:e},t,e)}catch{this.logger.warn("Template tsconfig.json.hbs not found, using fallback");let s=JSON.stringify({compilerOptions:{target:"ES2020",module:"commonjs",lib:["ES2020"],declaration:!0,outDir:"./dist",rootDir:"./src",strict:!0,esModuleInterop:!0,skipLibCheck:!0,forceConsistentCasingInFileNames:!0},include:["src/**/*"]},null,2);await w.promises.writeFile(t,s,"utf-8")}}async generateTsupConfig(e){let t=T.join(e.outDir,"tsup.config.ts");if(!this.configService.shouldExcludeFile(e,t))try{await this.renderTemplate("tsup.config.ts.hbs",{Client:e},t,e)}catch{this.logger.warn("Template tsup.config.ts.hbs not found, using fallback"),await w.promises.writeFile(t,`import { defineConfig } from "tsup";
5
5
 
6
- Generated SDK from OpenAPI specification.`;await S.promises.writeFile(r,n,"utf-8")}}async generatePrettierConfig(e){let t=T.join(e.outDir,".prettierrc");if(!this.configService.shouldExcludeFile(e,t))try{await this.renderTemplate(".prettierrc.hbs",{Client:e},t,e)}catch{this.logger.warn("Template .prettierrc.hbs not found, using fallback");let s=JSON.stringify({semi:!0,trailingComma:"es5",singleQuote:!0,printWidth:80,tabWidth:2,useTabs:!1},null,2);await S.promises.writeFile(t,s,"utf-8")}}};H=mt([(0,ne.Injectable)(),We("design:type",Function),We("design:paramtypes",[typeof v>"u"?Object:v])],H);function dt(o,e,t,r){var s=arguments.length,n=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,e,t,r);else for(var i=o.length-1;i>=0;i--)(a=o[i])&&(n=(s<3?a(n):s>3?a(e,t,n):a(e,t))||n);return s>3&&n&&Object.defineProperty(e,t,n),n}f(dt,"_ts_decorate");function Ge(o,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,e)}f(Ge,"_ts_metadata");var J=class{static{f(this,"GeneratorModule")}generatorService;typeScriptGenerator;constructor(e,t){this.generatorService=e,this.typeScriptGenerator=t,this.generatorService.register(this.typeScriptGenerator)}};J=dt([(0,Le.Module)({imports:[B,D],providers:[R,j,P,H],exports:[R,j,P]}),Ge("design:type",Function),Ge("design:paramtypes",[typeof R>"u"?Object:R,typeof H>"u"?Object:H])],J);var N=O(require("path")),Ze=O(require("fs"));async function ht(o,e){let t,r;if(typeof o=="string"){let u=N.isAbsolute(o)?o:N.resolve(o);t=await z(u),r=e?.baseDir??N.dirname(u)}else t=o,r=e?.baseDir;let s=new v,n=new x,a=new P,i=new j(a),c=new R(i,n),p=new H(s);c.register(p);for(let u of t.clients){if(e?.client&&u.name!==e.client)continue;let y=r?N.resolve(r,u.outDir):N.resolve(u.outDir);await Ze.promises.mkdir(y,{recursive:!0});let h={...u,outDir:y};await c.generate(t.spec,h)}}f(ht,"generate");async function gt(o){return z(o)}f(gt,"loadConfig");0&&(module.exports={ClientSchema,ConfigModule,ConfigSchema,ConfigService,GeneratorModule,GeneratorService,IRSchemaKind,OpenApiModule,OpenApiService,PredefinedTypeSchema,TYPESCRIPT_TEMPLATE_NAMES,TypeScriptClientSchema,defineConfig,generate,loadConfig,loadMjsConfig});
6
+ export default defineConfig({
7
+ entry: ["src/**/*.ts"],
8
+ format: ["cjs", "esm"],
9
+ dts: {
10
+ resolve: true,
11
+ },
12
+ splitting: false,
13
+ sourcemap: true,
14
+ clean: true,
15
+ outDir: "dist",
16
+ tsconfig: "./tsconfig.json",
17
+ external: [],
18
+ });
19
+ `,"utf-8")}}async generateReadme(e,t){let r=T.join(e.outDir,"README.md");if(!this.configService.shouldExcludeFile(e,r))try{await this.renderTemplate("README.md.hbs",{Client:e,IR:t},r,e)}catch{this.logger.warn("Template README.md.hbs not found, using fallback");let n=`# ${e.name}
20
+
21
+ Generated SDK from OpenAPI specification.`;await w.promises.writeFile(r,n,"utf-8")}}async generatePrettierConfig(e){let t=T.join(e.outDir,".prettierrc");if(!this.configService.shouldExcludeFile(e,t))try{await this.renderTemplate(".prettierrc.hbs",{Client:e},t,e)}catch{this.logger.warn("Template .prettierrc.hbs not found, using fallback");let s=JSON.stringify({semi:!0,trailingComma:"es5",singleQuote:!0,printWidth:80,tabWidth:2,useTabs:!1},null,2);await w.promises.writeFile(t,s,"utf-8")}}};H=gt([(0,ne.Injectable)(),We("design:type",Function),We("design:paramtypes",[typeof v>"u"?Object:v])],H);function yt(o,e,t,r){var s=arguments.length,n=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,a;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,e,t,r);else for(var i=o.length-1;i>=0;i--)(a=o[i])&&(n=(s<3?a(n):s>3?a(e,t,n):a(e,t))||n);return s>3&&n&&Object.defineProperty(e,t,n),n}f(yt,"_ts_decorate");function Ge(o,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,e)}f(Ge,"_ts_metadata");var J=class{static{f(this,"GeneratorModule")}generatorService;typeScriptGenerator;constructor(e,t){this.generatorService=e,this.typeScriptGenerator=t,this.generatorService.register(this.typeScriptGenerator)}};J=yt([(0,Le.Module)({imports:[B,D],providers:[C,j,P,H],exports:[C,j,P]}),Ge("design:type",Function),Ge("design:paramtypes",[typeof C>"u"?Object:C,typeof H>"u"?Object:H])],J);var F=O(require("path")),Ze=O(require("fs")),Je=require("child_process"),Ke=require("util");var bt=(0,Ke.promisify)(Je.exec);async function wt(o,e){let t,r;if(typeof o=="string"){let u=F.isAbsolute(o)?o:F.resolve(o);t=await M(u),r=e?.baseDir??F.dirname(u)}else t=o,r=e?.baseDir;let s=new v,n=new x,a=new P,i=new j(a),c=new C(i,n),p=new H(s);c.register(p);for(let u of t.clients){if(e?.client&&u.name!==e.client)continue;let y=r?F.resolve(r,u.outDir):F.resolve(u.outDir);await Ze.promises.mkdir(y,{recursive:!0});let m={...u,outDir:y};await St(s,m),await c.generate(t.spec,m),await Tt(s,m)}}f(wt,"generate");async function St(o,e){let t=o.getPreCommand(e);t.length!==0&&await Qe(t,e.outDir,"pre-command")}f(St,"executePreCommands");async function Tt(o,e){let t=o.getPostCommand(e);t.length!==0&&await Qe(t,e.outDir,"post-command")}f(Tt,"executePostCommands");async function Qe(o,e,t){try{let[r,...s]=o,{stdout:n,stderr:a}=await bt(`${r} ${s.map(i=>`"${i}"`).join(" ")}`,{cwd:e,maxBuffer:10*1024*1024});n&&console.debug(`[${t}] ${n}`),a&&!a.includes("warning")&&console.warn(`[${t}] ${a}`)}catch(r){let s=r instanceof Error?r.message:String(r);throw new Error(`${t} failed: ${s}`)}}f(Qe,"executeCommand");async function Ot(o){return M(o)}f(Ot,"loadConfig");0&&(module.exports={ClientSchema,ConfigModule,ConfigSchema,ConfigService,GeneratorModule,GeneratorService,IRSchemaKind,OpenApiModule,OpenApiService,PredefinedTypeSchema,TYPESCRIPT_TEMPLATE_NAMES,TypeScriptClientSchema,defineConfig,generate,loadConfig,loadMjsConfig});
7
22
  //# sourceMappingURL=index.js.map