Skip to content

Commit 30768d6

Browse files
committed
chore: run fmt
1 parent 734c5d0 commit 30768d6

File tree

5 files changed

+124
-115
lines changed

5 files changed

+124
-115
lines changed

packages/typed-openapi/src/cli.ts

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -15,11 +15,7 @@ cli
1515
`Runtime to use for validation; defaults to \`none\`; available: ${allowedRuntimes.toString()}`,
1616
{ default: "none" },
1717
)
18-
.option(
19-
"--schemas-only",
20-
"Only generate schemas, skipping client generation (defaults to false)",
21-
{ default: false },
22-
)
18+
.option("--schemas-only", "Only generate schemas, skipping client generation (defaults to false)", { default: false })
2319
.option(
2420
"--tanstack [name]",
2521
"Generate tanstack client, defaults to false, can optionally specify a name for the generated file",

packages/typed-openapi/src/generate-client-files.ts

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -32,11 +32,13 @@ export async function generateClientFiles(input: string, options: typeof options
3232
const ctx = mapOpenApiEndpoints(openApiDoc);
3333
console.log(`Found ${ctx.endpointList.length} endpoints`);
3434

35-
const content = await prettify(generateFile({
36-
...ctx,
37-
runtime: options.runtime,
38-
schemasOnly: options.schemasOnly,
39-
}));
35+
const content = await prettify(
36+
generateFile({
37+
...ctx,
38+
runtime: options.runtime,
39+
schemasOnly: options.schemasOnly,
40+
}),
41+
);
4042
const outputPath = join(
4143
cwd,
4244
options.output ?? input + `.${options.runtime === "none" ? "client" : options.runtime}.ts`,
@@ -49,9 +51,12 @@ export async function generateClientFiles(input: string, options: typeof options
4951
if (options.tanstack) {
5052
const tanstackContent = await generateTanstackQueryFile({
5153
...ctx,
52-
relativeApiClientPath: './' + basename(outputPath),
54+
relativeApiClientPath: "./" + basename(outputPath),
5355
});
54-
const tanstackOutputPath = join(dirname(outputPath), typeof options.tanstack === "string" ? options.tanstack : `tanstack.client.ts`);
56+
const tanstackOutputPath = join(
57+
dirname(outputPath),
58+
typeof options.tanstack === "string" ? options.tanstack : `tanstack.client.ts`,
59+
);
5560
console.log("Generating tanstack client...", tanstackOutputPath);
5661
await ensureDir(dirname(tanstackOutputPath));
5762
await writeFile(tanstackOutputPath, tanstackContent);

packages/typed-openapi/src/generator.ts

Lines changed: 86 additions & 83 deletions
Original file line numberDiff line numberDiff line change
@@ -70,29 +70,29 @@ export const generateFile = (options: GeneratorOptions) => {
7070
ctx.runtime === "none"
7171
? (file: string) => file
7272
: (file: string) => {
73-
const model = Codegen.TypeScriptToModel.Generate(file);
74-
const transformer = runtimeValidationGenerator[ctx.runtime as Exclude<typeof ctx.runtime, "none">];
75-
// tmp fix for typebox, there's currently a "// todo" only with Codegen.ModelToTypeBox.Generate
76-
// https://github.com/sinclairzx81/typebox-codegen/blob/44d44d55932371b69f349331b1c8a60f5d760d9e/src/model/model-to-typebox.ts#L31
77-
const generated = ctx.runtime === "typebox" ? Codegen.TypeScriptToTypeBox.Generate(file) : transformer(model);
78-
79-
let converted = "";
80-
const match = generated.match(/(const __ENDPOINTS_START__ =)([\s\S]*?)(export type __ENDPOINTS_END__)/);
81-
const content = match?.[2];
82-
83-
if (content && ctx.runtime in replacerByRuntime) {
84-
const before = generated.slice(0, generated.indexOf("export type __ENDPOINTS_START"));
85-
converted =
86-
before +
87-
replacerByRuntime[ctx.runtime as keyof typeof replacerByRuntime](
88-
content.slice(content.indexOf("export")),
89-
);
90-
} else {
91-
converted = generated;
92-
}
73+
const model = Codegen.TypeScriptToModel.Generate(file);
74+
const transformer = runtimeValidationGenerator[ctx.runtime as Exclude<typeof ctx.runtime, "none">];
75+
// tmp fix for typebox, there's currently a "// todo" only with Codegen.ModelToTypeBox.Generate
76+
// https://github.com/sinclairzx81/typebox-codegen/blob/44d44d55932371b69f349331b1c8a60f5d760d9e/src/model/model-to-typebox.ts#L31
77+
const generated = ctx.runtime === "typebox" ? Codegen.TypeScriptToTypeBox.Generate(file) : transformer(model);
78+
79+
let converted = "";
80+
const match = generated.match(/(const __ENDPOINTS_START__ =)([\s\S]*?)(export type __ENDPOINTS_END__)/);
81+
const content = match?.[2];
82+
83+
if (content && ctx.runtime in replacerByRuntime) {
84+
const before = generated.slice(0, generated.indexOf("export type __ENDPOINTS_START"));
85+
converted =
86+
before +
87+
replacerByRuntime[ctx.runtime as keyof typeof replacerByRuntime](
88+
content.slice(content.indexOf("export")),
89+
);
90+
} else {
91+
converted = generated;
92+
}
9393

94-
return converted;
95-
};
94+
return converted;
95+
};
9696

9797
const file = `
9898
${transform(schemaList + endpointSchemaList)}
@@ -136,19 +136,20 @@ const parameterObjectToString = (parameters: Box<AnyBoxDef> | Record<string, Any
136136
const responseHeadersObjectToString = (responseHeaders: Record<string, AnyBox>, ctx: GeneratorContext) => {
137137
let str = "{";
138138
for (const [key, responseHeader] of Object.entries(responseHeaders)) {
139-
const value = ctx.runtime === "none"
139+
const value =
140+
ctx.runtime === "none"
140141
? responseHeader.recompute((box) => {
141-
if (Box.isReference(box) && !box.params.generics && box.value !== "null") {
142-
box.value = `Schemas.${box.value}`;
143-
}
142+
if (Box.isReference(box) && !box.params.generics && box.value !== "null") {
143+
box.value = `Schemas.${box.value}`;
144+
}
144145

145-
return box;
146-
}).value
147-
: responseHeader.value
146+
return box;
147+
}).value
148+
: responseHeader.value;
148149
str += `${wrapWithQuotesIfNeeded(key.toLowerCase())}: ${value},\n`;
149150
}
150151
return str + "}";
151-
}
152+
};
152153

153154
const generateEndpointSchemaList = (ctx: GeneratorContext) => {
154155
let file = `
@@ -163,42 +164,44 @@ const generateEndpointSchemaList = (ctx: GeneratorContext) => {
163164
path: "${endpoint.path}",
164165
requestFormat: "${endpoint.requestFormat}",
165166
${
166-
endpoint.meta.hasParameters
167-
? `parameters: {
167+
endpoint.meta.hasParameters
168+
? `parameters: {
168169
${parameters.query ? `query: ${parameterObjectToString(parameters.query)},` : ""}
169170
${parameters.path ? `path: ${parameterObjectToString(parameters.path)},` : ""}
170171
${parameters.header ? `header: ${parameterObjectToString(parameters.header)},` : ""}
171172
${
172173
parameters.body
173174
? `body: ${parameterObjectToString(
174-
ctx.runtime === "none"
175-
? parameters.body.recompute((box) => {
176-
if (Box.isReference(box) && !box.params.generics) {
177-
box.value = `Schemas.${box.value}`;
178-
}
179-
return box;
180-
})
181-
: parameters.body,
182-
)},`
175+
ctx.runtime === "none"
176+
? parameters.body.recompute((box) => {
177+
if (Box.isReference(box) && !box.params.generics) {
178+
box.value = `Schemas.${box.value}`;
179+
}
180+
return box;
181+
})
182+
: parameters.body,
183+
)},`
183184
: ""
184185
}
185186
}`
186-
: "parameters: never,"
187-
}
187+
: "parameters: never,"
188+
}
188189
response: ${
189-
ctx.runtime === "none"
190-
? endpoint.response.recompute((box) => {
191-
if (Box.isReference(box) && !box.params.generics && box.value !== "null") {
192-
box.value = `Schemas.${box.value}`;
193-
}
194-
195-
return box;
196-
}).value
197-
: endpoint.response.value
198-
},
190+
ctx.runtime === "none"
191+
? endpoint.response.recompute((box) => {
192+
if (Box.isReference(box) && !box.params.generics && box.value !== "null") {
193+
box.value = `Schemas.${box.value}`;
194+
}
195+
196+
return box;
197+
}).value
198+
: endpoint.response.value
199+
},
199200
${
200-
endpoint.responseHeaders ? `responseHeaders: ${responseHeadersObjectToString(endpoint.responseHeaders, ctx)},` : ""
201-
}
201+
endpoint.responseHeaders
202+
? `responseHeaders: ${responseHeadersObjectToString(endpoint.responseHeaders, ctx)},`
203+
: ""
204+
}
202205
}\n`;
203206
});
204207

@@ -220,14 +223,14 @@ const generateEndpointByMethod = (ctx: GeneratorContext) => {
220223
// <EndpointByMethod>
221224
export ${ctx.runtime === "none" ? "type" : "const"} EndpointByMethod = {
222225
${Object.entries(byMethods)
223-
.map(([method, list]) => {
224-
return `${method}: {
226+
.map(([method, list]) => {
227+
return `${method}: {
225228
${list.map(
226-
(endpoint) => `"${endpoint.path}": ${ctx.runtime === "none" ? "Endpoints." : ""}${endpoint.meta.alias}`,
227-
)}
229+
(endpoint) => `"${endpoint.path}": ${ctx.runtime === "none" ? "Endpoints." : ""}${endpoint.meta.alias}`,
230+
)}
228231
}`;
229-
})
230-
.join(",\n")}
232+
})
233+
.join(",\n")}
231234
}
232235
${ctx.runtime === "none" ? "" : "export type EndpointByMethod = typeof EndpointByMethod;"}
233236
// </EndpointByMethod>
@@ -237,8 +240,8 @@ const generateEndpointByMethod = (ctx: GeneratorContext) => {
237240
238241
// <EndpointByMethod.Shorthands>
239242
${Object.keys(byMethods)
240-
.map((method) => `export type ${capitalize(method)}Endpoints = EndpointByMethod["${method}"]`)
241-
.join("\n")}
243+
.map((method) => `export type ${capitalize(method)}Endpoints = EndpointByMethod["${method}"]`)
244+
.join("\n")}
242245
// </EndpointByMethod.Shorthands>
243246
`;
244247

@@ -326,18 +329,18 @@ export class ApiClient {
326329
${method}<Path extends keyof ${capitalizedMethod}Endpoints, TEndpoint extends ${capitalizedMethod}Endpoints[Path]>(
327330
path: Path,
328331
...params: MaybeOptionalArg<${match(ctx.runtime)
329-
.with("zod", "yup", () => infer(`TEndpoint["parameters"]`))
330-
.with("arktype", "io-ts", "typebox", "valibot", () => infer(`TEndpoint`) + `["parameters"]`)
331-
.otherwise(() => `TEndpoint["parameters"]`)}>
332+
.with("zod", "yup", () => infer(`TEndpoint["parameters"]`))
333+
.with("arktype", "io-ts", "typebox", "valibot", () => infer(`TEndpoint`) + `["parameters"]`)
334+
.otherwise(() => `TEndpoint["parameters"]`)}>
332335
): Promise<${match(ctx.runtime)
333-
.with("zod", "yup", () => infer(`TEndpoint["response"]`))
334-
.with("arktype", "io-ts", "typebox", "valibot", () => infer(`TEndpoint`) + `["response"]`)
335-
.otherwise(() => `TEndpoint["response"]`)}> {
336+
.with("zod", "yup", () => infer(`TEndpoint["response"]`))
337+
.with("arktype", "io-ts", "typebox", "valibot", () => infer(`TEndpoint`) + `["response"]`)
338+
.otherwise(() => `TEndpoint["response"]`)}> {
336339
return this.fetcher("${method}", this.baseUrl + path, params[0])
337340
.then(response => this.parseResponse(response))${match(ctx.runtime)
338-
.with("zod", "yup", () => `as Promise<${infer(`TEndpoint["response"]`)}>`)
339-
.with("arktype", "io-ts", "typebox", "valibot", () => `as Promise<${infer(`TEndpoint`) + `["response"]`}>`)
340-
.otherwise(() => `as Promise<TEndpoint["response"]>`)};
341+
.with("zod", "yup", () => `as Promise<${infer(`TEndpoint["response"]`)}>`)
342+
.with("arktype", "io-ts", "typebox", "valibot", () => `as Promise<${infer(`TEndpoint`) + `["response"]`}>`)
343+
.otherwise(() => `as Promise<TEndpoint["response"]>`)};
341344
}
342345
// </ApiClient.${method}>
343346
`
@@ -357,17 +360,17 @@ export class ApiClient {
357360
method: TMethod,
358361
path: TPath,
359362
...params: MaybeOptionalArg<${match(ctx.runtime)
360-
.with("zod", "yup", () =>
361-
inferByRuntime[ctx.runtime](`TEndpoint extends { parameters: infer Params } ? Params : never`),
362-
)
363-
.with(
364-
"arktype",
365-
"io-ts",
366-
"typebox",
367-
"valibot",
368-
() => inferByRuntime[ctx.runtime](`TEndpoint`) + `["parameters"]`,
369-
)
370-
.otherwise(() => `TEndpoint extends { parameters: infer Params } ? Params : never`)}>)
363+
.with("zod", "yup", () =>
364+
inferByRuntime[ctx.runtime](`TEndpoint extends { parameters: infer Params } ? Params : never`),
365+
)
366+
.with(
367+
"arktype",
368+
"io-ts",
369+
"typebox",
370+
"valibot",
371+
() => inferByRuntime[ctx.runtime](`TEndpoint`) + `["parameters"]`,
372+
)
373+
.otherwise(() => `TEndpoint extends { parameters: infer Params } ? Params : never`)}>)
371374
: Promise<Omit<Response, "json"> & {
372375
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/json) */
373376
json: () => Promise<TEndpoint extends { response: infer Res } ? Res : never>;

