-
Notifications
You must be signed in to change notification settings - Fork 83
/
Copy pathgenerate-types.js
77 lines (62 loc) · 2.18 KB
/
generate-types.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
const { pascalCase } = require("pascal-case");
const TypeWriter = require("@gimenete/type-writer");
const webhooks = require("@octokit/webhooks-definitions/index.json");
const { generateFile } = require("./generate-file");
const tw = new TypeWriter();
const eventPayloadMapping = [
["error", "WebhookEventHandlerError"],
["*", "WebhookEvent<any>"],
];
const doNotEditThisFileDisclaimer = `
// THIS FILE IS GENERATED - DO NOT EDIT DIRECTLY
// make edits in scripts/generate-types.js`;
const eventPayloadsVariable = "EventPayloads";
const generatePayloadType = (typeName) => ({
rootTypeName: typeName,
namedKeyPaths: {
[`${typeName}.repository`]: "PayloadRepository",
// This prevents a naming colision between the payload of a `installation_repositories` event
// and the `repositories` attribute of a `installation` event
"WebhookPayloadInstallation.repositories":
"WebhookPayloadInstallation_Repositories",
},
});
const generateEventNameType = (name, actions) => [
name,
...actions.map((action) => {
return `${name}.${action}`;
}),
];
webhooks.forEach(({ name, actions, examples }) => {
if (!examples) {
return;
}
const typeName = `WebhookPayload${pascalCase(name)}`;
tw.add(examples, generatePayloadType(typeName));
const eventNameTypes = generateEventNameType(name, actions);
eventNameTypes.forEach((type) => {
eventPayloadMapping.push([
type,
`WebhookEvent<${eventPayloadsVariable}.${typeName}>`,
]);
});
});
const getWebhookPayloadTypeFromEvent = `
${doNotEditThisFileDisclaimer}
import { ${eventPayloadsVariable} } from "./event-payloads";
import { WebhookEvent, WebhookEventHandlerError } from "../types";
export interface EventTypesPayload {
${eventPayloadMapping.map(([name, type]) => `"${name}": ${type}`).join(`,\n`)}
}
export type WebhookEvents = keyof EventTypesPayload
`;
generateFile(
"src/generated/get-webhook-payload-type-from-event.ts",
getWebhookPayloadTypeFromEvent
);
const eventPayloadsContent = `
${doNotEditThisFileDisclaimer}
export declare module ${eventPayloadsVariable} {
${tw.generate("typescript", { inlined: false })}}
`;
generateFile("src/generated/event-payloads.ts", eventPayloadsContent);