/**
 * This file was auto-generated by `client-gen`.
 * Do not make direct changes to the file.
 */
import { Context, defaultContext } from "../context/context.js"
import { computeQuery } from "./utils.js"

/**
 * @hidden
 */
export type QueryTree = {
  operation: string
  args?: Record<string, unknown>
}

/**
 * @hidden
 */
export type Metadata = {
  [key: string]: {
    is_enum?: boolean
  }
}

interface ClientConfig {
  queryTree?: QueryTree[]
  ctx?: Context
}

class BaseClient {
  protected _queryTree: QueryTree[]
  protected _ctx: Context

  /**
   * @hidden
   */
  constructor({ queryTree, ctx }: ClientConfig = {}) {
    this._queryTree = queryTree || []
    this._ctx = ctx || new Context()
  }

  /**
   * @hidden
   */
  get queryTree() {
    return this._queryTree
  }
}

export type BuildArg = {
  /**
   * The build argument name.
   */
  name: string

  /**
   * The build argument value.
   */
  value: string
}

/**
 * Sharing mode of the cache volume.
 */
export enum CacheSharingMode {
  /**
   * Shares the cache volume amongst many build pipelines, but will serialize the writes
   */
  Locked = "LOCKED",

  /**
   * Keeps a cache volume for a single build pipeline
   */
  Private = "PRIVATE",

  /**
   * Shares the cache volume amongst many build pipelines
   */
  Shared = "SHARED",
}
/**
 * The `CacheVolumeID` scalar type represents an identifier for an object of type CacheVolume.
 */
export type CacheVolumeID = string & { __CacheVolumeID: never }

export type ContainerAsTarballOpts = {
  /**
   * Identifiers for other platform specific containers.
   *
   * Used for multi-platform images.
   */
  platformVariants?: Container[]

  /**
   * Force each layer of the image to use the specified compression algorithm.
   *
   * If this is unset, then if a layer already has a compressed blob in the engine's cache, that will be used (this can result in a mix of compression algorithms for different layers). If this is unset and a layer has no compressed blob in the engine's cache, then it will be compressed using Gzip.
   */
  forcedCompression?: ImageLayerCompression

  /**
   * Use the specified media types for the image's layers.
   *
   * Defaults to OCI, which is largely compatible with most recent container runtimes, but Docker may be needed for older runtimes without OCI support.
   */
  mediaTypes?: ImageMediaTypes
}

export type ContainerBuildOpts = {
  /**
   * Path to the Dockerfile to use.
   */
  dockerfile?: string

  /**
   * Target build stage to build.
   */
  target?: string

  /**
   * Additional build arguments.
   */
  buildArgs?: BuildArg[]

  /**
   * Secrets to pass to the build.
   *
   * They will be mounted at /run/secrets/[secret-name] in the build container
   *
   * They can be accessed in the Dockerfile using the "secret" mount type and mount path /run/secrets/[secret-name], e.g. RUN --mount=type=secret,id=my-secret curl http://example.com?token=$(cat /run/secrets/my-secret)
   */
  secrets?: Secret[]
}

export type ContainerExportOpts = {
  /**
   * Identifiers for other platform specific containers.
   *
   * Used for multi-platform image.
   */
  platformVariants?: Container[]

  /**
   * Force each layer of the exported image to use the specified compression algorithm.
   *
   * If this is unset, then if a layer already has a compressed blob in the engine's cache, that will be used (this can result in a mix of compression algorithms for different layers). If this is unset and a layer has no compressed blob in the engine's cache, then it will be compressed using Gzip.
   */
  forcedCompression?: ImageLayerCompression

  /**
   * Use the specified media types for the exported image's layers.
   *
   * Defaults to OCI, which is largely compatible with most recent container runtimes, but Docker may be needed for older runtimes without OCI support.
   */
  mediaTypes?: ImageMediaTypes
}

export type ContainerImportOpts = {
  /**
   * Identifies the tag to import from the archive, if the archive bundles multiple tags.
   */
  tag?: string
}

export type ContainerPipelineOpts = {
  /**
   * Description of the sub-pipeline.
   */
  description?: string

  /**
   * Labels to apply to the sub-pipeline.
   */
  labels?: PipelineLabel[]
}

export type ContainerPublishOpts = {
  /**
   * Identifiers for other platform specific containers.
   *
   * Used for multi-platform image.
   */
  platformVariants?: Container[]

  /**
   * Force each layer of the published image to use the specified compression algorithm.
   *
   * If this is unset, then if a layer already has a compressed blob in the engine's cache, that will be used (this can result in a mix of compression algorithms for different layers). If this is unset and a layer has no compressed blob in the engine's cache, then it will be compressed using Gzip.
   */
  forcedCompression?: ImageLayerCompression

  /**
   * Use the specified media types for the published image's layers.
   *
   * Defaults to OCI, which is largely compatible with most recent registries, but Docker may be needed for older registries without OCI support.
   */
  mediaTypes?: ImageMediaTypes
}

export type ContainerShellOpts = {
  /**
   * If set, override the container's default shell and invoke these arguments instead.
   */
  args?: string[]
}

export type ContainerWithDirectoryOpts = {
  /**
   * Patterns to exclude in the written directory (e.g. ["node_modules/**", ".gitignore", ".git/"]).
   */
  exclude?: string[]

  /**
   * Patterns to include in the written directory (e.g. ["*.go", "go.mod", "go.sum"]).
   */
  include?: string[]

  /**
   * A user:group to set for the directory and its contents.
   *
   * The user and group can either be an ID (1000:1000) or a name (foo:bar).
   *
   * If the group is omitted, it defaults to the same as the user.
   */
  owner?: string
}

export type ContainerWithEntrypointOpts = {
  /**
   * Don't remove the default arguments when setting the entrypoint.
   */
  keepDefaultArgs?: boolean
}

export type ContainerWithEnvVariableOpts = {
  /**
   * Replace `${VAR}` or `$VAR` in the value according to the current environment variables defined in the container (e.g., "/opt/bin:$PATH").
   */
  expand?: boolean
}

export type ContainerWithExecOpts = {
  /**
   * If the container has an entrypoint, ignore it for args rather than using it to wrap them.
   */
  skipEntrypoint?: boolean

  /**
   * Content to write to the command's standard input before closing (e.g., "Hello world").
   */
  stdin?: string

  /**
   * Redirect the command's standard output to a file in the container (e.g., "/tmp/stdout").
   */
  redirectStdout?: string

  /**
   * Redirect the command's standard error to a file in the container (e.g., "/tmp/stderr").
   */
  redirectStderr?: string

  /**
   * Provides dagger access to the executed command.
   *
   * Do not use this option unless you trust the command being executed; the command being executed WILL BE GRANTED FULL ACCESS TO YOUR HOST FILESYSTEM.
   */
  experimentalPrivilegedNesting?: boolean

  /**
   * Execute the command with all root capabilities. This is similar to running a command with "sudo" or executing "docker run" with the "--privileged" flag. Containerization does not provide any security guarantees when using this option. It should only be used when absolutely necessary and only with trusted commands.
   */
  insecureRootCapabilities?: boolean
}

export type ContainerWithExposedPortOpts = {
  /**
   * Transport layer network protocol
   */
  protocol?: NetworkProtocol

  /**
   * Optional port description
   */
  description?: string

  /**
   * Skip the health check when run as a service.
   */
  experimentalSkipHealthcheck?: boolean
}

export type ContainerWithFileOpts = {
  /**
   * Permission given to the copied file (e.g., 0600).
   */
  permissions?: number

  /**
   * A user:group to set for the file.
   *
   * The user and group can either be an ID (1000:1000) or a name (foo:bar).
   *
   * If the group is omitted, it defaults to the same as the user.
   */
  owner?: string
}

export type ContainerWithMountedCacheOpts = {
  /**
   * Identifier of the directory to use as the cache volume's root.
   */
  source?: Directory

  /**
   * Sharing mode of the cache volume.
   */
  sharing?: CacheSharingMode

  /**
   * A user:group to set for the mounted cache directory.
   *
   * Note that this changes the ownership of the specified mount along with the initial filesystem provided by source (if any). It does not have any effect if/when the cache has already been created.
   *
   * The user and group can either be an ID (1000:1000) or a name (foo:bar).
   *
   * If the group is omitted, it defaults to the same as the user.
   */
  owner?: string
}

export type ContainerWithMountedDirectoryOpts = {
  /**
   * A user:group to set for the mounted directory and its contents.
   *
   * The user and group can either be an ID (1000:1000) or a name (foo:bar).
   *
   * If the group is omitted, it defaults to the same as the user.
   */
  owner?: string
}

export type ContainerWithMountedFileOpts = {
  /**
   * A user or user:group to set for the mounted file.
   *
   * The user and group can either be an ID (1000:1000) or a name (foo:bar).
   *
   * If the group is omitted, it defaults to the same as the user.
   */
  owner?: string
}

export type ContainerWithMountedSecretOpts = {
  /**
   * A user:group to set for the mounted secret.
   *
   * The user and group can either be an ID (1000:1000) or a name (foo:bar).
   *
   * If the group is omitted, it defaults to the same as the user.
   */
  owner?: string

  /**
   * Permission given to the mounted secret (e.g., 0600).
   *
   * This option requires an owner to be set to be active.
   */
  mode?: number
}

export type ContainerWithNewFileOpts = {
  /**
   * Content of the file to write (e.g., "Hello world!").
   */
  contents?: string

  /**
   * Permission given to the written file (e.g., 0600).
   */
  permissions?: number

  /**
   * A user:group to set for the file.
   *
   * The user and group can either be an ID (1000:1000) or a name (foo:bar).
   *
   * If the group is omitted, it defaults to the same as the user.
   */
  owner?: string
}

export type ContainerWithUnixSocketOpts = {
  /**
   * A user:group to set for the mounted socket.
   *
   * The user and group can either be an ID (1000:1000) or a name (foo:bar).
   *
   * If the group is omitted, it defaults to the same as the user.
   */
  owner?: string
}

export type ContainerWithoutEntrypointOpts = {
  /**
   * Don't remove the default arguments when unsetting the entrypoint.
   */
  keepDefaultArgs?: boolean
}

export type ContainerWithoutExposedPortOpts = {
  /**
   * Port protocol to unexpose
   */
  protocol?: NetworkProtocol
}

/**
 * The `ContainerID` scalar type represents an identifier for an object of type Container.
 */
export type ContainerID = string & { __ContainerID: never }

export type CurrentModuleWorkdirOpts = {
  /**
   * Exclude artifacts that match the given pattern (e.g., ["node_modules/", ".git*"]).
   */
  exclude?: string[]

  /**
   * Include only artifacts that match the given pattern (e.g., ["app/", "package.*"]).
   */
  include?: string[]
}

/**
 * The `CurrentModuleID` scalar type represents an identifier for an object of type CurrentModule.
 */
export type CurrentModuleID = string & { __CurrentModuleID: never }

export type DirectoryAsModuleOpts = {
  /**
   * An optional subpath of the directory which contains the module's source code.
   *
   * This is needed when the module code is in a subdirectory but requires parent directories to be loaded in order to execute. For example, the module source code may need a go.mod, project.toml, package.json, etc. file from a parent directory.
   *
   * If not set, the module source code is loaded from the root of the directory.
   */
  sourceSubpath?: string
}

export type DirectoryDockerBuildOpts = {
  /**
   * The platform to build.
   */
  platform?: Platform

  /**
   * Path to the Dockerfile to use (e.g., "frontend.Dockerfile").
   */
  dockerfile?: string

  /**
   * Target build stage to build.
   */
  target?: string

  /**
   * Build arguments to use in the build.
   */
  buildArgs?: BuildArg[]

  /**
   * Secrets to pass to the build.
   *
   * They will be mounted at /run/secrets/[secret-name].
   */
  secrets?: Secret[]
}

export type DirectoryEntriesOpts = {
  /**
   * Location of the directory to look at (e.g., "/src").
   */
  path?: string
}

export type DirectoryPipelineOpts = {
  /**
   * Description of the sub-pipeline.
   */
  description?: string

  /**
   * Labels to apply to the sub-pipeline.
   */
  labels?: PipelineLabel[]
}

export type DirectoryWithDirectoryOpts = {
  /**
   * Exclude artifacts that match the given pattern (e.g., ["node_modules/", ".git*"]).
   */
  exclude?: string[]

  /**
   * Include only artifacts that match the given pattern (e.g., ["app/", "package.*"]).
   */
  include?: string[]
}

export type DirectoryWithFileOpts = {
  /**
   * Permission given to the copied file (e.g., 0600).
   */
  permissions?: number
}

export type DirectoryWithNewDirectoryOpts = {
  /**
   * Permission granted to the created directory (e.g., 0777).
   */
  permissions?: number
}

export type DirectoryWithNewFileOpts = {
  /**
   * Permission given to the copied file (e.g., 0600).
   */
  permissions?: number
}

/**
 * The `DirectoryID` scalar type represents an identifier for an object of type Directory.
 */
export type DirectoryID = string & { __DirectoryID: never }

/**
 * The `EnvVariableID` scalar type represents an identifier for an object of type EnvVariable.
 */
export type EnvVariableID = string & { __EnvVariableID: never }

/**
 * The `FieldTypeDefID` scalar type represents an identifier for an object of type FieldTypeDef.
 */
export type FieldTypeDefID = string & { __FieldTypeDefID: never }

export type FileExportOpts = {
  /**
   * If allowParentDirPath is true, the path argument can be a directory path, in which case the file will be created in that directory.
   */
  allowParentDirPath?: boolean
}

/**
 * The `FileID` scalar type represents an identifier for an object of type File.
 */
export type FileID = string & { __FileID: never }

export type FunctionWithArgOpts = {
  /**
   * A doc string for the argument, if any
   */
  description?: string

  /**
   * A default value to use for this argument if not explicitly set by the caller, if any
   */
  defaultValue?: JSON
}

/**
 * The `FunctionArgID` scalar type represents an identifier for an object of type FunctionArg.
 */
export type FunctionArgID = string & { __FunctionArgID: never }

/**
 * The `FunctionCallArgValueID` scalar type represents an identifier for an object of type FunctionCallArgValue.
 */
export type FunctionCallArgValueID = string & {
  __FunctionCallArgValueID: never
}

/**
 * The `FunctionCallID` scalar type represents an identifier for an object of type FunctionCall.
 */
export type FunctionCallID = string & { __FunctionCallID: never }

/**
 * The `FunctionID` scalar type represents an identifier for an object of type Function.
 */
export type FunctionID = string & { __FunctionID: never }

/**
 * The `GeneratedCodeID` scalar type represents an identifier for an object of type GeneratedCode.
 */
export type GeneratedCodeID = string & { __GeneratedCodeID: never }

/**
 * The `GitModuleSourceID` scalar type represents an identifier for an object of type GitModuleSource.
 */
export type GitModuleSourceID = string & { __GitModuleSourceID: never }

export type GitRefTreeOpts = {
  /**
   * DEPRECATED: This option should be passed to `git` instead.
   */
  sshKnownHosts?: string

  /**
   * DEPRECATED: This option should be passed to `git` instead.
   */
  sshAuthSocket?: Socket
}

/**
 * The `GitRefID` scalar type represents an identifier for an object of type GitRef.
 */
export type GitRefID = string & { __GitRefID: never }

/**
 * The `GitRepositoryID` scalar type represents an identifier for an object of type GitRepository.
 */
export type GitRepositoryID = string & { __GitRepositoryID: never }

export type HostDirectoryOpts = {
  /**
   * Exclude artifacts that match the given pattern (e.g., ["node_modules/", ".git*"]).
   */
  exclude?: string[]

  /**
   * Include only artifacts that match the given pattern (e.g., ["app/", "package.*"]).
   */
  include?: string[]
}

export type HostServiceOpts = {
  /**
   * Upstream host to forward traffic to.
   */
  host?: string

  /**
   * Ports to expose via the service, forwarding through the host network.
   *
   * If a port's frontend is unspecified or 0, it defaults to the same as the backend port.
   *
   * An empty set of ports is not valid; an error will be returned.
   */
  ports: PortForward[]
}

export type HostTunnelOpts = {
  /**
   * Configure explicit port forwarding rules for the tunnel.
   *
   * If a port's frontend is unspecified or 0, a random port will be chosen by the host.
   *
   * If no ports are given, all of the service's ports are forwarded. If native is true, each port maps to the same port on the host. If native is false, each port maps to a random port chosen by the host.
   *
   * If ports are given and native is true, the ports are additive.
   */
  ports?: PortForward[]

  /**
   * Map each service port to the same port on the host, as if the service were running natively.
   *
   * Note: enabling may result in port conflicts.
   */
  native?: boolean
}

/**
 * The `HostID` scalar type represents an identifier for an object of type Host.
 */
export type HostID = string & { __HostID: never }

/**
 * Compression algorithm to use for image layers.
 */
export enum ImageLayerCompression {
  Estargz = "EStarGZ",
  Gzip = "Gzip",
  Uncompressed = "Uncompressed",
  Zstd = "Zstd",
}
/**
 * Mediatypes to use in published or exported image metadata.
 */