packages/typed-openapi/src/map-openapi-endpoints.ts

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -148,11 +148,14 @@ export const mapOpenApiEndpoints = (doc: OpenAPIObject) => {
148148
// Map response headers
149149
const headers = responseObject?.headers;
150150
if (headers) {
151-
endpoint.responseHeaders = Object.entries(headers).reduce((acc, [name, headerOrRef]) => {
152-
const header = refs.unwrap(headerOrRef);
153-
acc[name] = openApiSchemaToTs({ schema: header.schema ?? {}, ctx });
154-
return acc;
155-
}, {} as Record<string, Box>);
151+
endpoint.responseHeaders = Object.entries(headers).reduce(
152+
(acc, [name, headerOrRef]) => {
153+
const header = refs.unwrap(headerOrRef);
154+
acc[name] = openApiSchemaToTs({ schema: header.schema ?? {}, ctx });
155+
return acc;
156+
},
157+
{} as Record<string, Box>,
158+
);
156159
}
157160

158161
endpointList.push(endpoint);
@@ -194,7 +197,7 @@ type RequestFormat = "json" | "form-data" | "form-url" | "binary" | "text";
194197
type DefaultEndpoint = {
195198
parameters?: EndpointParameters | undefined;
196199
response: AnyBox;
197-
responseHeaders?: Record<string, AnyBox>
200+
responseHeaders?: Record<string, AnyBox>;
198201
};
199202

200203
export type Endpoint<TConfig extends DefaultEndpoint = DefaultEndpoint> = {
@@ -210,4 +213,4 @@ export type Endpoint<TConfig extends DefaultEndpoint = DefaultEndpoint> = {
210213
};
211214
response: TConfig["response"];
212215
responseHeaders?: TConfig["responseHeaders"];
213-
};
216+
};

