@sdk-it/cli 0.12.6 → 0.12.7

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/index.js CHANGED
@@ -17,9 +17,9 @@ import { dirname, isAbsolute, join } from "node:path";
17
17
  import debug from "debug";
18
18
  import ts2 from "typescript";
19
19
  import { get as get2, merge } from "lodash-es";
20
- import { camelcase as camelcase2, pascalcase as pascalcase2, spinalcase as spinalcase2 } from "stringcase";
20
+ import { camelcase as camelcase2, pascalcase, spinalcase as spinalcase2 } from "stringcase";
21
21
  import { get } from "lodash-es";
22
- import { camelcase, pascalcase, spinalcase } from "stringcase";
22
+ import { camelcase, spinalcase } from "stringcase";
23
23
  import { debounceTime, from } from "rxjs";
24
24
  var deriveSymbol = Symbol.for("serialize");
25
25
  var $types = Symbol.for("types");
@@ -27,8 +27,11 @@ async function exist(file) {
27
27
  return stat(file).then(() => true).catch(() => false);
28
28
  }
29
29
  async function writeFiles(dir, contents) {
30
- return Promise.all(
30
+ await Promise.all(
31
31
  Object.entries(contents).map(async ([file, content]) => {
32
+ if (content === null) {
33
+ return;
34
+ }
32
35
  const filePath = isAbsolute(file) ? file : join(dir, file);
33
36
  await mkdir(dirname(filePath), { recursive: true });
34
37
  if (typeof content === "string") {
@@ -38,15 +41,20 @@ async function writeFiles(dir, contents) {
38
41
  if (!await exist(filePath)) {
39
42
  await writeFile(filePath, content.content, "utf-8");
40
43
  }
44
+ } else {
45
+ await writeFile(filePath, content.content, "utf-8");
41
46
  }
42
47
  }
43
48
  })
44
49
  );
45
50
  }
46
- async function getFolderExports(folder, extensions = ["ts"]) {
51
+ async function getFolderExports(folder, extensions = ["ts"], ignore = () => false) {
47
52
  const files = await readdir(folder, { withFileTypes: true });
48
53
  const exports = [];
49
54
  for (const file of files) {
55
+ if (ignore(file)) {
56
+ continue;
57
+ }
50
58
  if (file.isDirectory()) {
51
59
  exports.push(`export * from './${file.name}/index.ts';`);
52
60
  } else if (file.name !== "index.ts" && extensions.includes(getExt(file.name))) {
@@ -123,8 +131,10 @@ ${spec.servers.length ? `export type Servers = typeof servers[number];` : ""}
123
131
  type ${spec.name}Options = z.infer<typeof optionsSchema>;
124
132
 
125
133
  export class ${spec.name} {
126
-
127
- constructor(public options: ${spec.name}Options) {}
134
+ public options: ${spec.name}Options
135
+ constructor(options: ${spec.name}Options) {
136
+ this.options = options;
137
+ }
128
138
 
129
139
  async request<E extends keyof Endpoints>(
130
140
  endpoint: E,
@@ -199,37 +209,63 @@ ${this.endpoints.join("\n")}
199
209
  }`;
200
210
  }
201
211
  };
202
- var StreamEmitter = class extends Emitter {
203
- complete() {
204
- return `${this.imports.join("\n")}
205
- export interface StreamEndpoints {
206
- ${this.endpoints.join("\n")}
207
- }`;
212
+ function generateInputs(operationsSet, commonZod) {
213
+ const commonImports = commonZod.keys().toArray();
214
+ const inputs = {};
215
+ for (const [name, operations] of Object.entries(operationsSet)) {
216
+ const output = [];
217
+ const imports = /* @__PURE__ */ new Set(['import { z } from "zod";']);
218
+ for (const operation of operations) {
219
+ const schemaName = camelcase(`${operation.name} schema`);
220
+ const schema = `export const ${schemaName} = ${Object.keys(operation.schemas).length === 1 ? Object.values(operation.schemas)[0] : toLitObject(operation.schemas)};`;
221
+ const inputContent = schema;
222
+ for (const schema2 of commonImports) {
223
+ if (inputContent.includes(schema2)) {
224
+ imports.add(
225
+ `import { ${schema2} } from './schemas/${spinalcase(schema2)}.ts';`
226
+ );
227
+ }
228
+ }
229
+ output.push(inputContent);
230
+ }
231
+ inputs[`inputs/${spinalcase(name)}.ts`] = [...imports, ...output].join("\n") + "\n";
208
232
  }
209
- };
210
- function generateClientSdk(spec) {
233
+ const schemas = commonZod.entries().reduce((acc, [name, schema]) => {
234
+ const output = [`import { z } from 'zod';`];
235
+ const content = `export const ${name} = ${schema};`;
236
+ for (const schema2 of commonImports) {
237
+ const preciseMatch = new RegExp(`\\b${schema2}\\b`);
238
+ if (preciseMatch.test(content) && schema2 !== name) {
239
+ output.push(
240
+ `import { ${schema2} } from './${spinalcase(schema2)}.ts';`
241
+ );
242
+ }
243
+ }
244
+ output.push(content);
245
+ return [
246
+ [`inputs/schemas/${spinalcase(name)}.ts`, output.join("\n")],
247
+ ...acc
248
+ ];
249
+ }, []);
250
+ return {
251
+ ...Object.fromEntries(schemas),
252
+ ...inputs
253
+ };
254
+ }
255
+ function generateSDK(spec) {
211
256
  const emitter = new Emitter();
212
- const streamEmitter = new StreamEmitter();
213
- const schemas = {};
214
257
  const schemaEndpoint = new SchemaEndpoint();
215
258
  const errors = [];
216
259
  for (const [name, operations] of Object.entries(spec.operations)) {
217
- const featureSchemaFileName = camelcase(name);
218
- schemas[featureSchemaFileName] = [`import z from 'zod';`];
219
260
  emitter.addImport(
220
- `import * as ${featureSchemaFileName} from './inputs/${featureSchemaFileName}.ts';`
221
- );
222
- streamEmitter.addImport(
223
- `import * as ${featureSchemaFileName} from './inputs/${featureSchemaFileName}.ts';`
261
+ `import * as ${camelcase(name)} from './inputs/${spinalcase(name)}.ts';`
224
262
  );
225
263
  schemaEndpoint.addImport(
226
- `import * as ${featureSchemaFileName} from './inputs/${featureSchemaFileName}.ts';`
264
+ `import * as ${camelcase(name)} from './inputs/${spinalcase(name)}.ts';`
227
265
  );
228
266
  for (const operation of operations) {
229
267
  const schemaName = camelcase(`${operation.name} schema`);
230
- const schema = `export const ${schemaName} = ${Object.keys(operation.schemas).length === 1 ? Object.values(operation.schemas)[0] : toLitObject(operation.schemas)};`;
231
- schemas[featureSchemaFileName].push(schema);
232
- const schemaRef = `${featureSchemaFileName}.${schemaName}`;
268
+ const schemaRef = `${camelcase(name)}.${schemaName}`;
233
269
  const output = operation.formatOutput();
234
270
  const inputHeaders = [];
235
271
  const inputQuery = [];
@@ -254,51 +290,25 @@ function generateClientSdk(spec) {
254
290
  );
255
291
  }
256
292
  }
257
- if (operation.type === "sse") {
258
- const input = `z.infer<typeof ${schemaRef}>`;
259
- const endpoint = `${operation.trigger.method.toUpperCase()} ${operation.trigger.path}`;
260
- streamEmitter.addImport(
261
- `import type {${pascalcase(operation.name)}} from './outputs/${spinalcase(operation.name)}.ts';`
262
- );
263
- streamEmitter.addEndpoint(
293
+ emitter.addImport(
294
+ `import type {${output.import}} from './outputs/${spinalcase(operation.name)}.ts';`
295
+ );
296
+ errors.push(...operation.errors ?? []);
297
+ const addTypeParser = Object.keys(operation.schemas).length > 1;
298
+ for (const type in operation.schemas ?? {}) {
299
+ let typePrefix = "";
300
+ if (addTypeParser && type !== "json") {
301
+ typePrefix = `${type} `;
302
+ }
303
+ const input = `typeof ${schemaRef}${addTypeParser ? `.${type}` : ""}`;
304
+ const endpoint = `${typePrefix}${operation.trigger.method.toUpperCase()} ${operation.trigger.path}`;
305
+ emitter.addEndpoint(
264
306
  endpoint,
265
- `{input: ${input}, output: ${output.use}}`
307
+ `{input: z.infer<${input}>; output: ${output.use}; error: ${(operation.errors ?? ["ServerError"]).concat(`ParseError<${input}>`).join("|")}}`
266
308
  );
267
309
  schemaEndpoint.addEndpoint(
268
310
  endpoint,
269
311
  `{
270
- schema: ${schemaRef},
271
- toRequest(input: StreamEndpoints['${endpoint}']['input']) {
272
- const endpoint = '${endpoint}';
273
- return toRequest(endpoint, json(input, {
274
- inputHeaders: [${inputHeaders}],
275
- inputQuery: [${inputQuery}],
276
- inputBody: [${inputBody}],
277
- inputParams: [${inputParams}],
278
- }));
279
- },
280
- }`
281
- );
282
- } else {
283
- emitter.addImport(
284
- `import type {${output.import}} from './outputs/${spinalcase(operation.name)}.ts';`
285
- );
286
- errors.push(...operation.errors ?? []);
287
- const addTypeParser = Object.keys(operation.schemas).length > 1;
288
- for (const type in operation.schemas ?? {}) {
289
- let typePrefix = "";
290
- if (addTypeParser && type !== "json") {
291
- typePrefix = `${type} `;
292
- }
293
- const input = `typeof ${schemaRef}${addTypeParser ? `.${type}` : ""}`;
294
- const endpoint = `${typePrefix}${operation.trigger.method.toUpperCase()} ${operation.trigger.path}`;
295
- emitter.addEndpoint(
296
- endpoint,
297
- `{input: z.infer<${input}>; output: ${output.use}; error: ${(operation.errors ?? ["ServerError"]).concat(`ParseError<${input}>`).join("|")}}`
298
- );
299
- schemaEndpoint.addEndpoint(
300
- endpoint,
301
- `{
302
312
  schema: ${schemaRef}${addTypeParser ? `.${type}` : ""},
303
313
  toRequest(input: Endpoints['${endpoint}']['input']) {
304
314
  const endpoint = '${endpoint}';
@@ -310,8 +320,7 @@ function generateClientSdk(spec) {
310
320
  }));
311
321
  },
312
322
  }`
313
- );
314
- }
323
+ );
315
324
  }
316
325
  }
317
326
  }
@@ -319,19 +328,6 @@ function generateClientSdk(spec) {
319
328
  `import type { ${removeDuplicates(errors, (it) => it).join(", ")} } from './http/response.ts';`
320
329
  );
321
330
  return {
322
- ...Object.fromEntries(
323
- Object.entries(schemas).map(([key, value]) => [
324
- `inputs/${key}.ts`,
325
- [
326
- // schemasImports.length
327
- // ? `import {${removeDuplicates(schemasImports, (it) => it)}} from '../zod';`
328
- // : '',
329
- spec.commonZod ? 'import * as commonZod from "../zod.ts";' : "",
330
- ...value
331
- ].map((it) => it.trim()).filter(Boolean).join("\n") + "\n"
332
- // add a newline at the end
333
- ])
334
- ),
335
331
  "client.ts": client_default(spec),
336
332
  "schemas.ts": schemaEndpoint.complete(),
337
333
  "endpoints.ts": emitter.complete()
@@ -418,6 +414,25 @@ function importsToString(...imports) {
418
414
  throw new Error(`Invalid import ${JSON.stringify(it)}`);
419
415
  });
420
416
  }
417
+ function exclude2(list, exclude3) {
418
+ return list.filter((it) => !exclude3.includes(it));
419
+ }
420
+ function useImports(content, imports) {
421
+ const output = [];
422
+ for (const it of mergeImports(imports)) {
423
+ const singleImport = it.defaultImport ?? it.namespaceImport;
424
+ if (singleImport && content.includes(singleImport)) {
425
+ output.push(importsToString(it).join("\n"));
426
+ } else if (it.namedImports.length) {
427
+ for (const namedImport of it.namedImports) {
428
+ if (content.includes(namedImport.name)) {
429
+ output.push(importsToString(it).join("\n"));
430
+ }
431
+ }
432
+ }
433
+ }
434
+ return output;
435
+ }
421
436
  var TypeScriptDeserialzer = class {
422
437
  circularRefTracker = /* @__PURE__ */ new Set();
423
438
  #spec;
@@ -426,6 +441,70 @@ var TypeScriptDeserialzer = class {
426
441
  this.#spec = spec;
427
442
  this.#onRef = onRef;
428
443
  }
444
+ #stringifyKey = (key) => {
445
+ const reservedWords = [
446
+ "constructor",
447
+ "prototype",
448
+ "break",
449
+ "case",
450
+ "catch",
451
+ "class",
452
+ "const",
453
+ "continue",
454
+ "debugger",
455
+ "default",
456
+ "delete",
457
+ "do",
458
+ "else",
459
+ "export",
460
+ "extends",
461
+ "false",
462
+ "finally",
463
+ "for",
464
+ "function",
465
+ "if",
466
+ "import",
467
+ "in",
468
+ "instanceof",
469
+ "new",
470
+ "null",
471
+ "return",
472
+ "super",
473
+ "switch",
474
+ "this",
475
+ "throw",
476
+ "true",
477
+ "try",
478
+ "typeof",
479
+ "var",
480
+ "void",
481
+ "while",
482
+ "with",
483
+ "yield"
484
+ ];
485
+ if (reservedWords.includes(key)) {
486
+ return `'${key}'`;
487
+ }
488
+ if (key.trim() === "") {
489
+ return `'${key}'`;
490
+ }
491
+ const firstChar = key.charAt(0);
492
+ const validFirstChar = firstChar >= "a" && firstChar <= "z" || firstChar >= "A" && firstChar <= "Z" || firstChar === "_" || firstChar === "$";
493
+ if (!validFirstChar) {
494
+ return `'${key.replace(/'/g, "\\'")}'`;
495
+ }
496
+ for (let i = 1; i < key.length; i++) {
497
+ const char = key.charAt(i);
498
+ const validChar = char >= "a" && char <= "z" || char >= "A" && char <= "Z" || char >= "0" && char <= "9" || char === "_" || char === "$";
499
+ if (!validChar) {
500
+ return `'${key.replace(/'/g, "\\'")}'`;
501
+ }
502
+ }
503
+ return key;
504
+ };
505
+ #stringifyKeyV2 = (value) => {
506
+ return `'${value}'`;
507
+ };
429
508
  /**
430
509
  * Handle objects (properties)
431
510
  */