export enum ImageMediaTypes {
  Dockermediatypes = "DockerMediaTypes",
  Ocimediatypes = "OCIMediaTypes",
}
/**
 * The `InputTypeDefID` scalar type represents an identifier for an object of type InputTypeDef.
 */
export type InputTypeDefID = string & { __InputTypeDefID: never }

/**
 * The `InterfaceTypeDefID` scalar type represents an identifier for an object of type InterfaceTypeDef.
 */
export type InterfaceTypeDefID = string & { __InterfaceTypeDefID: never }

/**
 * An arbitrary JSON-encoded value.
 */
export type JSON = string & { __JSON: never }

/**
 * The `LabelID` scalar type represents an identifier for an object of type Label.
 */
export type LabelID = string & { __LabelID: never }

/**
 * The `ListTypeDefID` scalar type represents an identifier for an object of type ListTypeDef.
 */
export type ListTypeDefID = string & { __ListTypeDefID: never }

/**
 * The `LocalModuleSourceID` scalar type represents an identifier for an object of type LocalModuleSource.
 */
export type LocalModuleSourceID = string & { __LocalModuleSourceID: never }

/**
 * The `ModuleDependencyID` scalar type represents an identifier for an object of type ModuleDependency.
 */
export type ModuleDependencyID = string & { __ModuleDependencyID: never }

/**
 * The `ModuleID` scalar type represents an identifier for an object of type Module.
 */
export type ModuleID = string & { __ModuleID: never }

/**
 * The `ModuleSourceID` scalar type represents an identifier for an object of type ModuleSource.
 */
export type ModuleSourceID = string & { __ModuleSourceID: never }

/**
 * The kind of module source.
 */
export enum ModuleSourceKind {
  GitSource = "GIT_SOURCE",
  LocalSource = "LOCAL_SOURCE",
}
/**
 * Transport layer network protocol associated to a port.
 */
export enum NetworkProtocol {
  Tcp = "TCP",
  Udp = "UDP",
}
/**
 * The `ObjectTypeDefID` scalar type represents an identifier for an object of type ObjectTypeDef.
 */
export type ObjectTypeDefID = string & { __ObjectTypeDefID: never }

export type PipelineLabel = {
  /**
   * Label name.
   */
  name: string

  /**
   * Label value.
   */
  value: string
}

/**
 * The platform config OS and architecture in a Container.
 *
 * The format is [os]/[platform]/[version] (e.g., "darwin/arm64/v7", "windows/amd64", "linux/arm64").
 */
export type Platform = string & { __Platform: never }

export type PortForward = {
  /**
   * Destination port for traffic.
   */
  backend: number

  /**
   * Port to expose to clients. If unspecified, a default will be chosen.
   */
  frontend?: number

  /**
   * Transport layer protocol to use for traffic.
   */
  protocol?: NetworkProtocol
}

/**
 * The `PortID` scalar type represents an identifier for an object of type Port.
 */
export type PortID = string & { __PortID: never }

export type ClientContainerOpts = {
  /**
   * DEPRECATED: Use `loadContainerFromID` instead.
   */
  id?: ContainerID

  /**
   * Platform to initialize the container with.
   */
  platform?: Platform
}

export type ClientDirectoryOpts = {
  /**
   * DEPRECATED: Use `loadDirectoryFromID` isntead.
   */
  id?: DirectoryID
}

export type ClientGitOpts = {
  /**
   * Set to true to keep .git directory.
   */
  keepGitDir?: boolean

  /**
   * A service which must be started before the repo is fetched.
   */
  experimentalServiceHost?: Service

  /**
   * Set SSH known hosts
   */
  sshKnownHosts?: string

  /**
   * Set SSH auth socket
   */
  sshAuthSocket?: Socket
}

export type ClientHttpOpts = {
  /**
   * A service which must be started before the URL is fetched.
   */
  experimentalServiceHost?: Service
}

export type ClientModuleDependencyOpts = {
  /**
   * If set, the name to use for the dependency. Otherwise, once installed to a parent module, the name of the dependency module will be used by default.
   */
  name?: string
}

export type ClientModuleSourceOpts = {
  /**
   * An explicitly set root directory for the module source. This is required to load local sources as modules; other source types implicitly encode the root directory and do not require this.
   */
  rootDirectory?: Directory

  /**
   * If true, enforce that the source is a stable version for source kinds that support versioning.
   */
  stable?: boolean
}

export type ClientPipelineOpts = {
  /**
   * Description of the sub-pipeline.
   */
  description?: string

  /**
   * Labels to apply to the sub-pipeline.
   */
  labels?: PipelineLabel[]
}

/**
 * The `SecretID` scalar type represents an identifier for an object of type Secret.
 */
export type SecretID = string & { __SecretID: never }

export type ServiceEndpointOpts = {
  /**
   * The exposed port number for the endpoint
   */
  port?: number

  /**
   * Return a URL with the given scheme, eg. http for http://
   */
  scheme?: string
}

export type ServiceStopOpts = {
  /**
   * Immediately kill the service without waiting for a graceful exit
   */
  kill?: boolean
}

export type ServiceUpOpts = {
  ports?: PortForward[]
  native?: boolean
}

/**
 * The `ServiceID` scalar type represents an identifier for an object of type Service.
 */
export type ServiceID = string & { __ServiceID: never }

/**
 * The `SocketID` scalar type represents an identifier for an object of type Socket.
 */
export type SocketID = string & { __SocketID: never }

/**
 * The `TerminalID` scalar type represents an identifier for an object of type Terminal.
 */
export type TerminalID = string & { __TerminalID: never }

export type TypeDefWithFieldOpts = {
  /**
   * A doc string for the field, if any
   */
  description?: string
}

export type TypeDefWithInterfaceOpts = {
  description?: string
}

export type TypeDefWithObjectOpts = {
  description?: string
}

/**
 * The `TypeDefID` scalar type represents an identifier for an object of type TypeDef.
 */
export type TypeDefID = string & { __TypeDefID: never }

/**
 * Distinguishes the different kinds of TypeDefs.
 */
export enum TypeDefKind {
  /**
   * A boolean value.
   */
  BooleanKind = "BOOLEAN_KIND",

  /**
   * A graphql input type, used only when representing the core API via TypeDefs.
   */
  InputKind = "INPUT_KIND",

  /**
   * An integer value.
   */
  IntegerKind = "INTEGER_KIND",

  /**
   * A named type of functions that can be matched+implemented by other objects+interfaces.
   *
   * Always paired with an InterfaceTypeDef.
   */
  InterfaceKind = "INTERFACE_KIND",

  /**
   * A list of values all having the same type.
   *
   * Always paired with a ListTypeDef.
   */
  ListKind = "LIST_KIND",

  /**
   * A named type defined in the GraphQL schema, with fields and functions.
   *
   * Always paired with an ObjectTypeDef.
   */
  ObjectKind = "OBJECT_KIND",

  /**
   * A string value.
   */
  StringKind = "STRING_KIND",

  /**
   * A special kind used to signify that no value is returned.
   *
   * This is used for functions that have no return value. The outer TypeDef specifying this Kind is always Optional, as the Void is never actually represented.
   */
  VoidKind = "VOID_KIND",
}
/**
 * The absence of a value.
 *
 * A Null Void is used as a placeholder for resolvers that do not return anything.
 */
export type Void = string & { __Void: never }

export type __TypeEnumValuesOpts = {
  includeDeprecated?: boolean
}

export type __TypeFieldsOpts = {
  includeDeprecated?: boolean
}

/**
 * A directory whose contents persist across runs.
 */
export class CacheVolume extends BaseClient {
  private readonly _id?: CacheVolumeID = undefined

  /**
   * Constructor is used for internal usage only, do not create object from it.
   */
  constructor(
    parent?: { queryTree?: QueryTree[]; ctx: Context },
    _id?: CacheVolumeID
  ) {
    super(parent)

    this._id = _id
  }

  /**
   * A unique identifier for this CacheVolume.
   */
  id = async (): Promise<CacheVolumeID> => {
    if (this._id) {
      return this._id
    }

    const response: Awaited<CacheVolumeID> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "id",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }
}

/**
 * An OCI-compatible container, also known as a Docker container.
 */
export class Container extends BaseClient {
  private readonly _id?: ContainerID = undefined
  private readonly _envVariable?: string = undefined
  private readonly _export?: boolean = undefined
  private readonly _imageRef?: string = undefined
  private readonly _label?: string = undefined
  private readonly _platform?: Platform = undefined
  private readonly _publish?: string = undefined
  private readonly _stderr?: string = undefined
  private readonly _stdout?: string = undefined
  private readonly _sync?: ContainerID = undefined
  private readonly _user?: string = undefined
  private readonly _workdir?: string = undefined

  /**
   * Constructor is used for internal usage only, do not create object from it.
   */
  constructor(
    parent?: { queryTree?: QueryTree[]; ctx: Context },
    _id?: ContainerID,
    _envVariable?: string,
    _export?: boolean,
    _imageRef?: string,
    _label?: string,
    _platform?: Platform,
    _publish?: string,
    _stderr?: string,
    _stdout?: string,
    _sync?: ContainerID,
    _user?: string,
    _workdir?: string
  ) {
    super(parent)

    this._id = _id
    this._envVariable = _envVariable
    this._export = _export
    this._imageRef = _imageRef
    this._label = _label
    this._platform = _platform
    this._publish = _publish
    this._stderr = _stderr
    this._stdout = _stdout
    this._sync = _sync
    this._user = _user
    this._workdir = _workdir
  }

  /**
   * A unique identifier for this Container.
   */
  id = async (): Promise<ContainerID> => {
    if (this._id) {
      return this._id
    }

    const response: Awaited<ContainerID> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "id",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }

