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 { BaseCtor, MixinCtor } from './types';
5
6export type Modifiers = {
7 /**
8 * Checks if specified modifier is present.
9 *
10 * @param modifier - The modifier to check.
11 * @returns True if modifier is present, false otherwise.
12 */
13 hasModifier(modifier: Modifier): boolean;
14 modifiers: Array<py.Expression>;
15};
16
17type Modifier = 'async';
18
19export interface ModifierMethods extends Modifiers {
20 /**
21 * Adds a modifier of specified kind to modifiers list if condition is true.
22 *
23 * @param modifier - The modifier to add.
24 * @param condition - Whether to add modifier.
25 * @returns The parent node for chaining.
26 */
27 _m(modifier: Modifier, condition: boolean): this;
28}
29
30function modifierToKind(modifier: Modifier): py.Expression {
31 switch (modifier) {
32 case 'async':
33 return py.factory.createIdentifier('async');
34 }
35}
36
37export function ModifiersMixin<T extends py.Node, TBase extends BaseCtor<T>>(Base: TBase) {
38 abstract class Modifiers extends Base {
39 protected modifiers: Array<py.Expression> = [];
40
41 override analyze(ctx: AnalysisContext): void {
42 super.analyze(ctx);
43 }
44
45 protected hasModifier(modifier: Modifier): boolean {
46 const kind = modifierToKind(modifier);
47 return Boolean(this.modifiers.find((mod) => mod === kind));
48 }
49
50 protected _m(modifier: Modifier, condition: boolean): this {
51 if (condition) {
52 const kind = modifierToKind(modifier);
53 this.modifiers.push(kind);
54 }
55 return this;
56 }
57 }
58
59 return Modifiers as unknown as MixinCtor<TBase, ModifierMethods>;
60}
61
62export interface AsyncMethods extends Modifiers {
63 /**
64 * Adds an `async` keyword modifier if condition is true.
65 *
66 * @param condition - Whether to add modifier (default: true).
67 * @returns The target object for chaining.
68 */
69 async(condition?: boolean): this;
70}
71
72/**
73 * Mixin that adds an `async` modifier to a node.
74 */
75export function AsyncMixin<T extends py.Node, TBase extends BaseCtor<T>>(Base: TBase) {
76 const Mixed = ModifiersMixin(Base as BaseCtor<T>);
77
78 abstract class Async extends Mixed {
79 protected async(condition?: boolean): this {
80 const cond = arguments.length === 0 ? true : Boolean(condition);
81 return this._m('async', cond);
82 }
83 }
84
85 return Async as unknown as MixinCtor<TBase, AsyncMethods>;
86}