-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathgenerate-browser-session.ts
More file actions
332 lines (289 loc) · 11.3 KB
/
generate-browser-session.ts
File metadata and controls
332 lines (289 loc) · 11.3 KB
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
#!/usr/bin/env -S node
import fs from 'fs';
import path from 'path';
import {
Node,
Project,
SyntaxKind,
type MethodDeclaration,
type ParameterDeclaration,
type PropertyDeclaration,
} from 'ts-morph';
type ChildMeta = {
propName: string;
targetClass: string;
};
type MethodMeta = {
name: string;
signature: string;
returnType: string;
implArgs: string;
};
type ResourceMeta = {
className: string;
filePath: string;
importPath: string;
alias: string;
exportedTypeNames: Set<string>;
children: ChildMeta[];
methods: MethodMeta[];
};
const repoRoot = path.resolve(__dirname, '..');
const resourcesDir = path.join(repoRoot, 'src', 'resources', 'browsers');
const outputFile = path.join(repoRoot, 'src', 'lib', 'generated', 'browser-session-bindings.ts');
const project = new Project({
skipAddingFilesFromTsConfig: true,
});
project.addSourceFilesAtPaths(path.join(resourcesDir, '**/*.ts'));
const sourceFiles = project
.getSourceFiles()
.filter((sf) => !sf.getBaseName().endsWith('.test.ts') && sf.getBaseName() !== 'index.ts');
const resourceByClass = new Map<string, ResourceMeta>();
for (const sf of sourceFiles) {
for (const classDecl of sf.getClasses()) {
if (classDecl.getName() == null) continue;
if (!extendsAPIResource(classDecl)) continue;
const className = classDecl.getNameOrThrow();
const importPath = toImportPath(path.relative(path.dirname(outputFile), sf.getFilePath()));
const alias = `${className}API`;
const exportedTypeNames = new Set<string>(
sf
.getStatements()
.filter(
(stmt) =>
Node.isInterfaceDeclaration(stmt) ||
Node.isTypeAliasDeclaration(stmt) ||
Node.isEnumDeclaration(stmt),
)
.map((stmt) => {
if (
Node.isInterfaceDeclaration(stmt) ||
Node.isTypeAliasDeclaration(stmt) ||
Node.isEnumDeclaration(stmt)
) {
return stmt.getName();
}
return '';
})
.filter(Boolean),
);
const meta: ResourceMeta = {
className,
filePath: sf.getFilePath(),
importPath,
alias,
exportedTypeNames,
children: extractChildren(classDecl),
methods: [],
};
resourceByClass.set(className, meta);
}
}
for (const sf of sourceFiles) {
for (const classDecl of sf.getClasses()) {
const className = classDecl.getName();
if (!className) continue;
const meta = resourceByClass.get(className);
if (!meta) continue;
for (const method of classDecl.getMethods()) {
const parsed = parseMethod(meta, method);
if (parsed) meta.methods.push(parsed);
}
}
}
const browserMeta = resourceByClass.get('Browsers');
if (!browserMeta) {
throw new Error('Could not find Browsers resource');
}
const ordered = orderResources(browserMeta, resourceByClass);
const importLines = ordered
.map((meta) => `import type * as ${meta.alias} from '${meta.importPath}';`)
.join('\n');
const interfaces = ordered.map((meta) => emitInterface(meta, resourceByClass)).join('\n\n');
const constructorAssignments = browserMeta.children
.map((child) => emitAssignment(child, resourceByClass))
.join('\n ');
const rootMethods = browserMeta.methods.map((method) => emitMethod(method, 'browsers')).join('\n\n');
const output = `// This file is generated by scripts/generate-browser-session.ts.\n// Do not edit by hand.\n\nimport type { Kernel } from '../../client';\nimport type { APIPromise } from '../../core/api-promise';\nimport type { RequestOptions } from '../../internal/request-options';\nimport type { Stream } from '../../core/streaming';\nimport type * as Shared from '../../resources/shared';\n${importLines}\n\n${interfaces}\n\nexport class GeneratedBrowserSessionBindings {\n protected readonly sessionClient: Kernel;\n readonly sessionId: string;\n\n readonly ${browserMeta.children
.map((child) => `${child.propName}: ${bindingName(child.targetClass)}`)
.join(
'\n readonly ',
)};\n\n constructor(sessionClient: Kernel, sessionId: string) {\n this.sessionClient = sessionClient;\n this.sessionId = sessionId;\n ${constructorAssignments}\n }\n\n protected opt(options?: RequestOptions): RequestOptions | undefined {\n return options;\n }\n\n${indent(
rootMethods,
2,
)}\n}\n`;
fs.mkdirSync(path.dirname(outputFile), { recursive: true });
fs.writeFileSync(outputFile, output);
function extendsAPIResource(classDecl: import('ts-morph').ClassDeclaration): boolean {
const ext = classDecl.getExtends();
if (!ext) return false;
const text = ext.getExpression().getText();
return text === 'APIResource';
}
function extractChildren(classDecl: import('ts-morph').ClassDeclaration): ChildMeta[] {
return classDecl
.getProperties()
.filter((prop) => !prop.getName().startsWith('with_'))
.map((prop) => {
const targetClass = childClassName(prop);
if (!targetClass) return null;
return { propName: prop.getName(), targetClass };
})
.filter((v): v is ChildMeta => v !== null);
}
function childClassName(prop: PropertyDeclaration): string | null {
const init = prop.getInitializer();
if (!init || !Node.isNewExpression(init)) return null;
const expr = init.getExpression().getText();
const last = expr.split('.').pop() || expr;
return last;
}
function parseMethod(meta: ResourceMeta, method: MethodDeclaration): MethodMeta | null {
if (!isPublicMethod(method)) return null;
const pathText = getPathTemplate(method);
if (!pathText) return null;
if (meta.className === 'Browsers' && !pathText.includes('/browsers/${id}/')) return null;
const params = method.getParameters();
const idParam = params[0]?.getName() === 'id' ? params[0] : undefined;
const paramsIdName = detectParamsIdParam(method);
if (!idParam && !paramsIdName) return null;
const publicParams = params
.filter((param) => param !== idParam)
.map((param) => formatParam(meta, param, paramsIdName, true))
.join(', ');
const implArgs = params
.map((param) => {
const name = param.getName();
if (param === idParam) return 'this.sessionId';
if (paramsIdName && name === paramsIdName) return `{ ...${name}, id: this.sessionId }`;
if (name === 'options') return 'this.opt(options)';
return name;
})
.join(', ');
return {
name: method.getName(),
signature: publicParams,
returnType: rewriteType(meta, method.getReturnTypeNodeOrThrow().getText()),
implArgs,
};
}
function isPublicMethod(method: MethodDeclaration): boolean {
const name = method.getName();
if (name.startsWith('_')) return false;
if (method.isStatic()) return false;
return true;
}
function getPathTemplate(method: MethodDeclaration): string | null {
const tag = method
.getDescendantsOfKind(SyntaxKind.TaggedTemplateExpression)
.find((node) => node.getTag().getText() === 'path');
return tag?.getTemplate().getText() ?? null;
}
function detectParamsIdParam(method: MethodDeclaration): string | null {
const body = method.getBodyText() ?? '';
const match = body.match(/const\s+\{\s*id(?:\s*,\s*\.\.\.\w+)?\s*\}\s*=\s*(\w+)/);
return match?.[1] ?? null;
}
function formatParam(
meta: ResourceMeta,
param: ParameterDeclaration,
paramsIdName: string | null,
includeInitializer: boolean,
): string {
const name = param.getName();
let typeText = param.getTypeNodeOrThrow().getText();
typeText = rewriteType(meta, typeText);
if (paramsIdName && name === paramsIdName) {
typeText = `Omit<${typeText}, 'id'>`;
}
const initializer = includeInitializer ? param.getInitializer()?.getText() : undefined;
const question = param.hasQuestionToken() ? '?' : '';
return `${name}${question}: ${typeText}${initializer ? ` = ${initializer}` : ''}`;
}
function rewriteType(meta: ResourceMeta, text: string): string {
let out = text;
const typeNames = Array.from(meta.exportedTypeNames).sort((a, b) => b.length - a.length);
for (const name of typeNames) {
out = out.replace(new RegExp(`\\b${name}\\b`, 'g'), `${meta.alias}.${name}`);
}
return out;
}
function orderResources(root: ResourceMeta, all: Map<string, ResourceMeta>): ResourceMeta[] {
const out: ResourceMeta[] = [];
const seen = new Set<string>();
const visit = (meta: ResourceMeta) => {
if (seen.has(meta.className)) return;
seen.add(meta.className);
for (const child of meta.children) {
const childMeta = all.get(child.targetClass);
if (childMeta) visit(childMeta);
}
out.push(meta);
};
visit(root);
return out.filter((meta) => meta.className !== 'Browsers').concat(root);
}
function emitInterface(meta: ResourceMeta, all: Map<string, ResourceMeta>): string {
const lines: string[] = [];
for (const method of meta.methods) {
const noInitSignature = method.signature.replace(/\s*=\s*[^,)+]+/g, '');
lines.push(` ${method.name}(${noInitSignature}): ${method.returnType};`);
}
for (const child of meta.children) {
if (all.has(child.targetClass)) {
lines.push(` ${child.propName}: ${bindingName(child.targetClass)};`);
}
}
return `export interface ${bindingName(meta.className)} {\n${lines.join('\n')}\n}`;
}
function bindingName(className: string): string {
return `BrowserSession${className}Bindings`;
}
function emitAssignment(child: ChildMeta, all: Map<string, ResourceMeta>): string {
const meta = all.get(child.targetClass)!;
const methodLines = meta.methods.map((method) => {
return `${method.name}: (${method.signature}) => this.sessionClient.browsers.${resourceCallPath(
meta.filePath,
)}.${method.name}(${method.implArgs}),`;
});
const childLines = meta.children.map((nested) => emitNestedObject(nested, all));
return `this.${child.propName} = {\n ${[...methodLines, ...childLines].join('\n ')}\n };`;
}
function emitNestedObject(child: ChildMeta, all: Map<string, ResourceMeta>): string {
const meta = all.get(child.targetClass)!;
const methodLines = meta.methods.map((method) => {
return `${method.name}: (${method.signature}) => this.sessionClient.browsers.${resourceCallPath(
meta.filePath,
)}.${method.name}(${method.implArgs}),`;
});
const nestedLines = meta.children.map((nested) => emitNestedObject(nested, all));
return `${child.propName}: {\n ${[...methodLines, ...nestedLines].join('\n ')}\n },`;
}
function resourceCallPath(filePath: string): string {
const rel = path.relative(resourcesDir, filePath).replace(/\\/g, '/').replace(/\.ts$/, '');
const segments = rel.split('/');
if (segments[segments.length - 1] === 'fs') {
return 'fs';
}
if (segments[0] === 'fs') {
return ['fs', ...segments.slice(1)].join('.');
}
if (segments[0] === 'browsers') {
return segments.slice(1).join('.');
}
return segments.join('.');
}
function emitMethod(method: MethodMeta, resourcePrefix: string): string {
return `${method.name}(${method.signature}): ${method.returnType} {\n return this.sessionClient.${resourcePrefix}.${method.name}(${method.implArgs});\n }`;
}
function toImportPath(relPath: string): string {
const normalized = relPath.replace(/\\/g, '/').replace(/\.ts$/, '');
return normalized.startsWith('.') ? normalized : `./${normalized}`;
}
function indent(value: string, depth: number): string {
const prefix = ' '.repeat(depth);
return value
.split('\n')
.map((line) => (line.length ? `${prefix}${line}` : line))
.join('\n');
}