fork of hey-api/openapi-ts because I need some additional things
1import type { AnalysisContext } from '@hey-api/codegen-core';
2
3import { py } from '../../ts-python';
4import type { MaybePyDsl } from '../base';
5import { PyDsl } from '../base';
6
7export type CallArgs = ReadonlyArray<MaybePyDsl<py.Expression> | undefined>;
8
9const Mixed = PyDsl<py.CallExpression>;
10
11export class CallPyDsl extends Mixed {
12 readonly '~dsl' = 'CallPyDsl';
13
14 protected _args: Array<MaybePyDsl<py.Expression> | undefined> = [];
15 protected _callee?: MaybePyDsl<py.Expression>;
16
17 constructor(callee: MaybePyDsl<py.Expression>, ...args: CallArgs) {
18 super();
19 this._callee = callee;
20 this._args = [...args];
21 }
22
23 override analyze(ctx: AnalysisContext): void {
24 super.analyze(ctx);
25 ctx.analyze(this._callee);
26 for (const arg of this._args) {
27 if (arg) ctx.analyze(arg);
28 }
29 }
30
31 /** Returns true when all required builder calls are present. */
32 get isValid(): boolean {
33 return this.missingRequiredCalls().length === 0;
34 }
35
36 arg(arg: MaybePyDsl<py.Expression>): this {
37 this._args.push(arg);
38 return this;
39 }
40
41 args(...args: CallArgs): this {
42 this._args.push(...args);
43 return this;
44 }
45
46 override toAst(): py.CallExpression {
47 this.$validate();
48
49 const astArgs = this._args
50 .filter((a): a is MaybePyDsl<py.Expression> => a !== undefined)
51 .map((arg) => this.$node(arg) as py.Expression);
52
53 return py.factory.createCallExpression(this.$node(this._callee!) as py.Expression, astArgs);
54 }
55
56 $validate(): asserts this is this & {
57 _callee: MaybePyDsl<py.Expression>;
58 } {
59 const missing = this.missingRequiredCalls();
60 if (missing.length === 0) return;
61 throw new Error(`Call expression missing ${missing.join(' and ')}`);
62 }
63
64 private missingRequiredCalls(): ReadonlyArray<string> {
65 const missing: Array<string> = [];
66 if (!this._callee) missing.push('callee');
67 return missing;
68 }
69}