@@ -434,7 +513,7 @@ var TypeScriptDeserialzer = class {
434
513
  const propEntries = Object.entries(properties).map(([key, propSchema]) => {
435
514
  const isRequired = (schema.required ?? []).includes(key);
436
515
  const tsType = this.handle(propSchema, isRequired);
437
- return `${key}: ${tsType}`;
516
+ return `${this.#stringifyKeyV2(key)}: ${tsType}`;
438
517
  });
439
518
  if (schema.additionalProperties) {
440
519
  if (typeof schema.additionalProperties === "object") {
@@ -682,10 +761,16 @@ var ZodDeserialzer = class {
682
761
  }
683
762
  allOf(schemas) {
684
763
  const allOfSchemas = schemas.map((sub) => this.handle(sub, true));
764
+ if (allOfSchemas.length === 1) {
765
+ return allOfSchemas[0];
766
+ }
685
767
  return allOfSchemas.length ? `z.intersection(${allOfSchemas.join(", ")})` : allOfSchemas[0];
686
768
  }
687
769
  anyOf(schemas, required) {
688
770
  const anyOfSchemas = schemas.map((sub) => this.handle(sub, false));
771
+ if (anyOfSchemas.length === 1) {
772
+ return anyOfSchemas[0];
773
+ }
689
774
  return anyOfSchemas.length > 1 ? `z.union([${anyOfSchemas.join(", ")}])${appendOptional2(required)}` : (
690
775
  // Handle an invalid anyOf with one schema
691
776
  anyOfSchemas[0]
@@ -701,6 +786,9 @@ var ZodDeserialzer = class {
701
786
  }
702
787
  return this.handle(sub, false);
703
788
  });
789
+ if (oneOfSchemas.length === 1) {
790
+ return oneOfSchemas[0];
791
+ }
704
792
  return oneOfSchemas.length > 1 ? `z.union([${oneOfSchemas.join(", ")}])${appendOptional2(required)}` : (
705
793
  // Handle an invalid oneOf with one schema
706
794
  oneOfSchemas[0]
@@ -860,7 +948,18 @@ var defaults = {
860
948
  };
861
949
  function generateCode(config) {
862
950
  const commonSchemas = {};
863
- const zodDeserialzer = new ZodDeserialzer(config.spec);
951
+ const commonZod = /* @__PURE__ */ new Map();
952
+ const commonZodImports = [];
953
+ const zodDeserialzer = new ZodDeserialzer(config.spec, (model, schema) => {
954
+ commonZod.set(model, schema);
955
+ commonZodImports.push({
956
+ defaultImport: void 0,
957
+ isTypeOnly: true,
958
+ moduleSpecifier: `./${model}.ts`,
959
+ namedImports: [{ isTypeOnly: true, name: model }],
960
+ namespaceImport: void 0
961
+ });
962
+ });
864
963
  const groups = {};
865
964
  const outputs = {};
866
965
  for (const [path, methods2] of Object.entries(config.spec.paths ?? {})) {
@@ -994,26 +1093,15 @@ function generateCode(config) {
994
1093
  responseContent["application/json"].schema,
995
1094
  true
996
1095
  ) : "ReadableStream";
997
- for (const it of mergeImports(imports)) {
998
- const singleImport = it.defaultImport ?? it.namespaceImport;
999
- if (singleImport && responseSchema.includes(singleImport)) {
1000
- output.push(importsToString(it).join("\n"));
1001
- } else if (it.namedImports.length) {
1002
- for (const namedImport of it.namedImports) {
1003
- if (responseSchema.includes(namedImport.name)) {
1004
- output.push(importsToString(it).join("\n"));
1005
- }
1006
- }
1007
- }
1008
- }
1096
+ output.push(...useImports(responseSchema, imports));
1009
1097
  output.push(
1010
- `export type ${pascalcase2(operationName + " output")} = ${responseSchema}`
1098
+ `export type ${pascalcase(operationName + " output")} = ${responseSchema}`
1011
1099
  );
1012
1100
  }
1013
1101
  }
1014
1102
  if (!foundResponse) {
1015
1103
  output.push(
1016
- `export type ${pascalcase2(operationName + " output")} = void`
1104
+ `export type ${pascalcase(operationName + " output")} = void`
1017
1105
  );
1018
1106
  }
1019
1107
  outputs[`${spinalcase2(operationName)}.ts`] = output.join("\n");
@@ -1025,8 +1113,8 @@ function generateCode(config) {
1025
1113
  contentType,
1026
1114
  schemas: types,
1027
1115
  formatOutput: () => ({
1028
- import: pascalcase2(operationName + " output"),
1029
- use: pascalcase2(operationName + " output")
1116
+ import: pascalcase(operationName + " output"),
1117
+ use: pascalcase(operationName + " output")
1030
1118
  }),
1031
1119
  trigger: {
1032
1120
  path,
@@ -1035,12 +1123,12 @@ function generateCode(config) {
1035
1123
  });
1036
1124
  }
1037
1125
  }
1038
- return { groups, commonSchemas, outputs };
1126
+ return { groups, commonSchemas, commonZod, outputs };
1039
1127
  }
1040
1128
  var interceptors_default = "export interface Interceptor {\n before?: (request: Request) => Promise<Request> | Request;\n after?: (response: Response) => Promise<Response> | Response;\n}\n\nexport const createDefaultHeadersInterceptor = (\n getHeaders: () => Record<string, string | undefined>,\n) => {\n return {\n before(request: Request) {\n const headers = getHeaders();\n\n for (const [key, value] of Object.entries(headers)) {\n // Only set the header if it doesn't already exist and has a value\n if (value !== undefined && !request.headers.has(key)) {\n request.headers.set(key, value);\n }\n }\n\n return request;\n },\n };\n};\n\nexport const createBaseUrlInterceptor = (getBaseUrl: () => string) => {\n return {\n before(request: Request) {\n const baseUrl = getBaseUrl();\n if (request.url.startsWith('local://')) {\n return new Request(request.url.replace('local://', baseUrl), request);\n }\n return request;\n },\n };\n};\n\nexport const logInterceptor = {\n before(request: Request) {\n console.log('Request', request);\n return request;\n },\n after(response: Response) {\n console.log('Response', response);\n return response;\n },\n};\n";
1041
1129
  var parse_response_default = "import { parse } from 'fast-content-type-parse';\n\nexport async function handleError(response: Response) {\n try {\n if (response.status >= 400 && response.status < 500) {\n const body = (await response.json()) as Record<string, any>;\n return {\n status: response.status,\n body: body,\n };\n }\n return new Error(\n `An error occurred while fetching the data. Status: ${response.status}`,\n );\n } catch (error) {\n return error as any;\n }\n}\n\nasync function handleChunkedResponse(response: Response, contentType: string) {\n const { type } = parse(contentType);\n\n switch (type) {\n case 'application/json': {\n let buffer = '';\n const reader = response.body!.getReader();\n const decoder = new TextDecoder();\n while (true) {\n const { value, done } = await reader.read();\n if (done) break;\n buffer += decoder.decode(value);\n }\n return JSON.parse(buffer);\n }\n case 'text/html':\n case 'text/plain': {\n let buffer = '';\n const reader = response.body!.getReader();\n const decoder = new TextDecoder();\n while (true) {\n const { value, done } = await reader.read();\n if (done) break;\n buffer += decoder.decode(value);\n }\n return buffer;\n }\n default:\n return response.body;\n }\n}\n\nexport async function parseResponse(response: Response) {\n const contentType = response.headers.get('Content-Type');\n if (!contentType) {\n throw new Error('Content-Type header is missing');\n }\n\n if (response.status === 204) {\n return null;\n }\n const isChunked = response.headers.get('Transfer-Encoding') === 'chunked';\n if (isChunked) {\n return response.body!;\n // return handleChunkedResponse(response, contentType);\n }\n\n const { type } = parse(contentType);\n switch (type) {\n case 'application/json':\n return response.json();\n case 'text/plain':\n return response.text();\n case 'text/html':\n return response.text();\n case 'text/xml':\n case 'application/xml':\n return response.text();\n case 'application/x-www-form-urlencoded': {\n const text = await response.text();\n return Object.fromEntries(new URLSearchParams(text));\n }\n case 'multipart/form-data':\n return response.formData();\n default:\n throw new Error(`Unsupported content type: ${contentType}`);\n }\n}\n";
1042
1130
  var parser_default = "import { z } from 'zod';\n\nexport type ParseError<T extends z.ZodType<any, any, any>> = {\n kind: 'parse';\n} & z.inferFlattenedErrors<T>;\n\nexport function parse<T extends z.ZodType>(\n schema: T,\n input: unknown,\n) {\n const result = schema.safeParse(input);\n if (!result.success) {\n const errors = result.error.flatten((issue) => issue);\n return [null, errors];\n }\n return [result.data as z.infer<T>, null];\n}\n";
1043
- var request_default = "export type Method = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\nexport type ContentType = 'xml' | 'json' | 'urlencoded' | 'multipart';\nexport type Endpoint =\n | `${ContentType} ${Method} ${string}`\n | `${Method} ${string}`;\n\nexport type BodyInit =\n | ArrayBuffer\n | Blob\n | FormData\n | URLSearchParams\n | null\n | string;\n\nexport function createUrl(path: string, query: URLSearchParams) {\n const url = new URL(path, `local://`);\n url.search = query.toString();\n return url;\n}\n\nfunction template(\n templateString: string,\n templateVariables: Record<string, any>,\n): string {\n const nargs = /{([0-9a-zA-Z_]+)}/g;\n return templateString.replace(nargs, (match, key: string, index: number) => {\n // Handle escaped double braces\n if (\n templateString[index - 1] === '{' &&\n templateString[index + match.length] === '}'\n ) {\n return key;\n }\n\n const result = key in templateVariables ? templateVariables[key] : null;\n return result === null || result === undefined ? '' : String(result);\n });\n}\n\ntype Input = Record<string, any>;\ntype Props = {\n inputHeaders: string[];\n inputQuery: string[];\n inputBody: string[];\n inputParams: string[];\n};\n\nabstract class Serializer {\n constructor(\n protected input: Input,\n protected props: Props,\n ) {}\n abstract getBody(): BodyInit | null;\n abstract getHeaders(): Record<string, string>;\n serialize(): Serialized {\n const headers = new Headers({});\n for (const header of this.props.inputHeaders) {\n headers.set(header, this.input[header]);\n }\n\n const query = new URLSearchParams();\n for (const key of this.props.inputQuery) {\n const value = this.input[key];\n if (value !== undefined) {\n query.set(key, String(value));\n }\n }\n\n const params = this.props.inputParams.reduce<Record<string, any>>(\n (acc, key) => {\n acc[key] = this.input[key];\n return acc;\n },\n {},\n );\n\n return {\n body: this.getBody(),\n query,\n params,\n headers: this.getHeaders(),\n };\n }\n}\n\ninterface Serialized {\n body: BodyInit | null;\n query: URLSearchParams;\n params: Record<string, any>;\n headers: Record<string, string>;\n}\n\nclass JsonSerializer extends Serializer {\n getBody(): BodyInit | null {\n const body: Record<string, any> = {};\n for (const prop of this.props.inputBody) {\n body[prop] = this.input[prop];\n }\n return JSON.stringify(body);\n }\n getHeaders(): Record<string, string> {\n return {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n };\n }\n}\n\nclass UrlencodedSerializer extends Serializer {\n getBody(): BodyInit | null {\n const body = new URLSearchParams();\n for (const prop of this.props.inputBody) {\n body.set(prop, this.input[prop]);\n }\n return body;\n }\n getHeaders(): Record<string, string> {\n return {};\n }\n}\n\nclass NoBodySerializer extends Serializer {\n getBody(): BodyInit | null {\n return null;\n }\n getHeaders(): Record<string, string> {\n return {};\n }\n}\n\nclass FormDataSerializer extends Serializer {\n getBody(): BodyInit | null {\n const body = new FormData();\n for (const prop of this.props.inputBody) {\n body.append(prop, this.input[prop]);\n }\n return body;\n }\n getHeaders(): Record<string, string> {\n return {};\n }\n}\n\nexport function json(input: Input, props: Props) {\n return new JsonSerializer(input, props).serialize();\n}\nexport function urlencoded(input: Input, props: Props) {\n return new UrlencodedSerializer(input, props).serialize();\n}\nexport function nobody(input: Input, props: Props) {\n return new NoBodySerializer(input, props).serialize();\n}\nexport function formdata(input: Input, props: Props) {\n return new FormDataSerializer(input, props).serialize();\n}\n\nexport function toRequest<T extends Endpoint>(\n endpoint: T,\n input: Serialized,\n): Request {\n const [method, path] = endpoint.split(' ');\n const pathVariable = template(path, input.params);\n\n const url = createUrl(pathVariable, input.query);\n return new Request(url, {\n method: method,\n headers: input.headers,\n body: method === 'GET' ? undefined : input.body,\n });\n}\n";
1131
+ var request_default = "export type Method = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\nexport type ContentType = 'xml' | 'json' | 'urlencoded' | 'multipart';\nexport type Endpoint =\n | `${ContentType} ${Method} ${string}`\n | `${Method} ${string}`;\n\nexport type BodyInit =\n | ArrayBuffer\n | Blob\n | FormData\n | URLSearchParams\n | null\n | string;\n\nexport function createUrl(path: string, query: URLSearchParams) {\n const url = new URL(path, `local://`);\n url.search = query.toString();\n return url;\n}\n\nfunction template(\n templateString: string,\n templateVariables: Record<string, any>,\n): string {\n const nargs = /{([0-9a-zA-Z_]+)}/g;\n return templateString.replace(nargs, (match, key: string, index: number) => {\n // Handle escaped double braces\n if (\n templateString[index - 1] === '{' &&\n templateString[index + match.length] === '}'\n ) {\n return key;\n }\n\n const result = key in templateVariables ? templateVariables[key] : null;\n return result === null || result === undefined ? '' : String(result);\n });\n}\n\ntype Input = Record<string, any>;\ntype Props = {\n inputHeaders: string[];\n inputQuery: string[];\n inputBody: string[];\n inputParams: string[];\n};\n\nabstract class Serializer {\n protected input: Input;\n protected props: Props;\n\n constructor(\n input: Input,\n props: Props,\n ) {\n this.input = input;\n this.props = props;\n }\n\n abstract getBody(): BodyInit | null;\n abstract getHeaders(): Record<string, string>;\n serialize(): Serialized {\n const headers = new Headers({});\n for (const header of this.props.inputHeaders) {\n headers.set(header, this.input[header]);\n }\n\n const query = new URLSearchParams();\n for (const key of this.props.inputQuery) {\n const value = this.input[key];\n if (value !== undefined) {\n query.set(key, String(value));\n }\n }\n\n const params = this.props.inputParams.reduce<Record<string, any>>(\n (acc, key) => {\n acc[key] = this.input[key];\n return acc;\n },\n {},\n );\n\n return {\n body: this.getBody(),\n query,\n params,\n headers: this.getHeaders(),\n };\n }\n}\n\ninterface Serialized {\n body: BodyInit | null;\n query: URLSearchParams;\n params: Record<string, any>;\n headers: Record<string, string>;\n}\n\nclass JsonSerializer extends Serializer {\n getBody(): BodyInit | null {\n const body: Record<string, any> = {};\n for (const prop of this.props.inputBody) {\n body[prop] = this.input[prop];\n }\n return JSON.stringify(body);\n }\n getHeaders(): Record<string, string> {\n return {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n };\n }\n}\n\nclass UrlencodedSerializer extends Serializer {\n getBody(): BodyInit | null {\n const body = new URLSearchParams();\n for (const prop of this.props.inputBody) {\n body.set(prop, this.input[prop]);\n }\n return body;\n }\n getHeaders(): Record<string, string> {\n return {};\n }\n}\n\nclass NoBodySerializer extends Serializer {\n getBody(): BodyInit | null {\n return null;\n }\n getHeaders(): Record<string, string> {\n return {};\n }\n}\n\nclass FormDataSerializer extends Serializer {\n getBody(): BodyInit | null {\n const body = new FormData();\n for (const prop of this.props.inputBody) {\n body.append(prop, this.input[prop]);\n }\n return body;\n }\n getHeaders(): Record<string, string> {\n return {};\n }\n}\n\nexport function json(input: Input, props: Props) {\n return new JsonSerializer(input, props).serialize();\n}\nexport function urlencoded(input: Input, props: Props) {\n return new UrlencodedSerializer(input, props).serialize();\n}\nexport function nobody(input: Input, props: Props) {\n return new NoBodySerializer(input, props).serialize();\n}\nexport function formdata(input: Input, props: Props) {\n return new FormDataSerializer(input, props).serialize();\n}\n\nexport function toRequest<T extends Endpoint>(\n endpoint: T,\n input: Serialized,\n): Request {\n const [method, path] = endpoint.split(' ');\n const pathVariable = template(path, input.params);\n\n const url = createUrl(pathVariable, input.query);\n return new Request(url, {\n method: method,\n headers: input.headers,\n body: method === 'GET' ? undefined : input.body,\n });\n}\n";
1044
1132
  var response_default = "export interface ApiResponse<Status extends number, Body extends unknown> {\n kind: 'response';\n status: Status;\n body: Body;\n}\n\n// 4xx Client Errors\nexport type BadRequest = ApiResponse<400, { message: string }>;\nexport type Unauthorized = ApiResponse<401, { message: string }>;\nexport type PaymentRequired = ApiResponse<402, { message: string }>;\nexport type Forbidden = ApiResponse<403, { message: string }>;\nexport type NotFound = ApiResponse<404, { message: string }>;\nexport type MethodNotAllowed = ApiResponse<405, { message: string }>;\nexport type NotAcceptable = ApiResponse<406, { message: string }>;\nexport type Conflict = ApiResponse<409, { message: string }>;\nexport type Gone = ApiResponse<410, { message: string }>;\nexport type UnprocessableEntity = ApiResponse<422, { message: string; errors?: Record<string, string[]> }>;\nexport type TooManyRequests = ApiResponse<429, { message: string; retryAfter?: string }>;\nexport type PayloadTooLarge = ApiResponse<413, { message: string; }>;\nexport type UnsupportedMediaType = ApiResponse<415, { message: string; }>;\n\n// 5xx Server Errors\nexport type InternalServerError = ApiResponse<500, { message: string }>;\nexport type NotImplemented = ApiResponse<501, { message: string }>;\nexport type BadGateway = ApiResponse<502, { message: string }>;\nexport type ServiceUnavailable = ApiResponse<503, { message: string; retryAfter?: string }>;\nexport type GatewayTimeout = ApiResponse<504, { message: string }>;\n\nexport type ClientError =\n | BadRequest\n | Unauthorized\n | PaymentRequired\n | Forbidden\n | NotFound\n | MethodNotAllowed\n | NotAcceptable\n | Conflict\n | Gone\n | UnprocessableEntity\n | TooManyRequests;\n\nexport type ServerError =\n | InternalServerError\n | NotImplemented\n | BadGateway\n | ServiceUnavailable\n | GatewayTimeout;\n\nexport type ProblematicResponse = ClientError | ServerError;\n";
1045
1133
  var send_request_default = "import z from 'zod';\n\nimport type { Interceptor } from './interceptors.ts';\nimport { handleError, parseResponse } from './parse-response.ts';\nimport { parse } from './parser.ts';\n\nexport interface RequestSchema {\n schema: z.ZodType;\n toRequest: (input: any) => Request;\n}\n\nexport const fetchType = z\n .function()\n .args(z.instanceof(Request))\n .returns(z.promise(z.instanceof(Response)))\n .optional();\n\nexport async function sendRequest(\n input: any,\n route: RequestSchema,\n options: {\n fetch?: z.infer<typeof fetchType>;\n interceptors?: Interceptor[];\n },\n) {\n const { interceptors = [] } = options;\n const [parsedInput, parseError] = parse(route.schema, input);\n if (parseError) {\n return [null as never, { ...parseError, kind: 'parse' } as never] as const;\n }\n\n let request = route.toRequest(parsedInput as never);\n for (const interceptor of interceptors) {\n if (interceptor.before) {\n request = await interceptor.before(request);\n }\n }\n\n let response = await (options.fetch ?? fetch)(request);\n\n for (let i = interceptors.length - 1; i >= 0; i--) {\n const interceptor = interceptors[i];\n if (interceptor.after) {\n response = await interceptor.after(response.clone());\n }\n }\n\n if (response.ok) {\n const data = await parseResponse(response);\n return [data as never, null] as const;\n }\n const error = await handleError(response);\n return [null as never, { ...error, kind: 'response' }] as const;\n}\n";
1046
1134
  function security(spec) {
@@ -1064,23 +1152,24 @@ function security(spec) {
1064
1152
  return options;
1065
1153
  }
1066
1154
  async function generate(spec, settings) {
1067
- const { commonSchemas, groups, outputs } = generateCode({
1155
+ const { commonSchemas, groups, outputs, commonZod } = generateCode({
1068
1156
  spec,
1069
1157
  style: "github",
1070
1158
  target: "javascript"
1071
1159
  });
1072
1160
  const output = settings.mode === "full" ? join2(settings.output, "src") : settings.output;
1073
1161
  const options = security(spec);
1074
- const clientFiles = generateClientSdk({
1162
+ const clientFiles = generateSDK({
1075
1163
  name: settings.name || "Client",
1076
1164
  operations: groups,
1077
1165
  servers: spec.servers?.map((server) => server.url) || [],
1078
1166
  options
1079
1167
  });
1168
+ const inputFiles = generateInputs(groups, commonZod);
1080
1169
  await writeFiles(output, {
1081
- "outputs/index.ts": "",
1082
- "inputs/index.ts": ""
1083
- // 'models/index.ts': '',
1170
+ "outputs/.gitkeep": "",
1171
+ "inputs/.gitkeep": "",
1172
+ "models/.getkeep": ""
1084
1173
  // 'README.md': readme,
1085
1174
  });
1086
1175
  await writeFiles(join2(output, "http"), {
@@ -1092,15 +1181,16 @@ async function generate(spec, settings) {
1092
1181
  "request.ts": request_default
1093
1182
  });
1094
1183
  await writeFiles(join2(output, "outputs"), outputs);
1095
- const imports = Object.entries(commonSchemas).map(([name]) => name);
1184
+ const modelsImports = Object.entries(commonSchemas).map(([name]) => name);
1096
1185
  await writeFiles(output, {
1097
1186
  ...clientFiles,
1187
+ ...inputFiles,
1098
1188
  ...Object.fromEntries(
1099
1189
  Object.entries(commonSchemas).map(([name, schema]) => [
1100
1190
  `models/${name}.ts`,
1101
1191
  [
1102
1192
  `import { z } from 'zod';`,
1103
- ...exclude(imports, [name]).map(
1193
+ ...exclude2(modelsImports, [name]).map(
1104
1194
  (it) => `import type { ${it} } from './${it}.ts';`
1105
1195
  ),
1106
1196
  `export type ${name} = ${schema};`
@@ -1111,25 +1201,58 @@ async function generate(spec, settings) {
1111
1201
  const folders = [
1112
1202
  getFolderExports(output),
1113
1203
  getFolderExports(join2(output, "outputs")),
1114
- getFolderExports(join2(output, "inputs")),
1204
+ getFolderExports(
1205
+ join2(output, "inputs"),
1206
+ ["ts"],
1207
+ (dirent) => dirent.isDirectory() && dirent.name === "schemas"
1208
+ ),
1115
1209
  getFolderExports(join2(output, "http"))
1116
1210
  ];
1117
- if (imports.length) {
1211
+ if (modelsImports.length) {
1118
1212
  folders.push(getFolderExports(join2(output, "models")));
1119
1213
  }
1120
1214
  const [index, outputIndex, inputsIndex, httpIndex, modelsIndex] = await Promise.all(folders);
1121
1215
  await writeFiles(output, {
1122
1216
  "index.ts": index,
1123
1217
  "outputs/index.ts": outputIndex,
1124
- "inputs/index.ts": inputsIndex,
1218
+ "inputs/index.ts": inputsIndex || null,
1125
1219
  "http/index.ts": httpIndex,
1126
- ...imports.length ? { "models/index.ts": modelsIndex } : {}
1220
+ ...modelsImports.length ? { "models/index.ts": modelsIndex } : {}
1127
1221
  });
1128
1222
  if (settings.mode === "full") {
1129
1223
  await writeFiles(settings.output, {
1130
1224
  "package.json": {
1131
1225
  ignoreIfExists: true,
1132
- content: `{"type":"module","main":"./src/index.ts","dependencies":{"fast-content-type-parse":"^3.0.0"}}`
1226
+ content: JSON.stringify(
1227
+ {
1228
+ type: "module",
1229
+ main: "./src/index.ts",
1230
+ dependencies: { "fast-content-type-parse": "^3.0.0" }
1231
+ },
1232
+ null,
1233
+ 2
1234
+ )
1235
+ },
1236
+ "tsconfig.json": {
1237
+ ignoreIfExists: false,
1238
+ content: JSON.stringify(
1239
+ {
1240
+ compilerOptions: {
1241
+ skipLibCheck: true,
1242
+ skipDefaultLibCheck: true,
1243
+ target: "ESNext",
1244
+ module: "ESNext",
1245
+ noEmit: true,
1246
+ allowImportingTsExtensions: true,
1247
+ verbatimModuleSyntax: true,
1248
+ baseUrl: ".",
1249
+ moduleResolution: "bundler"
1250
+ },
1251
+ include: ["**/*.ts"]
1252
+ },
1253
+ null,
1254
+ 2
1255
+ )
1133
1256
  }
1134
1257
  });
1135
1258
  }
@@ -1138,9 +1261,6 @@ async function generate(spec, settings) {
1138
1261
  env: npmRunPathEnv()
1139
1262
  });
1140
1263
  }
1141
- function exclude(list, exclude2) {
1142
- return list.filter((it) => !exclude2.includes(it));
1143
- }
1144
1264
 
1145
1265
  // packages/cli/src/lib/generate.ts
1146
1266
  var specOption = new Option(
package/dist/index.js.map CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "version": 3,
3
3
  "sources": ["../src/lib/cli.ts", "../src/lib/generate.ts", "../../typescript/src/lib/generate.ts", "../../core/src/lib/deriver.ts", "../../core/src/lib/file-system.ts", "../../core/src/lib/paths.ts", "../../core/src/lib/program.ts", "../../core/src/index.ts", "../../typescript/src/lib/generator.ts", "../../typescript/src/lib/utils.ts", "../../typescript/src/lib/sdk.ts", "../../typescript/src/lib/client.ts", "../../typescript/src/lib/emitters/interface.ts", "../../typescript/src/lib/emitters/zod.ts", "../../typescript/src/lib/http/interceptors.txt", "../../typescript/src/lib/http/parse-response.txt", "../../typescript/src/lib/http/parser.txt", "../../typescript/src/lib/http/request.txt", "../../typescript/src/lib/http/response.txt", "../../typescript/src/lib/http/send-request.txt", "../../typescript/src/lib/watcher.ts"],
4
- "sourcesContent": ["#!/usr/bin/env node\nimport { Command, program } from 'commander';\n\nimport generate from './generate.ts';\n\nconst cli = program\n .description(`CLI tool to interact with SDK-IT.`)\n .addCommand(generate, { isDefault: true })\n .addCommand(\n new Command('_internal').action(() => {\n // do nothing\n }),\n { hidden: true },\n )\n .parse(process.argv);\n\nexport default cli;\n", "import { Command, Option } from 'commander';\nimport { execFile } from 'node:child_process';\nimport { readFile } from 'node:fs/promises';\nimport { extname } from 'node:path';\nimport { parse } from 'yaml';\n\nimport { generate } from '@sdk-it/typescript';\n\ninterface Options {\n spec: string;\n output: string;\n language: string;\n mode?: 'full' | 'minimal';\n name?: string;\n /**\n * Command to run the formatter.\n * @example 'biome check $SDK_IT_OUTPUT --write'\n * @example 'prettier $SDK_IT_OUTPUT --write'\n */\n formatter?: string;\n}\n\nconst specOption = new Option(\n '-s, --spec <spec>',\n 'Path to OpenAPI specification file',\n);\n\nconst outputOption = new Option(\n '-o, --output <output>',\n 'Output directory for the generated SDK',\n);\n\nasync function loadRemote(location: string) {\n const extName = extname(location);\n const response = await fetch(location);\n switch (extName) {\n case '.json':\n return response.json();\n case '.yaml':\n case '.yml': {\n const text = await response.text();\n return parse(text);\n }\n default:\n throw new Error(`Unsupported file extension: ${extName}`);\n }\n}\n\nasync function loadLocal(location: string) {\n const extName = extname(location);\n switch (extName) {\n case '.json':\n return import(location);\n case '.yaml':\n case '.yml': {\n const text = await await readFile(location, 'utf-8');\n return parse(text);\n }\n default:\n throw new Error(`Unsupported file extension: ${extName}`);\n }\n}\n\nfunction loadSpec(location: string) {\n const [protocol] = location.split(':');\n if (protocol === 'http' || protocol === 'https') {\n return loadRemote(location);\n }\n return loadLocal(location);\n}\n\nexport default new Command('generate')\n .description(`Generate SDK out of a openapi spec file.`)\n .addOption(specOption.makeOptionMandatory(true))\n .addOption(outputOption.makeOptionMandatory(true))\n .option('-l, --language <language>', 'Programming language for the SDK')\n .option(\n '-m, --mode <mode>',\n 'full: generate a full project including package.json and tsconfig.json. useful for monorepo/workspaces minimal: generate only the client sdk',\n )\n .option('-n, --name <name>', 'Name of the generated client', 'Client')\n .option('--formatter <formatter>', 'Formatter to use for the generated code')\n .action(async (options: Options) => {\n const spec = await loadSpec(options.spec);\n await generate(spec, {\n output: options.output,\n mode: options.mode || 'minimal',\n name: options.name,\n formatCode: ({ env, output }) => {\n if (options.formatter) {\n const [command, ...args] = options.formatter.split(' ');\n execFile(command, args, { env: { ...env, SDK_IT_OUTPUT: output } });\n }\n },\n });\n });\n", "import { join } from 'node:path';\nimport { npmRunPathEnv } from 'npm-run-path';\nimport type { OpenAPIObject } from 'openapi3-ts/oas31';\n\nimport { getFolderExports, methods, writeFiles } from '@sdk-it/core';\n\nimport { generateCode } from './generator.ts';\nimport interceptors from './http/interceptors.txt';\nimport parseResponse from './http/parse-response.txt';\nimport parserTxt from './http/parser.txt';\nimport requestTxt from './http/request.txt';\nimport responseTxt from './http/response.txt';\nimport sendRequest from './http/send-request.txt';\nimport { generateClientSdk } from './sdk.ts';\nimport { securityToOptions } from './utils.ts';\n\nfunction security(spec: OpenAPIObject) {\n const security = spec.security || [];\n const components = spec.components || {};\n const securitySchemas = components.securitySchemes || {};\n const paths = Object.values(spec.paths ?? {});\n\n const options = securityToOptions(security, securitySchemas);\n\n for (const it of paths) {\n for (const method of methods) {\n const operation = it[method];\n if (!operation) {\n continue;\n }\n Object.assign(\n options,\n securityToOptions(operation.security || [], securitySchemas, 'input'),\n );\n }\n }\n return options;\n}\n\nexport async function generate(\n spec: OpenAPIObject,\n settings: {\n output: string;\n name?: string;\n /**\n * full: generate a full project including package.json and tsconfig.json. useful for monorepo/workspaces\n * minimal: generate only the client sdk\n */\n mode?: 'full' | 'minimal';\n formatCode?: (options: {\n output: string;\n env: ReturnType<typeof npmRunPathEnv>;\n }) => void | Promise<void>;\n },\n) {\n const { commonSchemas, groups, outputs } = generateCode({\n spec,\n style: 'github',\n target: 'javascript',\n });\n const output =\n settings.mode === 'full' ? join(settings.output, 'src') : settings.output;\n\n const options = security(spec);\n\n const clientFiles = generateClientSdk({\n name: settings.name || 'Client',\n operations: groups,\n servers: spec.servers?.map((server) => server.url) || [],\n options: options,\n });\n\n // const readme = generateReadme(spec, {\n // name: settings.name || 'Client',\n // });\n\n // TODO: use .getkeep instead\n await writeFiles(output, {\n 'outputs/index.ts': '',\n 'inputs/index.ts': '',\n // 'models/index.ts': '',\n // 'README.md': readme,\n });\n\n await writeFiles(join(output, 'http'), {\n 'interceptors.ts': interceptors,\n 'parse-response.ts': parseResponse,\n 'send-request.ts': sendRequest,\n 'response.ts': responseTxt,\n 'parser.ts': parserTxt,\n 'request.ts': requestTxt,\n });\n\n await writeFiles(join(output, 'outputs'), outputs);\n\n const imports = Object.entries(commonSchemas).map(([name]) => name);\n await writeFiles(output, {\n ...clientFiles,\n ...Object.fromEntries(\n Object.entries(commonSchemas).map(([name, schema]) => [\n `models/${name}.ts`,\n [\n `import { z } from 'zod';`,\n ...exclude(imports, [name]).map(\n (it) => `import type { ${it} } from './${it}.ts';`,\n ),\n `export type ${name} = ${schema};`,\n ].join('\\n'),\n ]),\n ),\n });\n\n const folders = [\n getFolderExports(output),\n getFolderExports(join(output, 'outputs')),\n getFolderExports(join(output, 'inputs')),\n getFolderExports(join(output, 'http')),\n ];\n if (imports.length) {\n folders.push(getFolderExports(join(output, 'models')));\n }\n const [index, outputIndex, inputsIndex, httpIndex, modelsIndex] =\n await Promise.all(folders);\n await writeFiles(output, {\n 'index.ts': index,\n 'outputs/index.ts': outputIndex,\n 'inputs/index.ts': inputsIndex,\n 'http/index.ts': httpIndex,\n ...(imports.length ? { 'models/index.ts': modelsIndex } : {}),\n });\n if (settings.mode === 'full') {\n await writeFiles(settings.output, {\n 'package.json': {\n ignoreIfExists: true,\n content: `{\"type\":\"module\",\"main\":\"./src/index.ts\",\"dependencies\":{\"fast-content-type-parse\":\"^3.0.0\"}}`,\n },\n });\n }\n\n await settings.formatCode?.({\n output: output,\n env: npmRunPathEnv(),\n });\n}\n\nfunction exclude<T>(list: T[], exclude: T[]): T[] {\n return list.filter((it) => !exclude.includes(it));\n}\n", "import ts, { TypeFlags, symbolName } from 'typescript';\n\ntype Collector = Record<string, any>;\nexport const deriveSymbol = Symbol.for('serialize');\nexport const $types = Symbol.for('types');\nconst defaults: Record<string, string> = {\n Readable: 'any',\n ReadableStream: 'any',\n DateConstructor: 'string',\n ArrayBufferConstructor: 'any',\n SharedArrayBufferConstructor: 'any',\n Int8ArrayConstructor: 'any',\n Uint8Array: 'any',\n};\nexport class TypeDeriver {\n public readonly collector: Collector = {};\n public readonly checker: ts.TypeChecker;\n constructor(checker: ts.TypeChecker) {\n this.checker = checker;\n }\n\n serializeType(type: ts.Type): any {\n const indexType = type.getStringIndexType();\n if (indexType) {\n return {\n [deriveSymbol]: true,\n kind: 'record',\n optional: false,\n [$types]: [this.serializeType(indexType)],\n };\n }\n if (type.flags & TypeFlags.Any) {\n return {\n [deriveSymbol]: true,\n optional: false,\n [$types]: [],\n };\n }\n if (type.isStringLiteral()) {\n return {\n [deriveSymbol]: true,\n optional: false,\n kind: 'literal',\n value: type.value,\n [$types]: ['string'],\n };\n }\n if (type.isNumberLiteral()) {\n return {\n [deriveSymbol]: true,\n optional: false,\n kind: 'literal',\n value: type.value,\n [$types]: ['number'],\n };\n }\n if (type.flags & TypeFlags.TemplateLiteral) {\n return {\n [deriveSymbol]: true,\n optional: false,\n [$types]: ['string'],\n };\n }\n if (type.flags & TypeFlags.String) {\n return {\n [deriveSymbol]: true,\n optional: false,\n [$types]: ['string'],\n };\n }\n if (type.flags & TypeFlags.Number) {\n return {\n [deriveSymbol]: true,\n optional: false,\n [$types]: ['number'],\n };\n }\n if (type.flags & ts.TypeFlags.Boolean) {\n return {\n [deriveSymbol]: true,\n optional: false,\n [$types]: ['boolean'],\n };\n }\n if (type.flags & TypeFlags.Null) {\n return {\n [deriveSymbol]: true,\n optional: true,\n [$types]: ['null'],\n };\n }\n if (type.isIntersection()) {\n let optional: boolean | undefined;\n const types: any[] = [];\n for (const unionType of type.types) {\n if (optional === undefined) {\n optional = (unionType.flags & ts.TypeFlags.Undefined) !== 0;\n if (optional) {\n continue;\n }\n }\n\n types.push(this.serializeType(unionType));\n }\n return {\n [deriveSymbol]: true,\n kind: 'intersection',\n optional,\n [$types]: types,\n };\n }\n if (type.isUnion()) {\n let optional: boolean | undefined;\n const types: any[] = [];\n for (const unionType of type.types) {\n if (optional === undefined) {\n // ignore undefined\n optional = (unionType.flags & ts.TypeFlags.Undefined) !== 0;\n if (optional) {\n continue;\n }\n }\n\n types.push(this.serializeType(unionType));\n }\n return {\n [deriveSymbol]: true,\n kind: 'union',\n optional,\n [$types]: types,\n };\n }\n if (this.checker.isArrayLikeType(type)) {\n const [argType] = this.checker.getTypeArguments(type as ts.TypeReference);\n if (!argType) {\n const typeName = type.symbol?.getName() || '<unknown>';\n console.warn(\n `Could not find generic type argument for array type ${typeName}`,\n );\n return {\n [deriveSymbol]: true,\n optional: false,\n kind: 'array',\n [$types]: ['any'],\n };\n }\n const typeSymbol = argType.getSymbol();\n if (!typeSymbol) {\n return {\n [deriveSymbol]: true,\n optional: false,\n kind: 'array',\n [$types]: [this.serializeType(argType)],\n };\n }\n\n if (typeSymbol.valueDeclaration) {\n return {\n kind: 'array',\n [deriveSymbol]: true,\n [$types]: [this.serializeNode(typeSymbol.valueDeclaration)],\n };\n }\n const maybeDeclaration = typeSymbol.declarations?.[0];\n if (maybeDeclaration) {\n if (ts.isMappedTypeNode(maybeDeclaration)) {\n const resolvedType = this.checker\n .getPropertiesOfType(argType)\n .reduce<Record<string, unknown>>((acc, prop) => {\n const propType = this.checker.getTypeOfSymbol(prop);\n acc[prop.name] = this.serializeType(propType);\n return acc;\n }, {});\n return {\n kind: 'array',\n optional: false,\n [deriveSymbol]: true,\n [$types]: [resolvedType],\n };\n } else {\n return {\n kind: 'array',\n ...this.serializeNode(maybeDeclaration),\n };\n }\n }\n\n return {\n kind: 'array',\n optional: false,\n [deriveSymbol]: true,\n [$types]: ['any'],\n };\n }\n if (type.isClass()) {\n const declaration = type.symbol?.valueDeclaration;\n if (!declaration) {\n return {\n [deriveSymbol]: true,\n optional: false,\n [$types]: [type.symbol.getName()],\n };\n }\n return this.serializeNode(declaration);\n }\n if (isInterfaceType(type)) {\n const valueDeclaration =\n type.symbol.valueDeclaration ?? type.symbol.declarations?.[0];\n if (!valueDeclaration) {\n return {\n [deriveSymbol]: true,\n optional: false,\n [$types]: [type.symbol.getName()],\n };\n }\n return this.serializeNode(valueDeclaration);\n }\n if (type.flags & TypeFlags.Object) {\n if (defaults[symbolName(type.symbol)]) {\n return {\n [deriveSymbol]: true,\n optional: false,\n [$types]: [defaults[type.symbol.name]],\n };\n }\n const properties = this.checker.getPropertiesOfType(type);\n if (properties.length > 0) {\n const serializedProps: Record<string, any> = {};\n for (const prop of properties) {\n const propAssingment = (prop.getDeclarations() ?? []).find((it) =>\n ts.isPropertyAssignment(it),\n );\n // get literal properties values if any\n if (propAssingment) {\n const type = this.checker.getTypeAtLocation(\n propAssingment.initializer,\n );\n serializedProps[prop.name] = this.serializeType(type);\n }\n if (\n (prop.getDeclarations() ?? []).find((it) =>\n ts.isPropertySignature(it),\n )\n ) {\n const propType = this.checker.getTypeOfSymbol(prop);\n serializedProps[prop.name] = this.serializeType(propType);\n }\n }\n return {\n [deriveSymbol]: true,\n kind: 'object',\n optional: false,\n [$types]: [serializedProps],\n };\n }\n const declaration =\n type.symbol.valueDeclaration ?? type.symbol.declarations?.[0];\n if (!declaration) {\n return {\n [deriveSymbol]: true,\n optional: false,\n [$types]: [type.symbol.getName()],\n };\n }\n return this.serializeNode(declaration);\n }\n console.warn(`Unhandled type: ${type.flags} ${ts.TypeFlags[type.flags]}`);\n\n return {\n [deriveSymbol]: true,\n optional: false,\n [$types]: [\n this.checker.typeToString(\n type,\n undefined,\n ts.TypeFormatFlags.NoTruncation,\n ),\n ],\n };\n }\n\n serializeNode(node: ts.Node): any {\n if (ts.isObjectLiteralExpression(node)) {\n const symbolType = this.checker.getTypeAtLocation(node);\n const props: Record<string, any> = {};\n for (const symbol of symbolType.getProperties()) {\n const type = this.checker.getTypeOfSymbol(symbol);\n props[symbol.name] = this.serializeType(type);\n }\n\n // get literal properties values if any\n for (const prop of node.properties) {\n if (ts.isPropertyAssignment(prop)) {\n const type = this.checker.getTypeAtLocation(prop.initializer);\n props[prop.name.getText()] = this.serializeType(type);\n }\n }\n\n return props;\n }\n if (ts.isPropertyAccessExpression(node)) {\n const symbol = this.checker.getSymbolAtLocation(node.name);\n if (!symbol) {\n console.warn(`No symbol found for ${node.name.getText()}`);\n return null;\n }\n const type = this.checker.getTypeOfSymbol(symbol);\n return this.serializeType(type);\n }\n if (ts.isPropertySignature(node)) {\n const symbol = this.checker.getSymbolAtLocation(node.name);\n if (!symbol) {\n console.warn(`No symbol found for ${node.name.getText()}`);\n return null;\n }\n const type = this.checker.getTypeOfSymbol(symbol);\n return this.serializeType(type);\n }\n if (ts.isPropertyDeclaration(node)) {\n const symbol = this.checker.getSymbolAtLocation(node.name);\n if (!symbol) {\n console.warn(`No symbol found for ${node.name.getText()}`);\n return null;\n }\n const type = this.checker.getTypeOfSymbol(symbol);\n return this.serializeType(type);\n }\n if (ts.isInterfaceDeclaration(node)) {\n if (!node.name?.text) {\n throw new Error('Interface has no name');\n }\n if (defaults[node.name.text]) {\n return {\n [deriveSymbol]: true,\n optional: false,\n [$types]: [defaults[node.name.text]],\n };\n }\n if (!this.collector[node.name.text]) {\n this.collector[node.name.text] = {};\n const members: Record<string, any> = {};\n for (const member of node.members.filter(ts.isPropertySignature)) {\n members[member.name.getText()] = this.serializeNode(member);\n }\n this.collector[node.name.text] = members;\n }\n return {\n [deriveSymbol]: true,\n optional: false,\n [$types]: [`#/components/schemas/${node.name.text}`],\n };\n }\n if (ts.isClassDeclaration(node)) {\n if (!node.name?.text) {\n throw new Error('Class has no name');\n }\n if (defaults[node.name.text]) {\n return {\n [deriveSymbol]: true,\n optional: false,\n [$types]: [defaults[node.name.text]],\n };\n }\n\n if (!this.collector[node.name.text]) {\n this.collector[node.name.text] = {};\n const members: Record<string, unknown> = {};\n for (const member of node.members.filter(ts.isPropertyDeclaration)) {\n members[member.name!.getText()] = this.serializeNode(member);\n }\n this.collector[node.name.text] = members;\n }\n return {\n [deriveSymbol]: true,\n optional: false,\n [$types]: [`#/components/schemas/${node.name.text}`],\n $ref: `#/components/schemas/${node.name.text}`,\n };\n }\n if (ts.isVariableDeclaration(node)) {\n const symbol = this.checker.getSymbolAtLocation(node.name);\n if (!symbol) {\n console.warn(`No symbol found for ${node.name.getText()}`);\n return null;\n }\n if (!node.type) {\n console.warn(`No type found for ${node.name.getText()}`);\n return 'any';\n }\n const type = this.checker.getTypeFromTypeNode(node.type);\n return this.serializeType(type);\n }\n if (ts.isIdentifier(node)) {\n const symbol = this.checker.getSymbolAtLocation(node);\n if (!symbol) {\n console.warn(`Identifer: No symbol found for ${node.getText()}`);\n return null;\n }\n const type = this.checker.getTypeAtLocation(node);\n return this.serializeType(type);\n }\n if (ts.isAwaitExpression(node)) {\n const type = this.checker.getTypeAtLocation(node);\n return this.serializeType(type);\n }\n if (ts.isCallExpression(node)) {\n const type = this.checker.getTypeAtLocation(node);\n return this.serializeType(type);\n }\n if (ts.isAsExpression(node)) {\n const type = this.checker.getTypeAtLocation(node);\n return this.serializeType(type);\n }\n if (ts.isTypeLiteralNode(node)) {\n const symbolType = this.checker.getTypeAtLocation(node);\n const props: Record<string, unknown> = {};\n for (const symbol of symbolType.getProperties()) {\n const type = this.checker.getTypeOfSymbol(symbol);\n props[symbol.name] = this.serializeType(type);\n }\n return {\n [deriveSymbol]: true,\n optional: false,\n [$types]: [props],\n };\n }\n if (node.kind === ts.SyntaxKind.NullKeyword) {\n return {\n [deriveSymbol]: true,\n optional: true,\n [$types]: ['null'],\n };\n }\n if (node.kind === ts.SyntaxKind.BooleanKeyword) {\n return {\n [deriveSymbol]: true,\n optional: false,\n [$types]: ['boolean'],\n };\n }\n if (node.kind === ts.SyntaxKind.TrueKeyword) {\n return {\n [deriveSymbol]: true,\n optional: false,\n kind: 'literal',\n value: true,\n [$types]: ['boolean'],\n };\n }\n if (node.kind === ts.SyntaxKind.FalseKeyword) {\n return {\n [deriveSymbol]: true,\n optional: false,\n kind: 'literal',\n value: false,\n [$types]: ['boolean'],\n };\n }\n if (ts.isArrayLiteralExpression(node)) {\n const type = this.checker.getTypeAtLocation(node);\n return this.serializeType(type);\n }\n\n console.warn(`Unhandled node: ${ts.SyntaxKind[node.kind]} ${node.flags}`);\n return {\n [deriveSymbol]: true,\n optional: false,\n [$types]: ['any'],\n };\n }\n}\n\nfunction isInterfaceType(type: ts.Type): boolean {\n if (type.isClassOrInterface()) {\n // Check if it's an interface\n return !!(type.symbol.flags & ts.SymbolFlags.Interface);\n }\n return false;\n}\n", "import { mkdir, readFile, readdir, stat, writeFile } from 'node:fs/promises';\nimport { dirname, isAbsolute, join } from 'node:path';\n\nexport async function getFile(filePath: string) {\n if (await exist(filePath)) {\n return readFile(filePath, 'utf-8');\n }\n return null;\n}\n\nexport async function exist(file: string): Promise<boolean> {\n return stat(file)\n .then(() => true)\n .catch(() => false);\n}\n\nexport async function readFolder(path: string) {\n if (await exist(path)) {\n return readdir(path);\n }\n return [] as string[];\n}\n\nexport async function writeFiles(\n dir: string,\n contents: Record<\n string,\n string | { content: string; ignoreIfExists?: boolean }\n >,\n) {\n return Promise.all(\n Object.entries(contents).map(async ([file, content]) => {\n const filePath = isAbsolute(file) ? file : join(dir, file);\n await mkdir(dirname(filePath), { recursive: true });\n if (typeof content === 'string') {\n await writeFile(filePath, content, 'utf-8');\n } else {\n if (content.ignoreIfExists) {\n if (!(await exist(filePath))) {\n await writeFile(filePath, content.content, 'utf-8');\n }\n }\n }\n }),\n );\n}\n\nexport async function getFolderExports(folder: string, extensions = ['ts']) {\n const files = await readdir(folder, { withFileTypes: true });\n const exports: string[] = [];\n for (const file of files) {\n if (file.isDirectory()) {\n exports.push(`export * from './${file.name}/index.ts';`);\n } else if (\n file.name !== 'index.ts' &&\n extensions.includes(getExt(file.name))\n ) {\n exports.push(`export * from './${file.name}';`);\n }\n }\n return exports.join('\\n');\n}\n\nexport const getExt = (fileName?: string) => {\n if (!fileName) {\n return ''; // shouldn't happen as there will always be a file name\n }\n const lastDot = fileName.lastIndexOf('.');\n if (lastDot === -1) {\n return '';\n }\n const ext = fileName\n .slice(lastDot + 1)\n .split('/')\n .filter(Boolean)\n .join('');\n if (ext === fileName) {\n // files that have no extension\n return '';\n }\n return ext || 'txt';\n};\n", "import type {\n HeadersObject,\n OperationObject,\n ParameterObject,\n PathsObject,\n ResponseObject,\n ResponsesObject,\n SchemaObject,\n} from 'openapi3-ts/oas31';\n\nimport { $types } from './deriver.ts';\n\nexport type Method =\n | 'get'\n | 'post'\n | 'put'\n | 'patch'\n | 'delete'\n | 'trace'\n | 'head';\nexport const methods = [\n 'get',\n 'post',\n 'put',\n 'patch',\n 'delete',\n 'trace',\n 'head',\n] as const;\nexport type SemanticSource =\n | 'query'\n | 'queries'\n | 'body'\n | 'params'\n | 'headers';\n\nconst semanticSourceToOpenAPI = {\n queries: 'query',\n query: 'query',\n headers: 'header',\n params: 'path',\n} as const;\nexport interface Selector {\n name: string;\n select: string;\n against: string;\n source: SemanticSource;\n nullable: boolean;\n required: boolean;\n}\n\nexport interface ResponseItem {\n statusCode: string;\n response?: DateType;\n contentType: string;\n headers: (string | Record<string, string[]>)[];\n}\n\nexport type OnOperation = (\n sourceFile: string,\n method: Method,\n path: string,\n operation: OperationObject,\n) => PathsObject;\nexport class Paths {\n #commonZodImport?: string;\n #onOperation?: OnOperation;\n #operations: Array<{\n sourceFile: string;\n name: string;\n path: string;\n method: Method;\n selectors: Selector[];\n responses: ResponsesObject;\n tags?: string[];\n description?: string;\n }> = [];\n\n constructor(config: { commonZodImport?: string; onOperation?: OnOperation }) {\n this.#commonZodImport = config.commonZodImport;\n this.#onOperation = config.onOperation;\n }\n\n addPath(\n name: string,\n path: string,\n method: Method,\n selectors: Selector[],\n responses: ResponseItem[],\n sourceFile: string,\n tags?: string[],\n description?: string,\n ) {\n const responsesObject = this.#responseItemToResponses(responses);\n\n this.#operations.push({\n name,\n path: this.#tunePath(path),\n sourceFile,\n method,\n selectors,\n responses: responsesObject,\n tags,\n description,\n });\n return this;\n }\n\n #responseItemToResponses(responses: ResponseItem[]): ResponsesObject {\n const responsesObject: ResponsesObject = {};\n for (const item of responses) {\n const ct = item.contentType;\n const schema = item.response ? toSchema(item.response) : {};\n if (!responsesObject[item.statusCode]) {\n responsesObject[item.statusCode] = {\n description: `Response for ${item.statusCode}`,\n content:\n ct !== 'empty'\n ? {\n [ct]:\n ct === 'application/octet-stream'\n ? { schema: { type: 'string', format: 'binary' } }\n : { schema },\n }\n : undefined,\n headers: item.headers.length\n ? item.headers.reduce<HeadersObject>((acc, current) => {\n const headers =\n typeof current === 'string' ? { [current]: [] } : current;\n return Object.entries(headers).reduce<HeadersObject>(\n (subAcc, [key, value]) => {\n const header: HeadersObject = {\n [key]: {\n schema: {\n type: 'string',\n enum: value.length ? value : undefined,\n },\n },\n };\n return { ...subAcc, ...header };\n },\n acc,\n );\n }, {})\n : undefined,\n } satisfies ResponseObject;\n } else {\n if (!responsesObject[item.statusCode].content[ct]) {\n responsesObject[item.statusCode].content[ct] = { schema };\n } else {\n const existing = responsesObject[item.statusCode].content[ct]\n .schema as SchemaObject;\n if (existing.oneOf) {\n if (\n !existing.oneOf.find(\n (it) => JSON.stringify(it) === JSON.stringify(schema),\n )\n ) {\n existing.oneOf.push(schema);\n }\n } else if (JSON.stringify(existing) !== JSON.stringify(schema)) {\n responsesObject[item.statusCode].content[ct].schema = {\n oneOf: [existing, schema],\n };\n }\n }\n }\n }\n return responsesObject;\n }\n\n async #selectosToParameters(selectors: Selector[]) {\n const parameters: ParameterObject[] = [];\n const bodySchemaProps: Record<\n string,\n { required: boolean; schema: SchemaObject }\n > = {};\n for (const selector of selectors) {\n if (selector.source === 'body') {\n bodySchemaProps[selector.name] = {\n required: selector.required,\n schema: await evalZod(selector.against, this.#commonZodImport),\n };\n continue;\n }\n\n const parameter: ParameterObject = {\n in: semanticSourceToOpenAPI[selector.source],\n name: selector.name,\n required: selector.required,\n schema: await evalZod(selector.against, this.#commonZodImport),\n };\n parameters.push(parameter);\n }\n return { parameters, bodySchemaProps };\n }\n\n async getPaths() {\n const operations: PathsObject = {};\n for (const operation of this.#operations) {\n const { path, method, selectors } = operation;\n const { parameters, bodySchemaProps } =\n await this.#selectosToParameters(selectors);\n const bodySchema: Record<string, SchemaObject> = {};\n const required: string[] = [];\n for (const [key, value] of Object.entries(bodySchemaProps)) {\n if (value.required) {\n required.push(key);\n }\n bodySchema[key] = value.schema;\n }\n const operationObject: OperationObject = {\n operationId: operation.name,\n parameters,\n tags: operation.tags,\n description: operation.description,\n requestBody: Object.keys(bodySchema).length\n ? {\n content: {\n 'application/json': {\n schema: {\n required: required.length ? required : undefined,\n type: 'object',\n properties: bodySchema,\n },\n },\n },\n }\n : undefined,\n responses:\n Object.keys(operation.responses).length === 0\n ? undefined\n : operation.responses,\n };\n if (!operations[path]) {\n operations[path] = {};\n }\n operations[path][method] = operationObject;\n if (this.#onOperation) {\n const paths = this.#onOperation?.(\n operation.sourceFile,\n method,\n path,\n operationObject,\n );\n Object.assign(operations, paths ?? {});\n }\n }\n return operations;\n }\n\n /**\n * Converts Express/Node.js style path parameters (/path/:param) to OpenAPI style (/path/{param})\n */\n #tunePath(path: string): string {\n return path.replace(/:([^/]+)/g, '{$1}');\n }\n}\n\nasync function evalZod(schema: string, commonZodImport?: string) {\n // https://github.com/nodejs/node/issues/51956\n const lines = [\n `import { createRequire } from \"node:module\";`,\n `const filename = \"${import.meta.url}\";`,\n `const require = createRequire(filename);`,\n `const z = require(\"zod\");`,\n commonZodImport ? `const commonZod = require('${commonZodImport}');` : '',\n `const {zodToJsonSchema} = require('zod-to-json-schema');`,\n `const schema = ${schema.replace('.optional()', '')};`,\n `const jsonSchema = zodToJsonSchema(schema, {\n \t$refStrategy: 'root',\n \tbasePath: ['#', 'components', 'schemas']\n });`,\n `export default jsonSchema;`,\n ];\n const base64 = Buffer.from(lines.join('\\n')).toString('base64');\n return import(`data:text/javascript;base64,${base64}`)\n .then((mod) => mod.default)\n .then(({ $schema, ...result }) => result);\n}\n\ninterface DateType {\n [$types]: any[];\n kind: string;\n optional: boolean;\n value?: string;\n}\n\nexport function toSchema(data: DateType | string | null | undefined): any {\n if (data === null || data === undefined) {\n return { type: 'any' };\n } else if (typeof data === 'string') {\n const isRef = data.startsWith('#');\n if (isRef) {\n return { $ref: data };\n }\n return { type: data };\n } else if (data.kind === 'literal') {\n return { enum: [data.value], type: data[$types][0] };\n } else if (data.kind === 'record') {\n return {\n type: 'object',\n additionalProperties: toSchema(data[$types][0]),\n };\n } else if (data.kind === 'array') {\n const items = data[$types].map(toSchema);\n return { type: 'array', items: data[$types].length ? items[0] : {} };\n } else if (data.kind === 'union') {\n return { anyOf: data[$types].map(toSchema) };\n } else if (data.kind === 'intersection') {\n return { allOf: data[$types].map(toSchema) };\n } else if ($types in data) {\n return data[$types].map(toSchema)[0] ?? {};\n } else {\n const props: Record<string, unknown> = {};\n const required: string[] = [];\n for (const [key, value] of Object.entries(data)) {\n props[key] = toSchema(value as any);\n if (!(value as any).optional) {\n required.push(key);\n }\n }\n return {\n type: 'object',\n properties: props,\n required,\n additionalProperties: false,\n };\n }\n}\n\nexport function isHttpMethod(name: string): name is Method {\n return ['get', 'post', 'put', 'delete', 'patch'].includes(name);\n}\n", "import debug from 'debug';\nimport { dirname, join } from 'node:path';\nimport ts from 'typescript';\n\nconst logger = debug('january:client');\n\nexport function parseTsConfig(tsconfigPath: string) {\n logger(`Using TypeScript version: ${ts.version}`);\n const configContent = ts.readConfigFile(tsconfigPath, ts.sys.readFile);\n\n if (configContent.error) {\n console.error(\n `Failed to read tsconfig file:`,\n ts.formatDiagnosticsWithColorAndContext([configContent.error], {\n getCanonicalFileName: (path) => path,\n getCurrentDirectory: ts.sys.getCurrentDirectory,\n getNewLine: () => ts.sys.newLine,\n }),\n );\n throw new Error('Failed to parse tsconfig.json');\n }\n\n const parsed = ts.parseJsonConfigFileContent(\n configContent.config,\n ts.sys,\n dirname(tsconfigPath),\n );\n\n if (parsed.errors.length > 0) {\n console.error(\n `Errors found in tsconfig.json:`,\n ts.formatDiagnosticsWithColorAndContext(parsed.errors, {\n getCanonicalFileName: (path) => path,\n getCurrentDirectory: ts.sys.getCurrentDirectory,\n getNewLine: () => ts.sys.newLine,\n }),\n );\n throw new Error('Failed to parse tsconfig.json');\n }\n return parsed;\n}\nexport function getProgram(tsconfigPath: string) {\n const tsConfigParseResult = parseTsConfig(tsconfigPath);\n logger(`Parsing tsconfig`);\n return ts.createProgram({\n options: {\n ...tsConfigParseResult.options,\n noEmit: true,\n incremental: true,\n tsBuildInfoFile: join(dirname(tsconfigPath), './.tsbuildinfo'), // not working atm\n },\n rootNames: tsConfigParseResult.fileNames,\n projectReferences: tsConfigParseResult.projectReferences,\n configFileParsingDiagnostics: tsConfigParseResult.errors,\n });\n}\nexport function getPropertyAssignment(node: ts.Node, name: string) {\n if (ts.isObjectLiteralExpression(node)) {\n return node.properties\n .filter((prop) => ts.isPropertyAssignment(prop))\n .find((prop) => prop.name!.getText() === name);\n }\n return undefined;\n}\nexport function isCallExpression(\n node: ts.Node,\n name: string,\n): node is ts.CallExpression {\n return (\n ts.isCallExpression(node) &&\n node.expression &&\n ts.isIdentifier(node.expression) &&\n node.expression.text === name\n );\n}\n\nexport function isInterfaceType(type: ts.Type): boolean {\n if (type.isClassOrInterface()) {\n // Check if it's an interface\n return !!(type.symbol.flags & ts.SymbolFlags.Interface);\n }\n return false;\n}\n", "import type ts from 'typescript';\n\nimport type { TypeDeriver } from './lib/deriver.ts';\nimport type { ResponseItem } from './lib/paths.ts';\n\nexport * from './lib/deriver.ts';\nexport * from './lib/file-system.ts';\nexport * from './lib/paths.ts';\nexport * from './lib/program.ts';\n\nexport function removeDuplicates<T>(\n data: T[],\n accessor: (item: T) => T[keyof T],\n): T[] {\n return [...new Map(data.map((x) => [accessor(x), x])).values()];\n}\n\nexport type InferRecordValue<T> = T extends Record<string, infer U> ? U : any;\n\nexport function toLitObject<T extends Record<string, any>>(\n obj: T,\n accessor: (value: InferRecordValue<T>) => string = (value) => value,\n) {\n return `{${Object.keys(obj)\n .map((key) => `${key}: ${accessor(obj[key])}`)\n .join(', ')}}`;\n}\n\nexport type NaunceResponseAnalyzerFn = (\n handler: ts.ArrowFunction,\n deriver: TypeDeriver,\n node: ts.Node,\n) => ResponseItem[];\nexport type NaunceResponseAnalyzer = Record<string, NaunceResponseAnalyzerFn>;\n\nexport type ResponseAnalyzerFn = (\n handler: ts.ArrowFunction,\n deriver: TypeDeriver,\n) => ResponseItem[];\n", "import { get, merge } from 'lodash-es';\nimport type {\n ContentObject,\n OpenAPIObject,\n OperationObject,\n ParameterLocation,\n ParameterObject,\n ResponseObject,\n} from 'openapi3-ts/oas31';\nimport { camelcase, pascalcase, spinalcase } from 'stringcase';\n\nimport { TypeScriptDeserialzer } from './emitters/interface.ts';\nimport { ZodDeserialzer } from './emitters/zod.ts';\nimport { type Operation, type Spec } from './sdk.ts';\nimport {\n followRef,\n importsToString,\n isRef,\n mergeImports,\n securityToOptions,\n} from './utils.ts';\n\nexport interface NamedImport {\n name: string;\n alias?: string;\n isTypeOnly: boolean;\n}\nexport interface Import {\n isTypeOnly: boolean;\n moduleSpecifier: string;\n defaultImport: string | undefined;\n namedImports: NamedImport[];\n namespaceImport: string | undefined;\n}\n\nconst responses: Record<string, string> = {\n '400': 'BadRequest',\n '401': 'Unauthorized',\n '402': 'PaymentRequired',\n '403': 'Forbidden',\n '404': 'NotFound',\n '405': 'MethodNotAllowed',\n '406': 'NotAcceptable',\n '409': 'Conflict',\n '413': 'PayloadTooLarge',\n '410': 'Gone',\n '422': 'UnprocessableEntity',\n '429': 'TooManyRequests',\n '500': 'InternalServerError',\n '501': 'NotImplemented',\n '502': 'BadGateway',\n '503': 'ServiceUnavailable',\n '504': 'GatewayTimeout',\n};\n\nexport interface GenerateSdkConfig {\n spec: OpenAPIObject;\n target?: 'javascript';\n /**\n * No support for jsdoc in vscode\n * @issue https://github.com/microsoft/TypeScript/issues/38106\n */\n style?: 'github';\n operationId?: (\n operation: OperationObject,\n path: string,\n method: string,\n ) => string;\n}\n\nexport const defaults: Partial<GenerateSdkConfig> &\n Required<Pick<GenerateSdkConfig, 'operationId'>> = {\n target: 'javascript',\n style: 'github',\n operationId: (operation, path, method) => {\n if (operation.operationId) {\n return spinalcase(operation.operationId);\n }\n return camelcase(`${method} ${path.replace(/[\\\\/\\\\{\\\\}]/g, ' ').trim()}`);\n },\n};\n\nexport function generateCode(config: GenerateSdkConfig) {\n const commonSchemas: Record<string, string> = {};\n const zodDeserialzer = new ZodDeserialzer(config.spec);\n\n const groups: Spec['operations'] = {};\n const outputs: Record<string, string> = {};\n\n for (const [path, methods] of Object.entries(config.spec.paths ?? {})) {\n for (const [method, operation] of Object.entries(methods) as [\n string,\n OperationObject,\n ][]) {\n const formatOperationId = config.operationId ?? defaults.operationId;\n const operationName = formatOperationId(operation, path, method);\n\n console.log(`Processing ${method} ${path}`);\n const groupName = (operation.tags ?? ['unknown'])[0];\n groups[groupName] ??= [];\n const inputs: Operation['inputs'] = {};\n\n const additionalProperties: ParameterObject[] = [];\n for (const param of operation.parameters ?? []) {\n if (isRef(param)) {\n throw new Error(`Found reference in parameter ${param.$ref}`);\n }\n if (!param.schema) {\n throw new Error(`Schema not found for parameter ${param.name}`);\n }\n inputs[param.name] = {\n in: param.in,\n schema: '',\n };\n additionalProperties.push(param);\n }\n\n const security = operation.security ?? [];\n const securitySchemas = config.spec.components?.securitySchemes ?? {};\n\n const securityOptions = securityToOptions(security, securitySchemas);\n\n Object.assign(inputs, securityOptions);\n\n additionalProperties.push(\n ...Object.entries(securityOptions).map(\n ([name, value]) =>\n ({\n name: name,\n required: false,\n schema: {\n type: 'string',\n },\n in: value.in as ParameterLocation,\n }) satisfies ParameterObject,\n ),\n );\n\n const types: Record<string, string> = {};\n const shortContenTypeMap: Record<string, string> = {\n 'application/json': 'json',\n 'application/x-www-form-urlencoded': 'urlencoded',\n 'multipart/form-data': 'formdata',\n 'application/xml': 'xml',\n 'text/plain': 'text',\n };\n let contentType: string | undefined;\n if (operation.requestBody && Object.keys(operation.requestBody).length) {\n const content: ContentObject = isRef(operation.requestBody)\n ? get(followRef(config.spec, operation.requestBody.$ref), ['content'])\n : operation.requestBody.content;\n\n for (const type in content) {\n const ctSchema = isRef(content[type].schema)\n ? followRef(config.spec, content[type].schema.$ref)\n : content[type].schema;\n if (!ctSchema) {\n console.warn(`Schema not found for ${type}`);\n continue;\n }\n const schema = merge({}, ctSchema, {\n required: additionalProperties\n .filter((p) => p.required)\n .map((p) => p.name),\n properties: additionalProperties.reduce<Record<string, unknown>>(\n (acc, p) => ({\n ...acc,\n [p.name]: p.schema,\n }),\n {},\n ),\n });\n for (const [name] of Object.entries(ctSchema.properties ?? {})) {\n inputs[name] = {\n in: 'body',\n schema: '',\n };\n }\n types[shortContenTypeMap[type]] = zodDeserialzer.handle(schema, true);\n }\n\n if (content['application/json']) {\n contentType = 'json';\n } else if (content['application/x-www-form-urlencoded']) {\n contentType = 'urlencoded';\n } else if (content['multipart/form-data']) {\n contentType = 'formdata';\n } else {\n contentType = 'json';\n }\n } else {\n const properties = additionalProperties.reduce<Record<string, any>>(\n (acc, p) => ({\n ...acc,\n [p.name]: p.schema,\n }),\n {},\n );\n types[shortContenTypeMap['application/json']] = zodDeserialzer.handle(\n {\n type: 'object',\n required: additionalProperties\n .filter((p) => p.required)\n .map((p) => p.name),\n properties,\n },\n true,\n );\n }\n\n const errors: string[] = [];\n operation.responses ??= {};\n\n let foundResponse = false;\n const output = [`import z from 'zod';`];\n for (const status in operation.responses) {\n const response = operation.responses[status] as ResponseObject;\n const statusCode = +status;\n if (statusCode >= 400) {\n errors.push(responses[status] ?? 'ProblematicResponse');\n }\n if (statusCode >= 200 && statusCode < 300) {\n foundResponse = true;\n const responseContent = get(response, ['content']);\n const isJson = responseContent && responseContent['application/json'];\n // TODO: how the user is going to handle multiple response types\n const imports: Import[] = [];\n const typeScriptDeserialzer = new TypeScriptDeserialzer(\n config.spec,\n (schemaName, zod) => {\n commonSchemas[schemaName] = zod;\n imports.push({\n defaultImport: undefined,\n isTypeOnly: true,\n moduleSpecifier: `../models/${schemaName}.ts`,\n namedImports: [{ isTypeOnly: true, name: schemaName }],\n namespaceImport: undefined,\n });\n },\n );\n const responseSchema = isJson\n ? typeScriptDeserialzer.handle(\n responseContent['application/json'].schema!,\n true,\n )\n : 'ReadableStream'; // non-json response treated as stream\n for (const it of mergeImports(imports)) {\n const singleImport = it.defaultImport ?? it.namespaceImport;\n if (singleImport && responseSchema.includes(singleImport)) {\n output.push(importsToString(it).join('\\n'));\n } else if (it.namedImports.length) {\n for (const namedImport of it.namedImports) {\n if (responseSchema.includes(namedImport.name)) {\n output.push(importsToString(it).join('\\n'));\n }\n }\n }\n }\n output.push(\n `export type ${pascalcase(operationName + ' output')} = ${responseSchema}`,\n );\n }\n }\n\n if (!foundResponse) {\n output.push(\n `export type ${pascalcase(operationName + ' output')} = void`,\n );\n }\n outputs[`${spinalcase(operationName)}.ts`] = output.join('\\n');\n groups[groupName].push({\n name: operationName,\n type: 'http',\n inputs,\n errors: errors.length ? errors : ['ServerError'],\n contentType,\n schemas: types,\n formatOutput: () => ({\n import: pascalcase(operationName + ' output'),\n use: pascalcase(operationName + ' output'),\n }),\n trigger: {\n path,\n method,\n },\n });\n }\n }\n\n return { groups, commonSchemas, outputs };\n}\n\n// TODO - USE CASES\n// 1. Some parameters conflicts with request body\n// 2. Generate 400 and 500 response variations // done\n// 3. Generate 200 response variations\n// 3. Doc Security\n// 4. Operation Security\n// 5. JsDocs\n// 5. test all different types of parameters\n// 6. cookies\n// 6. x-www-form-urlencoded // done\n// 7. multipart/form-data // done\n// 7. application/octet-stream // done\n// 7. chunked response // done\n// we need to remove the stream fn in the backend\n", "import { get } from 'lodash-es';\nimport type {\n ComponentsObject,\n OpenAPIObject,\n ReferenceObject,\n SchemaObject,\n SecurityRequirementObject,\n} from 'openapi3-ts/oas31';\n\nimport { removeDuplicates } from '@sdk-it/core';\n\nimport { type Options } from './sdk.ts';\n\nexport function isRef(obj: any): obj is ReferenceObject {\n return '$ref' in obj;\n}\n\nexport function cleanRef(ref: string) {\n return ref.replace(/^#\\//, '');\n}\n\nexport function parseRef(ref: string) {\n const parts = ref.split('/');\n const [model] = parts.splice(-1);\n return { model, path: parts.join('/') };\n}\nexport function followRef(spec: OpenAPIObject, ref: string): SchemaObject {\n const pathParts = cleanRef(ref).split('/');\n const entry = get(spec, pathParts) as SchemaObject | ReferenceObject;\n if (entry && '$ref' in entry) {\n return followRef(spec, entry.$ref);\n }\n return entry;\n}\nexport function securityToOptions(\n security: SecurityRequirementObject[],\n securitySchemas: ComponentsObject['securitySchemes'],\n staticIn?: string,\n) {\n securitySchemas ??= {};\n const options: Options = {};\n for (const it of security) {\n const [name] = Object.keys(it);\n const schema = securitySchemas[name];\n if (isRef(schema)) {\n throw new Error(`Ref security schemas are not supported`);\n }\n if (schema.type === 'http') {\n options['authorization'] = {\n in: staticIn ?? 'header',\n schema:\n 'z.string().optional().transform((val) => (val ? `Bearer ${val}` : undefined))',\n optionName: 'token',\n };\n continue;\n }\n if (schema.type === 'apiKey') {\n if (!schema.in) {\n throw new Error(`apiKey security schema must have an \"in\" field`);\n }\n if (!schema.name) {\n throw new Error(`apiKey security schema must have a \"name\" field`);\n }\n options[schema.name] = {\n in: staticIn ?? schema.in,\n schema: 'z.string().optional()',\n };\n continue;\n }\n }\n return options;\n}\n\nexport function mergeImports(imports: Import[]) {\n const merged: Record<string, Import> = {};\n\n for (const i of imports) {\n merged[i.moduleSpecifier] = merged[i.moduleSpecifier] ?? {\n moduleSpecifier: i.moduleSpecifier,\n defaultImport: i.defaultImport,\n namespaceImport: i.namespaceImport,\n namedImports: [],\n };\n if (i.namedImports) {\n merged[i.moduleSpecifier].namedImports.push(...i.namedImports);\n }\n }\n\n return Object.values(merged);\n}\nexport interface Import {\n isTypeOnly: boolean;\n moduleSpecifier: string;\n defaultImport: string | undefined;\n namedImports: NamedImport[];\n namespaceImport: string | undefined;\n}\nexport interface NamedImport {\n name: string;\n alias?: string;\n isTypeOnly: boolean;\n}\n\nexport function importsToString(...imports: Import[]) {\n return imports.map((it) => {\n if (it.defaultImport) {\n return `import ${it.defaultImport} from '${it.moduleSpecifier}'`;\n }\n if (it.namespaceImport) {\n return `import * as ${it.namespaceImport} from '${it.moduleSpecifier}'`;\n }\n if (it.namedImports) {\n return `import {${removeDuplicates(it.namedImports, (it) => it.name)\n .map((n) => `${n.isTypeOnly ? 'type' : ''} ${n.name}`)\n .join(', ')}} from '${it.moduleSpecifier}'`;\n }\n throw new Error(`Invalid import ${JSON.stringify(it)}`);\n });\n}\n", "import { camelcase, pascalcase, spinalcase } from 'stringcase';\n\nimport { removeDuplicates, toLitObject } from '@sdk-it/core';\n\nimport backend from './client.ts';\n\nclass SchemaEndpoint {\n #imports: string[] = [\n `import z from 'zod';`,\n 'import type { Endpoints } from \"./endpoints.ts\";',\n `import { toRequest, json, urlencoded, nobody, formdata, createUrl } from './http/request.ts';`,\n `import type { ParseError } from './http/parser.ts';`,\n ];\n #endpoints: string[] = [];\n addEndpoint(endpoint: string, operation: any) {\n this.#endpoints.push(` \"${endpoint}\": ${operation},`);\n }\n addImport(value: string) {\n this.#imports.push(value);\n }\n complete() {\n return `${this.#imports.join('\\n')}\\nexport default {\\n${this.#endpoints.join('\\n')}\\n}`;\n }\n}\nclass Emitter {\n protected imports: string[] = [\n `import z from 'zod';`,\n `import type { ParseError } from './http/parser.ts';`,\n ];\n protected endpoints: string[] = [];\n addEndpoint(endpoint: string, operation: any) {\n this.endpoints.push(` \"${endpoint}\": ${operation};`);\n }\n addImport(value: string) {\n this.imports.push(value);\n }\n complete() {\n return `${this.imports.join('\\n')}\\nexport interface Endpoints {\\n${this.endpoints.join('\\n')}\\n}`;\n }\n}\nclass StreamEmitter extends Emitter {\n override complete() {\n return `${this.imports.join('\\n')}\\nexport interface StreamEndpoints {\\n${this.endpoints.join('\\n')}\\n}`;\n }\n}\n\nexport interface SdkConfig {\n /**\n * The name of the sdk client\n */\n name: string;\n packageName?: string;\n options?: Record<string, any>;\n emptyBodyAsNull?: boolean;\n stripBodyFromGetAndHead?: boolean;\n output: string;\n}\n\nexport type Options = Record<\n string,\n {\n in: string;\n schema: string;\n optionName?: string;\n }\n>;\nexport interface Spec {\n operations: Record<string, Operation[]>;\n commonZod?: string;\n name: string;\n options: Options;\n servers: string[];\n}\n\nexport interface OperationInput {\n in: string;\n schema: string;\n}\nexport interface Operation {\n name: string;\n errors: string[];\n type: string;\n trigger: Record<string, any>;\n contentType?: string;\n schemas: Record<string, string>;\n schema?: string;\n inputs: Record<string, OperationInput>;\n formatOutput: () => { import: string; use: string };\n}\n\nexport function generateClientSdk(spec: Spec) {\n const emitter = new Emitter();\n const streamEmitter = new StreamEmitter();\n const schemas: Record<string, string[]> = {};\n const schemaEndpoint = new SchemaEndpoint();\n const errors: string[] = [];\n for (const [name, operations] of Object.entries(spec.operations)) {\n const featureSchemaFileName = camelcase(name);\n schemas[featureSchemaFileName] = [`import z from 'zod';`];\n emitter.addImport(\n `import * as ${featureSchemaFileName} from './inputs/${featureSchemaFileName}.ts';`,\n );\n streamEmitter.addImport(\n `import * as ${featureSchemaFileName} from './inputs/${featureSchemaFileName}.ts';`,\n );\n schemaEndpoint.addImport(\n `import * as ${featureSchemaFileName} from './inputs/${featureSchemaFileName}.ts';`,\n );\n for (const operation of operations) {\n const schemaName = camelcase(`${operation.name} schema`);\n\n const schema = `export const ${schemaName} = ${\n Object.keys(operation.schemas).length === 1\n ? Object.values(operation.schemas)[0]\n : toLitObject(operation.schemas)\n };`;\n\n schemas[featureSchemaFileName].push(schema);\n const schemaRef = `${featureSchemaFileName}.${schemaName}`;\n const output = operation.formatOutput();\n const inputHeaders: string[] = [];\n const inputQuery: string[] = [];\n const inputBody: string[] = [];\n const inputParams: string[] = [];\n for (const [name, prop] of Object.entries(operation.inputs)) {\n if (prop.in === 'headers' || prop.in === 'header') {\n inputHeaders.push(`\"${name}\"`);\n } else if (prop.in === 'query') {\n inputQuery.push(`\"${name}\"`);\n } else if (prop.in === 'body') {\n inputBody.push(`\"${name}\"`);\n } else if (prop.in === 'path') {\n inputParams.push(`\"${name}\"`);\n } else if (prop.in === 'internal') {\n // ignore internal sources\n continue;\n } else {\n throw new Error(\n `Unknown source ${prop.in} in ${name} ${JSON.stringify(\n prop,\n )} in ${operation.name}`,\n );\n }\n }\n if (operation.type === 'sse') {\n const input = `z.infer<typeof ${schemaRef}>`;\n const endpoint = `${operation.trigger.method.toUpperCase()} ${operation.trigger.path}`;\n streamEmitter.addImport(\n `import type {${pascalcase(operation.name)}} from './outputs/${spinalcase(operation.name)}.ts';`,\n );\n streamEmitter.addEndpoint(\n endpoint,\n `{input: ${input}, output: ${output.use}}`,\n );\n schemaEndpoint.addEndpoint(\n endpoint,\n `{\n schema: ${schemaRef},\n toRequest(input: StreamEndpoints['${endpoint}']['input']) {\n const endpoint = '${endpoint}';\n return toRequest(endpoint, json(input, {\n inputHeaders: [${inputHeaders}],\n inputQuery: [${inputQuery}],\n inputBody: [${inputBody}],\n inputParams: [${inputParams}],\n }));\n },\n }`,\n );\n } else {\n emitter.addImport(\n `import type {${output.import}} from './outputs/${spinalcase(operation.name)}.ts';`,\n );\n errors.push(...(operation.errors ?? []));\n\n const addTypeParser = Object.keys(operation.schemas).length > 1;\n for (const type in operation.schemas ?? {}) {\n let typePrefix = '';\n if (addTypeParser && type !== 'json') {\n typePrefix = `${type} `;\n }\n const input = `typeof ${schemaRef}${addTypeParser ? `.${type}` : ''}`;\n\n const endpoint = `${typePrefix}${operation.trigger.method.toUpperCase()} ${operation.trigger.path}`;\n emitter.addEndpoint(\n endpoint,\n `{input: z.infer<${input}>; output: ${output.use}; error: ${(operation.errors ?? ['ServerError']).concat(`ParseError<${input}>`).join('|')}}`,\n );\n schemaEndpoint.addEndpoint(\n endpoint,\n `{\n schema: ${schemaRef}${addTypeParser ? `.${type}` : ''},\n toRequest(input: Endpoints['${endpoint}']['input']) {\n const endpoint = '${endpoint}';\n return toRequest(endpoint, ${operation.contentType || 'nobody'}(input, {\n inputHeaders: [${inputHeaders}],\n inputQuery: [${inputQuery}],\n inputBody: [${inputBody}],\n inputParams: [${inputParams}],\n }));\n },\n }`,\n );\n }\n }\n }\n }\n\n emitter.addImport(\n `import type { ${removeDuplicates(errors, (it) => it).join(', ')} } from './http/response.ts';`,\n );\n return {\n ...Object.fromEntries(\n Object.entries(schemas).map(([key, value]) => [\n `inputs/${key}.ts`,\n [\n // schemasImports.length\n // ? `import {${removeDuplicates(schemasImports, (it) => it)}} from '../zod';`\n // : '',\n spec.commonZod ? 'import * as commonZod from \"../zod.ts\";' : '',\n ...value,\n ]\n .map((it) => it.trim())\n .filter(Boolean)\n .join('\\n') + '\\n', // add a newline at the end\n ]),\n ),\n 'client.ts': backend(spec),\n 'schemas.ts': schemaEndpoint.complete(),\n 'endpoints.ts': emitter.complete(),\n };\n}\n", "import { toLitObject } from '@sdk-it/core';\n\nimport type { Spec } from './sdk.ts';\n\nexport default (spec: Spec) => {\n const optionsEntries = Object.entries(spec.options).map(\n ([key, value]) => [`'${key}'`, value] as const,\n );\n const defaultHeaders = `{${optionsEntries\n .filter(([, value]) => value.in === 'header')\n .map(\n ([key, value]) =>\n `${key}: this.options[${value.optionName ? `'${value.optionName}'` : key}]`,\n )\n .join(',\\n')}}`;\n const defaultInputs = `{${optionsEntries\n .filter(([, value]) => value.in === 'input')\n .map(\n ([key, value]) =>\n `${key}: this.options[${value.optionName ? `'${value.optionName}'` : key}]`,\n )\n .join(',\\n')}}`;\n const specOptions: Record<string, { schema: string }> = {\n ...Object.fromEntries(\n optionsEntries.map(([key, value]) => [value.optionName ?? key, value]),\n ),\n fetch: {\n schema: 'fetchType',\n },\n baseUrl: {\n schema: spec.servers.length\n ? `z.enum(servers).default(servers[0])`\n : 'z.string()',\n },\n };\n\n return `\nimport { fetchType, sendRequest } from './http/send-request.ts';\nimport z from 'zod';\nimport type { Endpoints } from './endpoints.ts';\nimport schemas from './schemas.ts';\nimport {\n createBaseUrlInterceptor,\n createDefaultHeadersInterceptor,\n} from './http/interceptors.ts';\n\n${spec.servers.length ? `export const servers = ${JSON.stringify(spec.servers, null, 2)} as const` : ''}\nconst optionsSchema = z.object(${toLitObject(specOptions, (x) => x.schema)});\n${spec.servers.length ? `export type Servers = typeof servers[number];` : ''}\n\ntype ${spec.name}Options = z.infer<typeof optionsSchema>;\n\nexport class ${spec.name} {\n\n constructor(public options: ${spec.name}Options) {}\n\n async request<E extends keyof Endpoints>(\n endpoint: E,\n input: Endpoints[E]['input'],\n ): Promise<readonly [Endpoints[E]['output'], Endpoints[E]['error'] | null]> {\n const route = schemas[endpoint];\n return sendRequest(Object.assign(this.#defaultInputs, input), route, {\n fetch: this.options.fetch,\n interceptors: [\n createDefaultHeadersInterceptor(() => this.defaultHeaders),\n createBaseUrlInterceptor(() => this.options.baseUrl),\n ],\n });\n }\n\n get defaultHeaders() {\n return ${defaultHeaders}\n }\n\n get #defaultInputs() {\n return ${defaultInputs}\n }\n\n setOptions(options: Partial<${spec.name}Options>) {\n const validated = optionsSchema.partial().parse(options);\n\n for (const key of Object.keys(validated) as (keyof ${spec.name}Options)[]) {\n if (validated[key] !== undefined) {\n (this.options[key] as typeof validated[typeof key]) = validated[key]!;\n }\n }\n }\n}`;\n};\n", "import type {\n OpenAPIObject,\n ReferenceObject,\n SchemaObject,\n} from 'openapi3-ts/oas31';\n\nimport { cleanRef, followRef, isRef, parseRef } from '../utils.ts';\n\ntype OnRefCallback = (ref: string, interfaceContent: string) => void;\n\n/**\n * Convert an OpenAPI (JSON Schema style) object into TypeScript interfaces,\n * following the same pattern as ZodDeserialzer for easy interchangeability.\n */\nexport class TypeScriptDeserialzer {\n circularRefTracker = new Set<string>();\n #spec: OpenAPIObject;\n #onRef: OnRefCallback;\n\n constructor(spec: OpenAPIObject, onRef: OnRefCallback) {\n this.#spec = spec;\n this.#onRef = onRef;\n }\n\n /**\n * Handle objects (properties)\n */\n object(schema: SchemaObject, required = false): string {\n const properties = schema.properties || {};\n\n // Convert each property\n const propEntries = Object.entries(properties).map(([key, propSchema]) => {\n const isRequired = (schema.required ?? []).includes(key);\n const tsType = this.handle(propSchema, isRequired);\n // Add question mark for optional properties\n return `${key}: ${tsType}`;\n });\n\n // Handle additionalProperties\n if (schema.additionalProperties) {\n if (typeof schema.additionalProperties === 'object') {\n const indexType = this.handle(schema.additionalProperties, true);\n propEntries.push(`[key: string]: ${indexType}`);\n } else if (schema.additionalProperties === true) {\n propEntries.push('[key: string]: any');\n }\n }\n\n return `{ ${propEntries.join('; ')} }`;\n }\n\n /**\n * Handle arrays (items could be a single schema or a tuple)\n */\n array(schema: SchemaObject, required = false): string {\n const { items } = schema;\n if (!items) {\n // No items => any[]\n return 'any[]';\n }\n\n // If items is an array => tuple\n if (Array.isArray(items)) {\n const tupleItems = items.map((sub) => this.handle(sub, true));\n return `[${tupleItems.join(', ')}]`;\n }\n\n // If items is a single schema => standard array\n const itemsType = this.handle(items, true);\n return `${itemsType}[]`;\n }\n\n /**\n * Convert a basic type (string | number | boolean | object | array, etc.) to TypeScript\n */\n normal(type: string, schema: SchemaObject, required = false): string {\n switch (type) {\n case 'string':\n return this.string(schema, required);\n case 'number':\n case 'integer':\n return this.number(schema, required);\n case 'boolean':\n return appendOptional('boolean', required);\n case 'object':\n return this.object(schema, required);\n case 'array':\n return this.array(schema, required);\n case 'null':\n return 'null';\n default:\n // Unknown type -> fallback\n return appendOptional('any', required);\n }\n }\n\n ref($ref: string, required: boolean): string {\n const schemaName = cleanRef($ref).split('/').pop()!;\n\n if (this.circularRefTracker.has(schemaName)) {\n return schemaName;\n }\n\n this.circularRefTracker.add(schemaName);\n this.#onRef(schemaName, this.handle(followRef(this.#spec, $ref), true));\n this.circularRefTracker.delete(schemaName);\n\n return appendOptional(schemaName, required);\n }\n\n allOf(schemas: (SchemaObject | ReferenceObject)[]): string {\n // For TypeScript we use intersection types for allOf\n const allOfTypes = schemas.map((sub) => this.handle(sub, true));\n return allOfTypes.length > 1 ? `${allOfTypes.join(' & ')}` : allOfTypes[0];\n }\n\n anyOf(\n schemas: (SchemaObject | ReferenceObject)[],\n required: boolean,\n ): string {\n // For TypeScript we use union types for anyOf/oneOf\n const anyOfTypes = schemas.map((sub) => this.handle(sub, true));\n return appendOptional(\n anyOfTypes.length > 1 ? `${anyOfTypes.join(' | ')}` : anyOfTypes[0],\n required,\n );\n }\n\n oneOf(\n schemas: (SchemaObject | ReferenceObject)[],\n required: boolean,\n ): string {\n const oneOfTypes = schemas.map((sub) => {\n if (isRef(sub)) {\n const { model } = parseRef(sub.$ref);\n if (this.circularRefTracker.has(model)) {\n return model;\n }\n }\n return this.handle(sub, false);\n });\n return appendOptional(\n oneOfTypes.length > 1 ? `${oneOfTypes.join(' | ')}` : oneOfTypes[0],\n required,\n );\n }\n\n enum(values: any[], required: boolean): string {\n // For TypeScript enums as union of literals\n const enumValues = values\n .map((val) => (typeof val === 'string' ? `'${val}'` : `${val}`))\n .join(' | ');\n return appendOptional(enumValues, required);\n }\n\n /**\n * Handle string type with formats\n */\n string(schema: SchemaObject, required?: boolean): string {\n let type: string;\n\n switch (schema.format) {\n case 'date-time':\n case 'datetime':\n case 'date':\n type = 'Date';\n break;\n case 'binary':\n case 'byte':\n type = 'Blob';\n break;\n case 'int64':\n type = 'bigint';\n break;\n default:\n type = 'string';\n }\n\n return appendOptional(type, required);\n }\n\n /**\n * Handle number/integer types with formats\n */\n number(schema: SchemaObject, required?: boolean): string {\n const type = schema.format === 'int64' ? 'bigint' : 'number';\n return appendOptional(type, required);\n }\n\n handle(schema: SchemaObject | ReferenceObject, required: boolean): string {\n if (isRef(schema)) {\n return this.ref(schema.$ref, required);\n }\n\n // Handle allOf (intersection in TypeScript)\n if (schema.allOf && Array.isArray(schema.allOf)) {\n return this.allOf(schema.allOf);\n }\n\n // anyOf (union in TypeScript)\n if (schema.anyOf && Array.isArray(schema.anyOf)) {\n return this.anyOf(schema.anyOf, required);\n }\n\n // oneOf (union in TypeScript)\n if (schema.oneOf && Array.isArray(schema.oneOf)) {\n return this.oneOf(schema.oneOf, required);\n }\n\n // enum\n if (schema.enum && Array.isArray(schema.enum)) {\n return this.enum(schema.enum, required);\n }\n\n // Handle types, in TypeScript we can have union types directly\n const types = Array.isArray(schema.type)\n ? schema.type\n : schema.type\n ? [schema.type]\n : [];\n\n // If no explicit \"type\", fallback to any\n if (!types.length) {\n return appendOptional('any', required);\n }\n\n // Handle union types (multiple types)\n if (types.length > 1) {\n const realTypes = types.filter((t) => t !== 'null');\n if (realTypes.length === 1 && types.includes('null')) {\n // Single real type + \"null\"\n const tsType = this.normal(realTypes[0], schema, false);\n return appendOptional(`${tsType} | null`, required);\n }\n\n // Multiple different types\n const typeResults = types.map((t) => this.normal(t, schema, false));\n return appendOptional(typeResults.join(' | '), required);\n }\n\n // Single type\n return this.normal(types[0], schema, required);\n }\n\n /**\n * Generate an interface declaration\n */\n generateInterface(\n name: string,\n schema: SchemaObject | ReferenceObject,\n ): string {\n const content = this.handle(schema, true);\n return `interface ${name} ${content}`;\n }\n}\n\n/**\n * Append \"| undefined\" if not required\n */\nfunction appendOptional(type: string, isRequired?: boolean): string {\n return isRequired ? type : `${type} | undefined`;\n}\n", "import type {\n OpenAPIObject,\n ReferenceObject,\n SchemaObject,\n} from 'openapi3-ts/oas31';\n\nimport { cleanRef, followRef, isRef, parseRef } from '../utils.ts';\n\ntype OnRefCallback = (ref: string, zod: string) => void;\n\n/**\n * Convert an OpenAPI (JSON Schema style) object into a Zod schema string,\n * adapted for OpenAPI 3.1 (fully aligned with JSON Schema 2020-12).\n */\nexport class ZodDeserialzer {\n circularRefTracker = new Set<string>();\n #spec: OpenAPIObject;\n #onRef?: OnRefCallback;\n\n constructor(spec: OpenAPIObject, onRef?: OnRefCallback) {\n this.#spec = spec;\n this.#onRef = onRef;\n }\n /**\n * Handle objects (properties, additionalProperties).\n */\n object(schema: SchemaObject, required = false): string {\n const properties = schema.properties || {};\n\n // Convert each property\n const propEntries = Object.entries(properties).map(([key, propSchema]) => {\n const isRequired = (schema.required ?? []).includes(key);\n const zodPart = this.handle(propSchema, isRequired);\n return `'${key}': ${zodPart}`;\n });\n\n // additionalProperties\n let additionalProps = '';\n if (schema.additionalProperties) {\n if (typeof schema.additionalProperties === 'object') {\n // e.g. z.record() if it\u2019s an object schema\n const addPropZod = this.handle(schema.additionalProperties, true);\n additionalProps = `.catchall(${addPropZod})`;\n } else if (schema.additionalProperties === true) {\n // free-form additional props\n additionalProps = `.catchall(z.unknown())`;\n }\n }\n\n const objectSchema = `z.object({${propEntries.join(', ')}})${additionalProps}`;\n return `${objectSchema}${appendOptional(required)}`;\n }\n\n /**\n * Handle arrays (items could be a single schema or a tuple (array of schemas)).\n * In JSON Schema 2020-12, `items` can be an array \u2192 tuple style.\n */\n array(schema: SchemaObject, required = false): string {\n const { items } = schema;\n if (!items) {\n // No items => z.array(z.unknown())\n return `z.array(z.unknown())${appendOptional(required)}`;\n }\n\n // If items is an array => tuple\n if (Array.isArray(items)) {\n // Build a Zod tuple\n const tupleItems = items.map((sub) => this.handle(sub, true));\n const base = `z.tuple([${tupleItems.join(', ')}])`;\n // // If we have additionalItems: false => that\u2019s a fixed length\n // // If additionalItems is a schema => rest(...)\n // if (schema.additionalItems) {\n // if (typeof schema.additionalItems === 'object') {\n // const restSchema = jsonSchemaToZod(spec, schema.additionalItems, true);\n // base += `.rest(${restSchema})`;\n // }\n // // If `additionalItems: false`, no rest is allowed => do nothing\n // }\n return `${base}${appendOptional(required)}`;\n }\n\n // If items is a single schema => standard z.array(...)\n const itemsSchema = this.handle(items, true);\n return `z.array(${itemsSchema})${appendOptional(required)}`;\n }\n // oneOf() {}\n // enum() {}\n\n /**\n * Convert a basic type (string | number | boolean | object | array, etc.) to Zod.\n * We'll also handle .optional() if needed.\n */\n normal(type: string, schema: SchemaObject, required = false) {\n switch (type) {\n case 'string':\n return this.string(schema, required);\n case 'number':\n case 'integer':\n return this.number(schema, required);\n case 'boolean':\n return `z.boolean()${appendDefault(schema.default)}${appendOptional(required)}`;\n case 'object':\n return this.object(schema, required);\n case 'array':\n return this.array(schema, required);\n case 'null':\n // If \"type\": \"null\" alone, this is basically z.null()\n return `z.null()${appendOptional(required)}`;\n default:\n // Unknown type -> fallback\n return `z.unknown()${appendOptional(required)}`;\n }\n }\n\n ref($ref: string, required: boolean) {\n const schemaName = cleanRef($ref).split('/').pop()!;\n\n if (this.circularRefTracker.has(schemaName)) {\n return schemaName;\n }\n\n this.circularRefTracker.add(schemaName);\n this.#onRef?.(\n schemaName,\n this.handle(followRef(this.#spec, $ref), required),\n );\n this.circularRefTracker.delete(schemaName);\n\n return schemaName;\n }\n allOf(schemas: (SchemaObject | ReferenceObject)[]) {\n const allOfSchemas = schemas.map((sub) => this.handle(sub, true));\n return allOfSchemas.length\n ? `z.intersection(${allOfSchemas.join(', ')})`\n : allOfSchemas[0];\n }\n\n anyOf(schemas: (SchemaObject | ReferenceObject)[], required: boolean) {\n const anyOfSchemas = schemas.map((sub) => this.handle(sub, false));\n return anyOfSchemas.length > 1\n ? `z.union([${anyOfSchemas.join(', ')}])${appendOptional(required)}`\n : // Handle an invalid anyOf with one schema\n anyOfSchemas[0];\n }\n\n oneOf(schemas: (SchemaObject | ReferenceObject)[], required: boolean) {\n const oneOfSchemas = schemas.map((sub) => {\n if ('$ref' in sub) {\n const { model } = parseRef(sub.$ref);\n if (this.circularRefTracker.has(model)) {\n return model;\n }\n }\n return this.handle(sub, false);\n });\n return oneOfSchemas.length > 1\n ? `z.union([${oneOfSchemas.join(', ')}])${appendOptional(required)}`\n : // Handle an invalid oneOf with one schema\n oneOfSchemas[0];\n }\n\n enum(values: any[], required: boolean) {\n const enumVals = values.map((val) => JSON.stringify(val)).join(', ');\n return `z.enum([${enumVals}])${appendOptional(required)}`;\n }\n\n /**\n * Handle a `string` schema with possible format keywords (JSON Schema).\n */\n string(schema: SchemaObject, required?: boolean): string {\n let base = 'z.string()';\n\n // 3.1 replaces `example` in the schema with `examples` (array).\n // We do not strictly need them for the Zod type, so they\u2019re optional\n // for validation. However, we could keep them as metadata if you want.\n\n switch (schema.format) {\n case 'date-time':\n case 'datetime':\n // parse to JS Date\n base = 'z.coerce.date()';\n break;\n case 'date':\n base =\n 'z.coerce.date() /* or z.string() if you want raw date strings */';\n break;\n case 'time':\n base =\n 'z.string() /* optionally add .regex(...) for HH:MM:SS format */';\n break;\n case 'email':\n base = 'z.string().email()';\n break;\n case 'uuid':\n base = 'z.string().uuid()';\n break;\n case 'url':\n case 'uri':\n base = 'z.string().url()';\n break;\n case 'ipv4':\n base = 'z.string().ip({version: \"v4\"})';\n break;\n case 'ipv6':\n base = 'z.string().ip({version: \"v6\"})';\n break;\n case 'phone':\n base = 'z.string() /* or add .regex(...) for phone formats */';\n break;\n case 'byte':\n case 'binary':\n base = 'z.instanceof(Blob) /* consider base64 check if needed */';\n break;\n case 'int64':\n // JS numbers can't reliably store int64, consider z.bigint() or keep as string\n base = 'z.string() /* or z.bigint() if your app can handle it */';\n break;\n default:\n // No special format\n break;\n }\n\n return `${base}${appendDefault(schema.default)}${appendOptional(required)}`;\n }\n\n /**\n * Handle number/integer constraints from OpenAPI/JSON Schema.\n * In 3.1, exclusiveMinimum/Maximum hold the actual numeric threshold,\n * rather than a boolean toggling `minimum`/`maximum`.\n */\n number(schema: SchemaObject, required?: boolean): string {\n let defaultValue =\n schema.default !== undefined ? `.default(${schema.default})` : ``;\n let base = 'z.number()';\n if (schema.format === 'int64') {\n base = 'z.bigint()';\n if (schema.default !== undefined) {\n defaultValue = `.default(BigInt(${schema.default}))`;\n }\n }\n\n if (schema.format === 'int32') {\n // 32-bit integer\n base += '.int()';\n }\n\n // If we see exclusiveMinimum as a number in 3.1:\n if (typeof schema.exclusiveMinimum === 'number') {\n // Zod doesn\u2019t have a direct \"exclusiveMinimum\" method, so we can do .gt()\n // If exclusiveMinimum=7 => .gt(7)\n base += `.gt(${schema.exclusiveMinimum})`;\n }\n // Similarly for exclusiveMaximum\n if (typeof schema.exclusiveMaximum === 'number') {\n // If exclusiveMaximum=10 => .lt(10)\n base += `.lt(${schema.exclusiveMaximum})`;\n }\n\n // If standard minimum/maximum\n if (typeof schema.minimum === 'number') {\n base +=\n schema.format === 'int64'\n ? `.min(BigInt(${schema.minimum}))`\n : `.min(${schema.minimum})`;\n }\n if (typeof schema.maximum === 'number') {\n base +=\n schema.format === 'int64'\n ? `.max(BigInt(${schema.maximum}))`\n : `.max(${schema.maximum})`;\n }\n\n // multipleOf\n if (typeof schema.multipleOf === 'number') {\n // There's no direct multipleOf in Zod. Some folks do a custom refine.\n // For example:\n base += `.refine((val) => Number.isInteger(val / ${schema.multipleOf}), \"Must be a multiple of ${schema.multipleOf}\")`;\n }\n\n return `${base}${defaultValue}${appendOptional(required)}`;\n }\n\n handle(schema: SchemaObject | ReferenceObject, required: boolean): string {\n if (isRef(schema)) {\n return this.ref(schema.$ref, required);\n }\n\n // Handle allOf \u2192 intersection\n if (schema.allOf && Array.isArray(schema.allOf)) {\n return this.allOf(schema.allOf ?? []);\n }\n\n // anyOf \u2192 union\n if (schema.anyOf && Array.isArray(schema.anyOf)) {\n return this.anyOf(schema.anyOf ?? [], required);\n }\n\n // oneOf \u2192 union\n if (schema.oneOf && Array.isArray(schema.oneOf)) {\n return this.oneOf(schema.oneOf ?? [], required);\n }\n\n // enum\n if (schema.enum && Array.isArray(schema.enum)) {\n return this.enum(schema.enum, required);\n }\n\n // 3.1 can have type: string or type: string[] (e.g. [\"string\",\"null\"])\n // Let's parse that carefully.\n const types = Array.isArray(schema.type)\n ? schema.type\n : schema.type\n ? [schema.type]\n : [];\n\n // If no explicit \"type\", fallback to unknown\n if (!types.length) {\n return `z.unknown()${appendOptional(required)}`;\n }\n\n // If it's a union type (like [\"string\", \"null\"]), we'll build a Zod union\n // or apply .nullable() if it's just \"type + null\".\n if (types.length > 1) {\n // If it\u2019s exactly one real type plus \"null\", we can do e.g. `z.string().nullable()`\n const realTypes = types.filter((t) => t !== 'null');\n if (realTypes.length === 1 && types.includes('null')) {\n // Single real type + \"null\"\n const typeZod = this.normal(realTypes[0], schema, false);\n return `${typeZod}.nullable()${appendOptional(required)}`;\n }\n // If multiple different types, build a union\n const subSchemas = types.map((t) => this.normal(t, schema, false));\n return `z.union([${subSchemas.join(', ')}])${appendOptional(required)}`;\n }\n return this.normal(types[0], schema, required);\n }\n}\n\n/**\n * Append .optional() if not required\n */\nfunction appendOptional(isRequired?: boolean) {\n return isRequired ? '' : '.optional()';\n}\nfunction appendDefault(defaultValue?: any) {\n return defaultValue !== undefined\n ? `.default(${JSON.stringify(defaultValue)})`\n : '';\n}\n\n// Todo: convert openapi 3.0 to 3.1 before proccesing\n", "export interface Interceptor {\n before?: (request: Request) => Promise<Request> | Request;\n after?: (response: Response) => Promise<Response> | Response;\n}\n\nexport const createDefaultHeadersInterceptor = (\n getHeaders: () => Record<string, string | undefined>,\n) => {\n return {\n before(request: Request) {\n const headers = getHeaders();\n\n for (const [key, value] of Object.entries(headers)) {\n // Only set the header if it doesn't already exist and has a value\n if (value !== undefined && !request.headers.has(key)) {\n request.headers.set(key, value);\n }\n }\n\n return request;\n },\n };\n};\n\nexport const createBaseUrlInterceptor = (getBaseUrl: () => string) => {\n return {\n before(request: Request) {\n const baseUrl = getBaseUrl();\n if (request.url.startsWith('local://')) {\n return new Request(request.url.replace('local://', baseUrl), request);\n }\n return request;\n },\n };\n};\n\nexport const logInterceptor = {\n before(request: Request) {\n console.log('Request', request);\n return request;\n },\n after(response: Response) {\n console.log('Response', response);\n return response;\n },\n};\n", "import { parse } from 'fast-content-type-parse';\n\nexport async function handleError(response: Response) {\n try {\n if (response.status >= 400 && response.status < 500) {\n const body = (await response.json()) as Record<string, any>;\n return {\n status: response.status,\n body: body,\n };\n }\n return new Error(\n `An error occurred while fetching the data. Status: ${response.status}`,\n );\n } catch (error) {\n return error as any;\n }\n}\n\nasync function handleChunkedResponse(response: Response, contentType: string) {\n const { type } = parse(contentType);\n\n switch (type) {\n case 'application/json': {\n let buffer = '';\n const reader = response.body!.getReader();\n const decoder = new TextDecoder();\n while (true) {\n const { value, done } = await reader.read();\n if (done) break;\n buffer += decoder.decode(value);\n }\n return JSON.parse(buffer);\n }\n case 'text/html':\n case 'text/plain': {\n let buffer = '';\n const reader = response.body!.getReader();\n const decoder = new TextDecoder();\n while (true) {\n const { value, done } = await reader.read();\n if (done) break;\n buffer += decoder.decode(value);\n }\n return buffer;\n }\n default:\n return response.body;\n }\n}\n\nexport async function parseResponse(response: Response) {\n const contentType = response.headers.get('Content-Type');\n if (!contentType) {\n throw new Error('Content-Type header is missing');\n }\n\n if (response.status === 204) {\n return null;\n }\n const isChunked = response.headers.get('Transfer-Encoding') === 'chunked';\n if (isChunked) {\n return response.body!;\n // return handleChunkedResponse(response, contentType);\n }\n\n const { type } = parse(contentType);\n switch (type) {\n case 'application/json':\n return response.json();\n case 'text/plain':\n return response.text();\n case 'text/html':\n return response.text();\n case 'text/xml':\n case 'application/xml':\n return response.text();\n case 'application/x-www-form-urlencoded': {\n const text = await response.text();\n return Object.fromEntries(new URLSearchParams(text));\n }\n case 'multipart/form-data':\n return response.formData();\n default:\n throw new Error(`Unsupported content type: ${contentType}`);\n }\n}\n", "import { z } from 'zod';\n\nexport type ParseError<T extends z.ZodType<any, any, any>> = {\n kind: 'parse';\n} & z.inferFlattenedErrors<T>;\n\nexport function parse<T extends z.ZodType>(\n schema: T,\n input: unknown,\n) {\n const result = schema.safeParse(input);\n if (!result.success) {\n const errors = result.error.flatten((issue) => issue);\n return [null, errors];\n }\n return [result.data as z.infer<T>, null];\n}\n", "export type Method = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\nexport type ContentType = 'xml' | 'json' | 'urlencoded' | 'multipart';\nexport type Endpoint =\n | `${ContentType} ${Method} ${string}`\n | `${Method} ${string}`;\n\nexport type BodyInit =\n | ArrayBuffer\n | Blob\n | FormData\n | URLSearchParams\n | null\n | string;\n\nexport function createUrl(path: string, query: URLSearchParams) {\n const url = new URL(path, `local://`);\n url.search = query.toString();\n return url;\n}\n\nfunction template(\n templateString: string,\n templateVariables: Record<string, any>,\n): string {\n const nargs = /{([0-9a-zA-Z_]+)}/g;\n return templateString.replace(nargs, (match, key: string, index: number) => {\n // Handle escaped double braces\n if (\n templateString[index - 1] === '{' &&\n templateString[index + match.length] === '}'\n ) {\n return key;\n }\n\n const result = key in templateVariables ? templateVariables[key] : null;\n return result === null || result === undefined ? '' : String(result);\n });\n}\n\ntype Input = Record<string, any>;\ntype Props = {\n inputHeaders: string[];\n inputQuery: string[];\n inputBody: string[];\n inputParams: string[];\n};\n\nabstract class Serializer {\n constructor(\n protected input: Input,\n protected props: Props,\n ) {}\n abstract getBody(): BodyInit | null;\n abstract getHeaders(): Record<string, string>;\n serialize(): Serialized {\n const headers = new Headers({});\n for (const header of this.props.inputHeaders) {\n headers.set(header, this.input[header]);\n }\n\n const query = new URLSearchParams();\n for (const key of this.props.inputQuery) {\n const value = this.input[key];\n if (value !== undefined) {\n query.set(key, String(value));\n }\n }\n\n const params = this.props.inputParams.reduce<Record<string, any>>(\n (acc, key) => {\n acc[key] = this.input[key];\n return acc;\n },\n {},\n );\n\n return {\n body: this.getBody(),\n query,\n params,\n headers: this.getHeaders(),\n };\n }\n}\n\ninterface Serialized {\n body: BodyInit | null;\n query: URLSearchParams;\n params: Record<string, any>;\n headers: Record<string, string>;\n}\n\nclass JsonSerializer extends Serializer {\n getBody(): BodyInit | null {\n const body: Record<string, any> = {};\n for (const prop of this.props.inputBody) {\n body[prop] = this.input[prop];\n }\n return JSON.stringify(body);\n }\n getHeaders(): Record<string, string> {\n return {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n };\n }\n}\n\nclass UrlencodedSerializer extends Serializer {\n getBody(): BodyInit | null {\n const body = new URLSearchParams();\n for (const prop of this.props.inputBody) {\n body.set(prop, this.input[prop]);\n }\n return body;\n }\n getHeaders(): Record<string, string> {\n return {};\n }\n}\n\nclass NoBodySerializer extends Serializer {\n getBody(): BodyInit | null {\n return null;\n }\n getHeaders(): Record<string, string> {\n return {};\n }\n}\n\nclass FormDataSerializer extends Serializer {\n getBody(): BodyInit | null {\n const body = new FormData();\n for (const prop of this.props.inputBody) {\n body.append(prop, this.input[prop]);\n }\n return body;\n }\n getHeaders(): Record<string, string> {\n return {};\n }\n}\n\nexport function json(input: Input, props: Props) {\n return new JsonSerializer(input, props).serialize();\n}\nexport function urlencoded(input: Input, props: Props) {\n return new UrlencodedSerializer(input, props).serialize();\n}\nexport function nobody(input: Input, props: Props) {\n return new NoBodySerializer(input, props).serialize();\n}\nexport function formdata(input: Input, props: Props) {\n return new FormDataSerializer(input, props).serialize();\n}\n\nexport function toRequest<T extends Endpoint>(\n endpoint: T,\n input: Serialized,\n): Request {\n const [method, path] = endpoint.split(' ');\n const pathVariable = template(path, input.params);\n\n const url = createUrl(pathVariable, input.query);\n return new Request(url, {\n method: method,\n headers: input.headers,\n body: method === 'GET' ? undefined : input.body,\n });\n}\n", "export interface ApiResponse<Status extends number, Body extends unknown> {\n kind: 'response';\n status: Status;\n body: Body;\n}\n\n// 4xx Client Errors\nexport type BadRequest = ApiResponse<400, { message: string }>;\nexport type Unauthorized = ApiResponse<401, { message: string }>;\nexport type PaymentRequired = ApiResponse<402, { message: string }>;\nexport type Forbidden = ApiResponse<403, { message: string }>;\nexport type NotFound = ApiResponse<404, { message: string }>;\nexport type MethodNotAllowed = ApiResponse<405, { message: string }>;\nexport type NotAcceptable = ApiResponse<406, { message: string }>;\nexport type Conflict = ApiResponse<409, { message: string }>;\nexport type Gone = ApiResponse<410, { message: string }>;\nexport type UnprocessableEntity = ApiResponse<422, { message: string; errors?: Record<string, string[]> }>;\nexport type TooManyRequests = ApiResponse<429, { message: string; retryAfter?: string }>;\nexport type PayloadTooLarge = ApiResponse<413, { message: string; }>;\nexport type UnsupportedMediaType = ApiResponse<415, { message: string; }>;\n\n// 5xx Server Errors\nexport type InternalServerError = ApiResponse<500, { message: string }>;\nexport type NotImplemented = ApiResponse<501, { message: string }>;\nexport type BadGateway = ApiResponse<502, { message: string }>;\nexport type ServiceUnavailable = ApiResponse<503, { message: string; retryAfter?: string }>;\nexport type GatewayTimeout = ApiResponse<504, { message: string }>;\n\nexport type ClientError =\n | BadRequest\n | Unauthorized\n | PaymentRequired\n | Forbidden\n | NotFound\n | MethodNotAllowed\n | NotAcceptable\n | Conflict\n | Gone\n | UnprocessableEntity\n | TooManyRequests;\n\nexport type ServerError =\n | InternalServerError\n | NotImplemented\n | BadGateway\n | ServiceUnavailable\n | GatewayTimeout;\n\nexport type ProblematicResponse = ClientError | ServerError;\n", "import z from 'zod';\n\nimport type { Interceptor } from './interceptors.ts';\nimport { handleError, parseResponse } from './parse-response.ts';\nimport { parse } from './parser.ts';\n\nexport interface RequestSchema {\n schema: z.ZodType;\n toRequest: (input: any) => Request;\n}\n\nexport const fetchType = z\n .function()\n .args(z.instanceof(Request))\n .returns(z.promise(z.instanceof(Response)))\n .optional();\n\nexport async function sendRequest(\n input: any,\n route: RequestSchema,\n options: {\n fetch?: z.infer<typeof fetchType>;\n interceptors?: Interceptor[];\n },\n) {\n const { interceptors = [] } = options;\n const [parsedInput, parseError] = parse(route.schema, input);\n if (parseError) {\n return [null as never, { ...parseError, kind: 'parse' } as never] as const;\n }\n\n let request = route.toRequest(parsedInput as never);\n for (const interceptor of interceptors) {\n if (interceptor.before) {\n request = await interceptor.before(request);\n }\n }\n\n let response = await (options.fetch ?? fetch)(request);\n\n for (let i = interceptors.length - 1; i >= 0; i--) {\n const interceptor = interceptors[i];\n if (interceptor.after) {\n response = await interceptor.after(response.clone());\n }\n }\n\n if (response.ok) {\n const data = await parseResponse(response);\n return [data as never, null] as const;\n }\n const error = await handleError(response);\n return [null as never, { ...error, kind: 'response' }] as const;\n}\n", "import { watch as nodeWatch } from 'node:fs/promises';\nimport { debounceTime, from } from 'rxjs';\n\nexport function watch(path: string) {\n return from(\n nodeWatch(path, {\n persistent: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,OAAO,EAAE,CAAC;AAAA,MACpE;AAAA,IACF;AAAA,EACF,CAAC;AACH,CAAC;;;AD1FH,IAAM,MAAM,QACT,YAAY,mCAAmC,EAC/C,WAAW,kBAAU,EAAE,WAAW,KAAK,CAAC,EACxC;AAAA,EACC,IAAIC,SAAQ,WAAW,EAAE,OAAO,MAAM;AAAA,EAEtC,CAAC;AAAA,EACD,EAAE,QAAQ,KAAK;AACjB,EACC,MAAM,QAAQ,IAAI;",
6
- "names": ["Command", "readFile", "join", "ts", "get", "camelcase", "pascalcase", "spinalcase", "name", "security", "it", "appendOptional", "spinalcase", "camelcase", "methods", "get", "pascalcase", "join", "exclude", "readFile", "Command"]
4
+ "sourcesContent": ["#!/usr/bin/env node\nimport { Command, program } from 'commander';\n\nimport generate from './generate.ts';\n\nconst cli = program\n .description(`CLI tool to interact with SDK-IT.`)\n .addCommand(generate, { isDefault: true })\n .addCommand(\n new Command('_internal').action(() => {\n // do nothing\n }),\n { hidden: true },\n )\n .parse(process.argv);\n\nexport default cli;\n", "import { Command, Option } from 'commander';\nimport { execFile } from 'node:child_process';\nimport { readFile } from 'node:fs/promises';\nimport { extname } from 'node:path';\nimport { parse } from 'yaml';\n\nimport { generate } from '@sdk-it/typescript';\n\ninterface Options {\n spec: string;\n output: string;\n language: string;\n mode?: 'full' | 'minimal';\n name?: string;\n /**\n * Command to run the formatter.\n * @example 'biome check $SDK_IT_OUTPUT --write'\n * @example 'prettier $SDK_IT_OUTPUT --write'\n */\n formatter?: string;\n}\n\nconst specOption = new Option(\n '-s, --spec <spec>',\n 'Path to OpenAPI specification file',\n);\n\nconst outputOption = new Option(\n '-o, --output <output>',\n 'Output directory for the generated SDK',\n);\n\nasync function loadRemote(location: string) {\n const extName = extname(location);\n const response = await fetch(location);\n switch (extName) {\n case '.json':\n return response.json();\n case '.yaml':\n case '.yml': {\n const text = await response.text();\n return parse(text);\n }\n default:\n throw new Error(`Unsupported file extension: ${extName}`);\n }\n}\n\nasync function loadLocal(location: string) {\n const extName = extname(location);\n switch (extName) {\n case '.json':\n return import(location);\n case '.yaml':\n case '.yml': {\n const text = await await readFile(location, 'utf-8');\n return parse(text);\n }\n default:\n throw new Error(`Unsupported file extension: ${extName}`);\n }\n}\n\nfunction loadSpec(location: string) {\n const [protocol] = location.split(':');\n if (protocol === 'http' || protocol === 'https') {\n return loadRemote(location);\n }\n return loadLocal(location);\n}\n\nexport default new Command('generate')\n .description(`Generate SDK out of a openapi spec file.`)\n .addOption(specOption.makeOptionMandatory(true))\n .addOption(outputOption.makeOptionMandatory(true))\n .option('-l, --language <language>', 'Programming language for the SDK')\n .option(\n '-m, --mode <mode>',\n 'full: generate a full project including package.json and tsconfig.json. useful for monorepo/workspaces minimal: generate only the client sdk',\n )\n .option('-n, --name <name>', 'Name of the generated client', 'Client')\n .option('--formatter <formatter>', 'Formatter to use for the generated code')\n .action(async (options: Options) => {\n const spec = await loadSpec(options.spec);\n await generate(spec, {\n output: options.output,\n mode: options.mode || 'minimal',\n name: options.name,\n formatCode: ({ env, output }) => {\n if (options.formatter) {\n const [command, ...args] = options.formatter.split(' ');\n execFile(command, args, { env: { ...env, SDK_IT_OUTPUT: output } });\n }\n },\n });\n });\n", "import { join } from 'node:path';\nimport { npmRunPathEnv } from 'npm-run-path';\nimport type { OpenAPIObject } from 'openapi3-ts/oas31';\n\nimport { getFolderExports, methods, writeFiles } from '@sdk-it/core';\n\nimport { generateCode } from './generator.ts';\nimport interceptors from './http/interceptors.txt';\nimport parseResponse from './http/parse-response.txt';\nimport parserTxt from './http/parser.txt';\nimport requestTxt from './http/request.txt';\nimport responseTxt from './http/response.txt';\nimport sendRequest from './http/send-request.txt';\nimport { generateInputs, generateSDK } from './sdk.ts';\nimport { exclude, securityToOptions } from './utils.ts';\n\nfunction security(spec: OpenAPIObject) {\n const security = spec.security || [];\n const components = spec.components || {};\n const securitySchemas = components.securitySchemes || {};\n const paths = Object.values(spec.paths ?? {});\n\n const options = securityToOptions(security, securitySchemas);\n\n for (const it of paths) {\n for (const method of methods) {\n const operation = it[method];\n if (!operation) {\n continue;\n }\n Object.assign(\n options,\n securityToOptions(operation.security || [], securitySchemas, 'input'),\n );\n }\n }\n return options;\n}\n\nexport async function generate(\n spec: OpenAPIObject,\n settings: {\n output: string;\n name?: string;\n /**\n * full: generate a full project including package.json and tsconfig.json. useful for monorepo/workspaces\n * minimal: generate only the client sdk\n */\n mode?: 'full' | 'minimal';\n formatCode?: (options: {\n output: string;\n env: ReturnType<typeof npmRunPathEnv>;\n }) => void | Promise<void>;\n },\n) {\n const { commonSchemas, groups, outputs, commonZod } = generateCode({\n spec,\n style: 'github',\n target: 'javascript',\n });\n const output =\n settings.mode === 'full' ? join(settings.output, 'src') : settings.output;\n\n const options = security(spec);\n\n const clientFiles = generateSDK({\n name: settings.name || 'Client',\n operations: groups,\n servers: spec.servers?.map((server) => server.url) || [],\n options: options,\n });\n\n // const readme = generateReadme(spec, {\n // name: settings.name || 'Client',\n // });\n\n const inputFiles = generateInputs(groups, commonZod);\n\n await writeFiles(output, {\n 'outputs/.gitkeep': '',\n 'inputs/.gitkeep': '',\n 'models/.getkeep': '',\n // 'README.md': readme,\n });\n\n await writeFiles(join(output, 'http'), {\n 'interceptors.ts': interceptors,\n 'parse-response.ts': parseResponse,\n 'send-request.ts': sendRequest,\n 'response.ts': responseTxt,\n 'parser.ts': parserTxt,\n 'request.ts': requestTxt,\n });\n\n await writeFiles(join(output, 'outputs'), outputs);\n const modelsImports = Object.entries(commonSchemas).map(([name]) => name);\n await writeFiles(output, {\n ...clientFiles,\n ...inputFiles,\n ...Object.fromEntries(\n Object.entries(commonSchemas).map(([name, schema]) => [\n `models/${name}.ts`,\n [\n `import { z } from 'zod';`,\n ...exclude(modelsImports, [name]).map(\n (it) => `import type { ${it} } from './${it}.ts';`,\n ),\n `export type ${name} = ${schema};`,\n ].join('\\n'),\n ]),\n ),\n });\n\n const folders = [\n getFolderExports(output),\n getFolderExports(join(output, 'outputs')),\n getFolderExports(\n join(output, 'inputs'),\n ['ts'],\n (dirent) => dirent.isDirectory() && dirent.name === 'schemas',\n ),\n getFolderExports(join(output, 'http')),\n ];\n if (modelsImports.length) {\n folders.push(getFolderExports(join(output, 'models')));\n }\n const [index, outputIndex, inputsIndex, httpIndex, modelsIndex] =\n await Promise.all(folders);\n await writeFiles(output, {\n 'index.ts': index,\n 'outputs/index.ts': outputIndex,\n 'inputs/index.ts': inputsIndex || null,\n 'http/index.ts': httpIndex,\n ...(modelsImports.length ? { 'models/index.ts': modelsIndex } : {}),\n });\n if (settings.mode === 'full') {\n await writeFiles(settings.output, {\n 'package.json': {\n ignoreIfExists: true,\n content: JSON.stringify(\n {\n type: 'module',\n main: './src/index.ts',\n dependencies: { 'fast-content-type-parse': '^3.0.0' },\n },\n null,\n 2,\n ),\n },\n 'tsconfig.json': {\n ignoreIfExists: false,\n content: JSON.stringify(\n {\n compilerOptions: {\n skipLibCheck: true,\n skipDefaultLibCheck: true,\n target: 'ESNext',\n module: 'ESNext',\n noEmit: true,\n allowImportingTsExtensions: true,\n verbatimModuleSyntax: true,\n baseUrl: '.',\n moduleResolution: 'bundler',\n },\n include: ['**/*.ts'],\n },\n null,\n 2,\n ),\n },\n });\n }\n\n await settings.formatCode?.({\n output: output,\n env: npmRunPathEnv(),\n });\n}\n", "import ts, { TypeFlags, symbolName } from 'typescript';\n\ntype Collector = Record<string, any>;\nexport const deriveSymbol = Symbol.for('serialize');\nexport const $types = Symbol.for('types');\nconst defaults: Record<string, string> = {\n Readable: 'any',\n ReadableStream: 'any',\n DateConstructor: 'string',\n ArrayBufferConstructor: 'any',\n SharedArrayBufferConstructor: 'any',\n Int8ArrayConstructor: 'any',\n Uint8Array: 'any',\n};\nexport class TypeDeriver {\n public readonly collector: Collector = {};\n public readonly checker: ts.TypeChecker;\n constructor(checker: ts.TypeChecker) {\n this.checker = checker;\n }\n\n serializeType(type: ts.Type): any {\n const indexType = type.getStringIndexType();\n if (indexType) {\n return {\n [deriveSymbol]: true,\n kind: 'record',\n optional: false,\n [$types]: [this.serializeType(indexType)],\n };\n }\n if (type.flags & TypeFlags.Any) {\n return {\n [deriveSymbol]: true,\n optional: false,\n [$types]: [],\n };\n }\n if (type.isStringLiteral()) {\n return {\n [deriveSymbol]: true,\n optional: false,\n kind: 'literal',\n value: type.value,\n [$types]: ['string'],\n };\n }\n if (type.isNumberLiteral()) {\n return {\n [deriveSymbol]: true,\n optional: false,\n kind: 'literal',\n value: type.value,\n [$types]: ['number'],\n };\n }\n if (type.flags & TypeFlags.TemplateLiteral) {\n return {\n [deriveSymbol]: true,\n optional: false,\n [$types]: ['string'],\n };\n }\n if (type.flags & TypeFlags.String) {\n return {\n [deriveSymbol]: true,\n optional: false,\n [$types]: ['string'],\n };\n }\n if (type.flags & TypeFlags.Number) {\n return {\n [deriveSymbol]: true,\n optional: false,\n [$types]: ['number'],\n };\n }\n if (type.flags & ts.TypeFlags.Boolean) {\n return {\n [deriveSymbol]: true,\n optional: false,\n [$types]: ['boolean'],\n };\n }\n if (type.flags & TypeFlags.Null) {\n return {\n [deriveSymbol]: true,\n optional: true,\n [$types]: ['null'],\n };\n }\n if (type.isIntersection()) {\n let optional: boolean | undefined;\n const types: any[] = [];\n for (const unionType of type.types) {\n if (optional === undefined) {\n optional = (unionType.flags & ts.TypeFlags.Undefined) !== 0;\n if (optional) {\n continue;\n }\n }\n\n types.push(this.serializeType(unionType));\n }\n return {\n [deriveSymbol]: true,\n kind: 'intersection',\n optional,\n [$types]: types,\n };\n }\n if (type.isUnion()) {\n let optional: boolean | undefined;\n const types: any[] = [];\n for (const unionType of type.types) {\n if (optional === undefined) {\n // ignore undefined\n optional = (unionType.flags & ts.TypeFlags.Undefined) !== 0;\n if (optional) {\n continue;\n }\n }\n\n types.push(this.serializeType(unionType));\n }\n return {\n [deriveSymbol]: true,\n kind: 'union',\n optional,\n [$types]: types,\n };\n }\n if (this.checker.isArrayLikeType(type)) {\n const [argType] = this.checker.getTypeArguments(type as ts.TypeReference);\n if (!argType) {\n const typeName = type.symbol?.getName() || '<unknown>';\n console.warn(\n `Could not find generic type argument for array type ${typeName}`,\n );\n return {\n [deriveSymbol]: true,\n optional: false,\n kind: 'array',\n [$types]: ['any'],\n };\n }\n const typeSymbol = argType.getSymbol();\n if (!typeSymbol) {\n return {\n [deriveSymbol]: true,\n optional: false,\n kind: 'array',\n [$types]: [this.serializeType(argType)],\n };\n }\n\n if (typeSymbol.valueDeclaration) {\n return {\n kind: 'array',\n [deriveSymbol]: true,\n [$types]: [this.serializeNode(typeSymbol.valueDeclaration)],\n };\n }\n const maybeDeclaration = typeSymbol.declarations?.[0];\n if (maybeDeclaration) {\n if (ts.isMappedTypeNode(maybeDeclaration)) {\n const resolvedType = this.checker\n .getPropertiesOfType(argType)\n .reduce<Record<string, unknown>>((acc, prop) => {\n const propType = this.checker.getTypeOfSymbol(prop);\n acc[prop.name] = this.serializeType(propType);\n return acc;\n }, {});\n return {\n kind: 'array',\n optional: false,\n [deriveSymbol]: true,\n [$types]: [resolvedType],\n };\n } else {\n return {\n kind: 'array',\n ...this.serializeNode(maybeDeclaration),\n };\n }\n }\n\n return {\n kind: 'array',\n optional: false,\n [deriveSymbol]: true,\n [$types]: ['any'],\n };\n }\n if (type.isClass()) {\n const declaration = type.symbol?.valueDeclaration;\n if (!declaration) {\n return {\n [deriveSymbol]: true,\n optional: false,\n [$types]: [type.symbol.getName()],\n };\n }\n return this.serializeNode(declaration);\n }\n if (isInterfaceType(type)) {\n const valueDeclaration =\n type.symbol.valueDeclaration ?? type.symbol.declarations?.[0];\n if (!valueDeclaration) {\n return {\n [deriveSymbol]: true,\n optional: false,\n [$types]: [type.symbol.getName()],\n };\n }\n return this.serializeNode(valueDeclaration);\n }\n if (type.flags & TypeFlags.Object) {\n if (defaults[symbolName(type.symbol)]) {\n return {\n [deriveSymbol]: true,\n optional: false,\n [$types]: [defaults[type.symbol.name]],\n };\n }\n const properties = this.checker.getPropertiesOfType(type);\n if (properties.length > 0) {\n const serializedProps: Record<string, any> = {};\n for (const prop of properties) {\n const propAssingment = (prop.getDeclarations() ?? []).find((it) =>\n ts.isPropertyAssignment(it),\n );\n // get literal properties values if any\n if (propAssingment) {\n const type = this.checker.getTypeAtLocation(\n propAssingment.initializer,\n );\n serializedProps[prop.name] = this.serializeType(type);\n }\n if (\n (prop.getDeclarations() ?? []).find((it) =>\n ts.isPropertySignature(it),\n )\n ) {\n const propType = this.checker.getTypeOfSymbol(prop);\n serializedProps[prop.name] = this.serializeType(propType);\n }\n }\n return {\n [deriveSymbol]: true,\n kind: 'object',\n optional: false,\n [$types]: [serializedProps],\n };\n }\n const declaration =\n type.symbol.valueDeclaration ?? type.symbol.declarations?.[0];\n if (!declaration) {\n return {\n [deriveSymbol]: true,\n optional: false,\n [$types]: [type.symbol.getName()],\n };\n }\n return this.serializeNode(declaration);\n }\n console.warn(`Unhandled type: ${type.flags} ${ts.TypeFlags[type.flags]}`);\n\n return {\n [deriveSymbol]: true,\n optional: false,\n [$types]: [\n this.checker.typeToString(\n type,\n undefined,\n ts.TypeFormatFlags.NoTruncation,\n ),\n ],\n };\n }\n\n serializeNode(node: ts.Node): any {\n if (ts.isObjectLiteralExpression(node)) {\n const symbolType = this.checker.getTypeAtLocation(node);\n const props: Record<string, any> = {};\n for (const symbol of symbolType.getProperties()) {\n const type = this.checker.getTypeOfSymbol(symbol);\n props[symbol.name] = this.serializeType(type);\n }\n\n // get literal properties values if any\n for (const prop of node.properties) {\n if (ts.isPropertyAssignment(prop)) {\n const type = this.checker.getTypeAtLocation(prop.initializer);\n props[prop.name.getText()] = this.serializeType(type);\n }\n }\n\n return props;\n }\n if (ts.isPropertyAccessExpression(node)) {\n const symbol = this.checker.getSymbolAtLocation(node.name);\n if (!symbol) {\n console.warn(`No symbol found for ${node.name.getText()}`);\n return null;\n }\n const type = this.checker.getTypeOfSymbol(symbol);\n return this.serializeType(type);\n }\n if (ts.isPropertySignature(node)) {\n const symbol = this.checker.getSymbolAtLocation(node.name);\n if (!symbol) {\n console.warn(`No symbol found for ${node.name.getText()}`);\n return null;\n }\n const type = this.checker.getTypeOfSymbol(symbol);\n return this.serializeType(type);\n }\n if (ts.isPropertyDeclaration(node)) {\n const symbol = this.checker.getSymbolAtLocation(node.name);\n if (!symbol) {\n console.warn(`No symbol found for ${node.name.getText()}`);\n return null;\n }\n const type = this.checker.getTypeOfSymbol(symbol);\n return this.serializeType(type);\n }\n if (ts.isInterfaceDeclaration(node)) {\n if (!node.name?.text) {\n throw new Error('Interface has no name');\n }\n if (defaults[node.name.text]) {\n return {\n [deriveSymbol]: true,\n optional: false,\n [$types]: [defaults[node.name.text]],\n };\n }\n if (!this.collector[node.name.text]) {\n this.collector[node.name.text] = {};\n const members: Record<string, any> = {};\n for (const member of node.members.filter(ts.isPropertySignature)) {\n members[member.name.getText()] = this.serializeNode(member);\n }\n this.collector[node.name.text] = members;\n }\n return {\n [deriveSymbol]: true,\n optional: false,\n [$types]: [`#/components/schemas/${node.name.text}`],\n };\n }\n if (ts.isClassDeclaration(node)) {\n if (!node.name?.text) {\n throw new Error('Class has no name');\n }\n if (defaults[node.name.text]) {\n return {\n [deriveSymbol]: true,\n optional: false,\n [$types]: [defaults[node.name.text]],\n };\n }\n\n if (!this.collector[node.name.text]) {\n this.collector[node.name.text] = {};\n const members: Record<string, unknown> = {};\n for (const member of node.members.filter(ts.isPropertyDeclaration)) {\n members[member.name!.getText()] = this.serializeNode(member);\n }\n this.collector[node.name.text] = members;\n }\n return {\n [deriveSymbol]: true,\n optional: false,\n [$types]: [`#/components/schemas/${node.name.text}`],\n $ref: `#/components/schemas/${node.name.text}`,\n };\n }\n if (ts.isVariableDeclaration(node)) {\n const symbol = this.checker.getSymbolAtLocation(node.name);\n if (!symbol) {\n console.warn(`No symbol found for ${node.name.getText()}`);\n return null;\n }\n if (!node.type) {\n console.warn(`No type found for ${node.name.getText()}`);\n return 'any';\n }\n const type = this.checker.getTypeFromTypeNode(node.type);\n return this.serializeType(type);\n }\n if (ts.isIdentifier(node)) {\n const symbol = this.checker.getSymbolAtLocation(node);\n if (!symbol) {\n console.warn(`Identifer: No symbol found for ${node.getText()}`);\n return null;\n }\n const type = this.checker.getTypeAtLocation(node);\n return this.serializeType(type);\n }\n if (ts.isAwaitExpression(node)) {\n const type = this.checker.getTypeAtLocation(node);\n return this.serializeType(type);\n }\n if (ts.isCallExpression(node)) {\n const type = this.checker.getTypeAtLocation(node);\n return this.serializeType(type);\n }\n if (ts.isAsExpression(node)) {\n const type = this.checker.getTypeAtLocation(node);\n return this.serializeType(type);\n }\n if (ts.isTypeLiteralNode(node)) {\n const symbolType = this.checker.getTypeAtLocation(node);\n const props: Record<string, unknown> = {};\n for (const symbol of symbolType.getProperties()) {\n const type = this.checker.getTypeOfSymbol(symbol);\n props[symbol.name] = this.serializeType(type);\n }\n return {\n [deriveSymbol]: true,\n optional: false,\n [$types]: [props],\n };\n }\n if (node.kind === ts.SyntaxKind.NullKeyword) {\n return {\n [deriveSymbol]: true,\n optional: true,\n [$types]: ['null'],\n };\n }\n if (node.kind === ts.SyntaxKind.BooleanKeyword) {\n return {\n [deriveSymbol]: true,\n optional: false,\n [$types]: ['boolean'],\n };\n }\n if (node.kind === ts.SyntaxKind.TrueKeyword) {\n return {\n [deriveSymbol]: true,\n optional: false,\n kind: 'literal',\n value: true,\n [$types]: ['boolean'],\n };\n }\n if (node.kind === ts.SyntaxKind.FalseKeyword) {\n return {\n [deriveSymbol]: true,\n optional: false,\n kind: 'literal',\n value: false,\n [$types]: ['boolean'],\n };\n }\n if (ts.isArrayLiteralExpression(node)) {\n const type = this.checker.getTypeAtLocation(node);\n return this.serializeType(type);\n }\n\n console.warn(`Unhandled node: ${ts.SyntaxKind[node.kind]} ${node.flags}`);\n return {\n [deriveSymbol]: true,\n optional: false,\n [$types]: ['any'],\n };\n }\n}\n\nfunction isInterfaceType(type: ts.Type): boolean {\n if (type.isClassOrInterface()) {\n // Check if it's an interface\n return !!(type.symbol.flags & ts.SymbolFlags.Interface);\n }\n return false;\n}\n", "import type { Dirent } from 'node:fs';\nimport { mkdir, readFile, readdir, stat, writeFile } from 'node:fs/promises';\nimport { dirname, isAbsolute, join } from 'node:path';\n\nexport async function getFile(filePath: string) {\n if (await exist(filePath)) {\n return readFile(filePath, 'utf-8');\n }\n return null;\n}\n\nexport async function exist(file: string): Promise<boolean> {\n return stat(file)\n .then(() => true)\n .catch(() => false);\n}\n\nexport async function readFolder(path: string) {\n if (await exist(path)) {\n return readdir(path);\n }\n return [] as string[];\n}\n\nexport async function writeFiles(\n dir: string,\n contents: Record<\n string,\n null | string | { content: string; ignoreIfExists?: boolean }\n >,\n) {\n await Promise.all(\n Object.entries(contents).map(async ([file, content]) => {\n if (content === null) {\n return;\n }\n const filePath = isAbsolute(file) ? file : join(dir, file);\n await mkdir(dirname(filePath), { recursive: true });\n if (typeof content === 'string') {\n await writeFile(filePath, content, 'utf-8');\n } else {\n if (content.ignoreIfExists) {\n if (!(await exist(filePath))) {\n await writeFile(filePath, content.content, 'utf-8');\n }\n } else {\n await writeFile(filePath, content.content, 'utf-8');\n }\n }\n }),\n );\n}\n\nexport async function getFolderExports(\n folder: string,\n extensions = ['ts'],\n ignore: (dirent: Dirent) => boolean = () => false,\n) {\n const files = await readdir(folder, { withFileTypes: true });\n const exports: string[] = [];\n for (const file of files) {\n if (ignore(file)) {\n continue;\n }\n if (file.isDirectory()) {\n exports.push(`export * from './${file.name}/index.ts';`);\n } else if (\n file.name !== 'index.ts' &&\n extensions.includes(getExt(file.name))\n ) {\n exports.push(`export * from './${file.name}';`);\n }\n }\n return exports.join('\\n');\n}\n\nexport const getExt = (fileName?: string) => {\n if (!fileName) {\n return ''; // shouldn't happen as there will always be a file name\n }\n const lastDot = fileName.lastIndexOf('.');\n if (lastDot === -1) {\n return '';\n }\n const ext = fileName\n .slice(lastDot + 1)\n .split('/')\n .filter(Boolean)\n .join('');\n if (ext === fileName) {\n // files that have no extension\n return '';\n }\n return ext || 'txt';\n};\n", "import type {\n HeadersObject,\n OperationObject,\n ParameterObject,\n PathsObject,\n ResponseObject,\n ResponsesObject,\n SchemaObject,\n} from 'openapi3-ts/oas31';\n\nimport { $types } from './deriver.ts';\n\nexport type Method =\n | 'get'\n | 'post'\n | 'put'\n | 'patch'\n | 'delete'\n | 'trace'\n | 'head';\nexport const methods = [\n 'get',\n 'post',\n 'put',\n 'patch',\n 'delete',\n 'trace',\n 'head',\n] as const;\nexport type SemanticSource =\n | 'query'\n | 'queries'\n | 'body'\n | 'params'\n | 'headers';\n\nconst semanticSourceToOpenAPI = {\n queries: 'query',\n query: 'query',\n headers: 'header',\n params: 'path',\n} as const;\nexport interface Selector {\n name: string;\n select: string;\n against: string;\n source: SemanticSource;\n nullable: boolean;\n required: boolean;\n}\n\nexport interface ResponseItem {\n statusCode: string;\n response?: DateType;\n contentType: string;\n headers: (string | Record<string, string[]>)[];\n}\n\nexport type OnOperation = (\n sourceFile: string,\n method: Method,\n path: string,\n operation: OperationObject,\n) => PathsObject;\nexport class Paths {\n #commonZodImport?: string;\n #onOperation?: OnOperation;\n #operations: Array<{\n sourceFile: string;\n name: string;\n path: string;\n method: Method;\n selectors: Selector[];\n responses: ResponsesObject;\n tags?: string[];\n description?: string;\n }> = [];\n\n constructor(config: { commonZodImport?: string; onOperation?: OnOperation }) {\n this.#commonZodImport = config.commonZodImport;\n this.#onOperation = config.onOperation;\n }\n\n addPath(\n name: string,\n path: string,\n method: Method,\n selectors: Selector[],\n responses: ResponseItem[],\n sourceFile: string,\n tags?: string[],\n description?: string,\n ) {\n const responsesObject = this.#responseItemToResponses(responses);\n\n this.#operations.push({\n name,\n path: this.#tunePath(path),\n sourceFile,\n method,\n selectors,\n responses: responsesObject,\n tags,\n description,\n });\n return this;\n }\n\n #responseItemToResponses(responses: ResponseItem[]): ResponsesObject {\n const responsesObject: ResponsesObject = {};\n for (const item of responses) {\n const ct = item.contentType;\n const schema = item.response ? toSchema(item.response) : {};\n if (!responsesObject[item.statusCode]) {\n responsesObject[item.statusCode] = {\n description: `Response for ${item.statusCode}`,\n content:\n ct !== 'empty'\n ? {\n [ct]:\n ct === 'application/octet-stream'\n ? { schema: { type: 'string', format: 'binary' } }\n : { schema },\n }\n : undefined,\n headers: item.headers.length\n ? item.headers.reduce<HeadersObject>((acc, current) => {\n const headers =\n typeof current === 'string' ? { [current]: [] } : current;\n return Object.entries(headers).reduce<HeadersObject>(\n (subAcc, [key, value]) => {\n const header: HeadersObject = {\n [key]: {\n schema: {\n type: 'string',\n enum: value.length ? value : undefined,\n },\n },\n };\n return { ...subAcc, ...header };\n },\n acc,\n );\n }, {})\n : undefined,\n } satisfies ResponseObject;\n } else {\n if (!responsesObject[item.statusCode].content[ct]) {\n responsesObject[item.statusCode].content[ct] = { schema };\n } else {\n const existing = responsesObject[item.statusCode].content[ct]\n .schema as SchemaObject;\n if (existing.oneOf) {\n if (\n !existing.oneOf.find(\n (it) => JSON.stringify(it) === JSON.stringify(schema),\n )\n ) {\n existing.oneOf.push(schema);\n }\n } else if (JSON.stringify(existing) !== JSON.stringify(schema)) {\n responsesObject[item.statusCode].content[ct].schema = {\n oneOf: [existing, schema],\n };\n }\n }\n }\n }\n return responsesObject;\n }\n\n async #selectosToParameters(selectors: Selector[]) {\n const parameters: ParameterObject[] = [];\n const bodySchemaProps: Record<\n string,\n { required: boolean; schema: SchemaObject }\n > = {};\n for (const selector of selectors) {\n if (selector.source === 'body') {\n bodySchemaProps[selector.name] = {\n required: selector.required,\n schema: await evalZod(selector.against, this.#commonZodImport),\n };\n continue;\n }\n\n const parameter: ParameterObject = {\n in: semanticSourceToOpenAPI[selector.source],\n name: selector.name,\n required: selector.required,\n schema: await evalZod(selector.against, this.#commonZodImport),\n };\n parameters.push(parameter);\n }\n return { parameters, bodySchemaProps };\n }\n\n async getPaths() {\n const operations: PathsObject = {};\n for (const operation of this.#operations) {\n const { path, method, selectors } = operation;\n const { parameters, bodySchemaProps } =\n await this.#selectosToParameters(selectors);\n const bodySchema: Record<string, SchemaObject> = {};\n const required: string[] = [];\n for (const [key, value] of Object.entries(bodySchemaProps)) {\n if (value.required) {\n required.push(key);\n }\n bodySchema[key] = value.schema;\n }\n const operationObject: OperationObject = {\n operationId: operation.name,\n parameters,\n tags: operation.tags,\n description: operation.description,\n requestBody: Object.keys(bodySchema).length\n ? {\n content: {\n 'application/json': {\n schema: {\n required: required.length ? required : undefined,\n type: 'object',\n properties: bodySchema,\n },\n },\n },\n }\n : undefined,\n responses:\n Object.keys(operation.responses).length === 0\n ? undefined\n : operation.responses,\n };\n if (!operations[path]) {\n operations[path] = {};\n }\n operations[path][method] = operationObject;\n if (this.#onOperation) {\n const paths = this.#onOperation?.(\n operation.sourceFile,\n method,\n path,\n operationObject,\n );\n Object.assign(operations, paths ?? {});\n }\n }\n return operations;\n }\n\n /**\n * Converts Express/Node.js style path parameters (/path/:param) to OpenAPI style (/path/{param})\n */\n #tunePath(path: string): string {\n return path.replace(/:([^/]+)/g, '{$1}');\n }\n}\n\nasync function evalZod(schema: string, commonZodImport?: string) {\n // https://github.com/nodejs/node/issues/51956\n const lines = [\n `import { createRequire } from \"node:module\";`,\n `const filename = \"${import.meta.url}\";`,\n `const require = createRequire(filename);`,\n `const z = require(\"zod\");`,\n commonZodImport ? `const commonZod = require('${commonZodImport}');` : '',\n `const {zodToJsonSchema} = require('zod-to-json-schema');`,\n `const schema = ${schema.replace('.optional()', '')};`,\n `const jsonSchema = zodToJsonSchema(schema, {\n \t$refStrategy: 'root',\n \tbasePath: ['#', 'components', 'schemas']\n });`,\n `export default jsonSchema;`,\n ];\n const base64 = Buffer.from(lines.join('\\n')).toString('base64');\n return import(`data:text/javascript;base64,${base64}`)\n .then((mod) => mod.default)\n .then(({ $schema, ...result }) => result);\n}\n\ninterface DateType {\n [$types]: any[];\n kind: string;\n optional: boolean;\n value?: string;\n}\n\nexport function toSchema(data: DateType | string | null | undefined): any {\n if (data === null || data === undefined) {\n return { type: 'any' };\n } else if (typeof data === 'string') {\n const isRef = data.startsWith('#');\n if (isRef) {\n return { $ref: data };\n }\n return { type: data };\n } else if (data.kind === 'literal') {\n return { enum: [data.value], type: data[$types][0] };\n } else if (data.kind === 'record') {\n return {\n type: 'object',\n additionalProperties: toSchema(data[$types][0]),\n };\n } else if (data.kind === 'array') {\n const items = data[$types].map(toSchema);\n return { type: 'array', items: data[$types].length ? items[0] : {} };\n } else if (data.kind === 'union') {\n return { anyOf: data[$types].map(toSchema) };\n } else if (data.kind === 'intersection') {\n return { allOf: data[$types].map(toSchema) };\n } else if ($types in data) {\n return data[$types].map(toSchema)[0] ?? {};\n } else {\n const props: Record<string, unknown> = {};\n const required: string[] = [];\n for (const [key, value] of Object.entries(data)) {\n props[key] = toSchema(value as any);\n if (!(value as any).optional) {\n required.push(key);\n }\n }\n return {\n type: 'object',\n properties: props,\n required,\n additionalProperties: false,\n };\n }\n}\n\nexport function isHttpMethod(name: string): name is Method {\n return ['get', 'post', 'put', 'delete', 'patch'].includes(name);\n}\n", "import debug from 'debug';\nimport { dirname, join } from 'node:path';\nimport ts from 'typescript';\n\nconst logger = debug('january:client');\n\nexport function parseTsConfig(tsconfigPath: string) {\n logger(`Using TypeScript version: ${ts.version}`);\n const configContent = ts.readConfigFile(tsconfigPath, ts.sys.readFile);\n\n if (configContent.error) {\n console.error(\n `Failed to read tsconfig file:`,\n ts.formatDiagnosticsWithColorAndContext([configContent.error], {\n getCanonicalFileName: (path) => path,\n getCurrentDirectory: ts.sys.getCurrentDirectory,\n getNewLine: () => ts.sys.newLine,\n }),\n );\n throw new Error('Failed to parse tsconfig.json');\n }\n\n const parsed = ts.parseJsonConfigFileContent(\n configContent.config,\n ts.sys,\n dirname(tsconfigPath),\n );\n\n if (parsed.errors.length > 0) {\n console.error(\n `Errors found in tsconfig.json:`,\n ts.formatDiagnosticsWithColorAndContext(parsed.errors, {\n getCanonicalFileName: (path) => path,\n getCurrentDirectory: ts.sys.getCurrentDirectory,\n getNewLine: () => ts.sys.newLine,\n }),\n );\n throw new Error('Failed to parse tsconfig.json');\n }\n return parsed;\n}\nexport function getProgram(tsconfigPath: string) {\n const tsConfigParseResult = parseTsConfig(tsconfigPath);\n logger(`Parsing tsconfig`);\n return ts.createProgram({\n options: {\n ...tsConfigParseResult.options,\n noEmit: true,\n incremental: true,\n tsBuildInfoFile: join(dirname(tsconfigPath), './.tsbuildinfo'), // not working atm\n },\n rootNames: tsConfigParseResult.fileNames,\n projectReferences: tsConfigParseResult.projectReferences,\n configFileParsingDiagnostics: tsConfigParseResult.errors,\n });\n}\nexport function getPropertyAssignment(node: ts.Node, name: string) {\n if (ts.isObjectLiteralExpression(node)) {\n return node.properties\n .filter((prop) => ts.isPropertyAssignment(prop))\n .find((prop) => prop.name!.getText() === name);\n }\n return undefined;\n}\nexport function isCallExpression(\n node: ts.Node,\n name: string,\n): node is ts.CallExpression {\n return (\n ts.isCallExpression(node) &&\n node.expression &&\n ts.isIdentifier(node.expression) &&\n node.expression.text === name\n );\n}\n\nexport function isInterfaceType(type: ts.Type): boolean {\n if (type.isClassOrInterface()) {\n // Check if it's an interface\n return !!(type.symbol.flags & ts.SymbolFlags.Interface);\n }\n return false;\n}\n", "import type ts from 'typescript';\n\nimport type { TypeDeriver } from './lib/deriver.ts';\nimport type { ResponseItem } from './lib/paths.ts';\n\nexport * from './lib/deriver.ts';\nexport * from './lib/file-system.ts';\nexport * from './lib/paths.ts';\nexport * from './lib/program.ts';\n\nexport function removeDuplicates<T>(\n data: T[],\n accessor: (item: T) => T[keyof T],\n): T[] {\n return [...new Map(data.map((x) => [accessor(x), x])).values()];\n}\n\nexport type InferRecordValue<T> = T extends Record<string, infer U> ? U : any;\n\nexport function toLitObject<T extends Record<string, any>>(\n obj: T,\n accessor: (value: InferRecordValue<T>) => string = (value) => value,\n) {\n return `{${Object.keys(obj)\n .map((key) => `${key}: ${accessor(obj[key])}`)\n .join(', ')}}`;\n}\n\nexport type NaunceResponseAnalyzerFn = (\n handler: ts.ArrowFunction,\n deriver: TypeDeriver,\n node: ts.Node,\n) => ResponseItem[];\nexport type NaunceResponseAnalyzer = Record<string, NaunceResponseAnalyzerFn>;\n\nexport type ResponseAnalyzerFn = (\n handler: ts.ArrowFunction,\n deriver: TypeDeriver,\n) => ResponseItem[];\n", "import { get, merge } from 'lodash-es';\nimport type {\n ContentObject,\n OpenAPIObject,\n OperationObject,\n ParameterLocation,\n ParameterObject,\n ResponseObject,\n} from 'openapi3-ts/oas31';\nimport { camelcase, pascalcase, spinalcase } from 'stringcase';\n\nimport { TypeScriptDeserialzer } from './emitters/interface.ts';\nimport { ZodDeserialzer } from './emitters/zod.ts';\nimport { type Operation, type Spec } from './sdk.ts';\nimport { followRef, isRef, securityToOptions, useImports } from './utils.ts';\n\nexport interface NamedImport {\n name: string;\n alias?: string;\n isTypeOnly: boolean;\n}\nexport interface Import {\n isTypeOnly: boolean;\n moduleSpecifier: string;\n defaultImport: string | undefined;\n namedImports: NamedImport[];\n namespaceImport: string | undefined;\n}\n\nconst responses: Record<string, string> = {\n '400': 'BadRequest',\n '401': 'Unauthorized',\n '402': 'PaymentRequired',\n '403': 'Forbidden',\n '404': 'NotFound',\n '405': 'MethodNotAllowed',\n '406': 'NotAcceptable',\n '409': 'Conflict',\n '413': 'PayloadTooLarge',\n '410': 'Gone',\n '422': 'UnprocessableEntity',\n '429': 'TooManyRequests',\n '500': 'InternalServerError',\n '501': 'NotImplemented',\n '502': 'BadGateway',\n '503': 'ServiceUnavailable',\n '504': 'GatewayTimeout',\n};\n\nexport interface GenerateSdkConfig {\n spec: OpenAPIObject;\n target?: 'javascript';\n /**\n * No support for jsdoc in vscode\n * @issue https://github.com/microsoft/TypeScript/issues/38106\n */\n style?: 'github';\n operationId?: (\n operation: OperationObject,\n path: string,\n method: string,\n ) => string;\n}\n\nexport const defaults: Partial<GenerateSdkConfig> &\n Required<Pick<GenerateSdkConfig, 'operationId'>> = {\n target: 'javascript',\n style: 'github',\n operationId: (operation, path, method) => {\n if (operation.operationId) {\n return spinalcase(operation.operationId);\n }\n return camelcase(`${method} ${path.replace(/[\\\\/\\\\{\\\\}]/g, ' ').trim()}`);\n },\n};\n\nexport function generateCode(config: GenerateSdkConfig) {\n const commonSchemas: Record<string, string> = {};\n const commonZod = new Map<string, string>();\n const commonZodImports: Import[] = [];\n const zodDeserialzer = new ZodDeserialzer(config.spec, (model, schema) => {\n commonZod.set(model, schema);\n commonZodImports.push({\n defaultImport: undefined,\n isTypeOnly: true,\n moduleSpecifier: `./${model}.ts`,\n namedImports: [{ isTypeOnly: true, name: model }],\n namespaceImport: undefined,\n });\n });\n\n const groups: Spec['operations'] = {};\n const outputs: Record<string, string> = {};\n\n for (const [path, methods] of Object.entries(config.spec.paths ?? {})) {\n for (const [method, operation] of Object.entries(methods) as [\n string,\n OperationObject,\n ][]) {\n const formatOperationId = config.operationId ?? defaults.operationId;\n const operationName = formatOperationId(operation, path, method);\n\n console.log(`Processing ${method} ${path}`);\n const groupName = (operation.tags ?? ['unknown'])[0];\n groups[groupName] ??= [];\n const inputs: Operation['inputs'] = {};\n\n const additionalProperties: ParameterObject[] = [];\n for (const param of operation.parameters ?? []) {\n if (isRef(param)) {\n throw new Error(`Found reference in parameter ${param.$ref}`);\n }\n if (!param.schema) {\n throw new Error(`Schema not found for parameter ${param.name}`);\n }\n inputs[param.name] = {\n in: param.in,\n schema: '',\n };\n additionalProperties.push(param);\n }\n\n const security = operation.security ?? [];\n const securitySchemas = config.spec.components?.securitySchemes ?? {};\n\n const securityOptions = securityToOptions(security, securitySchemas);\n\n Object.assign(inputs, securityOptions);\n\n additionalProperties.push(\n ...Object.entries(securityOptions).map(\n ([name, value]) =>\n ({\n name: name,\n required: false,\n schema: {\n type: 'string',\n },\n in: value.in as ParameterLocation,\n }) satisfies ParameterObject,\n ),\n );\n\n const types: Record<string, string> = {};\n const shortContenTypeMap: Record<string, string> = {\n 'application/json': 'json',\n 'application/x-www-form-urlencoded': 'urlencoded',\n 'multipart/form-data': 'formdata',\n 'application/xml': 'xml',\n 'text/plain': 'text',\n };\n let contentType: string | undefined;\n if (operation.requestBody && Object.keys(operation.requestBody).length) {\n const content: ContentObject = isRef(operation.requestBody)\n ? get(followRef(config.spec, operation.requestBody.$ref), ['content'])\n : operation.requestBody.content;\n\n for (const type in content) {\n const ctSchema = isRef(content[type].schema)\n ? followRef(config.spec, content[type].schema.$ref)\n : content[type].schema;\n if (!ctSchema) {\n console.warn(`Schema not found for ${type}`);\n continue;\n }\n const schema = merge({}, ctSchema, {\n required: additionalProperties\n .filter((p) => p.required)\n .map((p) => p.name),\n properties: additionalProperties.reduce<Record<string, unknown>>(\n (acc, p) => ({\n ...acc,\n [p.name]: p.schema,\n }),\n {},\n ),\n });\n for (const [name] of Object.entries(ctSchema.properties ?? {})) {\n inputs[name] = {\n in: 'body',\n schema: '',\n };\n }\n types[shortContenTypeMap[type]] = zodDeserialzer.handle(schema, true);\n }\n\n if (content['application/json']) {\n contentType = 'json';\n } else if (content['application/x-www-form-urlencoded']) {\n contentType = 'urlencoded';\n } else if (content['multipart/form-data']) {\n contentType = 'formdata';\n } else {\n contentType = 'json';\n }\n } else {\n const properties = additionalProperties.reduce<Record<string, any>>(\n (acc, p) => ({\n ...acc,\n [p.name]: p.schema,\n }),\n {},\n );\n types[shortContenTypeMap['application/json']] = zodDeserialzer.handle(\n {\n type: 'object',\n required: additionalProperties\n .filter((p) => p.required)\n .map((p) => p.name),\n properties,\n },\n true,\n );\n }\n\n const errors: string[] = [];\n operation.responses ??= {};\n\n let foundResponse = false;\n const output = [`import z from 'zod';`];\n for (const status in operation.responses) {\n const response = operation.responses[status] as ResponseObject;\n const statusCode = +status;\n if (statusCode >= 400) {\n errors.push(responses[status] ?? 'ProblematicResponse');\n }\n if (statusCode >= 200 && statusCode < 300) {\n foundResponse = true;\n const responseContent = get(response, ['content']);\n const isJson = responseContent && responseContent['application/json'];\n // TODO: how the user is going to handle multiple response types\n const imports: Import[] = [];\n const typeScriptDeserialzer = new TypeScriptDeserialzer(\n config.spec,\n (schemaName, zod) => {\n commonSchemas[schemaName] = zod;\n imports.push({\n defaultImport: undefined,\n isTypeOnly: true,\n moduleSpecifier: `../models/${schemaName}.ts`,\n namedImports: [{ isTypeOnly: true, name: schemaName }],\n namespaceImport: undefined,\n });\n },\n );\n const responseSchema = isJson\n ? typeScriptDeserialzer.handle(\n responseContent['application/json'].schema!,\n true,\n )\n : 'ReadableStream'; // non-json response treated as stream\n output.push(...useImports(responseSchema, imports));\n output.push(\n `export type ${pascalcase(operationName + ' output')} = ${responseSchema}`,\n );\n }\n }\n\n if (!foundResponse) {\n output.push(\n `export type ${pascalcase(operationName + ' output')} = void`,\n );\n }\n outputs[`${spinalcase(operationName)}.ts`] = output.join('\\n');\n groups[groupName].push({\n name: operationName,\n type: 'http',\n inputs,\n errors: errors.length ? errors : ['ServerError'],\n contentType,\n schemas: types,\n formatOutput: () => ({\n import: pascalcase(operationName + ' output'),\n use: pascalcase(operationName + ' output'),\n }),\n trigger: {\n path,\n method,\n },\n });\n }\n }\n\n return { groups, commonSchemas, commonZod, outputs };\n}\n\n// TODO - USE CASES\n// 1. Some parameters conflicts with request body\n// 2. Generate 400 and 500 response variations // done\n// 3. Generate 200 response variations\n// 3. Doc Security\n// 4. Operation Security\n// 5. JsDocs\n// 5. test all different types of parameters\n// 6. cookies\n// 6. x-www-form-urlencoded // done\n// 7. multipart/form-data // done\n// 7. application/octet-stream // done\n// 7. chunked response // done\n// we need to remove the stream fn in the backend\n", "import { get } from 'lodash-es';\nimport type {\n ComponentsObject,\n OpenAPIObject,\n ReferenceObject,\n SchemaObject,\n SecurityRequirementObject,\n} from 'openapi3-ts/oas31';\n\nimport { removeDuplicates } from '@sdk-it/core';\n\nimport { type Options } from './sdk.ts';\n\nexport function isRef(obj: any): obj is ReferenceObject {\n return '$ref' in obj;\n}\n\nexport function cleanRef(ref: string) {\n return ref.replace(/^#\\//, '');\n}\n\nexport function parseRef(ref: string) {\n const parts = ref.split('/');\n const [model] = parts.splice(-1);\n return { model, path: parts.join('/') };\n}\nexport function followRef(spec: OpenAPIObject, ref: string): SchemaObject {\n const pathParts = cleanRef(ref).split('/');\n const entry = get(spec, pathParts) as SchemaObject | ReferenceObject;\n if (entry && '$ref' in entry) {\n return followRef(spec, entry.$ref);\n }\n return entry;\n}\nexport function securityToOptions(\n security: SecurityRequirementObject[],\n securitySchemas: ComponentsObject['securitySchemes'],\n staticIn?: string,\n) {\n securitySchemas ??= {};\n const options: Options = {};\n for (const it of security) {\n const [name] = Object.keys(it);\n const schema = securitySchemas[name];\n if (isRef(schema)) {\n throw new Error(`Ref security schemas are not supported`);\n }\n if (schema.type === 'http') {\n options['authorization'] = {\n in: staticIn ?? 'header',\n schema:\n 'z.string().optional().transform((val) => (val ? `Bearer ${val}` : undefined))',\n optionName: 'token',\n };\n continue;\n }\n if (schema.type === 'apiKey') {\n if (!schema.in) {\n throw new Error(`apiKey security schema must have an \"in\" field`);\n }\n if (!schema.name) {\n throw new Error(`apiKey security schema must have a \"name\" field`);\n }\n options[schema.name] = {\n in: staticIn ?? schema.in,\n schema: 'z.string().optional()',\n };\n continue;\n }\n }\n return options;\n}\n\nexport function mergeImports(imports: Import[]) {\n const merged: Record<string, Import> = {};\n\n for (const i of imports) {\n merged[i.moduleSpecifier] = merged[i.moduleSpecifier] ?? {\n moduleSpecifier: i.moduleSpecifier,\n defaultImport: i.defaultImport,\n namespaceImport: i.namespaceImport,\n namedImports: [],\n };\n if (i.namedImports) {\n merged[i.moduleSpecifier].namedImports.push(...i.namedImports);\n }\n }\n\n return Object.values(merged);\n}\nexport interface Import {\n isTypeOnly: boolean;\n moduleSpecifier: string;\n defaultImport: string | undefined;\n namedImports: NamedImport[];\n namespaceImport: string | undefined;\n}\nexport interface NamedImport {\n name: string;\n alias?: string;\n isTypeOnly: boolean;\n}\n\nexport function importsToString(...imports: Import[]) {\n return imports.map((it) => {\n if (it.defaultImport) {\n return `import ${it.defaultImport} from '${it.moduleSpecifier}'`;\n }\n if (it.namespaceImport) {\n return `import * as ${it.namespaceImport} from '${it.moduleSpecifier}'`;\n }\n if (it.namedImports) {\n return `import {${removeDuplicates(it.namedImports, (it) => it.name)\n .map((n) => `${n.isTypeOnly ? 'type' : ''} ${n.name}`)\n .join(', ')}} from '${it.moduleSpecifier}'`;\n }\n throw new Error(`Invalid import ${JSON.stringify(it)}`);\n });\n}\n\nexport function exclude<T>(list: T[], exclude: T[]): T[] {\n return list.filter((it) => !exclude.includes(it));\n}\n\nexport function useImports(content: string, imports: Import[]) {\n const output: string[] = [];\n for (const it of mergeImports(imports)) {\n const singleImport = it.defaultImport ?? it.namespaceImport;\n if (singleImport && content.includes(singleImport)) {\n output.push(importsToString(it).join('\\n'));\n } else if (it.namedImports.length) {\n for (const namedImport of it.namedImports) {\n if (content.includes(namedImport.name)) {\n output.push(importsToString(it).join('\\n'));\n }\n }\n }\n }\n return output;\n}\n", "import { camelcase, spinalcase } from 'stringcase';\n\nimport { removeDuplicates, toLitObject } from '@sdk-it/core';\n\nimport backend from './client.ts';\nimport { exclude } from './utils.ts';\n\nclass SchemaEndpoint {\n #imports: string[] = [\n `import z from 'zod';`,\n 'import type { Endpoints } from \"./endpoints.ts\";',\n `import { toRequest, json, urlencoded, nobody, formdata, createUrl } from './http/request.ts';`,\n `import type { ParseError } from './http/parser.ts';`,\n ];\n #endpoints: string[] = [];\n addEndpoint(endpoint: string, operation: any) {\n this.#endpoints.push(` \"${endpoint}\": ${operation},`);\n }\n addImport(value: string) {\n this.#imports.push(value);\n }\n complete() {\n return `${this.#imports.join('\\n')}\\nexport default {\\n${this.#endpoints.join('\\n')}\\n}`;\n }\n}\nclass Emitter {\n protected imports: string[] = [\n `import z from 'zod';`,\n `import type { ParseError } from './http/parser.ts';`,\n ];\n protected endpoints: string[] = [];\n addEndpoint(endpoint: string, operation: any) {\n this.endpoints.push(` \"${endpoint}\": ${operation};`);\n }\n addImport(value: string) {\n this.imports.push(value);\n }\n complete() {\n return `${this.imports.join('\\n')}\\nexport interface Endpoints {\\n${this.endpoints.join('\\n')}\\n}`;\n }\n}\nclass StreamEmitter extends Emitter {\n override complete() {\n return `${this.imports.join('\\n')}\\nexport interface StreamEndpoints {\\n${this.endpoints.join('\\n')}\\n}`;\n }\n}\n\nexport interface SdkConfig {\n /**\n * The name of the sdk client\n */\n name: string;\n packageName?: string;\n options?: Record<string, any>;\n emptyBodyAsNull?: boolean;\n stripBodyFromGetAndHead?: boolean;\n output: string;\n}\n\nexport type Options = Record<\n string,\n {\n in: string;\n schema: string;\n optionName?: string;\n }\n>;\nexport interface Spec {\n operations: Record<string, Operation[]>;\n name: string;\n options: Options;\n servers: string[];\n}\n\nexport interface OperationInput {\n in: string;\n schema: string;\n}\nexport interface Operation {\n name: string;\n errors: string[];\n type: string;\n trigger: Record<string, any>;\n contentType?: string;\n schemas: Record<string, string>;\n schema?: string;\n inputs: Record<string, OperationInput>;\n formatOutput: () => { import: string; use: string };\n}\n\nexport function generateInputs(\n operationsSet: Spec['operations'],\n commonZod: Map<string, string>,\n) {\n const commonImports = commonZod.keys().toArray();\n const inputs: Record<string, string> = {};\n for (const [name, operations] of Object.entries(operationsSet)) {\n const output: string[] = [];\n const imports = new Set(['import { z } from \"zod\";']);\n\n for (const operation of operations) {\n const schemaName = camelcase(`${operation.name} schema`);\n\n const schema = `export const ${schemaName} = ${\n Object.keys(operation.schemas).length === 1\n ? Object.values(operation.schemas)[0]\n : toLitObject(operation.schemas)\n };`;\n\n const inputContent = schema;\n\n for (const schema of commonImports) {\n if (inputContent.includes(schema)) {\n imports.add(\n `import { ${schema} } from './schemas/${spinalcase(schema)}.ts';`,\n );\n }\n }\n output.push(inputContent);\n }\n inputs[`inputs/${spinalcase(name)}.ts`] =\n [...imports, ...output].join('\\n') + '\\n';\n }\n\n const schemas = commonZod\n .entries()\n .reduce<string[][]>((acc, [name, schema]) => {\n const output = [`import { z } from 'zod';`];\n const content = `export const ${name} = ${schema};`;\n for (const schema of commonImports) {\n const preciseMatch = new RegExp(`\\\\b${schema}\\\\b`);\n if (preciseMatch.test(content) && schema !== name) {\n output.push(\n `import { ${schema} } from './${spinalcase(schema)}.ts';`,\n );\n }\n }\n\n output.push(content);\n return [\n [`inputs/schemas/${spinalcase(name)}.ts`, output.join('\\n')],\n ...acc,\n ];\n }, []);\n\n return {\n ...Object.fromEntries(schemas),\n ...inputs,\n };\n}\n\nexport function generateSDK(spec: Spec) {\n const emitter = new Emitter();\n const schemaEndpoint = new SchemaEndpoint();\n const errors: string[] = [];\n for (const [name, operations] of Object.entries(spec.operations)) {\n emitter.addImport(\n `import * as ${camelcase(name)} from './inputs/${spinalcase(name)}.ts';`,\n );\n schemaEndpoint.addImport(\n `import * as ${camelcase(name)} from './inputs/${spinalcase(name)}.ts';`,\n );\n for (const operation of operations) {\n const schemaName = camelcase(`${operation.name} schema`);\n const schemaRef = `${camelcase(name)}.${schemaName}`;\n const output = operation.formatOutput();\n const inputHeaders: string[] = [];\n const inputQuery: string[] = [];\n const inputBody: string[] = [];\n const inputParams: string[] = [];\n for (const [name, prop] of Object.entries(operation.inputs)) {\n if (prop.in === 'headers' || prop.in === 'header') {\n inputHeaders.push(`\"${name}\"`);\n } else if (prop.in === 'query') {\n inputQuery.push(`\"${name}\"`);\n } else if (prop.in === 'body') {\n inputBody.push(`\"${name}\"`);\n } else if (prop.in === 'path') {\n inputParams.push(`\"${name}\"`);\n } else if (prop.in === 'internal') {\n // ignore internal sources\n continue;\n } else {\n throw new Error(\n `Unknown source ${prop.in} in ${name} ${JSON.stringify(\n prop,\n )} in ${operation.name}`,\n );\n }\n }\n emitter.addImport(\n `import type {${output.import}} from './outputs/${spinalcase(operation.name)}.ts';`,\n );\n errors.push(...(operation.errors ?? []));\n\n const addTypeParser = Object.keys(operation.schemas).length > 1;\n for (const type in operation.schemas ?? {}) {\n let typePrefix = '';\n if (addTypeParser && type !== 'json') {\n typePrefix = `${type} `;\n }\n const input = `typeof ${schemaRef}${addTypeParser ? `.${type}` : ''}`;\n\n const endpoint = `${typePrefix}${operation.trigger.method.toUpperCase()} ${operation.trigger.path}`;\n emitter.addEndpoint(\n endpoint,\n `{input: z.infer<${input}>; output: ${output.use}; error: ${(operation.errors ?? ['ServerError']).concat(`ParseError<${input}>`).join('|')}}`,\n );\n schemaEndpoint.addEndpoint(\n endpoint,\n `{\n schema: ${schemaRef}${addTypeParser ? `.${type}` : ''},\n toRequest(input: Endpoints['${endpoint}']['input']) {\n const endpoint = '${endpoint}';\n return toRequest(endpoint, ${operation.contentType || 'nobody'}(input, {\n inputHeaders: [${inputHeaders}],\n inputQuery: [${inputQuery}],\n inputBody: [${inputBody}],\n inputParams: [${inputParams}],\n }));\n },\n }`,\n );\n }\n }\n }\n\n emitter.addImport(\n `import type { ${removeDuplicates(errors, (it) => it).join(', ')} } from './http/response.ts';`,\n );\n return {\n 'client.ts': backend(spec),\n 'schemas.ts': schemaEndpoint.complete(),\n 'endpoints.ts': emitter.complete(),\n };\n}\n", "import { toLitObject } from '@sdk-it/core';\n\nimport type { Spec } from './sdk.ts';\n\nexport default (spec: Spec) => {\n const optionsEntries = Object.entries(spec.options).map(\n ([key, value]) => [`'${key}'`, value] as const,\n );\n const defaultHeaders = `{${optionsEntries\n .filter(([, value]) => value.in === 'header')\n .map(\n ([key, value]) =>\n `${key}: this.options[${value.optionName ? `'${value.optionName}'` : key}]`,\n )\n .join(',\\n')}}`;\n const defaultInputs = `{${optionsEntries\n .filter(([, value]) => value.in === 'input')\n .map(\n ([key, value]) =>\n `${key}: this.options[${value.optionName ? `'${value.optionName}'` : key}]`,\n )\n .join(',\\n')}}`;\n const specOptions: Record<string, { schema: string }> = {\n ...Object.fromEntries(\n optionsEntries.map(([key, value]) => [value.optionName ?? key, value]),\n ),\n fetch: {\n schema: 'fetchType',\n },\n baseUrl: {\n schema: spec.servers.length\n ? `z.enum(servers).default(servers[0])`\n : 'z.string()',\n },\n };\n\n return `\nimport { fetchType, sendRequest } from './http/send-request.ts';\nimport z from 'zod';\nimport type { Endpoints } from './endpoints.ts';\nimport schemas from './schemas.ts';\nimport {\n createBaseUrlInterceptor,\n createDefaultHeadersInterceptor,\n} from './http/interceptors.ts';\n\n${spec.servers.length ? `export const servers = ${JSON.stringify(spec.servers, null, 2)} as const` : ''}\nconst optionsSchema = z.object(${toLitObject(specOptions, (x) => x.schema)});\n${spec.servers.length ? `export type Servers = typeof servers[number];` : ''}\n\ntype ${spec.name}Options = z.infer<typeof optionsSchema>;\n\nexport class ${spec.name} {\n public options: ${spec.name}Options\n constructor(options: ${spec.name}Options) {\n this.options = options;\n }\n\n async request<E extends keyof Endpoints>(\n endpoint: E,\n input: Endpoints[E]['input'],\n ): Promise<readonly [Endpoints[E]['output'], Endpoints[E]['error'] | null]> {\n const route = schemas[endpoint];\n return sendRequest(Object.assign(this.#defaultInputs, input), route, {\n fetch: this.options.fetch,\n interceptors: [\n createDefaultHeadersInterceptor(() => this.defaultHeaders),\n createBaseUrlInterceptor(() => this.options.baseUrl),\n ],\n });\n }\n\n get defaultHeaders() {\n return ${defaultHeaders}\n }\n\n get #defaultInputs() {\n return ${defaultInputs}\n }\n\n setOptions(options: Partial<${spec.name}Options>) {\n const validated = optionsSchema.partial().parse(options);\n\n for (const key of Object.keys(validated) as (keyof ${spec.name}Options)[]) {\n if (validated[key] !== undefined) {\n (this.options[key] as typeof validated[typeof key]) = validated[key]!;\n }\n }\n }\n}`;\n};\n", "import type {\n OpenAPIObject,\n ReferenceObject,\n SchemaObject,\n} from 'openapi3-ts/oas31';\n\nimport { cleanRef, followRef, isRef, parseRef } from '../utils.ts';\n\ntype OnRefCallback = (ref: string, interfaceContent: string) => void;\n\n/**\n * Convert an OpenAPI (JSON Schema style) object into TypeScript interfaces,\n * following the same pattern as ZodDeserialzer for easy interchangeability.\n */\nexport class TypeScriptDeserialzer {\n circularRefTracker = new Set<string>();\n #spec: OpenAPIObject;\n #onRef: OnRefCallback;\n\n constructor(spec: OpenAPIObject, onRef: OnRefCallback) {\n this.#spec = spec;\n this.#onRef = onRef;\n }\n #stringifyKey = (key: string): string => {\n // List of JavaScript keywords and special object properties that should be quoted\n const reservedWords = [\n 'constructor',\n 'prototype',\n 'break',\n 'case',\n 'catch',\n 'class',\n 'const',\n 'continue',\n 'debugger',\n 'default',\n 'delete',\n 'do',\n 'else',\n 'export',\n 'extends',\n 'false',\n 'finally',\n 'for',\n 'function',\n 'if',\n 'import',\n 'in',\n 'instanceof',\n 'new',\n 'null',\n 'return',\n 'super',\n 'switch',\n 'this',\n 'throw',\n 'true',\n 'try',\n 'typeof',\n 'var',\n 'void',\n 'while',\n 'with',\n 'yield',\n ];\n\n // Check if key is a reserved word\n if (reservedWords.includes(key)) {\n return `'${key}'`;\n }\n\n // Check if key is empty or only whitespace\n if (key.trim() === '') {\n return `'${key}'`;\n }\n\n // Check if first character is valid for identifiers\n const firstChar = key.charAt(0);\n const validFirstChar =\n (firstChar >= 'a' && firstChar <= 'z') ||\n (firstChar >= 'A' && firstChar <= 'Z') ||\n firstChar === '_' ||\n firstChar === '$';\n\n if (!validFirstChar) {\n return `'${key.replace(/'/g, \"\\\\'\")}'`;\n }\n\n // Check if the rest of the characters are valid for identifiers\n for (let i = 1; i < key.length; i++) {\n const char = key.charAt(i);\n const validChar =\n (char >= 'a' && char <= 'z') ||\n (char >= 'A' && char <= 'Z') ||\n (char >= '0' && char <= '9') ||\n char === '_' ||\n char === '$';\n\n if (!validChar) {\n return `'${key.replace(/'/g, \"\\\\'\")}'`;\n }\n }\n\n return key;\n };\n #stringifyKeyV2 = (value: string): string => {\n return `'${value}'`;\n };\n\n /**\n * Handle objects (properties)\n */\n object(schema: SchemaObject, required = false): string {\n const properties = schema.properties || {};\n\n // Convert each property\n const propEntries = Object.entries(properties).map(([key, propSchema]) => {\n const isRequired = (schema.required ?? []).includes(key);\n const tsType = this.handle(propSchema, isRequired);\n // Add question mark for optional properties\n return `${this.#stringifyKeyV2(key)}: ${tsType}`;\n });\n\n // Handle additionalProperties\n if (schema.additionalProperties) {\n if (typeof schema.additionalProperties === 'object') {\n const indexType = this.handle(schema.additionalProperties, true);\n propEntries.push(`[key: string]: ${indexType}`);\n } else if (schema.additionalProperties === true) {\n propEntries.push('[key: string]: any');\n }\n }\n\n return `{ ${propEntries.join('; ')} }`;\n }\n\n /**\n * Handle arrays (items could be a single schema or a tuple)\n */\n array(schema: SchemaObject, required = false): string {\n const { items } = schema;\n if (!items) {\n // No items => any[]\n return 'any[]';\n }\n\n // If items is an array => tuple\n if (Array.isArray(items)) {\n const tupleItems = items.map((sub) => this.handle(sub, true));\n return `[${tupleItems.join(', ')}]`;\n }\n\n // If items is a single schema => standard array\n const itemsType = this.handle(items, true);\n return `${itemsType}[]`;\n }\n\n /**\n * Convert a basic type (string | number | boolean | object | array, etc.) to TypeScript\n */\n normal(type: string, schema: SchemaObject, required = false): string {\n switch (type) {\n case 'string':\n return this.string(schema, required);\n case 'number':\n case 'integer':\n return this.number(schema, required);\n case 'boolean':\n return appendOptional('boolean', required);\n case 'object':\n return this.object(schema, required);\n case 'array':\n return this.array(schema, required);\n case 'null':\n return 'null';\n default:\n // Unknown type -> fallback\n return appendOptional('any', required);\n }\n }\n\n ref($ref: string, required: boolean): string {\n const schemaName = cleanRef($ref).split('/').pop()!;\n\n if (this.circularRefTracker.has(schemaName)) {\n return schemaName;\n }\n\n this.circularRefTracker.add(schemaName);\n this.#onRef(schemaName, this.handle(followRef(this.#spec, $ref), true));\n this.circularRefTracker.delete(schemaName);\n\n return appendOptional(schemaName, required);\n }\n\n allOf(schemas: (SchemaObject | ReferenceObject)[]): string {\n // For TypeScript we use intersection types for allOf\n const allOfTypes = schemas.map((sub) => this.handle(sub, true));\n return allOfTypes.length > 1 ? `${allOfTypes.join(' & ')}` : allOfTypes[0];\n }\n\n anyOf(\n schemas: (SchemaObject | ReferenceObject)[],\n required: boolean,\n ): string {\n // For TypeScript we use union types for anyOf/oneOf\n const anyOfTypes = schemas.map((sub) => this.handle(sub, true));\n return appendOptional(\n anyOfTypes.length > 1 ? `${anyOfTypes.join(' | ')}` : anyOfTypes[0],\n required,\n );\n }\n\n oneOf(\n schemas: (SchemaObject | ReferenceObject)[],\n required: boolean,\n ): string {\n const oneOfTypes = schemas.map((sub) => {\n if (isRef(sub)) {\n const { model } = parseRef(sub.$ref);\n if (this.circularRefTracker.has(model)) {\n return model;\n }\n }\n return this.handle(sub, false);\n });\n return appendOptional(\n oneOfTypes.length > 1 ? `${oneOfTypes.join(' | ')}` : oneOfTypes[0],\n required,\n );\n }\n\n enum(values: any[], required: boolean): string {\n // For TypeScript enums as union of literals\n const enumValues = values\n .map((val) => (typeof val === 'string' ? `'${val}'` : `${val}`))\n .join(' | ');\n return appendOptional(enumValues, required);\n }\n\n /**\n * Handle string type with formats\n */\n string(schema: SchemaObject, required?: boolean): string {\n let type: string;\n\n switch (schema.format) {\n case 'date-time':\n case 'datetime':\n case 'date':\n type = 'Date';\n break;\n case 'binary':\n case 'byte':\n type = 'Blob';\n break;\n case 'int64':\n type = 'bigint';\n break;\n default:\n type = 'string';\n }\n\n return appendOptional(type, required);\n }\n\n /**\n * Handle number/integer types with formats\n */\n number(schema: SchemaObject, required?: boolean): string {\n const type = schema.format === 'int64' ? 'bigint' : 'number';\n return appendOptional(type, required);\n }\n\n handle(schema: SchemaObject | ReferenceObject, required: boolean): string {\n if (isRef(schema)) {\n return this.ref(schema.$ref, required);\n }\n\n // Handle allOf (intersection in TypeScript)\n if (schema.allOf && Array.isArray(schema.allOf)) {\n return this.allOf(schema.allOf);\n }\n\n // anyOf (union in TypeScript)\n if (schema.anyOf && Array.isArray(schema.anyOf)) {\n return this.anyOf(schema.anyOf, required);\n }\n\n // oneOf (union in TypeScript)\n if (schema.oneOf && Array.isArray(schema.oneOf)) {\n return this.oneOf(schema.oneOf, required);\n }\n\n // enum\n if (schema.enum && Array.isArray(schema.enum)) {\n return this.enum(schema.enum, required);\n }\n\n // Handle types, in TypeScript we can have union types directly\n const types = Array.isArray(schema.type)\n ? schema.type\n : schema.type\n ? [schema.type]\n : [];\n\n // If no explicit \"type\", fallback to any\n if (!types.length) {\n return appendOptional('any', required);\n }\n\n // Handle union types (multiple types)\n if (types.length > 1) {\n const realTypes = types.filter((t) => t !== 'null');\n if (realTypes.length === 1 && types.includes('null')) {\n // Single real type + \"null\"\n const tsType = this.normal(realTypes[0], schema, false);\n return appendOptional(`${tsType} | null`, required);\n }\n\n // Multiple different types\n const typeResults = types.map((t) => this.normal(t, schema, false));\n return appendOptional(typeResults.join(' | '), required);\n }\n\n // Single type\n return this.normal(types[0], schema, required);\n }\n\n /**\n * Generate an interface declaration\n */\n generateInterface(\n name: string,\n schema: SchemaObject | ReferenceObject,\n ): string {\n const content = this.handle(schema, true);\n return `interface ${name} ${content}`;\n }\n}\n\n/**\n * Append \"| undefined\" if not required\n */\nfunction appendOptional(type: string, isRequired?: boolean): string {\n return isRequired ? type : `${type} | undefined`;\n}\n", "import type {\n OpenAPIObject,\n ReferenceObject,\n SchemaObject,\n} from 'openapi3-ts/oas31';\n\nimport { cleanRef, followRef, isRef, parseRef } from '../utils.ts';\n\ntype OnRefCallback = (ref: string, zod: string) => void;\n\n/**\n * Convert an OpenAPI (JSON Schema style) object into a Zod schema string,\n * adapted for OpenAPI 3.1 (fully aligned with JSON Schema 2020-12).\n */\nexport class ZodDeserialzer {\n circularRefTracker = new Set<string>();\n #spec: OpenAPIObject;\n #onRef?: OnRefCallback;\n\n constructor(spec: OpenAPIObject, onRef?: OnRefCallback) {\n this.#spec = spec;\n this.#onRef = onRef;\n }\n /**\n * Handle objects (properties, additionalProperties).\n */\n object(schema: SchemaObject, required = false): string {\n const properties = schema.properties || {};\n\n // Convert each property\n const propEntries = Object.entries(properties).map(([key, propSchema]) => {\n const isRequired = (schema.required ?? []).includes(key);\n const zodPart = this.handle(propSchema, isRequired);\n return `'${key}': ${zodPart}`;\n });\n\n // additionalProperties\n let additionalProps = '';\n if (schema.additionalProperties) {\n if (typeof schema.additionalProperties === 'object') {\n // e.g. z.record() if it\u2019s an object schema\n const addPropZod = this.handle(schema.additionalProperties, true);\n additionalProps = `.catchall(${addPropZod})`;\n } else if (schema.additionalProperties === true) {\n // free-form additional props\n additionalProps = `.catchall(z.unknown())`;\n }\n }\n\n const objectSchema = `z.object({${propEntries.join(', ')}})${additionalProps}`;\n return `${objectSchema}${appendOptional(required)}`;\n }\n\n /**\n * Handle arrays (items could be a single schema or a tuple (array of schemas)).\n * In JSON Schema 2020-12, `items` can be an array \u2192 tuple style.\n */\n array(schema: SchemaObject, required = false): string {\n const { items } = schema;\n if (!items) {\n // No items => z.array(z.unknown())\n return `z.array(z.unknown())${appendOptional(required)}`;\n }\n\n // If items is an array => tuple\n if (Array.isArray(items)) {\n // Build a Zod tuple\n const tupleItems = items.map((sub) => this.handle(sub, true));\n const base = `z.tuple([${tupleItems.join(', ')}])`;\n // // If we have additionalItems: false => that\u2019s a fixed length\n // // If additionalItems is a schema => rest(...)\n // if (schema.additionalItems) {\n // if (typeof schema.additionalItems === 'object') {\n // const restSchema = jsonSchemaToZod(spec, schema.additionalItems, true);\n // base += `.rest(${restSchema})`;\n // }\n // // If `additionalItems: false`, no rest is allowed => do nothing\n // }\n return `${base}${appendOptional(required)}`;\n }\n\n // If items is a single schema => standard z.array(...)\n const itemsSchema = this.handle(items, true);\n return `z.array(${itemsSchema})${appendOptional(required)}`;\n }\n // oneOf() {}\n // enum() {}\n\n /**\n * Convert a basic type (string | number | boolean | object | array, etc.) to Zod.\n * We'll also handle .optional() if needed.\n */\n normal(type: string, schema: SchemaObject, required = false) {\n switch (type) {\n case 'string':\n return this.string(schema, required);\n case 'number':\n case 'integer':\n return this.number(schema, required);\n case 'boolean':\n return `z.boolean()${appendDefault(schema.default)}${appendOptional(required)}`;\n case 'object':\n return this.object(schema, required);\n case 'array':\n return this.array(schema, required);\n case 'null':\n // If \"type\": \"null\" alone, this is basically z.null()\n return `z.null()${appendOptional(required)}`;\n default:\n // Unknown type -> fallback\n return `z.unknown()${appendOptional(required)}`;\n }\n }\n\n ref($ref: string, required: boolean) {\n const schemaName = cleanRef($ref).split('/').pop()!;\n\n if (this.circularRefTracker.has(schemaName)) {\n return schemaName;\n }\n\n this.circularRefTracker.add(schemaName);\n this.#onRef?.(\n schemaName,\n this.handle(followRef(this.#spec, $ref), required),\n );\n this.circularRefTracker.delete(schemaName);\n\n return schemaName;\n }\n allOf(schemas: (SchemaObject | ReferenceObject)[]) {\n const allOfSchemas = schemas.map((sub) => this.handle(sub, true));\n if (allOfSchemas.length === 1) {\n return allOfSchemas[0];\n }\n return allOfSchemas.length\n ? `z.intersection(${allOfSchemas.join(', ')})`\n : allOfSchemas[0];\n }\n\n anyOf(schemas: (SchemaObject | ReferenceObject)[], required: boolean) {\n const anyOfSchemas = schemas.map((sub) => this.handle(sub, false));\n if (anyOfSchemas.length === 1) {\n return anyOfSchemas[0];\n }\n return anyOfSchemas.length > 1\n ? `z.union([${anyOfSchemas.join(', ')}])${appendOptional(required)}`\n : // Handle an invalid anyOf with one schema\n anyOfSchemas[0];\n }\n\n oneOf(schemas: (SchemaObject | ReferenceObject)[], required: boolean) {\n const oneOfSchemas = schemas.map((sub) => {\n if ('$ref' in sub) {\n const { model } = parseRef(sub.$ref);\n if (this.circularRefTracker.has(model)) {\n return model;\n }\n }\n return this.handle(sub, false);\n });\n if (oneOfSchemas.length === 1) {\n return oneOfSchemas[0];\n }\n return oneOfSchemas.length > 1\n ? `z.union([${oneOfSchemas.join(', ')}])${appendOptional(required)}`\n : // Handle an invalid oneOf with one schema\n oneOfSchemas[0];\n }\n\n enum(values: any[], required: boolean) {\n const enumVals = values.map((val) => JSON.stringify(val)).join(', ');\n return `z.enum([${enumVals}])${appendOptional(required)}`;\n }\n\n /**\n * Handle a `string` schema with possible format keywords (JSON Schema).\n */\n string(schema: SchemaObject, required?: boolean): string {\n let base = 'z.string()';\n\n // 3.1 replaces `example` in the schema with `examples` (array).\n // We do not strictly need them for the Zod type, so they\u2019re optional\n // for validation. However, we could keep them as metadata if you want.\n\n switch (schema.format) {\n case 'date-time':\n case 'datetime':\n // parse to JS Date\n base = 'z.coerce.date()';\n break;\n case 'date':\n base =\n 'z.coerce.date() /* or z.string() if you want raw date strings */';\n break;\n case 'time':\n base =\n 'z.string() /* optionally add .regex(...) for HH:MM:SS format */';\n break;\n case 'email':\n base = 'z.string().email()';\n break;\n case 'uuid':\n base = 'z.string().uuid()';\n break;\n case 'url':\n case 'uri':\n base = 'z.string().url()';\n break;\n case 'ipv4':\n base = 'z.string().ip({version: \"v4\"})';\n break;\n case 'ipv6':\n base = 'z.string().ip({version: \"v6\"})';\n break;\n case 'phone':\n base = 'z.string() /* or add .regex(...) for phone formats */';\n break;\n case 'byte':\n case 'binary':\n base = 'z.instanceof(Blob) /* consider base64 check if needed */';\n break;\n case 'int64':\n // JS numbers can't reliably store int64, consider z.bigint() or keep as string\n base = 'z.string() /* or z.bigint() if your app can handle it */';\n break;\n default:\n // No special format\n break;\n }\n\n return `${base}${appendDefault(schema.default)}${appendOptional(required)}`;\n }\n\n /**\n * Handle number/integer constraints from OpenAPI/JSON Schema.\n * In 3.1, exclusiveMinimum/Maximum hold the actual numeric threshold,\n * rather than a boolean toggling `minimum`/`maximum`.\n */\n number(schema: SchemaObject, required?: boolean): string {\n let defaultValue =\n schema.default !== undefined ? `.default(${schema.default})` : ``;\n let base = 'z.number()';\n if (schema.format === 'int64') {\n base = 'z.bigint()';\n if (schema.default !== undefined) {\n defaultValue = `.default(BigInt(${schema.default}))`;\n }\n }\n\n if (schema.format === 'int32') {\n // 32-bit integer\n base += '.int()';\n }\n\n // If we see exclusiveMinimum as a number in 3.1:\n if (typeof schema.exclusiveMinimum === 'number') {\n // Zod doesn\u2019t have a direct \"exclusiveMinimum\" method, so we can do .gt()\n // If exclusiveMinimum=7 => .gt(7)\n base += `.gt(${schema.exclusiveMinimum})`;\n }\n // Similarly for exclusiveMaximum\n if (typeof schema.exclusiveMaximum === 'number') {\n // If exclusiveMaximum=10 => .lt(10)\n base += `.lt(${schema.exclusiveMaximum})`;\n }\n\n // If standard minimum/maximum\n if (typeof schema.minimum === 'number') {\n base +=\n schema.format === 'int64'\n ? `.min(BigInt(${schema.minimum}))`\n : `.min(${schema.minimum})`;\n }\n if (typeof schema.maximum === 'number') {\n base +=\n schema.format === 'int64'\n ? `.max(BigInt(${schema.maximum}))`\n : `.max(${schema.maximum})`;\n }\n\n // multipleOf\n if (typeof schema.multipleOf === 'number') {\n // There's no direct multipleOf in Zod. Some folks do a custom refine.\n // For example:\n base += `.refine((val) => Number.isInteger(val / ${schema.multipleOf}), \"Must be a multiple of ${schema.multipleOf}\")`;\n }\n\n return `${base}${defaultValue}${appendOptional(required)}`;\n }\n\n handle(schema: SchemaObject | ReferenceObject, required: boolean): string {\n if (isRef(schema)) {\n return this.ref(schema.$ref, required);\n }\n\n // Handle allOf \u2192 intersection\n if (schema.allOf && Array.isArray(schema.allOf)) {\n return this.allOf(schema.allOf ?? []);\n }\n\n // anyOf \u2192 union\n if (schema.anyOf && Array.isArray(schema.anyOf)) {\n return this.anyOf(schema.anyOf ?? [], required);\n }\n\n // oneOf \u2192 union\n if (schema.oneOf && Array.isArray(schema.oneOf)) {\n return this.oneOf(schema.oneOf ?? [], required);\n }\n\n // enum\n if (schema.enum && Array.isArray(schema.enum)) {\n return this.enum(schema.enum, required);\n }\n\n // 3.1 can have type: string or type: string[] (e.g. [\"string\",\"null\"])\n // Let's parse that carefully.\n const types = Array.isArray(schema.type)\n ? schema.type\n : schema.type\n ? [schema.type]\n : [];\n\n // If no explicit \"type\", fallback to unknown\n if (!types.length) {\n return `z.unknown()${appendOptional(required)}`;\n }\n\n // If it's a union type (like [\"string\", \"null\"]), we'll build a Zod union\n // or apply .nullable() if it's just \"type + null\".\n if (types.length > 1) {\n // If it\u2019s exactly one real type plus \"null\", we can do e.g. `z.string().nullable()`\n const realTypes = types.filter((t) => t !== 'null');\n if (realTypes.length === 1 && types.includes('null')) {\n // Single real type + \"null\"\n const typeZod = this.normal(realTypes[0], schema, false);\n return `${typeZod}.nullable()${appendOptional(required)}`;\n }\n // If multiple different types, build a union\n const subSchemas = types.map((t) => this.normal(t, schema, false));\n return `z.union([${subSchemas.join(', ')}])${appendOptional(required)}`;\n }\n return this.normal(types[0], schema, required);\n }\n}\n\n/**\n * Append .optional() if not required\n */\nfunction appendOptional(isRequired?: boolean) {\n return isRequired ? '' : '.optional()';\n}\nfunction appendDefault(defaultValue?: any) {\n return defaultValue !== undefined\n ? `.default(${JSON.stringify(defaultValue)})`\n : '';\n}\n\n// Todo: convert openapi 3.0 to 3.1 before proccesing\n", "export interface Interceptor {\n before?: (request: Request) => Promise<Request> | Request;\n after?: (response: Response) => Promise<Response> | Response;\n}\n\nexport const createDefaultHeadersInterceptor = (\n getHeaders: () => Record<string, string | undefined>,\n) => {\n return {\n before(request: Request) {\n const headers = getHeaders();\n\n for (const [key, value] of Object.entries(headers)) {\n // Only set the header if it doesn't already exist and has a value\n if (value !== undefined && !request.headers.has(key)) {\n request.headers.set(key, value);\n }\n }\n\n return request;\n },\n };\n};\n\nexport const createBaseUrlInterceptor = (getBaseUrl: () => string) => {\n return {\n before(request: Request) {\n const baseUrl = getBaseUrl();\n if (request.url.startsWith('local://')) {\n return new Request(request.url.replace('local://', baseUrl), request);\n }\n return request;\n },\n };\n};\n\nexport const logInterceptor = {\n before(request: Request) {\n console.log('Request', request);\n return request;\n },\n after(response: Response) {\n console.log('Response', response);\n return response;\n },\n};\n", "import { parse } from 'fast-content-type-parse';\n\nexport async function handleError(response: Response) {\n try {\n if (response.status >= 400 && response.status < 500) {\n const body = (await response.json()) as Record<string, any>;\n return {\n status: response.status,\n body: body,\n };\n }\n return new Error(\n `An error occurred while fetching the data. Status: ${response.status}`,\n );\n } catch (error) {\n return error as any;\n }\n}\n\nasync function handleChunkedResponse(response: Response, contentType: string) {\n const { type } = parse(contentType);\n\n switch (type) {\n case 'application/json': {\n let buffer = '';\n const reader = response.body!.getReader();\n const decoder = new TextDecoder();\n while (true) {\n const { value, done } = await reader.read();\n if (done) break;\n buffer += decoder.decode(value);\n }\n return JSON.parse(buffer);\n }\n case 'text/html':\n case 'text/plain': {\n let buffer = '';\n const reader = response.body!.getReader();\n const decoder = new TextDecoder();\n while (true) {\n const { value, done } = await reader.read();\n if (done) break;\n buffer += decoder.decode(value);\n }\n return buffer;\n }\n default:\n return response.body;\n }\n}\n\nexport async function parseResponse(response: Response) {\n const contentType = response.headers.get('Content-Type');\n if (!contentType) {\n throw new Error('Content-Type header is missing');\n }\n\n if (response.status === 204) {\n return null;\n }\n const isChunked = response.headers.get('Transfer-Encoding') === 'chunked';\n if (isChunked) {\n return response.body!;\n // return handleChunkedResponse(response, contentType);\n }\n\n const { type } = parse(contentType);\n switch (type) {\n case 'application/json':\n return response.json();\n case 'text/plain':\n return response.text();\n case 'text/html':\n return response.text();\n case 'text/xml':\n case 'application/xml':\n return response.text();\n case 'application/x-www-form-urlencoded': {\n const text = await response.text();\n return Object.fromEntries(new URLSearchParams(text));\n }\n case 'multipart/form-data':\n return response.formData();\n default:\n throw new Error(`Unsupported content type: ${contentType}`);\n }\n}\n", "import { z } from 'zod';\n\nexport type ParseError<T extends z.ZodType<any, any, any>> = {\n kind: 'parse';\n} & z.inferFlattenedErrors<T>;\n\nexport function parse<T extends z.ZodType>(\n schema: T,\n input: unknown,\n) {\n const result = schema.safeParse(input);\n if (!result.success) {\n const errors = result.error.flatten((issue) => issue);\n return [null, errors];\n }\n return [result.data as z.infer<T>, null];\n}\n", "export type Method = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';\nexport type ContentType = 'xml' | 'json' | 'urlencoded' | 'multipart';\nexport type Endpoint =\n | `${ContentType} ${Method} ${string}`\n | `${Method} ${string}`;\n\nexport type BodyInit =\n | ArrayBuffer\n | Blob\n | FormData\n | URLSearchParams\n | null\n | string;\n\nexport function createUrl(path: string, query: URLSearchParams) {\n const url = new URL(path, `local://`);\n url.search = query.toString();\n return url;\n}\n\nfunction template(\n templateString: string,\n templateVariables: Record<string, any>,\n): string {\n const nargs = /{([0-9a-zA-Z_]+)}/g;\n return templateString.replace(nargs, (match, key: string, index: number) => {\n // Handle escaped double braces\n if (\n templateString[index - 1] === '{' &&\n templateString[index + match.length] === '}'\n ) {\n return key;\n }\n\n const result = key in templateVariables ? templateVariables[key] : null;\n return result === null || result === undefined ? '' : String(result);\n });\n}\n\ntype Input = Record<string, any>;\ntype Props = {\n inputHeaders: string[];\n inputQuery: string[];\n inputBody: string[];\n inputParams: string[];\n};\n\nabstract class Serializer {\n protected input: Input;\n protected props: Props;\n\n constructor(\n input: Input,\n props: Props,\n ) {\n this.input = input;\n this.props = props;\n }\n\n abstract getBody(): BodyInit | null;\n abstract getHeaders(): Record<string, string>;\n serialize(): Serialized {\n const headers = new Headers({});\n for (const header of this.props.inputHeaders) {\n headers.set(header, this.input[header]);\n }\n\n const query = new URLSearchParams();\n for (const key of this.props.inputQuery) {\n const value = this.input[key];\n if (value !== undefined) {\n query.set(key, String(value));\n }\n }\n\n const params = this.props.inputParams.reduce<Record<string, any>>(\n (acc, key) => {\n acc[key] = this.input[key];\n return acc;\n },\n {},\n );\n\n return {\n body: this.getBody(),\n query,\n params,\n headers: this.getHeaders(),\n };\n }\n}\n\ninterface Serialized {\n body: BodyInit | null;\n query: URLSearchParams;\n params: Record<string, any>;\n headers: Record<string, string>;\n}\n\nclass JsonSerializer extends Serializer {\n getBody(): BodyInit | null {\n const body: Record<string, any> = {};\n for (const prop of this.props.inputBody) {\n body[prop] = this.input[prop];\n }\n return JSON.stringify(body);\n }\n getHeaders(): Record<string, string> {\n return {\n 'Content-Type': 'application/json',\n Accept: 'application/json',\n };\n }\n}\n\nclass UrlencodedSerializer extends Serializer {\n getBody(): BodyInit | null {\n const body = new URLSearchParams();\n for (const prop of this.props.inputBody) {\n body.set(prop, this.input[prop]);\n }\n return body;\n }\n getHeaders(): Record<string, string> {\n return {};\n }\n}\n\nclass NoBodySerializer extends Serializer {\n getBody(): BodyInit | null {\n return null;\n }\n getHeaders(): Record<string, string> {\n return {};\n }\n}\n\nclass FormDataSerializer extends Serializer {\n getBody(): BodyInit | null {\n const body = new FormData();\n for (const prop of this.props.inputBody) {\n body.append(prop, this.input[prop]);\n }\n return body;\n }\n getHeaders(): Record<string, string> {\n return {};\n }\n}\n\nexport function json(input: Input, props: Props) {\n return new JsonSerializer(input, props).serialize();\n}\nexport function urlencoded(input: Input, props: Props) {\n return new UrlencodedSerializer(input, props).serialize();\n}\nexport function nobody(input: Input, props: Props) {\n return new NoBodySerializer(input, props).serialize();\n}\nexport function formdata(input: Input, props: Props) {\n return new FormDataSerializer(input, props).serialize();\n}\n\nexport function toRequest<T extends Endpoint>(\n endpoint: T,\n input: Serialized,\n): Request {\n const [method, path] = endpoint.split(' ');\n const pathVariable = template(path, input.params);\n\n const url = createUrl(pathVariable, input.query);\n return new Request(url, {\n method: method,\n headers: input.headers,\n body: method === 'GET' ? undefined : input.body,\n });\n}\n", "export interface ApiResponse<Status extends number, Body extends unknown> {\n kind: 'response';\n status: Status;\n body: Body;\n}\n\n// 4xx Client Errors\nexport type BadRequest = ApiResponse<400, { message: string }>;\nexport type Unauthorized = ApiResponse<401, { message: string }>;\nexport type PaymentRequired = ApiResponse<402, { message: string }>;\nexport type Forbidden = ApiResponse<403, { message: string }>;\nexport type NotFound = ApiResponse<404, { message: string }>;\nexport type MethodNotAllowed = ApiResponse<405, { message: string }>;\nexport type NotAcceptable = ApiResponse<406, { message: string }>;\nexport type Conflict = ApiResponse<409, { message: string }>;\nexport type Gone = ApiResponse<410, { message: string }>;\nexport type UnprocessableEntity = ApiResponse<422, { message: string; errors?: Record<string, string[]> }>;\nexport type TooManyRequests = ApiResponse<429, { message: string; retryAfter?: string }>;\nexport type PayloadTooLarge = ApiResponse<413, { message: string; }>;\nexport type UnsupportedMediaType = ApiResponse<415, { message: string; }>;\n\n// 5xx Server Errors\nexport type InternalServerError = ApiResponse<500, { message: string }>;\nexport type NotImplemented = ApiResponse<501, { message: string }>;\nexport type BadGateway = ApiResponse<502, { message: string }>;\nexport type ServiceUnavailable = ApiResponse<503, { message: string; retryAfter?: string }>;\nexport type GatewayTimeout = ApiResponse<504, { message: string }>;\n\nexport type ClientError =\n | BadRequest\n | Unauthorized\n | PaymentRequired\n | Forbidden\n | NotFound\n | MethodNotAllowed\n | NotAcceptable\n | Conflict\n | Gone\n | UnprocessableEntity\n | TooManyRequests;\n\nexport type ServerError =\n | InternalServerError\n | NotImplemented\n | BadGateway\n | ServiceUnavailable\n | GatewayTimeout;\n\nexport type ProblematicResponse = ClientError | ServerError;\n", "import z from 'zod';\n\nimport type { Interceptor } from './interceptors.ts';\nimport { handleError, parseResponse } from './parse-response.ts';\nimport { parse } from './parser.ts';\n\nexport interface RequestSchema {\n schema: z.ZodType;\n toRequest: (input: any) => Request;\n}\n\nexport const fetchType = z\n .function()\n .args(z.instanceof(Request))\n .returns(z.promise(z.instanceof(Response)))\n .optional();\n\nexport async function sendRequest(\n input: any,\n route: RequestSchema,\n options: {\n fetch?: z.infer<typeof fetchType>;\n interceptors?: Interceptor[];\n },\n) {\n const { interceptors = [] } = options;\n const [parsedInput, parseError] = parse(route.schema, input);\n if (parseError) {\n return [null as never, { ...parseError, kind: 'parse' } as never] as const;\n }\n\n let request = route.toRequest(parsedInput as never);\n for (const interceptor of interceptors) {\n if (interceptor.before) {\n request = await interceptor.before(request);\n }\n }\n\n let response = await (options.fetch ?? fetch)(request);\n\n for (let i = interceptors.length - 1; i >= 0; i--) {\n const interceptor = interceptors[i];\n if (interceptor.after) {\n response = await interceptor.after(response.clone());\n }\n }\n\n if (response.ok) {\n const data = await parseResponse(response);\n return [data as never, null] as const;\n }\n const error = await handleError(response);\n return [null as never, { ...error, kind: 'response' }] as const;\n}\n", "import { watch as nodeWatch } from 'node:fs/promises';\nimport { debounceTime, from } from 'rxjs';\n\nexport function watch(path: string) {\n return from(\n nodeWatch(path, {\n persistent: true,\n recursive: true,\n }),\n ).pipe(debounceTime(400));\n}\n"],
5
+ "mappings": ";AACA,SAAS,WAAAA,UAAS,eAAe;;;ACDjC,SAAS,SAAS,cAAc;AAChC,SAAS,gBAAgB;AACzB,SAAS,YAAAC,iBAAgB;AACzB,SAAS,eAAe;AACxB,SAAS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A,EAC5D;AACF;AAEA,SAAS,SAAS,UAAkB;AAClC,QAAM,CAAC,QAAQ,IAAI,SAAS,MAAM,GAAG;AACrC,MAAI,aAAa,UAAU,aAAa,SAAS;AAC/C,WAAO,WAAW,QAAQ;AAAA,EAC5B;AACA,SAAO,UAAU,QAAQ;AAC3B;AAEA,IAAO,mBAAQ,IAAI,QAAQ,UAAU,EAClC,YAAY,0CAA0C,EACtD,UAAU,WAAW,oBAAoB,IAAI,CAAC,EAC9C,UAAU,aAAa,oBAAoB,IAAI,CAAC,EAChD,OAAO,6BAA6B,kCAAkC,EACtE;AAAA,EACC;AAAA,EACA;AACF,EACC,OAAO,qBAAqB,gCAAgC,QAAQ,EACpE,OAAO,2BAA2B,yCAAyC,EAC3E,OAAO,OAAO,YAAqB;AAClC,QAAM,OAAO,MAAM,SAAS,QAAQ,IAAI;AACxC,QAAM,SAAS,MAAM;AAAA,IACnB,QAAQ,QAAQ;AAAA,IAChB,MAAM,QAAQ,QAAQ;AAAA,IACtB,MAAM,QAAQ;AAAA,IACd,YAAY,CAAC,EAAE,KAAK,OAAO,MAAM;AAC/B,UAAI,QAAQ,WAAW;AACrB,cAAM,CAAC,SAAS,GAAG,IAAI,IAAI,QAAQ,UAAU,MAAM,GAAG;AACtD,iBAAS,SAAS,MAAM,EAAE,KAAK,EAAE,GAAG,KAAK,eAAe,OAAO,EAAE,CAAC;AAAA,MACpE;AAAA,IACF;AAAA,EACF,CAAC;AACH,CAAC;;;AD1FH,IAAM,MAAM,QACT,YAAY,mCAAmC,EAC/C,WAAW,kBAAU,EAAE,WAAW,KAAK,CAAC,EACxC;AAAA,EACC,IAAIC,SAAQ,WAAW,EAAE,OAAO,MAAM;AAAA,EAEtC,CAAC;AAAA,EACD,EAAE,QAAQ,KAAK;AACjB,EACC,MAAM,QAAQ,IAAI;",
6
+ "names": ["Command", "readFile", "join", "ts", "get", "camelcase", "spinalcase", "schema", "name", "security", "it", "exclude", "appendOptional", "spinalcase", "camelcase", "methods", "get", "join", "readFile", "Command"]
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sdk-it/cli",
3
- "version": "0.12.6",
3
+ "version": "0.12.7",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.js",
@@ -22,7 +22,7 @@
22
22
  ],
23
23
  "dependencies": {
24
24
  "commander": "^13.1.0",
25
- "@sdk-it/typescript": "0.12.6",
25
+ "@sdk-it/typescript": "0.12.7",
26
26
  "yaml": "^2.7.0"
27
27
  },
28
28
  "publishConfig": {