  /**
   * Turn the container into a Service.
   *
   * Be sure to set any exposed ports before this conversion.
   */
  asService = (): Service => {
    return new Service({
      queryTree: [
        ...this._queryTree,
        {
          operation: "asService",
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Returns a File representing the container serialized to a tarball.
   * @param opts.platformVariants Identifiers for other platform specific containers.
   *
   * Used for multi-platform images.
   * @param opts.forcedCompression Force each layer of the image to use the specified compression algorithm.
   *
   * If this is unset, then if a layer already has a compressed blob in the engine's cache, that will be used (this can result in a mix of compression algorithms for different layers). If this is unset and a layer has no compressed blob in the engine's cache, then it will be compressed using Gzip.
   * @param opts.mediaTypes Use the specified media types for the image's layers.
   *
   * Defaults to OCI, which is largely compatible with most recent container runtimes, but Docker may be needed for older runtimes without OCI support.
   */
  asTarball = (opts?: ContainerAsTarballOpts): File => {
    const metadata: Metadata = {
      forcedCompression: { is_enum: true },
      mediaTypes: { is_enum: true },
    }

    return new File({
      queryTree: [
        ...this._queryTree,
        {
          operation: "asTarball",
          args: { ...opts, __metadata: metadata },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Initializes this container from a Dockerfile build.
   * @param context Directory context used by the Dockerfile.
   * @param opts.dockerfile Path to the Dockerfile to use.
   * @param opts.target Target build stage to build.
   * @param opts.buildArgs Additional build arguments.
   * @param opts.secrets Secrets to pass to the build.
   *
   * They will be mounted at /run/secrets/[secret-name] in the build container
   *
   * They can be accessed in the Dockerfile using the "secret" mount type and mount path /run/secrets/[secret-name], e.g. RUN --mount=type=secret,id=my-secret curl http://example.com?token=$(cat /run/secrets/my-secret)
   */
  build = (context: Directory, opts?: ContainerBuildOpts): Container => {
    return new Container({
      queryTree: [
        ...this._queryTree,
        {
          operation: "build",
          args: { context, ...opts },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Retrieves default arguments for future commands.
   */
  defaultArgs = async (): Promise<string[]> => {
    const response: Awaited<string[]> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "defaultArgs",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }

  /**
   * Retrieves a directory at the given path.
   *
   * Mounts are included.
   * @param path The path of the directory to retrieve (e.g., "./src").
   */
  directory = (path: string): Directory => {
    return new Directory({
      queryTree: [
        ...this._queryTree,
        {
          operation: "directory",
          args: { path },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Retrieves entrypoint to be prepended to the arguments of all commands.
   */
  entrypoint = async (): Promise<string[]> => {
    const response: Awaited<string[]> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "entrypoint",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }

  /**
   * Retrieves the value of the specified environment variable.
   * @param name The name of the environment variable to retrieve (e.g., "PATH").
   */
  envVariable = async (name: string): Promise<string> => {
    if (this._envVariable) {
      return this._envVariable
    }

    const response: Awaited<string> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "envVariable",
          args: { name },
        },
      ],
      await this._ctx.connection()
    )

    return response
  }

  /**
   * Retrieves the list of environment variables passed to commands.
   */
  envVariables = async (): Promise<EnvVariable[]> => {
    type envVariables = {
      id: EnvVariableID
    }

    const response: Awaited<envVariables[]> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "envVariables",
        },
        {
          operation: "id",
        },
      ],
      await this._ctx.connection()
    )

    return response.map(
      (r) =>
        new EnvVariable(
          {
            queryTree: [
              {
                operation: "loadEnvVariableFromID",
                args: { id: r.id },
              },
            ],
            ctx: this._ctx,
          },
          r.id
        )
    )
  }

  /**
   * EXPERIMENTAL API! Subject to change/removal at any time.
   *
   * Configures all available GPUs on the host to be accessible to this container.
   *
   * This currently works for Nvidia devices only.
   */
  experimentalWithAllGPUs = (): Container => {
    return new Container({
      queryTree: [
        ...this._queryTree,
        {
          operation: "experimentalWithAllGPUs",
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * EXPERIMENTAL API! Subject to change/removal at any time.
   *
   * Configures the provided list of devices to be accesible to this container.
   *
   * This currently works for Nvidia devices only.
   * @param devices List of devices to be accessible to this container.
   */
  experimentalWithGPU = (devices: string[]): Container => {
    return new Container({
      queryTree: [
        ...this._queryTree,
        {
          operation: "experimentalWithGPU",
          args: { devices },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Writes the container as an OCI tarball to the destination file path on the host.
   *
   * Return true on success.
   *
   * It can also export platform variants.
   * @param path Host's destination path (e.g., "./tarball").
   *
   * Path can be relative to the engine's workdir or absolute.
   * @param opts.platformVariants Identifiers for other platform specific containers.
   *
   * Used for multi-platform image.
   * @param opts.forcedCompression Force each layer of the exported image to use the specified compression algorithm.
   *
   * If this is unset, then if a layer already has a compressed blob in the engine's cache, that will be used (this can result in a mix of compression algorithms for different layers). If this is unset and a layer has no compressed blob in the engine's cache, then it will be compressed using Gzip.
   * @param opts.mediaTypes Use the specified media types for the exported image's layers.
   *
   * Defaults to OCI, which is largely compatible with most recent container runtimes, but Docker may be needed for older runtimes without OCI support.
   */
  export = async (
    path: string,
    opts?: ContainerExportOpts
  ): Promise<boolean> => {
    if (this._export) {
      return this._export
    }

    const metadata: Metadata = {
      forcedCompression: { is_enum: true },
      mediaTypes: { is_enum: true },
    }

    const response: Awaited<boolean> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "export",
          args: { path, ...opts, __metadata: metadata },
        },
      ],
      await this._ctx.connection()
    )

    return response
  }

  /**
   * Retrieves the list of exposed ports.
   *
   * This includes ports already exposed by the image, even if not explicitly added with dagger.
   */
  exposedPorts = async (): Promise<Port[]> => {
    type exposedPorts = {
      id: PortID
    }

    const response: Awaited<exposedPorts[]> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "exposedPorts",
        },
        {
          operation: "id",
        },
      ],
      await this._ctx.connection()
    )

    return response.map(
      (r) =>
        new Port(
          {
            queryTree: [
              {
                operation: "loadPortFromID",
                args: { id: r.id },
              },
            ],
            ctx: this._ctx,
          },
          r.id
        )
    )
  }

  /**
   * Retrieves a file at the given path.
   *
   * Mounts are included.
   * @param path The path of the file to retrieve (e.g., "./README.md").
   */
  file = (path: string): File => {
    return new File({
      queryTree: [
        ...this._queryTree,
        {
          operation: "file",
          args: { path },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Initializes this container from a pulled base image.
   * @param address Image's address from its registry.
   *
   * Formatted as [host]/[user]/[repo]:[tag] (e.g., "docker.io/dagger/dagger:main").
   */
  from = (address: string): Container => {
    return new Container({
      queryTree: [
        ...this._queryTree,
        {
          operation: "from",
          args: { address },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * The unique image reference which can only be retrieved immediately after the 'Container.From' call.
   */
  imageRef = async (): Promise<string> => {
    if (this._imageRef) {
      return this._imageRef
    }

    const response: Awaited<string> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "imageRef",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }

  /**
   * Reads the container from an OCI tarball.
   * @param source File to read the container from.
   * @param opts.tag Identifies the tag to import from the archive, if the archive bundles multiple tags.
   */
  import_ = (source: File, opts?: ContainerImportOpts): Container => {
    return new Container({
      queryTree: [
        ...this._queryTree,
        {
          operation: "import",
          args: { source, ...opts },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Retrieves the value of the specified label.
   * @param name The name of the label (e.g., "org.opencontainers.artifact.created").
   */
  label = async (name: string): Promise<string> => {
    if (this._label) {
      return this._label
    }

    const response: Awaited<string> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "label",
          args: { name },
        },
      ],
      await this._ctx.connection()
    )

    return response
  }

  /**
   * Retrieves the list of labels passed to container.
   */
  labels = async (): Promise<Label[]> => {
    type labels = {
      id: LabelID
    }

    const response: Awaited<labels[]> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "labels",
        },
        {
          operation: "id",
        },
      ],
      await this._ctx.connection()
    )

    return response.map(
      (r) =>
        new Label(
          {
            queryTree: [
              {
                operation: "loadLabelFromID",
                args: { id: r.id },
              },
            ],
            ctx: this._ctx,
          },
          r.id
        )
    )
  }

  /**
   * Retrieves the list of paths where a directory is mounted.
   */
  mounts = async (): Promise<string[]> => {
    const response: Awaited<string[]> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "mounts",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }

  /**
   * Creates a named sub-pipeline.
   * @param name Name of the sub-pipeline.
   * @param opts.description Description of the sub-pipeline.
   * @param opts.labels Labels to apply to the sub-pipeline.
   */
  pipeline = (name: string, opts?: ContainerPipelineOpts): Container => {
    return new Container({
      queryTree: [
        ...this._queryTree,
        {
          operation: "pipeline",
          args: { name, ...opts },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * The platform this container executes and publishes as.
   */
  platform = async (): Promise<Platform> => {
    if (this._platform) {
      return this._platform
    }

    const response: Awaited<Platform> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "platform",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }

  /**
   * Publishes this container as a new image to the specified address.
   *
   * Publish returns a fully qualified ref.
   *
   * It can also publish platform variants.
   * @param address Registry's address to publish the image to.
   *
   * Formatted as [host]/[user]/[repo]:[tag] (e.g. "docker.io/dagger/dagger:main").
   * @param opts.platformVariants Identifiers for other platform specific containers.
   *
   * Used for multi-platform image.
   * @param opts.forcedCompression Force each layer of the published image to use the specified compression algorithm.
   *
   * If this is unset, then if a layer already has a compressed blob in the engine's cache, that will be used (this can result in a mix of compression algorithms for different layers). If this is unset and a layer has no compressed blob in the engine's cache, then it will be compressed using Gzip.
   * @param opts.mediaTypes Use the specified media types for the published image's layers.
   *
   * Defaults to OCI, which is largely compatible with most recent registries, but Docker may be needed for older registries without OCI support.
   */
  publish = async (
    address: string,
    opts?: ContainerPublishOpts
  ): Promise<string> => {
    if (this._publish) {
      return this._publish
    }

    const metadata: Metadata = {
      forcedCompression: { is_enum: true },
      mediaTypes: { is_enum: true },
    }

    const response: Awaited<string> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "publish",
          args: { address, ...opts, __metadata: metadata },
        },
      ],
      await this._ctx.connection()
    )

    return response
  }

  /**
   * Retrieves this container's root filesystem. Mounts are not included.
   */
  rootfs = (): Directory => {
    return new Directory({
      queryTree: [
        ...this._queryTree,
        {
          operation: "rootfs",
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Return an interactive terminal for this container using its configured shell if not overridden by args (or sh as a fallback default).
   * @param opts.args If set, override the container's default shell and invoke these arguments instead.
   */
  shell = (opts?: ContainerShellOpts): Terminal => {
    return new Terminal({
      queryTree: [
        ...this._queryTree,
        {
          operation: "shell",
          args: { ...opts },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * The error stream of the last executed command.
   *
   * Will execute default command if none is set, or error if there's no default.
   */
  stderr = async (): Promise<string> => {
    if (this._stderr) {
      return this._stderr
    }

    const response: Awaited<string> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "stderr",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }

  /**
   * The output stream of the last executed command.
   *
   * Will execute default command if none is set, or error if there's no default.
   */
  stdout = async (): Promise<string> => {
    if (this._stdout) {
      return this._stdout
    }

    const response: Awaited<string> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "stdout",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }

  /**
   * Forces evaluation of the pipeline in the engine.
   *
   * It doesn't run the default command if no exec has been set.
   */
  sync = async (): Promise<Container> => {
    await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "sync",
        },
      ],
      await this._ctx.connection()
    )

    return this
  }

  /**
   * Retrieves the user to be set for all commands.
   */
  user = async (): Promise<string> => {
    if (this._user) {
      return this._user
    }

    const response: Awaited<string> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "user",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }

  /**
   * Configures default arguments for future commands.
   * @param args Arguments to prepend to future executions (e.g., ["-v", "--no-cache"]).
   */
  withDefaultArgs = (args: string[]): Container => {
    return new Container({
      queryTree: [
        ...this._queryTree,
        {
          operation: "withDefaultArgs",
          args: { args },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Set the default command to invoke for the "shell" API.
   * @param args The args of the command to set the default shell to.
   */
  withDefaultShell = (args: string[]): Container => {
    return new Container({
      queryTree: [
        ...this._queryTree,
        {
          operation: "withDefaultShell",
          args: { args },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Retrieves this container plus a directory written at the given path.
   * @param path Location of the written directory (e.g., "/tmp/directory").
   * @param directory Identifier of the directory to write
   * @param opts.exclude Patterns to exclude in the written directory (e.g. ["node_modules/**", ".gitignore", ".git/"]).
   * @param opts.include Patterns to include in the written directory (e.g. ["*.go", "go.mod", "go.sum"]).
   * @param opts.owner A user:group to set for the directory and its contents.
   *
   * The user and group can either be an ID (1000:1000) or a name (foo:bar).
   *
   * If the group is omitted, it defaults to the same as the user.
   */
  withDirectory = (
    path: string,
    directory: Directory,
    opts?: ContainerWithDirectoryOpts
  ): Container => {
    return new Container({
      queryTree: [
        ...this._queryTree,
        {
          operation: "withDirectory",
          args: { path, directory, ...opts },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Retrieves this container but with a different command entrypoint.
   * @param args Entrypoint to use for future executions (e.g., ["go", "run"]).
   * @param opts.keepDefaultArgs Don't remove the default arguments when setting the entrypoint.
   */
  withEntrypoint = (
    args: string[],
    opts?: ContainerWithEntrypointOpts
  ): Container => {
    return new Container({
      queryTree: [
        ...this._queryTree,
        {
          operation: "withEntrypoint",
          args: { args, ...opts },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Retrieves this container plus the given environment variable.
   * @param name The name of the environment variable (e.g., "HOST").
   * @param value The value of the environment variable. (e.g., "localhost").
   * @param opts.expand Replace `${VAR}` or `$VAR` in the value according to the current environment variables defined in the container (e.g., "/opt/bin:$PATH").
   */
  withEnvVariable = (
    name: string,
    value: string,
    opts?: ContainerWithEnvVariableOpts
  ): Container => {
    return new Container({
      queryTree: [
        ...this._queryTree,
        {
          operation: "withEnvVariable",
          args: { name, value, ...opts },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Retrieves this container after executing the specified command inside it.
   * @param args Command to run instead of the container's default command (e.g., ["run", "main.go"]).
   *
   * If empty, the container's default command is used.
   * @param opts.skipEntrypoint If the container has an entrypoint, ignore it for args rather than using it to wrap them.
   * @param opts.stdin Content to write to the command's standard input before closing (e.g., "Hello world").
   * @param opts.redirectStdout Redirect the command's standard output to a file in the container (e.g., "/tmp/stdout").
   * @param opts.redirectStderr Redirect the command's standard error to a file in the container (e.g., "/tmp/stderr").
   * @param opts.experimentalPrivilegedNesting Provides dagger access to the executed command.
   *
   * Do not use this option unless you trust the command being executed; the command being executed WILL BE GRANTED FULL ACCESS TO YOUR HOST FILESYSTEM.
   * @param opts.insecureRootCapabilities Execute the command with all root capabilities. This is similar to running a command with "sudo" or executing "docker run" with the "--privileged" flag. Containerization does not provide any security guarantees when using this option. It should only be used when absolutely necessary and only with trusted commands.
   */
  withExec = (args: string[], opts?: ContainerWithExecOpts): Container => {
    return new Container({
      queryTree: [
        ...this._queryTree,
        {
          operation: "withExec",
          args: { args, ...opts },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Expose a network port.
   *
   * Exposed ports serve two purposes:
   *
   * - For health checks and introspection, when running services
   *
   * - For setting the EXPOSE OCI field when publishing the container
   * @param port Port number to expose
   * @param opts.protocol Transport layer network protocol
   * @param opts.description Optional port description
   * @param opts.experimentalSkipHealthcheck Skip the health check when run as a service.
   */
  withExposedPort = (
    port: number,
    opts?: ContainerWithExposedPortOpts
  ): Container => {
    const metadata: Metadata = {
      protocol: { is_enum: true },
    }

    return new Container({
      queryTree: [
        ...this._queryTree,
        {
          operation: "withExposedPort",
          args: { port, ...opts, __metadata: metadata },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Retrieves this container plus the contents of the given file copied to the given path.
   * @param path Location of the copied file (e.g., "/tmp/file.txt").
   * @param source Identifier of the file to copy.
   * @param opts.permissions Permission given to the copied file (e.g., 0600).
   * @param opts.owner A user:group to set for the file.
   *
   * The user and group can either be an ID (1000:1000) or a name (foo:bar).
   *
   * If the group is omitted, it defaults to the same as the user.
   */
  withFile = (
    path: string,
    source: File,
    opts?: ContainerWithFileOpts
  ): Container => {
    return new Container({
      queryTree: [
        ...this._queryTree,
        {
          operation: "withFile",
          args: { path, source, ...opts },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Indicate that subsequent operations should be featured more prominently in the UI.
   */
  withFocus = (): Container => {
    return new Container({
      queryTree: [
        ...this._queryTree,
        {
          operation: "withFocus",
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Retrieves this container plus the given label.
   * @param name The name of the label (e.g., "org.opencontainers.artifact.created").
   * @param value The value of the label (e.g., "2023-01-01T00:00:00Z").
   */
  withLabel = (name: string, value: string): Container => {
    return new Container({
      queryTree: [
        ...this._queryTree,
        {
          operation: "withLabel",
          args: { name, value },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Retrieves this container plus a cache volume mounted at the given path.
   * @param path Location of the cache directory (e.g., "/cache/node_modules").
   * @param cache Identifier of the cache volume to mount.
   * @param opts.source Identifier of the directory to use as the cache volume's root.
   * @param opts.sharing Sharing mode of the cache volume.
   * @param opts.owner A user:group to set for the mounted cache directory.
   *
   * Note that this changes the ownership of the specified mount along with the initial filesystem provided by source (if any). It does not have any effect if/when the cache has already been created.
   *
   * The user and group can either be an ID (1000:1000) or a name (foo:bar).
   *
   * If the group is omitted, it defaults to the same as the user.
   */
  withMountedCache = (
    path: string,
    cache: CacheVolume,
    opts?: ContainerWithMountedCacheOpts
  ): Container => {
    const metadata: Metadata = {
      sharing: { is_enum: true },
    }

    return new Container({
      queryTree: [
        ...this._queryTree,
        {
          operation: "withMountedCache",
          args: { path, cache, ...opts, __metadata: metadata },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Retrieves this container plus a directory mounted at the given path.
   * @param path Location of the mounted directory (e.g., "/mnt/directory").
   * @param source Identifier of the mounted directory.
   * @param opts.owner A user:group to set for the mounted directory and its contents.
   *
   * The user and group can either be an ID (1000:1000) or a name (foo:bar).
   *
   * If the group is omitted, it defaults to the same as the user.
   */
  withMountedDirectory = (
    path: string,
    source: Directory,
    opts?: ContainerWithMountedDirectoryOpts
  ): Container => {
    return new Container({
      queryTree: [
        ...this._queryTree,
        {
          operation: "withMountedDirectory",
          args: { path, source, ...opts },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Retrieves this container plus a file mounted at the given path.
   * @param path Location of the mounted file (e.g., "/tmp/file.txt").
   * @param source Identifier of the mounted file.
   * @param opts.owner A user or user:group to set for the mounted file.
   *
   * The user and group can either be an ID (1000:1000) or a name (foo:bar).
   *
   * If the group is omitted, it defaults to the same as the user.
   */
  withMountedFile = (
    path: string,
    source: File,
    opts?: ContainerWithMountedFileOpts
  ): Container => {
    return new Container({
      queryTree: [
        ...this._queryTree,
        {
          operation: "withMountedFile",
          args: { path, source, ...opts },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Retrieves this container plus a secret mounted into a file at the given path.
   * @param path Location of the secret file (e.g., "/tmp/secret.txt").
   * @param source Identifier of the secret to mount.
   * @param opts.owner A user:group to set for the mounted secret.
   *
   * The user and group can either be an ID (1000:1000) or a name (foo:bar).
   *
   * If the group is omitted, it defaults to the same as the user.
   * @param opts.mode Permission given to the mounted secret (e.g., 0600).
   *
   * This option requires an owner to be set to be active.
   */
  withMountedSecret = (
    path: string,
    source: Secret,
    opts?: ContainerWithMountedSecretOpts
  ): Container => {
    return new Container({
      queryTree: [
        ...this._queryTree,
        {
          operation: "withMountedSecret",
          args: { path, source, ...opts },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Retrieves this container plus a temporary directory mounted at the given path.
   * @param path Location of the temporary directory (e.g., "/tmp/temp_dir").
   */
  withMountedTemp = (path: string): Container => {
    return new Container({
      queryTree: [
        ...this._queryTree,
        {
          operation: "withMountedTemp",
          args: { path },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Retrieves this container plus a new file written at the given path.
   * @param path Location of the written file (e.g., "/tmp/file.txt").
   * @param opts.contents Content of the file to write (e.g., "Hello world!").
   * @param opts.permissions Permission given to the written file (e.g., 0600).
   * @param opts.owner A user:group to set for the file.
   *
   * The user and group can either be an ID (1000:1000) or a name (foo:bar).
   *
   * If the group is omitted, it defaults to the same as the user.
   */
  withNewFile = (path: string, opts?: ContainerWithNewFileOpts): Container => {
    return new Container({
      queryTree: [
        ...this._queryTree,
        {
          operation: "withNewFile",
          args: { path, ...opts },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Retrieves this container with a registry authentication for a given address.
   * @param address Registry's address to bind the authentication to.
   *
   * Formatted as [host]/[user]/[repo]:[tag] (e.g. docker.io/dagger/dagger:main).
   * @param username The username of the registry's account (e.g., "Dagger").
   * @param secret The API key, password or token to authenticate to this registry.
   */
  withRegistryAuth = (
    address: string,
    username: string,
    secret: Secret
  ): Container => {
    return new Container({
      queryTree: [
        ...this._queryTree,
        {
          operation: "withRegistryAuth",
          args: { address, username, secret },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Retrieves the container with the given directory mounted to /.
   * @param directory Directory to mount.
   */
  withRootfs = (directory: Directory): Container => {
    return new Container({
      queryTree: [
        ...this._queryTree,
        {
          operation: "withRootfs",
          args: { directory },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Retrieves this container plus an env variable containing the given secret.
   * @param name The name of the secret variable (e.g., "API_SECRET").
   * @param secret The identifier of the secret value.
   */
  withSecretVariable = (name: string, secret: Secret): Container => {
    return new Container({
      queryTree: [
        ...this._queryTree,
        {
          operation: "withSecretVariable",
          args: { name, secret },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Establish a runtime dependency on a service.
   *
   * The service will be started automatically when needed and detached when it is no longer needed, executing the default command if none is set.
   *
   * The service will be reachable from the container via the provided hostname alias.
   *
   * The service dependency will also convey to any files or directories produced by the container.
   * @param alias A name that can be used to reach the service from the container
   * @param service Identifier of the service container
   */
  withServiceBinding = (alias: string, service: Service): Container => {
    return new Container({
      queryTree: [
        ...this._queryTree,
        {
          operation: "withServiceBinding",
          args: { alias, service },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Retrieves this container plus a socket forwarded to the given Unix socket path.
   * @param path Location of the forwarded Unix socket (e.g., "/tmp/socket").
   * @param source Identifier of the socket to forward.
   * @param opts.owner A user:group to set for the mounted socket.
   *
   * The user and group can either be an ID (1000:1000) or a name (foo:bar).
   *
   * If the group is omitted, it defaults to the same as the user.
   */
  withUnixSocket = (
    path: string,
    source: Socket,
    opts?: ContainerWithUnixSocketOpts
  ): Container => {
    return new Container({
      queryTree: [
        ...this._queryTree,
        {
          operation: "withUnixSocket",
          args: { path, source, ...opts },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Retrieves this container with a different command user.
   * @param name The user to set (e.g., "root").
   */
  withUser = (name: string): Container => {
    return new Container({
      queryTree: [
        ...this._queryTree,
        {
          operation: "withUser",
          args: { name },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Retrieves this container with a different working directory.
   * @param path The path to set as the working directory (e.g., "/app").
   */
  withWorkdir = (path: string): Container => {
    return new Container({
      queryTree: [
        ...this._queryTree,
        {
          operation: "withWorkdir",
          args: { path },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Retrieves this container with unset default arguments for future commands.
   */
  withoutDefaultArgs = (): Container => {
    return new Container({
      queryTree: [
        ...this._queryTree,
        {
          operation: "withoutDefaultArgs",
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Retrieves this container with an unset command entrypoint.
   * @param opts.keepDefaultArgs Don't remove the default arguments when unsetting the entrypoint.
   */
  withoutEntrypoint = (opts?: ContainerWithoutEntrypointOpts): Container => {
    return new Container({
      queryTree: [
        ...this._queryTree,
        {
          operation: "withoutEntrypoint",
          args: { ...opts },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Retrieves this container minus the given environment variable.
   * @param name The name of the environment variable (e.g., "HOST").
   */
  withoutEnvVariable = (name: string): Container => {
    return new Container({
      queryTree: [
        ...this._queryTree,
        {
          operation: "withoutEnvVariable",
          args: { name },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Unexpose a previously exposed port.
   * @param port Port number to unexpose
   * @param opts.protocol Port protocol to unexpose
   */
  withoutExposedPort = (
    port: number,
    opts?: ContainerWithoutExposedPortOpts
  ): Container => {
    const metadata: Metadata = {
      protocol: { is_enum: true },
    }

    return new Container({
      queryTree: [
        ...this._queryTree,
        {
          operation: "withoutExposedPort",
          args: { port, ...opts, __metadata: metadata },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Indicate that subsequent operations should not be featured more prominently in the UI.
   *
   * This is the initial state of all containers.
   */
  withoutFocus = (): Container => {
    return new Container({
      queryTree: [
        ...this._queryTree,
        {
          operation: "withoutFocus",
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Retrieves this container minus the given environment label.
   * @param name The name of the label to remove (e.g., "org.opencontainers.artifact.created").
   */
  withoutLabel = (name: string): Container => {
    return new Container({
      queryTree: [
        ...this._queryTree,
        {
          operation: "withoutLabel",
          args: { name },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Retrieves this container after unmounting everything at the given path.
   * @param path Location of the cache directory (e.g., "/cache/node_modules").
   */
  withoutMount = (path: string): Container => {
    return new Container({
      queryTree: [
        ...this._queryTree,
        {
          operation: "withoutMount",
          args: { path },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Retrieves this container without the registry authentication of a given address.
   * @param address Registry's address to remove the authentication from.
   *
   * Formatted as [host]/[user]/[repo]:[tag] (e.g. docker.io/dagger/dagger:main).
   */
  withoutRegistryAuth = (address: string): Container => {
    return new Container({
      queryTree: [
        ...this._queryTree,
        {
          operation: "withoutRegistryAuth",
          args: { address },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Retrieves this container with a previously added Unix socket removed.
   * @param path Location of the socket to remove (e.g., "/tmp/socket").
   */
  withoutUnixSocket = (path: string): Container => {
    return new Container({
      queryTree: [
        ...this._queryTree,
        {
          operation: "withoutUnixSocket",
          args: { path },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Retrieves this container with an unset command user.
   *
   * Should default to root.
   */
  withoutUser = (): Container => {
    return new Container({
      queryTree: [
        ...this._queryTree,
        {
          operation: "withoutUser",
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Retrieves this container with an unset working directory.
   *
   * Should default to "/".
   */
  withoutWorkdir = (): Container => {
    return new Container({
      queryTree: [
        ...this._queryTree,
        {
          operation: "withoutWorkdir",
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Retrieves the working directory for all commands.
   */
  workdir = async (): Promise<string> => {
    if (this._workdir) {
      return this._workdir
    }

    const response: Awaited<string> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "workdir",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }

  /**
   * Call the provided function with current Container.
   *
   * This is useful for reusability and readability by not breaking the calling chain.
   */
  with = (arg: (param: Container) => Container) => {
    return arg(this)
  }
}

/**
 * Reflective module API provided to functions at runtime.
 */
export class CurrentModule extends BaseClient {
  private readonly _id?: CurrentModuleID = undefined
  private readonly _name?: string = undefined

  /**
   * Constructor is used for internal usage only, do not create object from it.
   */
  constructor(
    parent?: { queryTree?: QueryTree[]; ctx: Context },
    _id?: CurrentModuleID,
    _name?: string
  ) {
    super(parent)

    this._id = _id
    this._name = _name
  }

  /**
   * A unique identifier for this CurrentModule.
   */
  id = async (): Promise<CurrentModuleID> => {
    if (this._id) {
      return this._id
    }

    const response: Awaited<CurrentModuleID> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "id",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }

  /**
   * The name of the module being executed in
   */
  name = async (): Promise<string> => {
    if (this._name) {
      return this._name
    }

    const response: Awaited<string> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "name",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }

  /**
   * The directory containing the module's source code loaded into the engine (plus any generated code that may have been created).
   */
  source = (): Directory => {
    return new Directory({
      queryTree: [
        ...this._queryTree,
        {
          operation: "source",
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Load a directory from the module's scratch working directory, including any changes that may have been made to it during module function execution.
   * @param path Location of the directory to access (e.g., ".").
   * @param opts.exclude Exclude artifacts that match the given pattern (e.g., ["node_modules/", ".git*"]).
   * @param opts.include Include only artifacts that match the given pattern (e.g., ["app/", "package.*"]).
   */
  workdir = (path: string, opts?: CurrentModuleWorkdirOpts): Directory => {
    return new Directory({
      queryTree: [
        ...this._queryTree,
        {
          operation: "workdir",
          args: { path, ...opts },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Load a file from the module's scratch working directory, including any changes that may have been made to it during module function execution.Load a file from the module's scratch working directory, including any changes that may have been made to it during module function execution.
   * @param path Location of the file to retrieve (e.g., "README.md").
   */
  workdirFile = (path: string): File => {
    return new File({
      queryTree: [
        ...this._queryTree,
        {
          operation: "workdirFile",
          args: { path },
        },
      ],
      ctx: this._ctx,
    })
  }
}

/**
 * A directory.
 */
export class Directory extends BaseClient {
  private readonly _id?: DirectoryID = undefined
  private readonly _export?: boolean = undefined
  private readonly _sync?: DirectoryID = undefined

  /**
   * Constructor is used for internal usage only, do not create object from it.
   */
  constructor(
    parent?: { queryTree?: QueryTree[]; ctx: Context },
    _id?: DirectoryID,
    _export?: boolean,
    _sync?: DirectoryID
  ) {
    super(parent)

    this._id = _id
    this._export = _export
    this._sync = _sync
  }

  /**
   * A unique identifier for this Directory.
   */
  id = async (): Promise<DirectoryID> => {
    if (this._id) {
      return this._id
    }

    const response: Awaited<DirectoryID> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "id",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }

  /**
   * Load the directory as a Dagger module
   * @param opts.sourceSubpath An optional subpath of the directory which contains the module's source code.
   *
   * This is needed when the module code is in a subdirectory but requires parent directories to be loaded in order to execute. For example, the module source code may need a go.mod, project.toml, package.json, etc. file from a parent directory.
   *
   * If not set, the module source code is loaded from the root of the directory.
   */
  asModule = (opts?: DirectoryAsModuleOpts): Module_ => {
    return new Module_({
      queryTree: [
        ...this._queryTree,
        {
          operation: "asModule",
          args: { ...opts },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Gets the difference between this directory and an another directory.
   * @param other Identifier of the directory to compare.
   */
  diff = (other: Directory): Directory => {
    return new Directory({
      queryTree: [
        ...this._queryTree,
        {
          operation: "diff",
          args: { other },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Retrieves a directory at the given path.
   * @param path Location of the directory to retrieve (e.g., "/src").
   */
  directory = (path: string): Directory => {
    return new Directory({
      queryTree: [
        ...this._queryTree,
        {
          operation: "directory",
          args: { path },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Builds a new Docker container from this directory.
   * @param opts.platform The platform to build.
   * @param opts.dockerfile Path to the Dockerfile to use (e.g., "frontend.Dockerfile").
   * @param opts.target Target build stage to build.
   * @param opts.buildArgs Build arguments to use in the build.
   * @param opts.secrets Secrets to pass to the build.
   *
   * They will be mounted at /run/secrets/[secret-name].
   */
  dockerBuild = (opts?: DirectoryDockerBuildOpts): Container => {
    return new Container({
      queryTree: [
        ...this._queryTree,
        {
          operation: "dockerBuild",
          args: { ...opts },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Returns a list of files and directories at the given path.
   * @param opts.path Location of the directory to look at (e.g., "/src").
   */
  entries = async (opts?: DirectoryEntriesOpts): Promise<string[]> => {
    const response: Awaited<string[]> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "entries",
          args: { ...opts },
        },
      ],
      await this._ctx.connection()
    )

    return response
  }

  /**
   * Writes the contents of the directory to a path on the host.
   * @param path Location of the copied directory (e.g., "logs/").
   */
  export = async (path: string): Promise<boolean> => {
    if (this._export) {
      return this._export
    }

    const response: Awaited<boolean> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "export",
          args: { path },
        },
      ],
      await this._ctx.connection()
    )

    return response
  }

  /**
   * Retrieves a file at the given path.
   * @param path Location of the file to retrieve (e.g., "README.md").
   */
  file = (path: string): File => {
    return new File({
      queryTree: [
        ...this._queryTree,
        {
          operation: "file",
          args: { path },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Returns a list of files and directories that matche the given pattern.
   * @param pattern Pattern to match (e.g., "*.md").
   */
  glob = async (pattern: string): Promise<string[]> => {
    const response: Awaited<string[]> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "glob",
          args: { pattern },
        },
      ],
      await this._ctx.connection()
    )

    return response
  }

  /**
   * Creates a named sub-pipeline.
   * @param name Name of the sub-pipeline.
   * @param opts.description Description of the sub-pipeline.
   * @param opts.labels Labels to apply to the sub-pipeline.
   */
  pipeline = (name: string, opts?: DirectoryPipelineOpts): Directory => {
    return new Directory({
      queryTree: [
        ...this._queryTree,
        {
          operation: "pipeline",
          args: { name, ...opts },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Force evaluation in the engine.
   */
  sync = async (): Promise<Directory> => {
    await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "sync",
        },
      ],
      await this._ctx.connection()
    )

    return this
  }

  /**
   * Retrieves this directory plus a directory written at the given path.
   * @param path Location of the written directory (e.g., "/src/").
   * @param directory Identifier of the directory to copy.
   * @param opts.exclude Exclude artifacts that match the given pattern (e.g., ["node_modules/", ".git*"]).
   * @param opts.include Include only artifacts that match the given pattern (e.g., ["app/", "package.*"]).
   */
  withDirectory = (
    path: string,
    directory: Directory,
    opts?: DirectoryWithDirectoryOpts
  ): Directory => {
    return new Directory({
      queryTree: [
        ...this._queryTree,
        {
          operation: "withDirectory",
          args: { path, directory, ...opts },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Retrieves this directory plus the contents of the given file copied to the given path.
   * @param path Location of the copied file (e.g., "/file.txt").
   * @param source Identifier of the file to copy.
   * @param opts.permissions Permission given to the copied file (e.g., 0600).
   */
  withFile = (
    path: string,
    source: File,
    opts?: DirectoryWithFileOpts
  ): Directory => {
    return new Directory({
      queryTree: [
        ...this._queryTree,
        {
          operation: "withFile",
          args: { path, source, ...opts },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Retrieves this directory plus a new directory created at the given path.
   * @param path Location of the directory created (e.g., "/logs").
   * @param opts.permissions Permission granted to the created directory (e.g., 0777).
   */
  withNewDirectory = (
    path: string,
    opts?: DirectoryWithNewDirectoryOpts
  ): Directory => {
    return new Directory({
      queryTree: [
        ...this._queryTree,
        {
          operation: "withNewDirectory",
          args: { path, ...opts },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Retrieves this directory plus a new file written at the given path.
   * @param path Location of the written file (e.g., "/file.txt").
   * @param contents Content of the written file (e.g., "Hello world!").
   * @param opts.permissions Permission given to the copied file (e.g., 0600).
   */
  withNewFile = (
    path: string,
    contents: string,
    opts?: DirectoryWithNewFileOpts
  ): Directory => {
    return new Directory({
      queryTree: [
        ...this._queryTree,
        {
          operation: "withNewFile",
          args: { path, contents, ...opts },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Retrieves this directory with all file/dir timestamps set to the given time.
   * @param timestamp Timestamp to set dir/files in.
   *
   * Formatted in seconds following Unix epoch (e.g., 1672531199).
   */
  withTimestamps = (timestamp: number): Directory => {
    return new Directory({
      queryTree: [
        ...this._queryTree,
        {
          operation: "withTimestamps",
          args: { timestamp },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Retrieves this directory with the directory at the given path removed.
   * @param path Location of the directory to remove (e.g., ".github/").
   */
  withoutDirectory = (path: string): Directory => {
    return new Directory({
      queryTree: [
        ...this._queryTree,
        {
          operation: "withoutDirectory",
          args: { path },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Retrieves this directory with the file at the given path removed.
   * @param path Location of the file to remove (e.g., "/file.txt").
   */
  withoutFile = (path: string): Directory => {
    return new Directory({
      queryTree: [
        ...this._queryTree,
        {
          operation: "withoutFile",
          args: { path },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Call the provided function with current Directory.
   *
   * This is useful for reusability and readability by not breaking the calling chain.
   */
  with = (arg: (param: Directory) => Directory) => {
    return arg(this)
  }
}

/**
 * An environment variable name and value.
 */
export class EnvVariable extends BaseClient {
  private readonly _id?: EnvVariableID = undefined
  private readonly _name?: string = undefined
  private readonly _value?: string = undefined

  /**
   * Constructor is used for internal usage only, do not create object from it.
   */
  constructor(
    parent?: { queryTree?: QueryTree[]; ctx: Context },
    _id?: EnvVariableID,
    _name?: string,
    _value?: string
  ) {
    super(parent)

    this._id = _id
    this._name = _name
    this._value = _value
  }

  /**
   * A unique identifier for this EnvVariable.
   */
  id = async (): Promise<EnvVariableID> => {
    if (this._id) {
      return this._id
    }

    const response: Awaited<EnvVariableID> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "id",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }
  name = async (): Promise<string> => {
    if (this._name) {
      return this._name
    }

    const response: Awaited<string> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "name",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }
  value = async (): Promise<string> => {
    if (this._value) {
      return this._value
    }

    const response: Awaited<string> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "value",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }
}

/**
 * A definition of a field on a custom object defined in a Module.
 *
 * A field on an object has a static value, as opposed to a function on an object whose value is computed by invoking code (and can accept arguments).
 */
export class FieldTypeDef extends BaseClient {
  private readonly _id?: FieldTypeDefID = undefined
  private readonly _description?: string = undefined
  private readonly _name?: string = undefined

  /**
   * Constructor is used for internal usage only, do not create object from it.
   */
  constructor(
    parent?: { queryTree?: QueryTree[]; ctx: Context },
    _id?: FieldTypeDefID,
    _description?: string,
    _name?: string
  ) {
    super(parent)

    this._id = _id
    this._description = _description
    this._name = _name
  }

  /**
   * A unique identifier for this FieldTypeDef.
   */
  id = async (): Promise<FieldTypeDefID> => {
    if (this._id) {
      return this._id
    }

    const response: Awaited<FieldTypeDefID> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "id",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }
  description = async (): Promise<string> => {
    if (this._description) {
      return this._description
    }

    const response: Awaited<string> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "description",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }
  name = async (): Promise<string> => {
    if (this._name) {
      return this._name
    }

    const response: Awaited<string> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "name",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }
  typeDef = (): TypeDef => {
    return new TypeDef({
      queryTree: [
        ...this._queryTree,
        {
          operation: "typeDef",
        },
      ],
      ctx: this._ctx,
    })
  }
}

/**
 * A file.
 */
export class File extends BaseClient {
  private readonly _id?: FileID = undefined
  private readonly _contents?: string = undefined
  private readonly _export?: boolean = undefined
  private readonly _name?: string = undefined
  private readonly _size?: number = undefined
  private readonly _sync?: FileID = undefined

  /**
   * Constructor is used for internal usage only, do not create object from it.
   */
  constructor(
    parent?: { queryTree?: QueryTree[]; ctx: Context },
    _id?: FileID,
    _contents?: string,
    _export?: boolean,
    _name?: string,
    _size?: number,
    _sync?: FileID
  ) {
    super(parent)

    this._id = _id
    this._contents = _contents
    this._export = _export
    this._name = _name
    this._size = _size
    this._sync = _sync
  }

  /**
   * A unique identifier for this File.
   */
  id = async (): Promise<FileID> => {
    if (this._id) {
      return this._id
    }

    const response: Awaited<FileID> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "id",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }

  /**
   * Retrieves the contents of the file.
   */
  contents = async (): Promise<string> => {
    if (this._contents) {
      return this._contents
    }

    const response: Awaited<string> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "contents",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }

  /**
   * Writes the file to a file path on the host.
   * @param path Location of the written directory (e.g., "output.txt").
   * @param opts.allowParentDirPath If allowParentDirPath is true, the path argument can be a directory path, in which case the file will be created in that directory.
   */
  export = async (path: string, opts?: FileExportOpts): Promise<boolean> => {
    if (this._export) {
      return this._export
    }

    const response: Awaited<boolean> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "export",
          args: { path, ...opts },
        },
      ],
      await this._ctx.connection()
    )

    return response
  }

  /**
   * Retrieves the name of the file.
   */
  name = async (): Promise<string> => {
    if (this._name) {
      return this._name
    }

    const response: Awaited<string> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "name",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }

  /**
   * Retrieves the size of the file, in bytes.
   */
  size = async (): Promise<number> => {
    if (this._size) {
      return this._size
    }

    const response: Awaited<number> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "size",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }

  /**
   * Force evaluation in the engine.
   */
  sync = async (): Promise<File> => {
    await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "sync",
        },
      ],
      await this._ctx.connection()
    )

    return this
  }

  /**
   * Retrieves this file with its created/modified timestamps set to the given time.
   * @param timestamp Timestamp to set dir/files in.
   *
   * Formatted in seconds following Unix epoch (e.g., 1672531199).
   */
  withTimestamps = (timestamp: number): File => {
    return new File({
      queryTree: [
        ...this._queryTree,
        {
          operation: "withTimestamps",
          args: { timestamp },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Call the provided function with current File.
   *
   * This is useful for reusability and readability by not breaking the calling chain.
   */
  with = (arg: (param: File) => File) => {
    return arg(this)
  }
}

/**
 * Function represents a resolver provided by a Module.
 *
 * A function always evaluates against a parent object and is given a set of named arguments.
 */
export class Function_ extends BaseClient {
  private readonly _id?: FunctionID = undefined
  private readonly _description?: string = undefined
  private readonly _name?: string = undefined

  /**
   * Constructor is used for internal usage only, do not create object from it.
   */
  constructor(
    parent?: { queryTree?: QueryTree[]; ctx: Context },
    _id?: FunctionID,
    _description?: string,
    _name?: string
  ) {
    super(parent)

    this._id = _id
    this._description = _description
    this._name = _name
  }

  /**
   * A unique identifier for this Function.
   */
  id = async (): Promise<FunctionID> => {
    if (this._id) {
      return this._id
    }

    const response: Awaited<FunctionID> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "id",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }
  args = async (): Promise<FunctionArg[]> => {
    type args = {
      id: FunctionArgID
    }

    const response: Awaited<args[]> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "args",
        },
        {
          operation: "id",
        },
      ],
      await this._ctx.connection()
    )

    return response.map(
      (r) =>
        new FunctionArg(
          {
            queryTree: [
              {
                operation: "loadFunctionArgFromID",
                args: { id: r.id },
              },
            ],
            ctx: this._ctx,
          },
          r.id
        )
    )
  }
  description = async (): Promise<string> => {
    if (this._description) {
      return this._description
    }

    const response: Awaited<string> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "description",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }
  name = async (): Promise<string> => {
    if (this._name) {
      return this._name
    }

    const response: Awaited<string> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "name",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }
  returnType = (): TypeDef => {
    return new TypeDef({
      queryTree: [
        ...this._queryTree,
        {
          operation: "returnType",
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Returns the function with the provided argument
   * @param name The name of the argument
   * @param typeDef The type of the argument
   * @param opts.description A doc string for the argument, if any
   * @param opts.defaultValue A default value to use for this argument if not explicitly set by the caller, if any
   */
  withArg = (
    name: string,
    typeDef: TypeDef,
    opts?: FunctionWithArgOpts
  ): Function_ => {
    return new Function_({
      queryTree: [
        ...this._queryTree,
        {
          operation: "withArg",
          args: { name, typeDef, ...opts },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Returns the function with the given doc string.
   * @param description The doc string to set.
   */
  withDescription = (description: string): Function_ => {
    return new Function_({
      queryTree: [
        ...this._queryTree,
        {
          operation: "withDescription",
          args: { description },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Call the provided function with current Function.
   *
   * This is useful for reusability and readability by not breaking the calling chain.
   */
  with = (arg: (param: Function_) => Function_) => {
    return arg(this)
  }
}

/**
 * An argument accepted by a function.
 *
 * This is a specification for an argument at function definition time, not an argument passed at function call time.
 */
export class FunctionArg extends BaseClient {
  private readonly _id?: FunctionArgID = undefined
  private readonly _defaultValue?: JSON = undefined
  private readonly _description?: string = undefined
  private readonly _name?: string = undefined

  /**
   * Constructor is used for internal usage only, do not create object from it.
   */
  constructor(
    parent?: { queryTree?: QueryTree[]; ctx: Context },
    _id?: FunctionArgID,
    _defaultValue?: JSON,
    _description?: string,
    _name?: string
  ) {
    super(parent)

    this._id = _id
    this._defaultValue = _defaultValue
    this._description = _description
    this._name = _name
  }

  /**
   * A unique identifier for this FunctionArg.
   */
  id = async (): Promise<FunctionArgID> => {
    if (this._id) {
      return this._id
    }

    const response: Awaited<FunctionArgID> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "id",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }
  defaultValue = async (): Promise<JSON> => {
    if (this._defaultValue) {
      return this._defaultValue
    }

    const response: Awaited<JSON> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "defaultValue",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }
  description = async (): Promise<string> => {
    if (this._description) {
      return this._description
    }

    const response: Awaited<string> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "description",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }
  name = async (): Promise<string> => {
    if (this._name) {
      return this._name
    }

    const response: Awaited<string> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "name",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }
  typeDef = (): TypeDef => {
    return new TypeDef({
      queryTree: [
        ...this._queryTree,
        {
          operation: "typeDef",
        },
      ],
      ctx: this._ctx,
    })
  }
}

/**
 * An active function call.
 */
export class FunctionCall extends BaseClient {
  private readonly _id?: FunctionCallID = undefined
  private readonly _name?: string = undefined
  private readonly _parent?: JSON = undefined
  private readonly _parentName?: string = undefined
  private readonly _returnValue?: Void = undefined

  /**
   * Constructor is used for internal usage only, do not create object from it.
   */
  constructor(
    parent?: { queryTree?: QueryTree[]; ctx: Context },
    _id?: FunctionCallID,
    _name?: string,
    _parent?: JSON,
    _parentName?: string,
    _returnValue?: Void
  ) {
    super(parent)

    this._id = _id
    this._name = _name
    this._parent = _parent
    this._parentName = _parentName
    this._returnValue = _returnValue
  }

  /**
   * A unique identifier for this FunctionCall.
   */
  id = async (): Promise<FunctionCallID> => {
    if (this._id) {
      return this._id
    }

    const response: Awaited<FunctionCallID> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "id",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }
  inputArgs = async (): Promise<FunctionCallArgValue[]> => {
    type inputArgs = {
      id: FunctionCallArgValueID
    }

    const response: Awaited<inputArgs[]> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "inputArgs",
        },
        {
          operation: "id",
        },
      ],
      await this._ctx.connection()
    )

    return response.map(
      (r) =>
        new FunctionCallArgValue(
          {
            queryTree: [
              {
                operation: "loadFunctionCallArgValueFromID",
                args: { id: r.id },
              },
            ],
            ctx: this._ctx,
          },
          r.id
        )
    )
  }
  name = async (): Promise<string> => {
    if (this._name) {
      return this._name
    }

    const response: Awaited<string> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "name",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }
  parent = async (): Promise<JSON> => {
    if (this._parent) {
      return this._parent
    }

    const response: Awaited<JSON> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "parent",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }
  parentName = async (): Promise<string> => {
    if (this._parentName) {
      return this._parentName
    }

    const response: Awaited<string> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "parentName",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }

  /**
   * Set the return value of the function call to the provided value.
   * @param value JSON serialization of the return value.
   */
  returnValue = async (value: JSON): Promise<Void> => {
    if (this._returnValue) {
      return this._returnValue
    }

    const response: Awaited<Void> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "returnValue",
          args: { value },
        },
      ],
      await this._ctx.connection()
    )

    return response
  }
}

/**
 * A value passed as a named argument to a function call.
 */
export class FunctionCallArgValue extends BaseClient {
  private readonly _id?: FunctionCallArgValueID = undefined
  private readonly _name?: string = undefined
  private readonly _value?: JSON = undefined

  /**
   * Constructor is used for internal usage only, do not create object from it.
   */
  constructor(
    parent?: { queryTree?: QueryTree[]; ctx: Context },
    _id?: FunctionCallArgValueID,
    _name?: string,
    _value?: JSON
  ) {
    super(parent)

    this._id = _id
    this._name = _name
    this._value = _value
  }

  /**
   * A unique identifier for this FunctionCallArgValue.
   */
  id = async (): Promise<FunctionCallArgValueID> => {
    if (this._id) {
      return this._id
    }

    const response: Awaited<FunctionCallArgValueID> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "id",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }
  name = async (): Promise<string> => {
    if (this._name) {
      return this._name
    }

    const response: Awaited<string> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "name",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }
  value = async (): Promise<JSON> => {
    if (this._value) {
      return this._value
    }

    const response: Awaited<JSON> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "value",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }
}

/**
 * The result of running an SDK's codegen.
 */
export class GeneratedCode extends BaseClient {
  private readonly _id?: GeneratedCodeID = undefined

  /**
   * Constructor is used for internal usage only, do not create object from it.
   */
  constructor(
    parent?: { queryTree?: QueryTree[]; ctx: Context },
    _id?: GeneratedCodeID
  ) {
    super(parent)

    this._id = _id
  }

  /**
   * A unique identifier for this GeneratedCode.
   */
  id = async (): Promise<GeneratedCodeID> => {
    if (this._id) {
      return this._id
    }

    const response: Awaited<GeneratedCodeID> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "id",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }
  code = (): Directory => {
    return new Directory({
      queryTree: [
        ...this._queryTree,
        {
          operation: "code",
        },
      ],
      ctx: this._ctx,
    })
  }
  vcsGeneratedPaths = async (): Promise<string[]> => {
    const response: Awaited<string[]> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "vcsGeneratedPaths",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }
  vcsIgnoredPaths = async (): Promise<string[]> => {
    const response: Awaited<string[]> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "vcsIgnoredPaths",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }

  /**
   * Set the list of paths to mark generated in version control.
   */
  withVCSGeneratedPaths = (paths: string[]): GeneratedCode => {
    return new GeneratedCode({
      queryTree: [
        ...this._queryTree,
        {
          operation: "withVCSGeneratedPaths",
          args: { paths },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Set the list of paths to ignore in version control.
   */
  withVCSIgnoredPaths = (paths: string[]): GeneratedCode => {
    return new GeneratedCode({
      queryTree: [
        ...this._queryTree,
        {
          operation: "withVCSIgnoredPaths",
          args: { paths },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Call the provided function with current GeneratedCode.
   *
   * This is useful for reusability and readability by not breaking the calling chain.
   */
  with = (arg: (param: GeneratedCode) => GeneratedCode) => {
    return arg(this)
  }
}

/**
 * Module source originating from a git repo.
 */
export class GitModuleSource extends BaseClient {
  private readonly _id?: GitModuleSourceID = undefined
  private readonly _cloneURL?: string = undefined
  private readonly _commit?: string = undefined
  private readonly _htmlURL?: string = undefined
  private readonly _sourceSubpath?: string = undefined
  private readonly _version?: string = undefined

  /**
   * Constructor is used for internal usage only, do not create object from it.
   */
  constructor(
    parent?: { queryTree?: QueryTree[]; ctx: Context },
    _id?: GitModuleSourceID,
    _cloneURL?: string,
    _commit?: string,
    _htmlURL?: string,
    _sourceSubpath?: string,
    _version?: string
  ) {
    super(parent)

    this._id = _id
    this._cloneURL = _cloneURL
    this._commit = _commit
    this._htmlURL = _htmlURL
    this._sourceSubpath = _sourceSubpath
    this._version = _version
  }

  /**
   * A unique identifier for this GitModuleSource.
   */
  id = async (): Promise<GitModuleSourceID> => {
    if (this._id) {
      return this._id
    }

    const response: Awaited<GitModuleSourceID> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "id",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }

  /**
   * The URL from which the source's git repo can be cloned.
   */
  cloneURL = async (): Promise<string> => {
    if (this._cloneURL) {
      return this._cloneURL
    }

    const response: Awaited<string> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "cloneURL",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }
  commit = async (): Promise<string> => {
    if (this._commit) {
      return this._commit
    }

    const response: Awaited<string> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "commit",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }

  /**
   * The URL to the source's git repo in a web browser
   */
  htmlURL = async (): Promise<string> => {
    if (this._htmlURL) {
      return this._htmlURL
    }

    const response: Awaited<string> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "htmlURL",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }
  sourceSubpath = async (): Promise<string> => {
    if (this._sourceSubpath) {
      return this._sourceSubpath
    }

    const response: Awaited<string> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "sourceSubpath",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }
  version = async (): Promise<string> => {
    if (this._version) {
      return this._version
    }

    const response: Awaited<string> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "version",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }
}

/**
 * A git ref (tag, branch, or commit).
 */
export class GitRef extends BaseClient {
  private readonly _id?: GitRefID = undefined
  private readonly _commit?: string = undefined

  /**
   * Constructor is used for internal usage only, do not create object from it.
   */
  constructor(
    parent?: { queryTree?: QueryTree[]; ctx: Context },
    _id?: GitRefID,
    _commit?: string
  ) {
    super(parent)

    this._id = _id
    this._commit = _commit
  }

  /**
   * A unique identifier for this GitRef.
   */
  id = async (): Promise<GitRefID> => {
    if (this._id) {
      return this._id
    }

    const response: Awaited<GitRefID> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "id",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }

  /**
   * The resolved commit id at this ref.
   */
  commit = async (): Promise<string> => {
    if (this._commit) {
      return this._commit
    }

    const response: Awaited<string> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "commit",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }

  /**
   * The filesystem tree at this ref.
   * @param opts.sshKnownHosts DEPRECATED: This option should be passed to `git` instead.
   * @param opts.sshAuthSocket DEPRECATED: This option should be passed to `git` instead.
   */
  tree = (opts?: GitRefTreeOpts): Directory => {
    return new Directory({
      queryTree: [
        ...this._queryTree,
        {
          operation: "tree",
          args: { ...opts },
        },
      ],
      ctx: this._ctx,
    })
  }
}

/**
 * A git repository.
 */
export class GitRepository extends BaseClient {
  private readonly _id?: GitRepositoryID = undefined

  /**
   * Constructor is used for internal usage only, do not create object from it.
   */
  constructor(
    parent?: { queryTree?: QueryTree[]; ctx: Context },
    _id?: GitRepositoryID
  ) {
    super(parent)

    this._id = _id
  }

  /**
   * A unique identifier for this GitRepository.
   */
  id = async (): Promise<GitRepositoryID> => {
    if (this._id) {
      return this._id
    }

    const response: Awaited<GitRepositoryID> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "id",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }

  /**
   * Returns details of a branch.
   * @param name Branch's name (e.g., "main").
   */
  branch = (name: string): GitRef => {
    return new GitRef({
      queryTree: [
        ...this._queryTree,
        {
          operation: "branch",
          args: { name },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Returns details of a commit.
   * @param id Identifier of the commit (e.g., "b6315d8f2810962c601af73f86831f6866ea798b").
   */
  commit = (id: string): GitRef => {
    return new GitRef({
      queryTree: [
        ...this._queryTree,
        {
          operation: "commit",
          args: { id },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Returns details of a tag.
   * @param name Tag's name (e.g., "v0.3.9").
   */
  tag = (name: string): GitRef => {
    return new GitRef({
      queryTree: [
        ...this._queryTree,
        {
          operation: "tag",
          args: { name },
        },
      ],
      ctx: this._ctx,
    })
  }
}

/**
 * Information about the host environment.
 */
export class Host extends BaseClient {
  private readonly _id?: HostID = undefined

  /**
   * Constructor is used for internal usage only, do not create object from it.
   */
  constructor(
    parent?: { queryTree?: QueryTree[]; ctx: Context },
    _id?: HostID
  ) {
    super(parent)

    this._id = _id
  }

  /**
   * A unique identifier for this Host.
   */
  id = async (): Promise<HostID> => {
    if (this._id) {
      return this._id
    }

    const response: Awaited<HostID> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "id",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }

  /**
   * Accesses a directory on the host.
   * @param path Location of the directory to access (e.g., ".").
   * @param opts.exclude Exclude artifacts that match the given pattern (e.g., ["node_modules/", ".git*"]).
   * @param opts.include Include only artifacts that match the given pattern (e.g., ["app/", "package.*"]).
   */
  directory = (path: string, opts?: HostDirectoryOpts): Directory => {
    return new Directory({
      queryTree: [
        ...this._queryTree,
        {
          operation: "directory",
          args: { path, ...opts },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Accesses a file on the host.
   * @param path Location of the file to retrieve (e.g., "README.md").
   */
  file = (path: string): File => {
    return new File({
      queryTree: [
        ...this._queryTree,
        {
          operation: "file",
          args: { path },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Creates a service that forwards traffic to a specified address via the host.
   * @param opts.host Upstream host to forward traffic to.
   * @param opts.ports Ports to expose via the service, forwarding through the host network.
   *
   * If a port's frontend is unspecified or 0, it defaults to the same as the backend port.
   *
   * An empty set of ports is not valid; an error will be returned.
   */
  service = (opts?: HostServiceOpts): Service => {
    return new Service({
      queryTree: [
        ...this._queryTree,
        {
          operation: "service",
          args: { ...opts },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Sets a secret given a user-defined name and the file path on the host, and returns the secret.
   *
   * The file is limited to a size of 512000 bytes.
   * @param name The user defined name for this secret.
   * @param path Location of the file to set as a secret.
   */
  setSecretFile = (name: string, path: string): Secret => {
    return new Secret({
      queryTree: [
        ...this._queryTree,
        {
          operation: "setSecretFile",
          args: { name, path },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Creates a tunnel that forwards traffic from the host to a service.
   * @param service Service to send traffic from the tunnel.
   * @param opts.ports Configure explicit port forwarding rules for the tunnel.
   *
   * If a port's frontend is unspecified or 0, a random port will be chosen by the host.
   *
   * If no ports are given, all of the service's ports are forwarded. If native is true, each port maps to the same port on the host. If native is false, each port maps to a random port chosen by the host.
   *
   * If ports are given and native is true, the ports are additive.
   * @param opts.native Map each service port to the same port on the host, as if the service were running natively.
   *
   * Note: enabling may result in port conflicts.
   */
  tunnel = (service: Service, opts?: HostTunnelOpts): Service => {
    return new Service({
      queryTree: [
        ...this._queryTree,
        {
          operation: "tunnel",
          args: { service, ...opts },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Accesses a Unix socket on the host.
   * @param path Location of the Unix socket (e.g., "/var/run/docker.sock").
   */
  unixSocket = (path: string): Socket => {
    return new Socket({
      queryTree: [
        ...this._queryTree,
        {
          operation: "unixSocket",
          args: { path },
        },
      ],
      ctx: this._ctx,
    })
  }
}

/**
 * A graphql input type, which is essentially just a group of named args.
 * This is currently only used to represent pre-existing usage of graphql input types
 * in the core API. It is not used by user modules and shouldn't ever be as user
 * module accept input objects via their id rather than graphql input types.
 */
export class InputTypeDef extends BaseClient {
  private readonly _id?: InputTypeDefID = undefined
  private readonly _name?: string = undefined

  /**
   * Constructor is used for internal usage only, do not create object from it.
   */
  constructor(
    parent?: { queryTree?: QueryTree[]; ctx: Context },
    _id?: InputTypeDefID,
    _name?: string
  ) {
    super(parent)

    this._id = _id
    this._name = _name
  }

  /**
   * A unique identifier for this InputTypeDef.
   */
  id = async (): Promise<InputTypeDefID> => {
    if (this._id) {
      return this._id
    }

    const response: Awaited<InputTypeDefID> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "id",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }
  fields = async (): Promise<FieldTypeDef[]> => {
    type fields = {
      id: FieldTypeDefID
    }

    const response: Awaited<fields[]> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "fields",
        },
        {
          operation: "id",
        },
      ],
      await this._ctx.connection()
    )

    return response.map(
      (r) =>
        new FieldTypeDef(
          {
            queryTree: [
              {
                operation: "loadFieldTypeDefFromID",
                args: { id: r.id },
              },
            ],
            ctx: this._ctx,
          },
          r.id
        )
    )
  }
  name = async (): Promise<string> => {
    if (this._name) {
      return this._name
    }

    const response: Awaited<string> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "name",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }
}

/**
 * A definition of a custom interface defined in a Module.
 */
export class InterfaceTypeDef extends BaseClient {
  private readonly _id?: InterfaceTypeDefID = undefined
  private readonly _description?: string = undefined
  private readonly _name?: string = undefined
  private readonly _sourceModuleName?: string = undefined

  /**
   * Constructor is used for internal usage only, do not create object from it.
   */
  constructor(
    parent?: { queryTree?: QueryTree[]; ctx: Context },
    _id?: InterfaceTypeDefID,
    _description?: string,
    _name?: string,
    _sourceModuleName?: string
  ) {
    super(parent)

    this._id = _id
    this._description = _description
    this._name = _name
    this._sourceModuleName = _sourceModuleName
  }

  /**
   * A unique identifier for this InterfaceTypeDef.
   */
  id = async (): Promise<InterfaceTypeDefID> => {
    if (this._id) {
      return this._id
    }

    const response: Awaited<InterfaceTypeDefID> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "id",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }
  description = async (): Promise<string> => {
    if (this._description) {
      return this._description
    }

    const response: Awaited<string> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "description",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }
  functions = async (): Promise<Function_[]> => {
    type functions = {
      id: FunctionID
    }

    const response: Awaited<functions[]> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "functions",
        },
        {
          operation: "id",
        },
      ],
      await this._ctx.connection()
    )

    return response.map(
      (r) =>
        new Function_(
          {
            queryTree: [
              {
                operation: "loadFunction_FromID",
                args: { id: r.id },
              },
            ],
            ctx: this._ctx,
          },
          r.id
        )
    )
  }
  name = async (): Promise<string> => {
    if (this._name) {
      return this._name
    }

    const response: Awaited<string> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "name",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }
  sourceModuleName = async (): Promise<string> => {
    if (this._sourceModuleName) {
      return this._sourceModuleName
    }

    const response: Awaited<string> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "sourceModuleName",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }
}

/**
 * A simple key value object that represents a label.
 */
export class Label extends BaseClient {
  private readonly _id?: LabelID = undefined
  private readonly _name?: string = undefined
  private readonly _value?: string = undefined

  /**
   * Constructor is used for internal usage only, do not create object from it.
   */
  constructor(
    parent?: { queryTree?: QueryTree[]; ctx: Context },
    _id?: LabelID,
    _name?: string,
    _value?: string
  ) {
    super(parent)

    this._id = _id
    this._name = _name
    this._value = _value
  }

  /**
   * A unique identifier for this Label.
   */
  id = async (): Promise<LabelID> => {
    if (this._id) {
      return this._id
    }

    const response: Awaited<LabelID> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "id",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }
  name = async (): Promise<string> => {
    if (this._name) {
      return this._name
    }

    const response: Awaited<string> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "name",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }
  value = async (): Promise<string> => {
    if (this._value) {
      return this._value
    }

    const response: Awaited<string> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "value",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }
}

/**
 * A definition of a list type in a Module.
 */
export class ListTypeDef extends BaseClient {
  private readonly _id?: ListTypeDefID = undefined

  /**
   * Constructor is used for internal usage only, do not create object from it.
   */
  constructor(
    parent?: { queryTree?: QueryTree[]; ctx: Context },
    _id?: ListTypeDefID
  ) {
    super(parent)

    this._id = _id
  }

  /**
   * A unique identifier for this ListTypeDef.
   */
  id = async (): Promise<ListTypeDefID> => {
    if (this._id) {
      return this._id
    }

    const response: Awaited<ListTypeDefID> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "id",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }
  elementTypeDef = (): TypeDef => {
    return new TypeDef({
      queryTree: [
        ...this._queryTree,
        {
          operation: "elementTypeDef",
        },
      ],
      ctx: this._ctx,
    })
  }
}

/**
 * Module source that that originates from a path locally relative to an arbitrary directory.
 */
export class LocalModuleSource extends BaseClient {
  private readonly _id?: LocalModuleSourceID = undefined
  private readonly _sourceSubpath?: string = undefined

  /**
   * Constructor is used for internal usage only, do not create object from it.
   */
  constructor(
    parent?: { queryTree?: QueryTree[]; ctx: Context },
    _id?: LocalModuleSourceID,
    _sourceSubpath?: string
  ) {
    super(parent)

    this._id = _id
    this._sourceSubpath = _sourceSubpath
  }

  /**
   * A unique identifier for this LocalModuleSource.
   */
  id = async (): Promise<LocalModuleSourceID> => {
    if (this._id) {
      return this._id
    }

    const response: Awaited<LocalModuleSourceID> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "id",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }
  sourceSubpath = async (): Promise<string> => {
    if (this._sourceSubpath) {
      return this._sourceSubpath
    }

    const response: Awaited<string> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "sourceSubpath",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }
}

/**
 * A Dagger module.
 */
export class Module_ extends BaseClient {
  private readonly _id?: ModuleID = undefined
  private readonly _description?: string = undefined
  private readonly _name?: string = undefined
  private readonly _sdk?: string = undefined
  private readonly _serve?: Void = undefined

  /**
   * Constructor is used for internal usage only, do not create object from it.
   */
  constructor(
    parent?: { queryTree?: QueryTree[]; ctx: Context },
    _id?: ModuleID,
    _description?: string,
    _name?: string,
    _sdk?: string,
    _serve?: Void
  ) {
    super(parent)

    this._id = _id
    this._description = _description
    this._name = _name
    this._sdk = _sdk
    this._serve = _serve
  }

  /**
   * A unique identifier for this Module.
   */
  id = async (): Promise<ModuleID> => {
    if (this._id) {
      return this._id
    }

    const response: Awaited<ModuleID> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "id",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }
  dependencies = async (): Promise<Module_[]> => {
    type dependencies = {
      id: ModuleID
    }

    const response: Awaited<dependencies[]> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "dependencies",
        },
        {
          operation: "id",
        },
      ],
      await this._ctx.connection()
    )

    return response.map(
      (r) =>
        new Module_(
          {
            queryTree: [
              {
                operation: "loadModule_FromID",
                args: { id: r.id },
              },
            ],
            ctx: this._ctx,
          },
          r.id
        )
    )
  }
  dependencyConfig = async (): Promise<ModuleDependency[]> => {
    type dependencyConfig = {
      id: ModuleDependencyID
    }

    const response: Awaited<dependencyConfig[]> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "dependencyConfig",
        },
        {
          operation: "id",
        },
      ],
      await this._ctx.connection()
    )

    return response.map(
      (r) =>
        new ModuleDependency(
          {
            queryTree: [
              {
                operation: "loadModuleDependencyFromID",
                args: { id: r.id },
              },
            ],
            ctx: this._ctx,
          },
          r.id
        )
    )
  }
  description = async (): Promise<string> => {
    if (this._description) {
      return this._description
    }

    const response: Awaited<string> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "description",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }

  /**
   * The module's root directory containing the config file for it and its source (possibly as a subdir). It includes any generated code or updated config files created after initial load, but not any files/directories that were unchanged after sdk codegen was run.
   */
  generatedSourceRootDirectory = (): Directory => {
    return new Directory({
      queryTree: [
        ...this._queryTree,
        {
          operation: "generatedSourceRootDirectory",
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Retrieves the module with the objects loaded via its SDK.
   */
  initialize = (): Module_ => {
    return new Module_({
      queryTree: [
        ...this._queryTree,
        {
          operation: "initialize",
        },
      ],
      ctx: this._ctx,
    })
  }
  interfaces = async (): Promise<TypeDef[]> => {
    type interfaces = {
      id: TypeDefID
    }

    const response: Awaited<interfaces[]> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "interfaces",
        },
        {
          operation: "id",
        },
      ],
      await this._ctx.connection()
    )

    return response.map(
      (r) =>
        new TypeDef(
          {
            queryTree: [
              {
                operation: "loadTypeDefFromID",
                args: { id: r.id },
              },
            ],
            ctx: this._ctx,
          },
          r.id
        )
    )
  }
  name = async (): Promise<string> => {
    if (this._name) {
      return this._name
    }

    const response: Awaited<string> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "name",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }
  objects = async (): Promise<TypeDef[]> => {
    type objects = {
      id: TypeDefID
    }

    const response: Awaited<objects[]> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "objects",
        },
        {
          operation: "id",
        },
      ],
      await this._ctx.connection()
    )

    return response.map(
      (r) =>
        new TypeDef(
          {
            queryTree: [
              {
                operation: "loadTypeDefFromID",
                args: { id: r.id },
              },
            ],
            ctx: this._ctx,
          },
          r.id
        )
    )
  }
  runtime = (): Container => {
    return new Container({
      queryTree: [
        ...this._queryTree,
        {
          operation: "runtime",
        },
      ],
      ctx: this._ctx,
    })
  }
  sdk = async (): Promise<string> => {
    if (this._sdk) {
      return this._sdk
    }

    const response: Awaited<string> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "sdk",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }

  /**
   * Serve a module's API in the current session.
   *
   * Note: this can only be called once per session. In the future, it could return a stream or service to remove the side effect.
   */
  serve = async (): Promise<Void> => {
    if (this._serve) {
      return this._serve
    }

    const response: Awaited<Void> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "serve",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }
  source = (): ModuleSource => {
    return new ModuleSource({
      queryTree: [
        ...this._queryTree,
        {
          operation: "source",
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Update the module configuration to use the given dependencies.
   * @param dependencies The dependency modules to install.
   */
  withDependencies = (dependencies: ModuleDependency[]): Module_ => {
    return new Module_({
      queryTree: [
        ...this._queryTree,
        {
          operation: "withDependencies",
          args: { dependencies },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Retrieves the module with the given description
   * @param description The description to set
   */
  withDescription = (description: string): Module_ => {
    return new Module_({
      queryTree: [
        ...this._queryTree,
        {
          operation: "withDescription",
          args: { description },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * This module plus the given Interface type and associated functions
   */
  withInterface = (iface: TypeDef): Module_ => {
    return new Module_({
      queryTree: [
        ...this._queryTree,
        {
          operation: "withInterface",
          args: { iface },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Update the module configuration to use the given name.
   * @param name The name to use.
   */
  withName = (name: string): Module_ => {
    return new Module_({
      queryTree: [
        ...this._queryTree,
        {
          operation: "withName",
          args: { name },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * This module plus the given Object type and associated functions.
   */
  withObject = (object: TypeDef): Module_ => {
    return new Module_({
      queryTree: [
        ...this._queryTree,
        {
          operation: "withObject",
          args: { object },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Update the module configuration to use the given SDK.
   * @param sdk The SDK to use.
   */
  withSDK = (sdk: string): Module_ => {
    return new Module_({
      queryTree: [
        ...this._queryTree,
        {
          operation: "withSDK",
          args: { sdk },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Retrieves the module with basic configuration loaded if present.
   * @param source The module source to initialize from.
   */
  withSource = (source: ModuleSource): Module_ => {
    return new Module_({
      queryTree: [
        ...this._queryTree,
        {
          operation: "withSource",
          args: { source },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Call the provided function with current Module.
   *
   * This is useful for reusability and readability by not breaking the calling chain.
   */
  with = (arg: (param: Module_) => Module_) => {
    return arg(this)
  }
}

/**
 * The configuration of dependency of a module.
 */
export class ModuleDependency extends BaseClient {
  private readonly _id?: ModuleDependencyID = undefined
  private readonly _name?: string = undefined

  /**
   * Constructor is used for internal usage only, do not create object from it.
   */
  constructor(
    parent?: { queryTree?: QueryTree[]; ctx: Context },
    _id?: ModuleDependencyID,
    _name?: string
  ) {
    super(parent)

    this._id = _id
    this._name = _name
  }

  /**
   * A unique identifier for this ModuleDependency.
   */
  id = async (): Promise<ModuleDependencyID> => {
    if (this._id) {
      return this._id
    }

    const response: Awaited<ModuleDependencyID> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "id",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }
  name = async (): Promise<string> => {
    if (this._name) {
      return this._name
    }

    const response: Awaited<string> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "name",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }
  source = (): ModuleSource => {
    return new ModuleSource({
      queryTree: [
        ...this._queryTree,
        {
          operation: "source",
        },
      ],
      ctx: this._ctx,
    })
  }
}

/**
 * The source needed to load and run a module, along with any metadata about the source such as versions/urls/etc.
 */
export class ModuleSource extends BaseClient {
  private readonly _id?: ModuleSourceID = undefined
  private readonly _asString?: string = undefined
  private readonly _kind?: ModuleSourceKind = undefined
  private readonly _moduleName?: string = undefined
  private readonly _subpath?: string = undefined

  /**
   * Constructor is used for internal usage only, do not create object from it.
   */
  constructor(
    parent?: { queryTree?: QueryTree[]; ctx: Context },
    _id?: ModuleSourceID,
    _asString?: string,
    _kind?: ModuleSourceKind,
    _moduleName?: string,
    _subpath?: string
  ) {
    super(parent)

    this._id = _id
    this._asString = _asString
    this._kind = _kind
    this._moduleName = _moduleName
    this._subpath = _subpath
  }

  /**
   * A unique identifier for this ModuleSource.
   */
  id = async (): Promise<ModuleSourceID> => {
    if (this._id) {
      return this._id
    }

    const response: Awaited<ModuleSourceID> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "id",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }
  asGitSource = (): GitModuleSource => {
    return new GitModuleSource({
      queryTree: [
        ...this._queryTree,
        {
          operation: "asGitSource",
        },
      ],
      ctx: this._ctx,
    })
  }
  asLocalSource = (): LocalModuleSource => {
    return new LocalModuleSource({
      queryTree: [
        ...this._queryTree,
        {
          operation: "asLocalSource",
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Load the source as a module. If this is a local source, the parent directory must have been provided during module source creation
   */
  asModule = (): Module_ => {
    return new Module_({
      queryTree: [
        ...this._queryTree,
        {
          operation: "asModule",
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * A human readable ref string representation of this module source.
   */
  asString = async (): Promise<string> => {
    if (this._asString) {
      return this._asString
    }

    const response: Awaited<string> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "asString",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }

  /**
   * The directory containing the actual module's source code, as determined from the root directory and subpath.
   * @param path The path from the source directory to select.
   */
  directory = (path: string): Directory => {
    return new Directory({
      queryTree: [
        ...this._queryTree,
        {
          operation: "directory",
          args: { path },
        },
      ],
      ctx: this._ctx,
    })
  }
  kind = async (): Promise<ModuleSourceKind> => {
    if (this._kind) {
      return this._kind
    }

    const response: Awaited<ModuleSourceKind> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "kind",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }

  /**
   * If set, the name of the module this source references
   */
  moduleName = async (): Promise<string> => {
    if (this._moduleName) {
      return this._moduleName
    }

    const response: Awaited<string> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "moduleName",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }

  /**
   * Resolve the provided module source arg as a dependency relative to this module source.
   * @param dep The dependency module source to resolve.
   */
  resolveDependency = (dep: ModuleSource): ModuleSource => {
    return new ModuleSource({
      queryTree: [
        ...this._queryTree,
        {
          operation: "resolveDependency",
          args: { dep },
        },
      ],
      ctx: this._ctx,
    })
  }
  rootDirectory = (): Directory => {
    return new Directory({
      queryTree: [
        ...this._queryTree,
        {
          operation: "rootDirectory",
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * The path to the module subdirectory containing the actual module's source code.
   */
  subpath = async (): Promise<string> => {
    if (this._subpath) {
      return this._subpath
    }

    const response: Awaited<string> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "subpath",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }

  /**
   * Call the provided function with current ModuleSource.
   *
   * This is useful for reusability and readability by not breaking the calling chain.
   */
  with = (arg: (param: ModuleSource) => ModuleSource) => {
    return arg(this)
  }
}

/**
 * A definition of a custom object defined in a Module.
 */
export class ObjectTypeDef extends BaseClient {
  private readonly _id?: ObjectTypeDefID = undefined
  private readonly _description?: string = undefined
  private readonly _name?: string = undefined
  private readonly _sourceModuleName?: string = undefined

  /**
   * Constructor is used for internal usage only, do not create object from it.
   */
  constructor(
    parent?: { queryTree?: QueryTree[]; ctx: Context },
    _id?: ObjectTypeDefID,
    _description?: string,
    _name?: string,
    _sourceModuleName?: string
  ) {
    super(parent)

    this._id = _id
    this._description = _description
    this._name = _name
    this._sourceModuleName = _sourceModuleName
  }

  /**
   * A unique identifier for this ObjectTypeDef.
   */
  id = async (): Promise<ObjectTypeDefID> => {
    if (this._id) {
      return this._id
    }

    const response: Awaited<ObjectTypeDefID> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "id",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }
  constructor_ = (): Function_ => {
    return new Function_({
      queryTree: [
        ...this._queryTree,
        {
          operation: "constructor",
        },
      ],
      ctx: this._ctx,
    })
  }
  description = async (): Promise<string> => {
    if (this._description) {
      return this._description
    }

    const response: Awaited<string> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "description",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }
  fields = async (): Promise<FieldTypeDef[]> => {
    type fields = {
      id: FieldTypeDefID
    }

    const response: Awaited<fields[]> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "fields",
        },
        {
          operation: "id",
        },
      ],
      await this._ctx.connection()
    )

    return response.map(
      (r) =>
        new FieldTypeDef(
          {
            queryTree: [
              {
                operation: "loadFieldTypeDefFromID",
                args: { id: r.id },
              },
            ],
            ctx: this._ctx,
          },
          r.id
        )
    )
  }
  functions = async (): Promise<Function_[]> => {
    type functions = {
      id: FunctionID
    }

    const response: Awaited<functions[]> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "functions",
        },
        {
          operation: "id",
        },
      ],
      await this._ctx.connection()
    )

    return response.map(
      (r) =>
        new Function_(
          {
            queryTree: [
              {
                operation: "loadFunction_FromID",
                args: { id: r.id },
              },
            ],
            ctx: this._ctx,
          },
          r.id
        )
    )
  }
  name = async (): Promise<string> => {
    if (this._name) {
      return this._name
    }

    const response: Awaited<string> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "name",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }
  sourceModuleName = async (): Promise<string> => {
    if (this._sourceModuleName) {
      return this._sourceModuleName
    }

    const response: Awaited<string> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "sourceModuleName",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }
}

/**
 * A port exposed by a container.
 */
export class Port extends BaseClient {
  private readonly _id?: PortID = undefined
  private readonly _description?: string = undefined
  private readonly _experimentalSkipHealthcheck?: boolean = undefined
  private readonly _port?: number = undefined
  private readonly _protocol?: NetworkProtocol = undefined

  /**
   * Constructor is used for internal usage only, do not create object from it.
   */
  constructor(
    parent?: { queryTree?: QueryTree[]; ctx: Context },
    _id?: PortID,
    _description?: string,
    _experimentalSkipHealthcheck?: boolean,
    _port?: number,
    _protocol?: NetworkProtocol
  ) {
    super(parent)

    this._id = _id
    this._description = _description
    this._experimentalSkipHealthcheck = _experimentalSkipHealthcheck
    this._port = _port
    this._protocol = _protocol
  }

  /**
   * A unique identifier for this Port.
   */
  id = async (): Promise<PortID> => {
    if (this._id) {
      return this._id
    }

    const response: Awaited<PortID> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "id",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }
  description = async (): Promise<string> => {
    if (this._description) {
      return this._description
    }

    const response: Awaited<string> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "description",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }
  experimentalSkipHealthcheck = async (): Promise<boolean> => {
    if (this._experimentalSkipHealthcheck) {
      return this._experimentalSkipHealthcheck
    }

    const response: Awaited<boolean> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "experimentalSkipHealthcheck",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }
  port = async (): Promise<number> => {
    if (this._port) {
      return this._port
    }

    const response: Awaited<number> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "port",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }
  protocol = async (): Promise<NetworkProtocol> => {
    if (this._protocol) {
      return this._protocol
    }

    const response: Awaited<NetworkProtocol> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "protocol",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }
}

/**
 * The root of the DAG.
 */
export class Client extends BaseClient {
  private readonly _checkVersionCompatibility?: boolean = undefined
  private readonly _defaultPlatform?: Platform = undefined

  /**
   * Constructor is used for internal usage only, do not create object from it.
   */
  constructor(
    parent?: { queryTree?: QueryTree[]; ctx: Context },
    _checkVersionCompatibility?: boolean,
    _defaultPlatform?: Platform
  ) {
    super(parent)

    this._checkVersionCompatibility = _checkVersionCompatibility
    this._defaultPlatform = _defaultPlatform
  }

  /**
   * Retrieves a content-addressed blob.
   * @param digest Digest of the blob
   * @param size Size of the blob
   * @param mediaType Media type of the blob
   * @param uncompressed Digest of the uncompressed blob
   */
  blob = (
    digest: string,
    size: number,
    mediaType: string,
    uncompressed: string
  ): Directory => {
    return new Directory({
      queryTree: [
        ...this._queryTree,
        {
          operation: "blob",
          args: { digest, size, mediaType, uncompressed },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Constructs a cache volume for a given cache key.
   * @param key A string identifier to target this cache volume (e.g., "modules-cache").
   */
  cacheVolume = (key: string): CacheVolume => {
    return new CacheVolume({
      queryTree: [
        ...this._queryTree,
        {
          operation: "cacheVolume",
          args: { key },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Checks if the current Dagger Engine is compatible with an SDK's required version.
   * @param version Version required by the SDK.
   */
  checkVersionCompatibility = async (version: string): Promise<boolean> => {
    const response: Awaited<boolean> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "checkVersionCompatibility",
          args: { version },
        },
      ],
      await this._ctx.connection()
    )

    return response
  }

  /**
   * Creates a scratch container.
   *
   * Optional platform argument initializes new containers to execute and publish as that platform. Platform defaults to that of the builder's host.
   * @param opts.id DEPRECATED: Use `loadContainerFromID` instead.
   * @param opts.platform Platform to initialize the container with.
   */
  container = (opts?: ClientContainerOpts): Container => {
    return new Container({
      queryTree: [
        ...this._queryTree,
        {
          operation: "container",
          args: { ...opts },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * The FunctionCall context that the SDK caller is currently executing in.
   *
   * If the caller is not currently executing in a function, this will return an error.
   */
  currentFunctionCall = (): FunctionCall => {
    return new FunctionCall({
      queryTree: [
        ...this._queryTree,
        {
          operation: "currentFunctionCall",
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * The module currently being served in the session, if any.
   */
  currentModule = (): CurrentModule => {
    return new CurrentModule({
      queryTree: [
        ...this._queryTree,
        {
          operation: "currentModule",
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * The TypeDef representations of the objects currently being served in the session.
   */
  currentTypeDefs = async (): Promise<TypeDef[]> => {
    type currentTypeDefs = {
      id: TypeDefID
    }

    const response: Awaited<currentTypeDefs[]> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "currentTypeDefs",
        },
        {
          operation: "id",
        },
      ],
      await this._ctx.connection()
    )

    return response.map(
      (r) =>
        new TypeDef(
          {
            queryTree: [
              {
                operation: "loadTypeDefFromID",
                args: { id: r.id },
              },
            ],
            ctx: this._ctx,
          },
          r.id
        )
    )
  }

  /**
   * The default platform of the engine.
   */
  defaultPlatform = async (): Promise<Platform> => {
    const response: Awaited<Platform> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "defaultPlatform",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }

  /**
   * Creates an empty directory.
   * @param opts.id DEPRECATED: Use `loadDirectoryFromID` isntead.
   */
  directory = (opts?: ClientDirectoryOpts): Directory => {
    return new Directory({
      queryTree: [
        ...this._queryTree,
        {
          operation: "directory",
          args: { ...opts },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * @deprecated Use loadFileFromID instead.
   */
  file = (id: FileID): File => {
    return new File({
      queryTree: [
        ...this._queryTree,
        {
          operation: "file",
          args: { id },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Creates a function.
   * @param name Name of the function, in its original format from the implementation language.
   * @param returnType Return type of the function.
   */
  function_ = (name: string, returnType: TypeDef): Function_ => {
    return new Function_({
      queryTree: [
        ...this._queryTree,
        {
          operation: "function",
          args: { name, returnType },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Create a code generation result, given a directory containing the generated code.
   */
  generatedCode = (code: Directory): GeneratedCode => {
    return new GeneratedCode({
      queryTree: [
        ...this._queryTree,
        {
          operation: "generatedCode",
          args: { code },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Queries a Git repository.
   * @param url URL of the git repository.
   *
   * Can be formatted as `https://{host}/{owner}/{repo}`, `git@{host}:{owner}/{repo}`.
   *
   * Suffix ".git" is optional.
   * @param opts.keepGitDir Set to true to keep .git directory.
   * @param opts.experimentalServiceHost A service which must be started before the repo is fetched.
   * @param opts.sshKnownHosts Set SSH known hosts
   * @param opts.sshAuthSocket Set SSH auth socket
   */
  git = (url: string, opts?: ClientGitOpts): GitRepository => {
    return new GitRepository({
      queryTree: [
        ...this._queryTree,
        {
          operation: "git",
          args: { url, ...opts },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Queries the host environment.
   */
  host = (): Host => {
    return new Host({
      queryTree: [
        ...this._queryTree,
        {
          operation: "host",
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Returns a file containing an http remote url content.
   * @param url HTTP url to get the content from (e.g., "https://docs.dagger.io").
   * @param opts.experimentalServiceHost A service which must be started before the URL is fetched.
   */
  http = (url: string, opts?: ClientHttpOpts): File => {
    return new File({
      queryTree: [
        ...this._queryTree,
        {
          operation: "http",
          args: { url, ...opts },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Load a CacheVolume from its ID.
   */
  loadCacheVolumeFromID = (id: CacheVolumeID): CacheVolume => {
    return new CacheVolume({
      queryTree: [
        ...this._queryTree,
        {
          operation: "loadCacheVolumeFromID",
          args: { id },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Load a Container from its ID.
   */
  loadContainerFromID = (id: ContainerID): Container => {
    return new Container({
      queryTree: [
        ...this._queryTree,
        {
          operation: "loadContainerFromID",
          args: { id },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Load a CurrentModule from its ID.
   */
  loadCurrentModuleFromID = (id: CurrentModuleID): CurrentModule => {
    return new CurrentModule({
      queryTree: [
        ...this._queryTree,
        {
          operation: "loadCurrentModuleFromID",
          args: { id },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Load a Directory from its ID.
   */
  loadDirectoryFromID = (id: DirectoryID): Directory => {
    return new Directory({
      queryTree: [
        ...this._queryTree,
        {
          operation: "loadDirectoryFromID",
          args: { id },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Load a EnvVariable from its ID.
   */
  loadEnvVariableFromID = (id: EnvVariableID): EnvVariable => {
    return new EnvVariable({
      queryTree: [
        ...this._queryTree,
        {
          operation: "loadEnvVariableFromID",
          args: { id },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Load a FieldTypeDef from its ID.
   */
  loadFieldTypeDefFromID = (id: FieldTypeDefID): FieldTypeDef => {
    return new FieldTypeDef({
      queryTree: [
        ...this._queryTree,
        {
          operation: "loadFieldTypeDefFromID",
          args: { id },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Load a File from its ID.
   */
  loadFileFromID = (id: FileID): File => {
    return new File({
      queryTree: [
        ...this._queryTree,
        {
          operation: "loadFileFromID",
          args: { id },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Load a FunctionArg from its ID.
   */
  loadFunctionArgFromID = (id: FunctionArgID): FunctionArg => {
    return new FunctionArg({
      queryTree: [
        ...this._queryTree,
        {
          operation: "loadFunctionArgFromID",
          args: { id },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Load a FunctionCallArgValue from its ID.
   */
  loadFunctionCallArgValueFromID = (
    id: FunctionCallArgValueID
  ): FunctionCallArgValue => {
    return new FunctionCallArgValue({
      queryTree: [
        ...this._queryTree,
        {
          operation: "loadFunctionCallArgValueFromID",
          args: { id },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Load a FunctionCall from its ID.
   */
  loadFunctionCallFromID = (id: FunctionCallID): FunctionCall => {
    return new FunctionCall({
      queryTree: [
        ...this._queryTree,
        {
          operation: "loadFunctionCallFromID",
          args: { id },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Load a Function from its ID.
   */
  loadFunctionFromID = (id: FunctionID): Function_ => {
    return new Function_({
      queryTree: [
        ...this._queryTree,
        {
          operation: "loadFunctionFromID",
          args: { id },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Load a GeneratedCode from its ID.
   */
  loadGeneratedCodeFromID = (id: GeneratedCodeID): GeneratedCode => {
    return new GeneratedCode({
      queryTree: [
        ...this._queryTree,
        {
          operation: "loadGeneratedCodeFromID",
          args: { id },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Load a GitModuleSource from its ID.
   */
  loadGitModuleSourceFromID = (id: GitModuleSourceID): GitModuleSource => {
    return new GitModuleSource({
      queryTree: [
        ...this._queryTree,
        {
          operation: "loadGitModuleSourceFromID",
          args: { id },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Load a GitRef from its ID.
   */
  loadGitRefFromID = (id: GitRefID): GitRef => {
    return new GitRef({
      queryTree: [
        ...this._queryTree,
        {
          operation: "loadGitRefFromID",
          args: { id },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Load a GitRepository from its ID.
   */
  loadGitRepositoryFromID = (id: GitRepositoryID): GitRepository => {
    return new GitRepository({
      queryTree: [
        ...this._queryTree,
        {
          operation: "loadGitRepositoryFromID",
          args: { id },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Load a Host from its ID.
   */
  loadHostFromID = (id: HostID): Host => {
    return new Host({
      queryTree: [
        ...this._queryTree,
        {
          operation: "loadHostFromID",
          args: { id },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Load a InputTypeDef from its ID.
   */
  loadInputTypeDefFromID = (id: InputTypeDefID): InputTypeDef => {
    return new InputTypeDef({
      queryTree: [
        ...this._queryTree,
        {
          operation: "loadInputTypeDefFromID",
          args: { id },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Load a InterfaceTypeDef from its ID.
   */
  loadInterfaceTypeDefFromID = (id: InterfaceTypeDefID): InterfaceTypeDef => {
    return new InterfaceTypeDef({
      queryTree: [
        ...this._queryTree,
        {
          operation: "loadInterfaceTypeDefFromID",
          args: { id },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Load a Label from its ID.
   */
  loadLabelFromID = (id: LabelID): Label => {
    return new Label({
      queryTree: [
        ...this._queryTree,
        {
          operation: "loadLabelFromID",
          args: { id },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Load a ListTypeDef from its ID.
   */
  loadListTypeDefFromID = (id: ListTypeDefID): ListTypeDef => {
    return new ListTypeDef({
      queryTree: [
        ...this._queryTree,
        {
          operation: "loadListTypeDefFromID",
          args: { id },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Load a LocalModuleSource from its ID.
   */
  loadLocalModuleSourceFromID = (
    id: LocalModuleSourceID
  ): LocalModuleSource => {
    return new LocalModuleSource({
      queryTree: [
        ...this._queryTree,
        {
          operation: "loadLocalModuleSourceFromID",
          args: { id },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Load a ModuleDependency from its ID.
   */
  loadModuleDependencyFromID = (id: ModuleDependencyID): ModuleDependency => {
    return new ModuleDependency({
      queryTree: [
        ...this._queryTree,
        {
          operation: "loadModuleDependencyFromID",
          args: { id },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Load a Module from its ID.
   */
  loadModuleFromID = (id: ModuleID): Module_ => {
    return new Module_({
      queryTree: [
        ...this._queryTree,
        {
          operation: "loadModuleFromID",
          args: { id },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Load a ModuleSource from its ID.
   */
  loadModuleSourceFromID = (id: ModuleSourceID): ModuleSource => {
    return new ModuleSource({
      queryTree: [
        ...this._queryTree,
        {
          operation: "loadModuleSourceFromID",
          args: { id },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Load a ObjectTypeDef from its ID.
   */
  loadObjectTypeDefFromID = (id: ObjectTypeDefID): ObjectTypeDef => {
    return new ObjectTypeDef({
      queryTree: [
        ...this._queryTree,
        {
          operation: "loadObjectTypeDefFromID",
          args: { id },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Load a Port from its ID.
   */
  loadPortFromID = (id: PortID): Port => {
    return new Port({
      queryTree: [
        ...this._queryTree,
        {
          operation: "loadPortFromID",
          args: { id },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Load a Secret from its ID.
   */
  loadSecretFromID = (id: SecretID): Secret => {
    return new Secret({
      queryTree: [
        ...this._queryTree,
        {
          operation: "loadSecretFromID",
          args: { id },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Load a Service from its ID.
   */
  loadServiceFromID = (id: ServiceID): Service => {
    return new Service({
      queryTree: [
        ...this._queryTree,
        {
          operation: "loadServiceFromID",
          args: { id },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Load a Socket from its ID.
   */
  loadSocketFromID = (id: SocketID): Socket => {
    return new Socket({
      queryTree: [
        ...this._queryTree,
        {
          operation: "loadSocketFromID",
          args: { id },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Load a Terminal from its ID.
   */
  loadTerminalFromID = (id: TerminalID): Terminal => {
    return new Terminal({
      queryTree: [
        ...this._queryTree,
        {
          operation: "loadTerminalFromID",
          args: { id },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Load a TypeDef from its ID.
   */
  loadTypeDefFromID = (id: TypeDefID): TypeDef => {
    return new TypeDef({
      queryTree: [
        ...this._queryTree,
        {
          operation: "loadTypeDefFromID",
          args: { id },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Create a new module.
   */
  module_ = (): Module_ => {
    return new Module_({
      queryTree: [
        ...this._queryTree,
        {
          operation: "module",
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Create a new module dependency configuration from a module source and name
   * @param source The source of the dependency
   * @param opts.name If set, the name to use for the dependency. Otherwise, once installed to a parent module, the name of the dependency module will be used by default.
   */
  moduleDependency = (
    source: ModuleSource,
    opts?: ClientModuleDependencyOpts
  ): ModuleDependency => {
    return new ModuleDependency({
      queryTree: [
        ...this._queryTree,
        {
          operation: "moduleDependency",
          args: { source, ...opts },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Create a new module source instance from a source ref string.
   * @param refString The string ref representation of the module source
   * @param opts.rootDirectory An explicitly set root directory for the module source. This is required to load local sources as modules; other source types implicitly encode the root directory and do not require this.
   * @param opts.stable If true, enforce that the source is a stable version for source kinds that support versioning.
   */
  moduleSource = (
    refString: string,
    opts?: ClientModuleSourceOpts
  ): ModuleSource => {
    return new ModuleSource({
      queryTree: [
        ...this._queryTree,
        {
          operation: "moduleSource",
          args: { refString, ...opts },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Creates a named sub-pipeline.
   * @param name Name of the sub-pipeline.
   * @param opts.description Description of the sub-pipeline.
   * @param opts.labels Labels to apply to the sub-pipeline.
   */
  pipeline = (name: string, opts?: ClientPipelineOpts): Client => {
    return new Client({
      queryTree: [
        ...this._queryTree,
        {
          operation: "pipeline",
          args: { name, ...opts },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Reference a secret by name.
   */
  secret = (name: string): Secret => {
    return new Secret({
      queryTree: [
        ...this._queryTree,
        {
          operation: "secret",
          args: { name },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Sets a secret given a user defined name to its plaintext and returns the secret.
   *
   * The plaintext value is limited to a size of 128000 bytes.
   * @param name The user defined name for this secret
   * @param plaintext The plaintext of the secret
   */
  setSecret = (name: string, plaintext: string): Secret => {
    return new Secret({
      queryTree: [
        ...this._queryTree,
        {
          operation: "setSecret",
          args: { name, plaintext },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Loads a socket by its ID.
   * @deprecated Use loadSocketFromID instead.
   */
  socket = (id: SocketID): Socket => {
    return new Socket({
      queryTree: [
        ...this._queryTree,
        {
          operation: "socket",
          args: { id },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Create a new TypeDef.
   */
  typeDef = (): TypeDef => {
    return new TypeDef({
      queryTree: [
        ...this._queryTree,
        {
          operation: "typeDef",
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Call the provided function with current Client.
   *
   * This is useful for reusability and readability by not breaking the calling chain.
   */
  with = (arg: (param: Client) => Client) => {
    return arg(this)
  }
}

/**
 * A reference to a secret value, which can be handled more safely than the value itself.
 */
export class Secret extends BaseClient {
  private readonly _id?: SecretID = undefined
  private readonly _plaintext?: string = undefined

  /**
   * Constructor is used for internal usage only, do not create object from it.
   */
  constructor(
    parent?: { queryTree?: QueryTree[]; ctx: Context },
    _id?: SecretID,
    _plaintext?: string
  ) {
    super(parent)

    this._id = _id
    this._plaintext = _plaintext
  }

  /**
   * A unique identifier for this Secret.
   */
  id = async (): Promise<SecretID> => {
    if (this._id) {
      return this._id
    }

    const response: Awaited<SecretID> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "id",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }

  /**
   * The value of this secret.
   */
  plaintext = async (): Promise<string> => {
    if (this._plaintext) {
      return this._plaintext
    }

    const response: Awaited<string> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "plaintext",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }
}

/**
 * A content-addressed service providing TCP connectivity.
 */
export class Service extends BaseClient {
  private readonly _id?: ServiceID = undefined
  private readonly _endpoint?: string = undefined
  private readonly _hostname?: string = undefined
  private readonly _start?: ServiceID = undefined
  private readonly _stop?: ServiceID = undefined
  private readonly _up?: Void = undefined

  /**
   * Constructor is used for internal usage only, do not create object from it.
   */
  constructor(
    parent?: { queryTree?: QueryTree[]; ctx: Context },
    _id?: ServiceID,
    _endpoint?: string,
    _hostname?: string,
    _start?: ServiceID,
    _stop?: ServiceID,
    _up?: Void
  ) {
    super(parent)

    this._id = _id
    this._endpoint = _endpoint
    this._hostname = _hostname
    this._start = _start
    this._stop = _stop
    this._up = _up
  }

  /**
   * A unique identifier for this Service.
   */
  id = async (): Promise<ServiceID> => {
    if (this._id) {
      return this._id
    }

    const response: Awaited<ServiceID> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "id",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }

  /**
   * Retrieves an endpoint that clients can use to reach this container.
   *
   * If no port is specified, the first exposed port is used. If none exist an error is returned.
   *
   * If a scheme is specified, a URL is returned. Otherwise, a host:port pair is returned.
   * @param opts.port The exposed port number for the endpoint
   * @param opts.scheme Return a URL with the given scheme, eg. http for http://
   */
  endpoint = async (opts?: ServiceEndpointOpts): Promise<string> => {
    if (this._endpoint) {
      return this._endpoint
    }

    const response: Awaited<string> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "endpoint",
          args: { ...opts },
        },
      ],
      await this._ctx.connection()
    )

    return response
  }

  /**
   * Retrieves a hostname which can be used by clients to reach this container.
   */
  hostname = async (): Promise<string> => {
    if (this._hostname) {
      return this._hostname
    }

    const response: Awaited<string> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "hostname",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }

  /**
   * Retrieves the list of ports provided by the service.
   */
  ports = async (): Promise<Port[]> => {
    type ports = {
      id: PortID
    }

    const response: Awaited<ports[]> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "ports",
        },
        {
          operation: "id",
        },
      ],
      await this._ctx.connection()
    )

    return response.map(
      (r) =>
        new Port(
          {
            queryTree: [
              {
                operation: "loadPortFromID",
                args: { id: r.id },
              },
            ],
            ctx: this._ctx,
          },
          r.id
        )
    )
  }

  /**
   * Start the service and wait for its health checks to succeed.
   *
   * Services bound to a Container do not need to be manually started.
   */
  start = async (): Promise<Service> => {
    await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "start",
        },
      ],
      await this._ctx.connection()
    )

    return this
  }

  /**
   * Stop the service.
   * @param opts.kill Immediately kill the service without waiting for a graceful exit
   */
  stop = async (opts?: ServiceStopOpts): Promise<Service> => {
    await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "stop",
          args: { ...opts },
        },
      ],
      await this._ctx.connection()
    )

    return this
  }

  /**
   * Creates a tunnel that forwards traffic from the caller's network to this service.
   */
  up = async (opts?: ServiceUpOpts): Promise<Void> => {
    if (this._up) {
      return this._up
    }

    const response: Awaited<Void> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "up",
          args: { ...opts },
        },
      ],
      await this._ctx.connection()
    )

    return response
  }
}

/**
 * A Unix or TCP/IP socket that can be mounted into a container.
 */
export class Socket extends BaseClient {
  private readonly _id?: SocketID = undefined

  /**
   * Constructor is used for internal usage only, do not create object from it.
   */
  constructor(
    parent?: { queryTree?: QueryTree[]; ctx: Context },
    _id?: SocketID
  ) {
    super(parent)

    this._id = _id
  }

  /**
   * A unique identifier for this Socket.
   */
  id = async (): Promise<SocketID> => {
    if (this._id) {
      return this._id
    }

    const response: Awaited<SocketID> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "id",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }
}

/**
 * An interactive terminal that clients can connect to.
 */
export class Terminal extends BaseClient {
  private readonly _id?: TerminalID = undefined
  private readonly _websocketEndpoint?: string = undefined

  /**
   * Constructor is used for internal usage only, do not create object from it.
   */
  constructor(
    parent?: { queryTree?: QueryTree[]; ctx: Context },
    _id?: TerminalID,
    _websocketEndpoint?: string
  ) {
    super(parent)

    this._id = _id
    this._websocketEndpoint = _websocketEndpoint
  }

  /**
   * A unique identifier for this Terminal.
   */
  id = async (): Promise<TerminalID> => {
    if (this._id) {
      return this._id
    }

    const response: Awaited<TerminalID> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "id",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }

  /**
   * An http endpoint at which this terminal can be connected to over a websocket.
   */
  websocketEndpoint = async (): Promise<string> => {
    if (this._websocketEndpoint) {
      return this._websocketEndpoint
    }

    const response: Awaited<string> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "websocketEndpoint",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }
}

/**
 * A definition of a parameter or return type in a Module.
 */
export class TypeDef extends BaseClient {
  private readonly _id?: TypeDefID = undefined
  private readonly _kind?: TypeDefKind = undefined
  private readonly _optional?: boolean = undefined

  /**
   * Constructor is used for internal usage only, do not create object from it.
   */
  constructor(
    parent?: { queryTree?: QueryTree[]; ctx: Context },
    _id?: TypeDefID,
    _kind?: TypeDefKind,
    _optional?: boolean
  ) {
    super(parent)

    this._id = _id
    this._kind = _kind
    this._optional = _optional
  }

  /**
   * A unique identifier for this TypeDef.
   */
  id = async (): Promise<TypeDefID> => {
    if (this._id) {
      return this._id
    }

    const response: Awaited<TypeDefID> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "id",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }
  asInput = (): InputTypeDef => {
    return new InputTypeDef({
      queryTree: [
        ...this._queryTree,
        {
          operation: "asInput",
        },
      ],
      ctx: this._ctx,
    })
  }
  asInterface = (): InterfaceTypeDef => {
    return new InterfaceTypeDef({
      queryTree: [
        ...this._queryTree,
        {
          operation: "asInterface",
        },
      ],
      ctx: this._ctx,
    })
  }
  asList = (): ListTypeDef => {
    return new ListTypeDef({
      queryTree: [
        ...this._queryTree,
        {
          operation: "asList",
        },
      ],
      ctx: this._ctx,
    })
  }
  asObject = (): ObjectTypeDef => {
    return new ObjectTypeDef({
      queryTree: [
        ...this._queryTree,
        {
          operation: "asObject",
        },
      ],
      ctx: this._ctx,
    })
  }
  kind = async (): Promise<TypeDefKind> => {
    if (this._kind) {
      return this._kind
    }

    const response: Awaited<TypeDefKind> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "kind",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }
  optional = async (): Promise<boolean> => {
    if (this._optional) {
      return this._optional
    }

    const response: Awaited<boolean> = await computeQuery(
      [
        ...this._queryTree,
        {
          operation: "optional",
        },
      ],
      await this._ctx.connection()
    )

    return response
  }

  /**
   * Adds a function for constructing a new instance of an Object TypeDef, failing if the type is not an object.
   */
  withConstructor = (function_: Function_): TypeDef => {
    return new TypeDef({
      queryTree: [
        ...this._queryTree,
        {
          operation: "withConstructor",
          args: {
            function: function_,
          },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Adds a static field for an Object TypeDef, failing if the type is not an object.
   * @param name The name of the field in the object
   * @param typeDef The type of the field
   * @param opts.description A doc string for the field, if any
   */
  withField = (
    name: string,
    typeDef: TypeDef,
    opts?: TypeDefWithFieldOpts
  ): TypeDef => {
    return new TypeDef({
      queryTree: [
        ...this._queryTree,
        {
          operation: "withField",
          args: { name, typeDef, ...opts },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Adds a function for an Object or Interface TypeDef, failing if the type is not one of those kinds.
   */
  withFunction = (function_: Function_): TypeDef => {
    return new TypeDef({
      queryTree: [
        ...this._queryTree,
        {
          operation: "withFunction",
          args: {
            function: function_,
          },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Returns a TypeDef of kind Interface with the provided name.
   */
  withInterface = (name: string, opts?: TypeDefWithInterfaceOpts): TypeDef => {
    return new TypeDef({
      queryTree: [
        ...this._queryTree,
        {
          operation: "withInterface",
          args: { name, ...opts },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Sets the kind of the type.
   */
  withKind = (kind: TypeDefKind): TypeDef => {
    const metadata: Metadata = {
      kind: { is_enum: true },
    }

    return new TypeDef({
      queryTree: [
        ...this._queryTree,
        {
          operation: "withKind",
          args: { kind, __metadata: metadata },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Returns a TypeDef of kind List with the provided type for its elements.
   */
  withListOf = (elementType: TypeDef): TypeDef => {
    return new TypeDef({
      queryTree: [
        ...this._queryTree,
        {
          operation: "withListOf",
          args: { elementType },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Returns a TypeDef of kind Object with the provided name.
   *
   * Note that an object's fields and functions may be omitted if the intent is only to refer to an object. This is how functions are able to return their own object, or any other circular reference.
   */
  withObject = (name: string, opts?: TypeDefWithObjectOpts): TypeDef => {
    return new TypeDef({
      queryTree: [
        ...this._queryTree,
        {
          operation: "withObject",
          args: { name, ...opts },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Sets whether this type can be set to null.
   */
  withOptional = (optional: boolean): TypeDef => {
    return new TypeDef({
      queryTree: [
        ...this._queryTree,
        {
          operation: "withOptional",
          args: { optional },
        },
      ],
      ctx: this._ctx,
    })
  }

  /**
   * Call the provided function with current TypeDef.
   *
   * This is useful for reusability and readability by not breaking the calling chain.
   */
  with = (arg: (param: TypeDef) => TypeDef) => {
    return arg(this)
  }
}

export const dag = new Client({ ctx: defaultContext })