packages/typed-openapi/src/openapi-schema-to-ts.ts

Lines changed: 15 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -53,9 +53,9 @@ export const openApiSchemaToTs = ({ schema, meta: _inheritedMeta, ctx }: Openapi
5353

5454
if (schema.allOf) {
5555
const types = schema.allOf.map((prop) => openApiSchemaToTs({ schema: prop, ctx, meta }));
56-
const {allOf, externalDocs, example, examples, description, title, ...rest} = schema
56+
const { allOf, externalDocs, example, examples, description, title, ...rest } = schema;
5757
if (Object.keys(rest).length > 0) {
58-
types.push(openApiSchemaToTs({schema: rest, ctx, meta}))
58+
types.push(openApiSchemaToTs({ schema: rest, ctx, meta }));
5959
}
6060
return t.intersection(types);
6161
}
@@ -72,7 +72,7 @@ export const openApiSchemaToTs = ({ schema, meta: _inheritedMeta, ctx }: Openapi
7272
} else if (value === false) {
7373
return t.literal("false");
7474
} else if (typeof value === "number") {
75-
return t.literal(`${value}`)
75+
return t.literal(`${value}`);
7676
} else {
7777
return t.literal(`"${value}"`);
7878
}
@@ -95,16 +95,18 @@ export const openApiSchemaToTs = ({ schema, meta: _inheritedMeta, ctx }: Openapi
9595
if (schemaType === "null") return t.literal("null");
9696
}
9797
if (!schemaType && schema.enum) {
98-
return t.union(schema.enum.map((value) => {
99-
if (typeof value === "string") {
100-
return t.literal(`"${value}"`)
101-
}
102-
if (value === null) {
103-
return t.literal("null")
104-
}
105-
// handle boolean and number literals
106-
return t.literal(value)
107-
}));
98+
return t.union(
99+
schema.enum.map((value) => {
100+
if (typeof value === "string") {
101+
return t.literal(`"${value}"`);
102+
}
103+
if (value === null) {
104+
return t.literal("null");
105+
}
106+
// handle boolean and number literals
107+
return t.literal(value);
108+
}),
109+
);
108110
}
109111

110112
if (schemaType === "array") {

0 commit comments

Comments
 (0)