Skip to content

Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

1.5 KB
Raw Blame
import type { BasicBuilder } from './BasicBuilder';
import { DocComment } from './DocComment';
import { isValidJsIdentifier } from './isValidJsIdentifier';
import { TypeContext } from './OperatorPrecedence';
import { TypeBuilder } from './TypeBuilder';
import { WellKnownSymbol } from './WellKnownSymbol';
import { Writer } from './Writer';

export class Property implements BasicBuilder {
  private isOptional = false;
  private isReadonly = false;
  private docComment?: DocComment;

  constructor(
    private name: string | WellKnownSymbol,
    private type: TypeBuilder
  ) {}

  optional(): this {
    this.isOptional = true;
    return this;
  }

  readonly(): this {
    this.isReadonly = true;
    return this;
  }

  setDocComment(docComment: DocComment): this {
    this.docComment = docComment;
    return this;
  }

  write(writer: Writer): void {
    if (this.docComment) {
      writer.write(this.docComment);
    }
    if (this.isReadonly) {
      writer.write('readonly ');
    }

    if (typeof this.name === 'string') {
      if (isValidJsIdentifier(this.name)) {
        writer.write(this.name);
      } else {
        writer.write('[').write(JSON.stringify(this.name)).write(']');
      }
    } else {
      writer.write('[').write(this.name).write(']');
    }

    if (this.isOptional) {
      writer.write('?');
    }
    writer.write(': ');
    this.type.writeInContext(writer, TypeContext.ObjectProperty);
  }
}

export function property(name: string | WellKnownSymbol, type: TypeBuilder) {
  return new Property(name, type);
}