-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.ts
162 lines (141 loc) · 5.31 KB
/
main.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
import { parseArgs } from "@std/cli/parse-args";
import * as yaml from "@std/yaml/parse";
import { wait } from "@denosaurs/wait";
import { ModuleDeclarationKind, Project } from "ts-morph";
import { addComponents, addPathsObject, writeModuleComment } from "./mod.ts";
import { empty, resolve } from "./utils/mod.ts";
import manifest from "./deno.json" with { type: "json" };
export * from "./mod.ts";
const parseOptions = {
string: [
"output",
"config",
"import",
"base-urls",
],
boolean: [
"help",
"include-absolute-url",
"include-server-urls",
"include-relative-url",
"experimental-urlsearchparams",
],
alias: { "output": "o", "help": "h", "version": "V" },
default: {
"output": "./typefetch.d.ts",
"import": "__npm" in globalThis
? manifest.name
: "https://raw.githubusercontent.com/denosaurs/typefetch/main",
"include-server-urls": true,
"include-absolute-url": false,
"include-relative-url": false,
"experimental-urlsearchparams": false,
},
unknown: (arg: string, key?: string) => {
if (key === undefined) return;
console.error(
`Unknown option: ${arg}\n` +
`Run typefetch --help to see a list of available options`,
);
Deno.exit(1);
},
} as const;
const args = parseArgs(Deno.args, parseOptions);
if (args.help) {
// deno-fmt-ignore
console.log(
`Usage: typefetch [OPTIONS] <PATH>\n\n` +
`Options:\n` +
` -h, --help Print this help message\n` +
` -V, --version Print the version of TypeFetch\n` +
` -o, --output <PATH> Output file path (default: ${parseOptions.default["output"]})\n` +
` --config <PATH> File path to the tsconfig.json file\n` +
` --import <PATH> Import path for TypeFetch (default: ${parseOptions.default["import"]})\n` +
` --base-urls <URLS> A comma separated list of custom base urls for paths to start with\n` +
` --include-server-urls Include server URLs from the schema in the generated paths (default: ${parseOptions.default["include-server-urls"]})\n` +
` --include-absolute-url Include absolute URLs in the generated paths (default: ${parseOptions.default["include-absolute-url"]})\n` +
` --include-relative-url Include relative URLs in the generated paths (default: ${parseOptions.default["include-relative-url"]})\n` +
` --experimental-urlsearchparams Enable the experimental fully typed URLSearchParams type (default: ${parseOptions.default["experimental-urlsearchparams"]})\n`,
);
Deno.exit(0);
}
if (args.version) {
console.log(manifest.version);
Deno.exit(0);
}
if (args._.length !== 1 || empty(args._[0])) {
console.error(
`Expected a single OpenAPI schema to transform\n` +
`Run typefetch --help for more information`,
);
Deno.exit(1);
}
const importSpinner = wait("Resolving schema").start();
const input = args._[0] as string;
const output = resolve(args.output);
let openapi;
try {
importSpinner.text = "Trying to import OpenAPI schema as JSON";
openapi = (await import(input, { with: { type: "json" } })).default;
} catch (error) {
importSpinner.text = "Trying to import OpenAPI schema as YAML";
try {
// Try to import the OpenAPI schema as YAML
openapi = yaml.parse(await (await fetch(input)).text());
} catch {
importSpinner.fail(`Failed to load OpenAPI schema from ${input}`);
console.group();
console.error(error);
console.groupEnd();
Deno.exit(1);
}
}
importSpinner.succeed("Schema resolved");
const options = {
baseUrls: args["base-urls"]?.split(","),
includeAbsoluteUrl: args["include-absolute-url"],
includeServerUrls: args["include-server-urls"],
includeRelativeUrl: args["include-relative-url"],
experimentalURLSearchParams: args["experimental-urlsearchparams"],
};
const project = new Project({ tsConfigFilePath: args.config });
const source = project.createSourceFile(output, undefined, {
overwrite: true,
});
source.addImportDeclaration({
isTypeOnly: true,
moduleSpecifier: `${args["import"]}/types/json${
URL.canParse(args["import"]) ? ".ts" : ""
}`,
namedImports: ["JSONString"],
});
source.addImportDeclaration({
isTypeOnly: true,
moduleSpecifier: `${args["import"]}/types/headers${
URL.canParse(args["import"]) ? ".ts" : ""
}`,
namedImports: ["TypedHeadersInit"],
});
if (options.experimentalURLSearchParams) {
source.addImportDeclaration({
isTypeOnly: true,
moduleSpecifier: `${args["import"]}/types/urlsearchparams${
URL.canParse(args["import"]) ? ".ts" : ""
}`,
namedImports: ["URLSearchParamsString"],
});
}
source.insertText(0, (writer) => {
writeModuleComment(writer, openapi.info);
});
const global = source.addModule({
hasDeclareKeyword: true,
declarationKind: ModuleDeclarationKind.Global,
name: "global",
});
addPathsObject(global, openapi, openapi.paths, options);
addComponents(source, openapi, openapi.components);
const saveSpinner = wait("Saving generated definitions").start();
source.formatText({ indentSize: 2, ensureNewLineAtEndOfFile: true });
await source.save();
saveSpinner.succeed("Definitions saved");