@blimu/codegen 0.1.1 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/generator/typescript/templates/.prettierrc.hbs +8 -0
- package/dist/generator/typescript/templates/README.md.hbs +10 -7
- package/dist/generator/typescript/templates/client.ts.hbs +108 -332
- package/dist/generator/typescript/templates/index.ts.hbs +4 -2
- package/dist/generator/typescript/templates/package.json.hbs +13 -7
- package/dist/generator/typescript/templates/schema.zod.ts.hbs +7 -7
- package/dist/generator/typescript/templates/service.ts.hbs +2 -34
- package/dist/generator/typescript/templates/utils.ts.hbs +4 -136
- package/dist/index.d.mts +4 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +4 -4
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +4 -4
- package/dist/index.mjs.map +1 -1
- package/dist/main.js +3 -3
- package/dist/main.js.map +1 -1
- package/package.json +8 -6
|
@@ -38,23 +38,7 @@ export class {{serviceName Service.tag}} {
|
|
|
38
38
|
query,
|
|
39
39
|
{{/if}}
|
|
40
40
|
{{#if requestBody}}
|
|
41
|
-
|
|
42
|
-
headers: {
|
|
43
|
-
...(init?.headers || {}),
|
|
44
|
-
"content-type": "application/json",
|
|
45
|
-
},
|
|
46
|
-
body: JSON.stringify(body),
|
|
47
|
-
{{else if (eq requestBody.contentType "multipart/form-data")}}
|
|
48
|
-
body: (body as any),
|
|
49
|
-
{{else if (eq requestBody.contentType "application/x-www-form-urlencoded")}}
|
|
50
|
-
headers: {
|
|
51
|
-
...(init?.headers || {}),
|
|
52
|
-
"content-type": "application/x-www-form-urlencoded",
|
|
53
|
-
},
|
|
54
|
-
body: (body as any),
|
|
55
|
-
{{else}}
|
|
56
|
-
body: (body as any),
|
|
57
|
-
{{/if}}
|
|
41
|
+
body: body as any,
|
|
58
42
|
{{/if}}
|
|
59
43
|
contentType: "{{response.contentType}}",
|
|
60
44
|
streamingFormat: "{{response.streamingFormat}}",
|
|
@@ -74,23 +58,7 @@ export class {{serviceName Service.tag}} {
|
|
|
74
58
|
query,
|
|
75
59
|
{{/if}}
|
|
76
60
|
{{#if requestBody}}
|
|
77
|
-
|
|
78
|
-
headers: {
|
|
79
|
-
...(init?.headers || {}),
|
|
80
|
-
"content-type": "application/json",
|
|
81
|
-
},
|
|
82
|
-
body: JSON.stringify(body),
|
|
83
|
-
{{else if (eq requestBody.contentType "multipart/form-data")}}
|
|
84
|
-
body: (body as any),
|
|
85
|
-
{{else if (eq requestBody.contentType "application/x-www-form-urlencoded")}}
|
|
86
|
-
headers: {
|
|
87
|
-
...(init?.headers || {}),
|
|
88
|
-
"content-type": "application/x-www-form-urlencoded",
|
|
89
|
-
},
|
|
90
|
-
body: (body as any),
|
|
91
|
-
{{else}}
|
|
92
|
-
body: (body as any),
|
|
93
|
-
{{/if}}
|
|
61
|
+
body: body as any,
|
|
94
62
|
{{/if}}
|
|
95
63
|
...(init || {}),
|
|
96
64
|
});
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { parseSSEStream, parseNDJSONStream } from "@blimu/fetch";
|
|
2
|
+
|
|
1
3
|
export type PaginableQuery = { limit?: number; offset?: number } & Record<string, unknown>;
|
|
2
4
|
|
|
3
5
|
export async function* paginate<T>(
|
|
@@ -30,139 +32,5 @@ export async function listAll<T>(
|
|
|
30
32
|
return out;
|
|
31
33
|
}
|
|
32
34
|
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
* Extracts data fields from text/event-stream format
|
|
36
|
-
*/
|
|
37
|
-
export async function* parseSSEStream(
|
|
38
|
-
response: Response
|
|
39
|
-
): AsyncGenerator<string, void, unknown> {
|
|
40
|
-
if (!response.body) {
|
|
41
|
-
return;
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
const reader = response.body.getReader();
|
|
45
|
-
const decoder = new TextDecoder();
|
|
46
|
-
let buffer = "";
|
|
47
|
-
|
|
48
|
-
try {
|
|
49
|
-
while (true) {
|
|
50
|
-
const { done, value } = await reader.read();
|
|
51
|
-
if (done) break;
|
|
52
|
-
|
|
53
|
-
buffer += decoder.decode(value, { stream: true });
|
|
54
|
-
const lines = buffer.split("\n");
|
|
55
|
-
buffer = lines.pop() || ""; // Keep incomplete line in buffer
|
|
56
|
-
|
|
57
|
-
let currentEvent: { type?: string; data?: string; id?: string } = {};
|
|
58
|
-
|
|
59
|
-
for (const line of lines) {
|
|
60
|
-
if (line.trim() === "") {
|
|
61
|
-
// Empty line indicates end of event
|
|
62
|
-
if (currentEvent.data !== undefined) {
|
|
63
|
-
yield currentEvent.data;
|
|
64
|
-
}
|
|
65
|
-
currentEvent = {};
|
|
66
|
-
continue;
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
const colonIndex = line.indexOf(":");
|
|
70
|
-
if (colonIndex === -1) continue;
|
|
71
|
-
|
|
72
|
-
const field = line.substring(0, colonIndex).trim();
|
|
73
|
-
const value = line.substring(colonIndex + 1).trim();
|
|
74
|
-
|
|
75
|
-
if (field === "data") {
|
|
76
|
-
currentEvent.data = currentEvent.data
|
|
77
|
-
? currentEvent.data + "\n" + value
|
|
78
|
-
: value;
|
|
79
|
-
} else if (field === "event") {
|
|
80
|
-
currentEvent.type = value;
|
|
81
|
-
} else if (field === "id") {
|
|
82
|
-
currentEvent.id = value;
|
|
83
|
-
}
|
|
84
|
-
}
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
// Handle any remaining event in buffer
|
|
88
|
-
if (buffer.trim()) {
|
|
89
|
-
const lines = buffer.split("\n");
|
|
90
|
-
let currentEvent: { data?: string } = {};
|
|
91
|
-
for (const line of lines) {
|
|
92
|
-
if (line.trim() === "" && currentEvent.data !== undefined) {
|
|
93
|
-
yield currentEvent.data;
|
|
94
|
-
currentEvent = {};
|
|
95
|
-
continue;
|
|
96
|
-
}
|
|
97
|
-
const colonIndex = line.indexOf(":");
|
|
98
|
-
if (colonIndex !== -1) {
|
|
99
|
-
const field = line.substring(0, colonIndex).trim();
|
|
100
|
-
const value = line.substring(colonIndex + 1).trim();
|
|
101
|
-
if (field === "data") {
|
|
102
|
-
currentEvent.data = currentEvent.data
|
|
103
|
-
? currentEvent.data + "\n" + value
|
|
104
|
-
: value;
|
|
105
|
-
}
|
|
106
|
-
}
|
|
107
|
-
}
|
|
108
|
-
if (currentEvent.data !== undefined) {
|
|
109
|
-
yield currentEvent.data;
|
|
110
|
-
}
|
|
111
|
-
}
|
|
112
|
-
} finally {
|
|
113
|
-
reader.releaseLock();
|
|
114
|
-
}
|
|
115
|
-
}
|
|
116
|
-
|
|
117
|
-
/**
|
|
118
|
-
* Parse NDJSON (Newline-Delimited JSON) stream
|
|
119
|
-
* Yields each JSON object as it arrives
|
|
120
|
-
*/
|
|
121
|
-
export async function* parseNDJSONStream<T = any>(
|
|
122
|
-
response: Response
|
|
123
|
-
): AsyncGenerator<T, void, unknown> {
|
|
124
|
-
if (!response.body) {
|
|
125
|
-
return;
|
|
126
|
-
}
|
|
127
|
-
|
|
128
|
-
const reader = response.body.getReader();
|
|
129
|
-
const decoder = new TextDecoder();
|
|
130
|
-
let buffer = "";
|
|
131
|
-
|
|
132
|
-
try {
|
|
133
|
-
while (true) {
|
|
134
|
-
const { done, value } = await reader.read();
|
|
135
|
-
if (done) break;
|
|
136
|
-
|
|
137
|
-
buffer += decoder.decode(value, { stream: true });
|
|
138
|
-
const lines = buffer.split("\n");
|
|
139
|
-
buffer = lines.pop() || ""; // Keep incomplete line in buffer
|
|
140
|
-
|
|
141
|
-
for (const line of lines) {
|
|
142
|
-
const trimmed = line.trim();
|
|
143
|
-
if (trimmed === "") continue;
|
|
144
|
-
|
|
145
|
-
try {
|
|
146
|
-
const parsed = JSON.parse(trimmed) as T;
|
|
147
|
-
yield parsed;
|
|
148
|
-
} catch (error) {
|
|
149
|
-
// Skip invalid JSON lines
|
|
150
|
-
console.warn("Skipping invalid JSON line:", trimmed);
|
|
151
|
-
}
|
|
152
|
-
}
|
|
153
|
-
}
|
|
154
|
-
|
|
155
|
-
// Handle any remaining line in buffer
|
|
156
|
-
if (buffer.trim()) {
|
|
157
|
-
try {
|
|
158
|
-
const parsed = JSON.parse(buffer.trim()) as T;
|
|
159
|
-
yield parsed;
|
|
160
|
-
} catch (error) {
|
|
161
|
-
// Skip invalid JSON
|
|
162
|
-
console.warn("Skipping invalid JSON in buffer:", buffer.trim());
|
|
163
|
-
}
|
|
164
|
-
}
|
|
165
|
-
} finally {
|
|
166
|
-
reader.releaseLock();
|
|
167
|
-
}
|
|
168
|
-
}
|
|
35
|
+
// Re-export streaming parsers from @blimu/fetch
|
|
36
|
+
export { parseSSEStream, parseNDJSONStream };
|
package/dist/index.d.mts
CHANGED
|
@@ -31,6 +31,7 @@ declare const TypeScriptClientSchema: z.ZodObject<{
|
|
|
31
31
|
}, z.core.$strip>>>;
|
|
32
32
|
dependencies: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
|
|
33
33
|
devDependencies: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
|
|
34
|
+
formatCode: z.ZodOptional<z.ZodBoolean>;
|
|
34
35
|
templates: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
|
|
35
36
|
}, z.core.$strip>;
|
|
36
37
|
declare const ClientSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
@@ -54,6 +55,7 @@ declare const ClientSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
|
54
55
|
}, z.core.$strip>>>;
|
|
55
56
|
dependencies: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
|
|
56
57
|
devDependencies: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
|
|
58
|
+
formatCode: z.ZodOptional<z.ZodBoolean>;
|
|
57
59
|
templates: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
|
|
58
60
|
}, z.core.$strip>], "type">;
|
|
59
61
|
declare const ConfigSchema: z.ZodObject<{
|
|
@@ -80,6 +82,7 @@ declare const ConfigSchema: z.ZodObject<{
|
|
|
80
82
|
}, z.core.$strip>>>;
|
|
81
83
|
dependencies: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
|
|
82
84
|
devDependencies: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
|
|
85
|
+
formatCode: z.ZodOptional<z.ZodBoolean>;
|
|
83
86
|
templates: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
|
|
84
87
|
}, z.core.$strip>], "type">>;
|
|
85
88
|
}, z.core.$strip>;
|
|
@@ -296,6 +299,7 @@ declare class TypeScriptGeneratorService implements Generator<TypeScriptClient>
|
|
|
296
299
|
private generatePackageJson;
|
|
297
300
|
private generateTsConfig;
|
|
298
301
|
private generateReadme;
|
|
302
|
+
private generatePrettierConfig;
|
|
299
303
|
}
|
|
300
304
|
|
|
301
305
|
declare class GeneratorModule {
|
package/dist/index.d.ts
CHANGED
|
@@ -31,6 +31,7 @@ declare const TypeScriptClientSchema: z.ZodObject<{
|
|
|
31
31
|
}, z.core.$strip>>>;
|
|
32
32
|
dependencies: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
|
|
33
33
|
devDependencies: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
|
|
34
|
+
formatCode: z.ZodOptional<z.ZodBoolean>;
|
|
34
35
|
templates: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
|
|
35
36
|
}, z.core.$strip>;
|
|
36
37
|
declare const ClientSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
@@ -54,6 +55,7 @@ declare const ClientSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
|
|
|
54
55
|
}, z.core.$strip>>>;
|
|
55
56
|
dependencies: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
|
|
56
57
|
devDependencies: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
|
|
58
|
+
formatCode: z.ZodOptional<z.ZodBoolean>;
|
|
57
59
|
templates: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
|
|
58
60
|
}, z.core.$strip>], "type">;
|
|
59
61
|
declare const ConfigSchema: z.ZodObject<{
|
|
@@ -80,6 +82,7 @@ declare const ConfigSchema: z.ZodObject<{
|
|
|
80
82
|
}, z.core.$strip>>>;
|
|
81
83
|
dependencies: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
|
|
82
84
|
devDependencies: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
|
|
85
|
+
formatCode: z.ZodOptional<z.ZodBoolean>;
|
|
83
86
|
templates: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
|
|
84
87
|
}, z.core.$strip>], "type">>;
|
|
85
88
|
}, z.core.$strip>;
|
|
@@ -296,6 +299,7 @@ declare class TypeScriptGeneratorService implements Generator<TypeScriptClient>
|
|
|
296
299
|
private generatePackageJson;
|
|
297
300
|
private generateTsConfig;
|
|
298
301
|
private generateReadme;
|
|
302
|
+
private generatePrettierConfig;
|
|
299
303
|
}
|
|
300
304
|
|
|
301
305
|
declare class GeneratorModule {
|
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
"use strict";var Ue=Object.create;var G=Object.defineProperty;var Le=Object.getOwnPropertyDescriptor;var Ge=Object.getOwnPropertyNames;var We=Object.getPrototypeOf,Ze=Object.prototype.hasOwnProperty;var f=(o,e)=>G(o,"name",{value:e,configurable:!0});var Ve=(o,e)=>{for(var t in e)G(o,t,{get:e[t],enumerable:!0})},me=(o,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Ge(e))!Ze.call(o,s)&&s!==t&&G(o,s,{get:()=>e[s],enumerable:!(r=Le(e,s))||r.enumerable});return o};var x=(o,e,t)=>(t=o!=null?Ue(We(o)):{},me(e||!o||!o.__esModule?G(t,"default",{value:o,enumerable:!0}):t,o)),Je=o=>me(G({},"__esModule",{value:!0}),o);var pt={};Ve(pt,{ClientSchema:()=>ge,ConfigModule:()=>F,ConfigSchema:()=>W,ConfigService:()=>O,GeneratorModule:()=>V,GeneratorService:()=>R,IRSchemaKind:()=>l,OpenApiModule:()=>B,OpenApiService:()=>k,PredefinedTypeSchema:()=>de,TYPESCRIPT_TEMPLATE_NAMES:()=>oe,TypeScriptClientSchema:()=>he,defineConfig:()=>Xe,generate:()=>lt,loadConfig:()=>ft,loadMjsConfig:()=>z});module.exports=Je(pt);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"],Ke=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=Ke.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(),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]),W=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 Y=require("@nestjs/common"),be=x(require("fs")),S=x(require("path"));var ye=require("url"),Q=x(require("path"));async function z(o){try{let e=Q.isAbsolute(o)?o:Q.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 W.parse(s)}catch(e){throw e instanceof Error?new Error(`Failed to load MJS config from ${o}: ${e.message}`):e}}f(z,"loadMjsConfig");function Qe(o,e,t,r){var s=arguments.length,n=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,e,t,r);else for(var a=o.length-1;a>=0;a--)(i=o[a])&&(n=(s<3?i(n):s>3?i(e,t,n):i(e,t))||n);return s>3&&n&&Object.defineProperty(e,t,n),n}f(Qe,"_ts_decorate");var O=class o{static{f(this,"ConfigService")}logger=new Y.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 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=S.dirname(S.resolve(t)),s=e.spec;this.isUrl(s)||S.isAbsolute(s)||(s=S.resolve(r,s));let n=e.clients.map(i=>{let a=i.outDir;return S.isAbsolute(a)||(a=S.resolve(r,a)),{...i,outDir:a}});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}};O=Qe([(0,Y.Injectable)()],O);var Se=require("@nestjs/common");function Ye(o,e,t,r){var s=arguments.length,n=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,e,t,r);else for(var a=o.length-1;a>=0;a--)(i=o[a])&&(n=(s<3?i(n):s>3?i(e,t,n):i(e,t))||n);return s>3&&n&&Object.defineProperty(e,t,n),n}f(Ye,"_ts_decorate");var F=class{static{f(this,"ConfigModule")}};F=Ye([(0,Se.Module)({providers:[O],exports:[O]})],F);function Xe(o){return W.parse(o)}f(Xe,"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 ee=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 ie(o){if(!(!o||!("type"in o)))return o.type}f(ie,"getSchemaType");function et(o,e,t,r){var s=arguments.length,n=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,e,t,r);else for(var a=o.length-1;a>=0;a--)(i=o[a])&&(n=(s<3?i(n):s>3?i(e,t,n):i(e,t))||n);return s>3&&n&&Object.defineProperty(e,t,n),n}f(et,"_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 i=ie(r),a=Array.isArray(i)?i.filter(c=>c!=="null")[0]:i;if(a)switch(a){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],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=ie(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=et([(0,ve.Injectable)()],P);function v(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(v,"toPascalCase");function $(o){let e=v(o);return e===""?"":e.charAt(0).toLowerCase()+e.slice(1)}f($,"toCamelCase");function Z(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(Z,"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],i=!1;s>0&&ae(n)&&(ae(r[s-1])?s<r.length-1&&!ae(r[s+1])&&(i=!0):i=!0),i&&t.length>0&&(e.push(t),t=""),t+=n}return t.length>0&&e.push(t),e}f(ce,"splitCamelCase");function ae(o){return o>="A"&&o<="Z"}f(ae,"isUppercase");function tt(o,e,t,r){var s=arguments.length,n=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,e,t,r);else for(var a=o.length-1;a>=0;a--)(i=o[a])&&(n=(s<3?i(n):s>3?i(e,t,n):i(e,t))||n);return s>3&&n&&Object.defineProperty(e,t,n),n}f(tt,"_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 a of t)n[a]=!0;let i=this.buildIRFromDoc(e,n);return i.securitySchemes=r,i.modelDefs=[...s,...i.modelDefs],i.openApiDocument=e,i}filterIR(e,t){let r=this.compileTagFilters(t.includeTags||[]),s=this.compileTagFilters(t.excludeTags||[]),n=[];for(let a of e.services){let c=[];for(let p of a.operations)this.shouldIncludeOperation(p.originalTags,r,s)&&c.push(p);c.length>0&&n.push({...a,operations:c})}let i={services:n,models:e.models,securitySchemes:e.securitySchemes,modelDefs:e.modelDefs,openApiDocument:e.openApiDocument};return i.modelDefs=this.filterUnusedModelDefs(i,e.modelDefs),i}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 i of n)if(!(!i||!i.tags))for(let a of i.tags)t.add(a)}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 i of t)if(i.test(n)){s=!0;break}if(s)break}if(!s)return!1;if(r.length>0){for(let n of e)for(let i of r)if(i.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 i=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:N,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 J=p.tags&&p.tags.length>0?[...p.tags]:["misc"];r[c].operations.push({operationID:h,method:u,path:y,tag:c,originalTags:J,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:h}of u){if(!y)continue;let b=this.firstAllowedTag(y.tags||[],t);b&&i(b,y,h,c)}}let a=Object.values(r);for(let c of a)c.operations.sort((p,u)=>p.path===u.path?p.method.localeCompare(u.method):p.path.localeCompare(u.path));return a.sort((c,p)=>c.tag.localeCompare(p.tag)),{services:a,models:[],securitySchemes:[],modelDefs:s}}deriveMethodName(e,t,r){if(e){let n=e.indexOf("Controller_"),i=n>=0?e.substring(n+11):e;return $(i)}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 i={key:s,type:n.type};switch(n.type){case"http":i.scheme=n.scheme,i.bearerFormat=n.bearerFormat;break;case"apiKey":i.in=n.in,i.name=n.name;break;case"oauth2":case"openIdConnect":break}r.push(i)}return r}collectParams(e,t){let r=[],s=[];if(t.parameters)for(let n of t.parameters){if(!n||"$ref"in n)continue;let i=n,a=this.schemaConverter.schemaRefToIR(e,i.schema),c={name:i.name,required:i.required||!1,schema:a,description:i.description||""};i.in==="path"?r.push(c):i.in==="query"&&s.push(c)}return r.sort((n,i)=>n.name.localeCompare(i.name)),s.sort((n,i)=>n.name.localeCompare(i.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 i=this.schemaConverter.schemaRefToIR(e,n);if(this.compareSchemas(r,i))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(a=>[a.name,{type:a.type,required:a.required}])),i=new Map(s.map(a=>[a.name,{type:a.type,required:a.required}]));if(n.size!==i.size)return!1;for(let[a,c]of n){let p=i.get(a);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,i){let a=this.extractModelNameFromSchema(e);if(a)return a;let c=this.deriveMethodName(r,s,n);return`${v(t)}${v(c)}${i}`}extractRequestBodyWithTypes(e,t,r,s,n,i){let a=[];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&&!i.has(b)?(i.add(b),a.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:a}):{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,i){let a=[];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 J=this.detectStreamingContentType(E),L=this.schemaConverter.schemaRefToIR(e,U.schema);if(J.isStreaming)return{response:{typeTS:"",schema:L,description:h.description||"",isStreaming:!0,contentType:E,streamingFormat:J.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 K=this.generateTypeName(L,r,s,n,t.path,"Response");return L.kind===l.Object&&!i.has(K)?(i.add(K),a.push({name:K,schema:L,annotations:this.schemaConverter.extractAnnotations(U.schema)}),{response:{typeTS:"",schema:{kind:l.Ref,ref:K,nullable:!1},description:h.description||"",isStreaming:!1,contentType:E},extractedTypes:a}):{response:{typeTS:"",schema:L,description:h.description||"",isStreaming:!1,contentType:E},extractedTypes:[]}}}let b=Object.keys(h.content)[0],q=h.content[b],N=this.schemaConverter.schemaRefToIR(e,q.schema),_=this.detectStreamingContentType(b);return{response:{typeTS:"",schema:N,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 i=n;if(i.content){for(let[u,y]of Object.entries(i.content)){let h=this.detectStreamingContentType(u);if(h.isStreaming)return{typeTS:"",schema:this.schemaConverter.schemaRefToIR(e,y.schema),description:i.description||"",isStreaming:!0,contentType:u,streamingFormat:h.format}}if(i.content["application/json"]){let u=i.content["application/json"];return{typeTS:"",schema:this.schemaConverter.schemaRefToIR(e,u.schema),description:i.description||"",isStreaming:!1,contentType:"application/json"}}let a=Object.keys(i.content)[0],c=i.content[a],p=this.detectStreamingContentType(a);return{typeTS:"",schema:this.schemaConverter.schemaRefToIR(e,c.schema),description:i.description||"",isStreaming:p.isStreaming,contentType:a,streamingFormat:p.format}}return{typeTS:"void",schema:{kind:l.Unknown,nullable:!1},description:i.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 i=n;if(s==="204")return{typeTS:"void",schema:{kind:l.Unknown,nullable:!1},description:i.description||"",isStreaming:!1,contentType:""};if(i.content){for(let[u,y]of Object.entries(i.content)){let h=this.detectStreamingContentType(u);if(h.isStreaming)return{typeTS:"",schema:this.schemaConverter.schemaRefToIR(e,y.schema),description:i.description||"",isStreaming:!0,contentType:u,streamingFormat:h.format}}if(i.content["application/json"]){let u=i.content["application/json"];return{typeTS:"",schema:this.schemaConverter.schemaRefToIR(e,u.schema),description:i.description||"",isStreaming:!1,contentType:"application/json"}}let a=Object.keys(i.content)[0],c=i.content[a],p=this.detectStreamingContentType(a);return{typeTS:"",schema:this.schemaConverter.schemaRefToIR(e,c.schema),description:i.description||"",isStreaming:p.isStreaming,contentType:a,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 i=e.components.schemas[n],a=this.schemaConverter.schemaRefToIR(e,i);t.push({name:n,schema:a,annotations:this.schemaConverter.extractAnnotations(i)})}return t}filterUnusedModelDefs(e,t){let r=new Map;for(let a of t)r.set(a.name,a);let s=new Set,n=new Set,i=f(a=>{if(a.kind==="ref"&&a.ref){let c=a.ref;if(s.add(c),!n.has(c)){n.add(c);let p=r.get(c);p&&i(p.schema)}}if(a.items&&i(a.items),a.additionalProperties&&i(a.additionalProperties),a.oneOf)for(let c of a.oneOf)i(c);if(a.anyOf)for(let c of a.anyOf)i(c);if(a.allOf)for(let c of a.allOf)i(c);if(a.not&&i(a.not),a.properties)for(let c of a.properties)i(c.type)},"collectRefs");for(let a of e.services)for(let c of a.operations){for(let p of c.pathParams)i(p.schema);for(let p of c.queryParams)i(p.schema);c.requestBody&&i(c.requestBody.schema),i(c.response.schema)}return t.filter(a=>s.has(a.name))}};j=tt([(0,Pe.Injectable)(),xe("design:type",Function),xe("design:paramtypes",[typeof P>"u"?Object:P])],j);var X=require("@nestjs/common"),A=x(require("@apidevtools/swagger-parser")),le=x(require("fs")),fe=x(require("path"));function rt(o,e,t,r){var s=arguments.length,n=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,e,t,r);else for(var a=o.length-1;a>=0;a--)(i=o[a])&&(n=(s<3?i(n):s>3?i(e,t,n):i(e,t))||n);return s>3&&n&&Object.defineProperty(e,t,n),n}f(rt,"_ts_decorate");var k=class o{static{f(this,"OpenApiService")}logger=new X.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 i=await n.text(),a;try{a=JSON.parse(i)}catch{throw new Error("OpenAPI spec is not valid JSON")}try{let c=await A.default.parse(a);r=await A.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 A.default.parse(a);r=await A.default.dereference(p)}catch(p){throw p}}}else{let n=fe.resolve(e);if(!le.existsSync(n))throw new Error(`OpenAPI spec file not found: ${n}`);this.logger.debug(`Loading OpenAPI spec from file: ${n}`);try{r=await A.default.bundle(n)}catch(i){this.logger.debug(`Bundle failed: ${i instanceof Error?i.message:String(i)}`),this.logger.debug("Attempting dereference directly"),r=await A.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 A.default.validate(e);else{let r=fe.resolve(e);if(!le.existsSync(r))throw new Error(`OpenAPI spec file not found: ${r}`);await A.default.validate(r)}}catch(t){throw t instanceof Error?new Error(`Invalid OpenAPI document: ${t.message}`):t}}};k=rt([(0,X.Injectable)()],k);function nt(o,e,t,r){var s=arguments.length,n=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,e,t,r);else for(var a=o.length-1;a>=0;a--)(i=o[a])&&(n=(s<3?i(n):s>3?i(e,t,n):i(e,t))||n);return s>3&&n&&Object.defineProperty(e,t,n),n}f(nt,"_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 ee.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),i=this.irBuilder.filterIR(n,t);await r.generate(t,i)}};R=nt([(0,ee.Injectable)(),je("design:type",Function),je("design:paramtypes",[typeof j>"u"?Object:j,typeof k>"u"?Object:k])],R);var ze=require("@nestjs/common");var Re=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,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,e,t,r);else for(var a=o.length-1;a>=0;a--)(i=o[a])&&(n=(s<3?i(n):s>3?i(e,t,n):i(e,t))||n);return s>3&&n&&Object.defineProperty(e,t,n),n}f(ot,"_ts_decorate");var B=class{static{f(this,"OpenApiModule")}};B=ot([(0,Re.Module)({providers:[k],exports:[k]})],B);var ne=require("@nestjs/common"),w=x(require("fs")),T=x(require("path")),m=x(require("handlebars"));var g=x(require("handlebars"));function He(){g.registerHelper("pascal",o=>v(o)),g.registerHelper("camel",o=>$(o)),g.registerHelper("kebab",o=>ke(o)),g.registerHelper("snake",o=>Z(o)),g.registerHelper("serviceName",o=>v(o)+"Service"),g.registerHelper("serviceProp",o=>$(o)),g.registerHelper("fileBase",o=>Z(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(He,"registerCommonHandlebarsHelpers");function C(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(${C(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(), ${C(o.additionalProperties,s,t,r)})`:n="z.record(z.string(), z.unknown())";else{let i=[];for(let c of o.properties){let p=C(c.type,s,t,r),u=te(c.name);c.required?i.push(`${s}${u}: ${p}`):i.push(`${s}${u}: ${p}.optional()`)}let a=`z.object({
|
|
2
|
-
${
|
|
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(/"/g,'"').replace(/</g,"<").replace(/>/g,">").replace(/`/g,"`").replace(/`/g,"`").replace(/&/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({
|
|
2
|
+
${a.join(`,
|
|
3
3
|
`)}
|
|
4
|
-
${e}})`;if(o.additionalProperties){let c=C(o.additionalProperties,s,t,r);n=`${a}.catchall(${c})`}else n=a}break;case l.Enum:o.enumValues&&o.enumValues.length>0?n=`z.enum([${o.enumValues.map(a=>a==="true"||a==="false"||/^-?[0-9]+(\.[0-9]+)?$/.test(a)?a:JSON.stringify(a)).join(", ")}])`:n="z.string()";break;case l.OneOf:o.oneOf&&o.oneOf.length>0?n=`z.union([${o.oneOf.map(a=>C(a,s,t,r)).join(", ")}])`:n="z.unknown()";break;case l.AnyOf:o.anyOf&&o.anyOf.length>0?n=`z.union([${o.anyOf.map(a=>C(a,s,t,r)).join(", ")}])`:n="z.unknown()";break;case l.AllOf:if(o.allOf&&o.allOf.length>0){let i=o.allOf.map(a=>C(a,s,t,r));n=i.join(".and(")+")".repeat(i.length-1)}else n="z.unknown()";break;default:n="z.unknown()"}return o.nullable&&n!=="z.null()"&&(n=`${n}.nullable()`),n}f(C,"schemaToZodSchema");function st(o){return o.replace(/"/g,'"').replace(/</g,"<").replace(/>/g,">").replace(/`/g,"`").replace(/`/g,"`").replace(/&/g,"&")}f(st,"decodeHtmlEntities");function H(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(i=>i.name===o.ref)?s=o.ref:s="Schema."+o.ref:s="unknown";break;case l.Array:if(o.items){let n=H(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(i=>H(i,e,t)).join(" | "):s="unknown";break;case l.AnyOf:o.anyOf?s=o.anyOf.map(i=>H(i,e,t)).join(" | "):s="unknown";break;case l.AllOf:o.allOf?s=o.allOf.map(i=>H(i,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 i of o.enumValues)n.push(i);break;case l.Boolean:for(let i of o.enumValues)i==="true"||i==="false"?n.push(i):n.push(`"${i}"`);break;default:for(let i of o.enumValues)n.push(`"${i}"`)}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 i of o.properties){let a=H(i.type,e,t,r);i.required?n.push(`${i.name}: ${a}`):n.push(`${i.name}?: ${a}`)}s="{ "+n.join("; ")+" }"}break;default:s="unknown"}return o.nullable&&s!=="null"&&(s+=" | null"),st(s)}f(H,"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 Ie(o,e){if(o.operationIdParser)try{let r=await o.operationIdParser(e.operationID,e.method,e.path);if(r)return $(r)}catch{}let t=it(e.operationID);return t?$(t):M(e)}f(Ie,"resolveMethodName");function it(o){if(!o)return"";let e=o.indexOf("Controller_");return e>=0?o.substring(e+11):o}f(it,"defaultParseOperationID");function $e(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($e,"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 i=r.substring(s+1,n),a=t.get(i);a!==void 0&&e.push(o.pathParams[a]),s=n;continue}}return e}f(re,"orderPathParams");function Ce(o,e,t,r=!1){return H(o,t,e,r)}f(Ce,"schemaToTSTypeWithSimpleTypes");function pe(o,e,t,r,s=!1){let n=[];for(let i of re(o))n.push(`${i.name}: ${Ce(i.schema,t,r,s)}`);if(o.queryParams.length>0){let i=v(o.tag)+v(e)+"Query";n.push(`query?: Schema.${i}`)}if(o.requestBody){let i=o.requestBody.required===!0?"":"?";n.push(`body${i}: ${Ce(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 i=o.find(a=>a.name===n);return i?i.schema:null},"resolveRef"),s=f(n=>{if(n.kind==="ref"&&n.ref)if(e.some(a=>a.type===n.ref))t.add(n.ref);else{let a=r(n.ref);a&&s(a)}else if(n.kind==="array"&&n.items)s(n.items);else if(n.kind==="object"&&n.properties)for(let i of n.properties)s(i.type);else if(n.kind==="oneOf"&&n.oneOf)for(let i of n.oneOf)s(i);else if(n.kind==="anyOf"&&n.anyOf)for(let i of n.anyOf)s(i);else if(n.kind==="allOf"&&n.allOf)for(let i of n.allOf)s(i)},"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(i=>{if(!t)return null;let a=t.find(c=>c.name===i);return a?a.schema:null},"resolveRef"),n=f(i=>{if(i.kind==="ref"&&i.ref)if(e.some(c=>c.type===i.ref))r.add(i.ref);else{let c=s(i.ref);c&&n(c)}else if(i.kind==="array"&&i.items)n(i.items);else if(i.kind==="object"&&i.properties)for(let a of i.properties)n(a.type);else if(i.kind==="oneOf"&&i.oneOf)for(let a of i.oneOf)n(a);else if(i.kind==="anyOf"&&i.anyOf)for(let a of i.anyOf)n(a);else if(i.kind==="allOf"&&i.allOf)for(let a of i.allOf)n(a)},"checkSchema");for(let i of o.operations)for(let a of i.pathParams)n(a.schema);return e.filter(i=>r.has(i.type))}f(Ee,"collectPredefinedTypesUsedInService");function De(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(De,"queryKeyArgs");function te(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(te,"quoteTSPropertyName");function Ne(o){return o.response.isStreaming===!0}f(Ne,"isStreamingOperation");function Fe(o){let e=o.response.schema;return e.kind===l.Array&&e.items?H(e.items):o.response.streamingFormat==="sse"?"string":H(e)}f(Fe,"getStreamingItemType");function at(o,e,t,r){var s=arguments.length,n=s<3?e:r===null?r=Object.getOwnPropertyDescriptor(e,t):r,i;if(typeof Reflect=="object"&&typeof Reflect.decorate=="function")n=Reflect.decorate(o,e,t,r);else for(var a=o.length-1;a>=0;a--)(i=o[a])&&(n=(s<3?i(n):s>3?i(e,t,n):i(e,t))||n);return s>3&&n&&Object.defineProperty(e,t,n),n}f(at,"_ts_decorate");function Be(o,e){if(typeof Reflect=="object"&&typeof Reflect.metadata=="function")return Reflect.metadata(o,e)}f(Be,"_ts_metadata");var I=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){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.generateReadme(e,n)}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 i=await Ie(e,n);return{...n,_resolvedMethodName:i}}))})));return{...t,services:r}}registerHandlebarsHelpers(e){He(),m.registerHelper("methodName",t=>t._resolvedMethodName||M(t)),m.registerHelper("queryTypeName",t=>{let r=t._resolvedMethodName||M(t);return v(t.tag)+v(r)+"Query"}),m.registerHelper("pathTemplate",t=>{let r=$e(t);return new m.SafeString(r)}),m.registerHelper("queryKeyBase",t=>{let r=Ae(t);return new m.SafeString(r)}),m.registerHelper("pathParamsInOrder",t=>re(t)),m.registerHelper("methodSignature",(t,r)=>{let s=t._resolvedMethodName||M(t),n=r?.data?.root?.IR?.modelDefs||[],i=r?.data?.root?.PredefinedTypes||[],a=r?.data?.root?.isSameFile||!1;return pe(t,s,n,i,a).map(p=>new m.SafeString(p))}),m.registerHelper("methodSignatureNoInit",(t,r)=>{let s=t._resolvedMethodName||M(t),n=r?.data?.root?.IR?.modelDefs||[],i=r?.data?.root?.PredefinedTypes||[],a=r?.data?.root?.isSameFile||!1;return pe(t,s,n,i,a).slice(0,-1)}),m.registerHelper("queryKeyArgs",t=>De(t).map(s=>new m.SafeString(s))),m.registerHelper("tsType",(t,r)=>{if(t&&typeof t=="object"&&"kind"in t){let s=r?.data?.root?.PredefinedTypes||[],n=r?.data?.root?.IR?.modelDefs||[],i=r?.data?.root?.isSameFile||!1;return H(t,s,n,i)}return"unknown"}),m.registerHelper("stripSchemaNs",t=>t.replace(/^Schema\./,"")),m.registerHelper("tsTypeStripNs",(t,r)=>{let s=r?.data?.root?.PredefinedTypes||[],n=r?.data?.root?.IR?.modelDefs||[],i=r?.data?.root?.isSameFile||!1;if(t&&typeof t=="object"&&"kind"in t){let c=H(t,s,n,i).replace(/Schema\./g,"");return new m.SafeString(c)}if(typeof t=="string"){if(t.startsWith("Schema.")){let a=t.replace(/^Schema\./,"");return s.find(p=>p.type===a)?new m.SafeString(a):new m.SafeString(a)}return new m.SafeString(t)}return"unknown"}),m.registerHelper("isPredefinedType",(t,r)=>(r?.data?.root?.PredefinedTypes||[]).some(n=>n.type===t)),m.registerHelper("getPredefinedType",(t,r)=>(r?.data?.root?.PredefinedTypes||[]).find(n=>n.type===t)),m.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)}),m.registerHelper("getServicePredefinedTypes",(t,r)=>{let s=r?.data?.root?.PredefinedTypes||[],n=r?.data?.root?.IR?.modelDefs||[];return Ee(t,s,n)}),m.registerHelper("getSchemaPredefinedTypes",t=>{let r=t?.data?.root?.PredefinedTypes||[],s=t?.data?.root?.IR?.modelDefs||[];return qe(s,r)}),m.registerHelper("joinTypes",t=>t.join(", ")),m.registerHelper("uniquePackages",t=>{let r=new Set;for(let s of t||[])s.package&&r.add(s.package);return Array.from(r)}),m.registerHelper("isPredefinedPackage",(t,r)=>r?r.some(s=>s.package===t):!1),m.registerHelper("getAllDependencies",t=>{let r={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}),m.registerHelper("decodeHtml",t=>{if(typeof t!="string")return t;let r=t.replace(/&#x60;/g,"`").replace(/&#96;/g,"`").replace(/&quot;/g,""").replace(/&lt;/g,"<").replace(/&gt;/g,">");return r=r.replace(/"/g,'"').replace(/</g,"<").replace(/>/g,">").replace(/`/g,"`").replace(/`/g,"`").replace(/&/g,"&"),new m.SafeString(r)}),m.registerHelper("quotePropName",t=>te(t)),m.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 m.SafeString(C(t,"",s,n))}return"z.unknown()"}),m.registerHelper("isStreaming",t=>Ne(t)),m.registerHelper("streamingItemType",t=>new m.SafeString(Fe(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 h=await w.promises.readFile(n,"utf-8"),b=m.compile(h),q={...t,_templateName:e},N=b(q);await w.promises.writeFile(r,N,"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 i=[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)],a=null;for(let h of i)try{await w.promises.access(h),a=h,this.logger.debug(`Found template at: ${a}`);break}catch{this.logger.debug(`Template not found at: ${h}`)}if(!a)throw this.logger.error(`Template not found: ${e}`),this.logger.error(`Checked paths: ${i.join(", ")}`),this.logger.error(`__dirname: ${__dirname}`),new Error(`Template not found: ${e}`);let c=await w.promises.readFile(a,"utf-8"),p=m.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 i=n instanceof Error?n.message:String(n);this.logger.warn(`Template client.ts.hbs not found: ${i}, 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,`${Z(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 a=`// Generated service ${s.tag} - template rendering to be implemented`;await w.promises.writeFile(n,a,"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 i=n instanceof Error?n.message:String(n);this.logger.warn(`Template schema.ts.hbs error: ${i}, 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 i=n instanceof Error?n.message:String(n);this.logger.warn(`Template schema.zod.ts.hbs error: ${i}, 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 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"),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(/&#x60;/g,"`").replace(/&#96;/g,"`").replace(/&quot;/g,""").replace(/&lt;/g,"<").replace(/&gt;/g,">");return r=r.replace(/"/g,'"').replace(/</g,"<").replace(/>/g,">").replace(/`/g,"`").replace(/`/g,"`").replace(/&/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}
|
|
5
5
|
|
|
6
|
-
Generated SDK from OpenAPI specification.`;await
|
|
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});
|
|
7
7
|
//# sourceMappingURL=index.js.map
|