-
Notifications
You must be signed in to change notification settings - Fork 97
/
Copy pathbuild-types.ts
492 lines (435 loc) · 13 KB
/
build-types.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
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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
import * as fs from 'fs';
import * as path from 'path';
import * as prettier from 'prettier';
import * as got from 'got';
import deburr = require('lodash.deburr');
interface RawType {
type: string;
name: string;
description: string;
}
interface RawComments {
typedefs: {
typedefs: RawType[];
properties: RawType[];
}[];
events: {
[k: string]: {
description: string;
name: string;
returns?: RawType[];
}[];
};
requests: {
[k: string]: {
description: string;
name: string;
params?: RawType[];
returns?: RawType[];
}[];
};
}
interface Tree {
[k: string]: AnyType;
}
type AnyType = PrimitiveType | ObjectType | OutputType | ArrayType | SceneType | SceneItemType | SceneItemTransformType | OBSStatsType;
interface PrimitiveType {
type: 'string' | 'number' | 'boolean';
optional: boolean;
}
interface ObjectType {
type: 'object';
properties: Tree;
optional: boolean;
}
interface OutputType {
type: 'object';
properties: Tree;
optional: boolean;
}
interface ArrayType {
type: 'array';
items: PrimitiveType | ObjectType | OutputType | SceneType | SceneItemType | SceneItemTransformType;
optional: boolean;
}
interface SceneType {
type: 'ObsWebSocket.Scene';
optional: boolean;
}
interface SceneItemType {
type: 'ObsWebSocket.SceneItem';
optional: boolean;
}
interface SceneItemTransformType {
type: 'ObsWebSocket.SceneItemTransform';
optional: boolean;
}
interface OBSStatsType {
type: 'ObsWebSocket.OBSStats';
optional: boolean;
}
const DOTS_REGEX = /\./g;
const outFile = path.join(__dirname, '../types/index.d.ts');
async function getLatestComments(): Promise<any> {
const headers = {
Authorization: `token ${process.env.GH_TOKEN}`
};
if (!process.env.GH_TOKEN) {
delete headers.Authorization;
}
const latestReleaseResponse = await got('https://api.github.com/repos/Palakis/obs-websocket/releases/latest', {
json: true,
headers
});
const latestReleaseTag = latestReleaseResponse.body.tag_name;
const commentsResponse = await got(`https://raw.githubusercontent.com/Palakis/obs-websocket/${latestReleaseTag}/docs/generated/comments.json`, {
json: true,
headers
});
return commentsResponse.body;
}
getLatestComments().then(rawComments => {
parseApi(rawComments);
}).catch(error => {
console.error(error);
});
function parseApi(raw: RawComments): void {
const interfaces: string[] = [];
const requestArgs: string[] = [];
const requestResponses: string[] = [];
const eventOverloads: string[] = [];
Object.values(raw.typedefs).forEach(typedef => {
let typedefString = `interface ${typedef.typedefs[0].name} {`;
const foo = unflattenAndResolveTypes(typedef.properties);
typedefString += stringifyTypes(foo, {terminator: ';', finalTerminator: true});
typedefString += '}';
interfaces.push(typedefString);
});
Object.values(raw.requests).forEach(requestGroup => {
requestGroup.forEach(request => {
let argsString = `"${request.name}": `;
let responseString = argsString;
if (request.params) {
const foo = unflattenAndResolveTypes(request.params);
argsString += '{';
argsString += stringifyTypes(foo, {terminator: ',', finalTerminator: false});
argsString += '}';
} else {
argsString += 'void';
}
let returnTypeString = 'void';
if (request.returns) {
const foo = unflattenAndResolveTypes(request.returns);
returnTypeString = `{messageId: string;status: "ok";${stringifyTypes(foo, {terminator: ';', finalTerminator: false})}}`;
}
responseString += `${returnTypeString};`;
requestArgs.push(argsString);
requestResponses.push(responseString);
});
});
Object.values(raw.events).forEach(eventGroup => {
eventGroup.forEach(event => {
let dataTypeString = '{';
if (event.returns) {
const foo = unflattenAndResolveTypes(event.returns);
dataTypeString += stringifyTypes(foo);
}
dataTypeString += '}';
const eventType = `"${event.name}": ${event.returns ? dataTypeString : 'void'}`;
eventOverloads.push(eventType);
});
});
/* tslint:disable:no-trailing-whitespace no-dead-reference */
const sourceCode = `// This file is generated, do not edit.
// TypeScript Version: 3.1
/// <reference types="node" />
declare module 'obs-websocket-js' {
import { EventEmitter } from 'events';
namespace ObsWebSocket {
type Callback<K extends keyof RequestMethodReturnMap> = (
error?: Error | ObsWebSocket.ObsError,
response?: RequestMethodReturnMap[K]
) => void;
interface ObsError {
messageId: string;
status: "error";
error: string;
}
${interfaces.join('\n\n ')}
}
interface RequestMethodsArgsMap {
${requestArgs.join('\n\n ')}
}
interface RequestMethodReturnMap {
${requestResponses.join('\n\n ')}
}
interface EventHandlersDataMap {
"error": string;
"ConnectionOpened": void;
"ConnectionClosed": void;
"AuthenticationSuccess": void;
"AuthenticationFailure": void;
${eventOverloads.join('\n\n ')}
}
class ObsWebSocket extends EventEmitter {
connect(options?: {address?: string; password?: string; secure?: boolean}, callback?: (error?: Error) => void): Promise<void>;
disconnect(): void;
send<K extends keyof RequestMethodsArgsMap>(
requestType: K,
...args: (RequestMethodsArgsMap[K] extends object ? [RequestMethodsArgsMap[K]] : [undefined?])
): Promise<RequestMethodReturnMap[K]>;
sendCallback<K extends keyof RequestMethodsArgsMap>(
requestType: K,
...args: RequestMethodsArgsMap[K] extends object
? [RequestMethodsArgsMap[K], ObsWebSocket.Callback<K>]
: [ObsWebSocket.Callback<K>],
): void;
on<K extends keyof EventHandlersDataMap>(
type: K,
listener: (data: EventHandlersDataMap[K]) => void
): this;
}
export = ObsWebSocket;
}`;
/* tslint:enable:no-trailing-whitespace no-dead-reference */
fs.writeFileSync(outFile, prettier.format(sourceCode, {
parser: 'typescript'
}));
}
function unflattenAndResolveTypes(inputItems: RawType[]): Tree {
const tree: Tree = {};
const items = inputItems.slice(0);
// Sort items by depth (number of dots in their key).
// This ensures that we build our tree starting from the roots and ending at the leaves.
items.sort((a, b) => {
const aDots = a.name.match(DOTS_REGEX);
const bDots = b.name.match(DOTS_REGEX);
const numADots = aDots ? aDots.length : 0;
const numBDots = bDots ? bDots.length : 0;
return numADots - numBDots;
});
// Build the tree, one item at a time.
items.forEach(item => {
// Split the name of this item into parts, splitting it at each dot character.
const parts = item.name.split('.').map(str => {
return deburr(str.trim());
});
// If there are somehow zero parts (should be impossible), just bail out.
if (parts.length === 0) {
return;
}
// If there is exactly one part, then we know we are dealing with a root node of our tree.
// Anything else is a branch or leaf of the tree.
if (parts.length === 1) {
tree[parts[0]] = resolveType(item.type);
return;
}
// Many intermediate branches of the tree are not explicitly listed as their own
// values in the comments of obs-websocket. For example, `foo.bar.baz` might be listed,
// but `foo.bar` might not be. Therefore, we need to sniff out these "implicit" branches and add them to our tree.
let currentNode: (AnyType | Tree) = tree;
parts.slice(0, -1).forEach(nodeName => {
// A nodeName of '*' means that we're describing the items of an array.
// Don't do anything just yet.
if (nodeName === '*') {
return;
}
if (currentNode.type === 'array') {
const arrayNode = currentNode;
// If the currentNode is an array, then we must be describing the items of that array.
if (!arrayNode.items) {
arrayNode.items = {
type: 'object',
properties: {},
optional: false
};
}
const arrayNodeItems = arrayNode.items as ObjectType;
const newNode = {
type: 'object',
properties: {},
optional: false
};
(arrayNodeItems.properties as any)[nodeName] = newNode;
currentNode = newNode.properties;
} else { // Else, we must be describing an intermediate object node.
if (!currentNode.hasOwnProperty(nodeName)) {
(currentNode as any)[nodeName] = {
type: 'object',
properties: {},
optional: false
};
}
const firstIntermediate = (currentNode as any)[nodeName];
if (firstIntermediate.type === 'array') {
firstIntermediate.items = {
type: 'object',
properties: {},
optional: false
};
currentNode = firstIntermediate.items.properties;
} else {
currentNode = firstIntermediate.properties;
}
}
});
// Finally, we can define the leaf of this branch!
const leafName = String(parts.pop());
// A part of '*' means that we're describing the items of an array.
if (leafName === '*') {
currentNode.items = resolveType(item.type);
} else {
currentNode[leafName] = resolveType(item.type);
}
});
return tree;
}
function resolveType(inType: string): AnyType {
const isOptional = inType.toLowerCase().includes('(optional)');
switch (inType.toLowerCase().replace('(optional)', '').trim()) {
case 'bool':
case 'boolean':
return {
type: 'boolean',
optional: isOptional
};
case 'string':
return {
type: 'string',
optional: isOptional
};
case 'double':
case 'float':
case 'int':
case 'integer':
case 'number':
return {
type: 'number',
optional: isOptional
};
case 'array<string>':
return {
type: 'array',
items: {
type: 'string',
optional: true
},
optional: isOptional
};
case 'array<boolean>':
return {
type: 'array',
items: {
type: 'boolean',
optional: true
},
optional: isOptional
};
case 'array<object>':
return {
type: 'array',
items: {
type: 'object',
properties: {},
optional: true
},
optional: isOptional
};
case 'array<output>':
return {
type: 'array',
items: {
type: 'object',
properties: {},
optional: true
},
optional: isOptional
};
case 'array<scene>':
return {
type: 'array',
items: {
type: 'ObsWebSocket.Scene',
optional: true
},
optional: isOptional
};
case 'array<sceneitem>':
return {
type: 'array',
items: {
type: 'ObsWebSocket.SceneItem',
optional: true
},
optional: isOptional
};
case 'array<sceneitemtransform>':
return {
type: 'array',
items: {
type: 'ObsWebSocket.SceneItemTransform',
optional: true
},
optional: isOptional
};
case 'sceneitemtransform':
return {
type: 'ObsWebSocket.SceneItemTransform',
optional: isOptional
};
case 'obsstats':
return {
type: 'ObsWebSocket.OBSStats',
optional: isOptional
};
case 'string | object':
case 'object':
return {
type: 'object',
properties: {},
optional: isOptional
};
case 'output':
return {
type: 'object',
properties: {},
optional: isOptional
};
default:
throw new Error(`Unknown type: ${inType}`);
}
}
function stringifyTypes(inputTypes: Tree, {terminator = ';', finalTerminator = true, includePrefix = true} = {}): string {
let returnString = '';
Object.entries(inputTypes).forEach(([key, typeDef]) => {
if (includePrefix) {
const cleanedKey = `'${key}'`;
const separator = typeDef.optional ? '?:' : ':';
returnString += `${cleanedKey}${separator} `;
}
if (typeDef.type === 'object') {
returnString += `{${stringifyTypes(typeDef.properties)}}`;
} else if (typeDef.type === 'array') {
if (typeDef.items) {
if (typeDef.items.type === 'object') {
if (Object.keys(typeDef.items.properties).length > 0) {
returnString += `${stringifyTypes(typeDef.items.properties, {includePrefix: false, terminator: ''})}[]`;
} else {
returnString += 'Array<{[k: string]: any}>';
}
} else {
returnString += `${typeDef.items.type}[]`;
}
} else {
returnString += 'any[]';
}
} else {
returnString += typeDef.type;
}
returnString += terminator;
});
if (!finalTerminator) {
returnString = returnString.slice(0, -terminator.length);
}
return returnString;
}