fork of hey-api/openapi-ts because I need some additional things
1import type { AnalysisContext, NodeName, Ref } from '@hey-api/codegen-core';
2import { fromRef, isSymbol, ref } from '@hey-api/codegen-core';
3
4import { py } from '../../py-compiler';
5import type { MaybePyDsl } from '../base';
6import { PyDsl } from '../base';
7import { ExprMixin } from '../mixins/expr';
8import { f } from '../utils/factories';
9
10export type AttrLeft = NodeName | MaybePyDsl<py.Expression>;
11export type AttrCtor = (left: AttrLeft, right: NodeName) => AttrPyDsl;
12
13const Mixed = ExprMixin(PyDsl<py.MemberExpression>);
14
15export class AttrPyDsl extends Mixed {
16 readonly '~dsl' = 'AttrPyDsl';
17
18 protected left: Ref<AttrLeft>;
19
20 constructor(left: AttrLeft, right: NodeName) {
21 super();
22 this.left = ref(left);
23 this.name.set(right);
24 }
25
26 override analyze(ctx: AnalysisContext): void {
27 super.analyze(ctx);
28 ctx.analyze(this.left);
29 ctx.analyze(this.name);
30 }
31
32 /** Returns true when all required builder calls are present. */
33 get isValid(): boolean {
34 return !this.missingRequiredCalls().length;
35 }
36
37 override toAst() {
38 this.$validate();
39
40 const leftNode = this.$node(this.left);
41 const right = fromRef(this.name);
42 const value = isSymbol(right) ? right.finalName : right;
43 return py.factory.createMemberExpression(
44 leftNode,
45 py.factory.createIdentifier(value as string),
46 );
47 }
48
49 $validate(): asserts this is this & {
50 left: MaybePyDsl<py.Expression>;
51 } {
52 const missing = this.missingRequiredCalls();
53 if (!missing.length) return;
54 throw new Error(`Attribute access missing ${missing.join(' and ')}`);
55 }
56
57 private missingRequiredCalls(): ReadonlyArray<string> {
58 const missing: Array<string> = [];
59 if (!this.name.toString()) missing.push('property name');
60 return missing;
61 }
62}
63
64f.attr.set((...args) => new AttrPyDsl(...args));