-
Notifications
You must be signed in to change notification settings - Fork 1
/
build.js
328 lines (283 loc) · 10 KB
/
build.js
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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
const { execSync } = require("child_process");
const extract = require("extract-zip");
const marked = require("marked");
const lodash = require("lodash");
const https = require("https");
const fs = require("fs-extra");
const top = [];
const types = ["string", "number", "boolean"];
async function download() {
log("Downloading docs", true);
await new Promise(resolve => {
https.get(
"https://github.com/discord/discord-api-docs/archive/refs/heads/master.zip",
({ headers: { location } }) =>
https.get(location, res => res.pipe(fs.createWriteStream("temp.zip")).on("close", resolve))
);
});
log("Extracting docs", true);
await extract(__dirname + "/temp.zip", { dir: __dirname + "/temp" });
log("Deleting docs");
await fs.unlink("temp.zip");
log("Moving docs");
await fs.move("temp/discord-api-docs-main/docs", "docs");
log("Deleting temporary folder");
await fs.rm("temp", { recursive: true });
}
async function parse() {
const endpoints = {};
const api = { endpoints };
log("Parsing docs", true);
const reference = marked.lexer(await fs.readFile("docs/Reference.md", "utf-8"));
reference.filter(({ type, text }, i) => {
if (api.base && api.version) return;
if (type !== "heading") return;
if (text === "Base URL") {
const code = reference.slice(i + 1).find(({ type }) => type === "code");
api.base = code.text;
} else if (text === "API Versioning") {
const table = reference.slice(i + 1).find(({ type }) => type === "table");
api.version = +table.rows[0][0].text;
}
});
const files = await fs.readdir("docs/resources");
for await (const file of files) {
log("Reading " + file);
const data = await fs.readFile("docs/resources/" + file, "utf-8");
log("Parsing " + file);
const blocks = marked.lexer(data);
blocks.forEach((block, blockIndex) => {
if (!validate(block)) return;
let extraComplete = false;
const extra = blocks.slice(blockIndex + 1).filter(extraBlock => {
if (extraComplete) return;
if (validate(extraBlock)) {
extraComplete = true;
return;
}
return true;
});
let split = block.text.split(" % ");
let [name] = split;
name = lodash.camelCase(name);
log("Getting params for " + name);
let params = [];
let [method, path] = split[1].split(" ");
path = path.replace(/\{[^\{\}]+\}/g, block => {
let [param] = block.slice(1, -1).split("#");
param = lodash.camelCase(param);
params.push(param);
return ":" + param;
});
log("Getting query for " + name);
let query;
extra.forEach(({ type, text }, i) => {
if (type !== "heading") return;
if (text !== "Query String Params") return;
query ??= {};
const table = extra.slice(i + 1).find(({ type }) => type === "table");
table.rows.forEach(([field, type, description, required]) => {
field.text = field.text.replace(/[^\w]+$/, "");
query[lodash.camelCase(field.text)] = {
type: type.text,
name: field.text,
description: description.text,
required: boolean(required?.text)
};
});
});
log("Getting body for " + name);
let body;
extra.forEach(({ type, text }, i) => {
if (type !== "heading") return;
if (!text.includes("Form Params") && !text.includes("JSON Params")) return;
body ??= {};
const table = extra.slice(i + 1).find(({ type }) => type === "table");
table.rows.forEach(([field, type, description, required]) => {
type.text = type.text.replace(
/\[[^\]]+\]\([^\)]+\)/g,
hyperlink => hyperlink.slice(1, -1).split("](")[0]
);
field.text = field.text
.replace("(deprecated)", "")
.replace(/^\?/, "")
.replace(/[^\w]+$/, "")
.trim();
description.text = description.text
.replace("(deprecated)", "")
.replace(/[^\w]+$/, "")
.replace(/\[[^\]]+\]\([^\)]+\)/g, hyperlink => hyperlink.slice(1, -1).split("](")[0])
.trim();
body[lodash.camelCase(field.text)] = {
type: type.text,
name: field.text,
description: description.text,
required: boolean(required?.text)
};
});
});
endpoints[name] = { method, path, params, query, body };
});
}
return api;
}
async function compile(api) {
log("Compiling to TypeScript", true);
const prefix =
[
"const hostname = '" + new URL(api.base).hostname + "'",
"const prefix = '/api/v" + api.version + "'",
"const request = require('../request')",
"import { Stream } from 'stream'",
"interface File { name: string, value: string | Buffer | Stream }"
].join("\n") + "\n";
const lib = sort(
Object.entries(api.endpoints).map(([key, { method, path, params, query, body }]) => {
const args = [];
const requestArgs = [
[
"'" + method + "'",
params.includes("channelId") ? "channelId" : "'none'",
params.includes("guildId") ? "guildId" : "'none'",
"'" + path + "'"
].join("+':'+"),
"'" + method + "'",
"'" + path + "'"
];
log("Creating params for " + path);
if (params.length)
args.push(
...params.map(param => {
const last = requestArgs.length - 1;
requestArgs[last] = requestArgs[last]
.replace(":" + param, "'+" + param + "+'")
.replace(/\+''$/, "");
return param + ":string";
})
);
log("Creating body for " + path);
if (body) {
args.push("body:" + key + "Body");
requestArgs.push(...parseBody(key, body));
} else requestArgs.push("null");
log("Creating query for " + path);
if (query) {
args.push("query:" + key + "Query={}");
requestArgs.push(...parseQuery(key, query));
} else requestArgs.push("null");
let pre = key + "(" + args + "):Promise<any>{return $(" + requestArgs + ")},";
if (method !== "GET") {
let last = args.pop();
if (last) {
requestArgs.push("files");
if (last.startsWith("query:")) {
args.push("files?:File|File[]");
args.push(last);
return pre + "\n" + key + "Files(" + args + "){return $(" + requestArgs + ")},";
} else {
args.push(last);
args.push("files?:File|File[]");
return key + "(" + args + "):Promise<any>{return $(" + requestArgs + ")},";
}
}
}
return pre;
})
).join("\n");
return (
prefix +
sort(top).join("\n") +
"\nexport = function(token: string, type: string = 'Bot') {\nconst $ = request(hostname, prefix, typeof type === 'string' ? type + ' ' + token : token)\nreturn {\n" +
lib +
"\n}\n}"
);
}
function validate(block) {
if (block.type !== "heading") return;
if (!block.text.includes(" % ")) return;
return true;
}
function boolean(string) {
if (!string) return;
if (string === "false") return false;
if (string === "true") return true;
return string;
}
function sort(array) {
return array.sort(({ length: a }, { length: b }) => a - b);
}
function parseQuery(name, query) {
let transform = [];
top.push(
"interface " +
name +
"Query{" +
sort(
Object.entries(query).map(([key, { required, type, name }]) => {
transform.push("['" + name + "',query." + key + "]");
return (
key + (required === true ? "" : "?") + ":" + (types.includes(type) ? type : "string")
);
})
) +
"}"
);
return ["[" + sort(transform) + "]"];
}
function parseBody(name, body) {
let transform = [];
top.push(
"interface " +
name +
"Body{" +
sort(
Object.entries(body).map(([key, { required, type, name }]) => {
transform.push(name + ":body." + key);
return key + (required === true ? "" : "?") + ":" + (types.includes(type) ? type : "any");
})
) +
"}"
);
return ["{" + sort(transform) + "}"];
}
let loggingLevel = "none";
function log(string, important) {
if (loggingLevel === "none") return;
if (important) console.log(string);
else if (loggingLevel === "verbose") console.log(string);
}
(async () => {
const bin = process.cwd() + "/node_modules/.bin/";
const package = require("./package.json");
const options = process.argv
.slice(2)
.filter(a => a.startsWith("-"))
.map(a => a.replace(/-+/, "").toLowerCase());
if (options.includes("a") || options.includes("all")) options.push(..."pdgt".split(""));
if (process.argv[2] && !process.argv[2].startsWith("-")) loggingLevel = process.argv[2];
if (!(await fs.pathExists("docs"))) await download();
const parsed = await parse();
if (options.includes("p") || options.includes("parsed"))
await fs.writeFile("parsed.json", JSON.stringify(parsed, null, 2));
else if (await fs.pathExists("parsed.json")) await fs.unlink("parsed.json");
if (!options.includes("d") && !options.includes("docs") && !options.includes("documentation"))
await fs.rm("docs", { recursive: true });
const compiled = await compile(parsed);
await fs.writeFile("index.ts", compiled);
if (options.includes("g") || options.includes("gen") || options.includes("generate")) {
log("Building Docs", true);
await fs.writeFile("tsconfig.json", JSON.stringify({}));
await execSync(
bin +
'typedoc index.ts --out web --theme default --readme README.MD --name "' +
package.name +
'" --includeVersion'
);
await fs.unlink("tsconfig.json");
} else if (await fs.pathExists("web")) await fs.rm("web", { recursive: true });
log("Compiling to JavaScript", true);
execSync(bin + "tsc index.ts -d --outdir dist");
if (!options.includes("t") && !options.includes("ts") && !options.includes("typescript"))
await fs.unlink("index.ts");
log("Completed", true);
})();