import type {ContentSourceMapDocuments as ContentSourceMapDocuments_2} from '@sanity/client/csm'
import {ContentSourceMapParsedPath} from '@sanity/client/csm'
import {ContentSourceMapParsedPathKeyedSegment} from '@sanity/client/csm'
import type {HttpContext} from 'get-it'
import {Observable} from 'rxjs'
import {Requester} from 'get-it'
import type {ResolveStudioUrl} from '@sanity/client/csm'
import {StudioBaseRoute} from '@sanity/client/csm'
import {StudioBaseUrl} from '@sanity/client/csm'
import {StudioUrl} from '@sanity/client/csm'
import {adapter as unstable__adapter} from 'get-it'
import {environment as unstable__environment} from 'get-it'

/** @public */
export declare type Action =
  | CreateAction
  | ReplaceDraftAction
  | EditAction
  | DeleteAction
  | DiscardAction
  | PublishAction
  | UnpublishAction
  | VersionAction
  | ReleaseAction

/** @internal */
export declare interface ActionError {
  type: 'actionError'
  description: string
  items?: ActionErrorItem[]
}

/** @internal */
export declare interface ActionErrorItem {
  error: {
    type: string
    description: string
    value?: unknown
  }
  index: number
}

/** @beta */
declare interface AgentActionAsync {
  /**
   * When async: true, requests responds with status 201 and \{_id\} as response body as soon as the request is validated.
   * The instruction operation will carry on in the background.
   *
   * When async: false (default), requests respond with status 200 and the document value after instruction has been applied.
   *
   * async: true is incompatible with noWrite, as async: true does not return the resulting document
   */
  async: true
}

/** @beta */
export declare type AgentActionParam<
  TParamConfig extends {
    docIdRequired: boolean
  } = {
    docIdRequired: false
  },
> =
  | string
  | ConstantAgentActionParam
  | FieldAgentActionParam<TParamConfig>
  | DocumentAgentActionParam<TParamConfig>
  | GroqAgentActionParam

/** @beta */
export declare type AgentActionParams<
  TParamConfig extends {
    docIdRequired: boolean
  } = {
    docIdRequired: false
  },
> = Record<string, AgentActionParam<TParamConfig>>

/**  @beta */
export declare type AgentActionPath = AgentActionPathSegment[]

/**  @beta */
export declare type AgentActionPathSegment =
  | string
  | {
      _key: string
    }

/** @beta */
declare interface AgentActionRequestBase extends AgentActionSchema {
  /**
   * When localeSettings is provided on the request, instruct can write to date and datetime fields.
   * Otherwise, such fields will be ignored.
   */
  localeSettings?: {
    /**
     * A valid Unicode BCP 47 locale identifier used to interpret and format
     * natural language inputs and date output. Examples include "en-US", "fr-FR", or "ja-JP".
     *
     * This affects how phrases like "next Friday" or "in two weeks" are parsed,
     * and how resulting dates are presented (e.g., 12-hour vs 24-hour format).
     *
     * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#getcanonicalocales
     */
    locale: string
    /**
     * A valid IANA time zone identifier used to resolve relative and absolute
     * date expressions to a specific point in time. Examples include
     * "America/New_York", "Europe/Paris", or "Asia/Tokyo".
     *
     * This ensures phrases like "tomorrow at 9am" are interpreted correctly
     * based on the user's local time.
     *
     * @see https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
     */
    timeZone: string
  }
  /**
   * Controls how much variance the instructions will run with.
   *
   * Value must be in the range [0, 1] (inclusive).
   *
   * Defaults:
   * - generate: 0.3
   * - translate: 0
   * - transform: 0
   */
  temperature?: number
}

/** @beta */
declare interface AgentActionSchema {
  /** schemaId as reported by sanity deploy / sanity schema store */
  schemaId: string
  /**
   * ### forcePublishedWrite: false (default)
   * By default, agent actions will never write to a published document.
   *
   * Instead, they will force the use of a draft ID ("drafts.some-id") instead of the published ID ("some-id"),
   * even when a published ID is provided.
   *
   * Actions will use state from an existing draft if it exists,
   * or use the published document to create a draft, if no draft exists.
   *
   * Successful responses contains the _id that was mutated by the action.
   *
   *
   * ### forcePublishedWrite: true
   *
   * When forcePublishedWrite: true an agent action will write to the exact id provided.
   * The action will also not fallback to published state for draft ids.
   *
   *
   * ### Versioned ids (releases)
   *
   * When an ID on the form "versions.<release>.some-id" is provided, agent actions will
   * always behave as if `forcePublishedWrite: true`.
   * That is, only the exact document state of the id provided is considered and mutated.
   * */
  forcePublishedWrite?: boolean
  /**
   * When a type or field in the schema has a function set for `hidden` or `readOnly`, it is conditional.
   *
   * By default, Generate will not output to conditional `readOnly` and `hidden` fields,
   * ie, they are considered to resolve to `readOnly: true` / `hidden: true`.
   *
   * `conditionalPaths` param allows setting the default conditional value for
   * `hidden` and `readOnly` to false,
   * or individually set `hidden` and `readOnly` state for individual document paths.
   *
   * Note: fields and types with explicit readOnly: true or hidden: true in the schema, are not available to Generate,
   * and cannot be changed via conditionalPaths
   *
   * conditionalPaths state only apply to fields and types that have conditional `hidden` or `readOnly` in their schema definition.
   *
   * Consider using `hidden: () => true` in schema config, if a field should be writeable only by Generate and never
   * visible in the studio – then make the field visible to the Generate using `conditionalPaths`.
   *
   * @see GenerateRequestBase#target
   */
  conditionalPaths?: {
    defaultReadOnly?: boolean
    defaultHidden?: boolean
    paths?: {
      /** path here is not a relative path: it must be the full document path, regardless of `path` param used in targets */
      path: AgentActionPath
      readOnly: boolean
      hidden: boolean
    }[]
  }
}

/** @public */
declare class AgentActionsClient {
  #private
  constructor(client: SanityClient, httpRequest: HttpRequest)
  /**
   * Run an instruction to generate content in a target document.
   * @param request - instruction request
   */
  generate<DocumentShape extends Record<string, Any>>(
    request: GenerateInstruction<DocumentShape>,
  ): Promise<
    (typeof request)['async'] extends true
      ? {
          _id: string
        }
      : IdentifiedSanityDocumentStub & DocumentShape
  >
  /**
   * Transform a target document based on a source.
   * @param request - translation request
   */
  transform<DocumentShape extends Record<string, Any>>(
    request: TransformDocument<DocumentShape>,
  ): Promise<
    (typeof request)['async'] extends true
      ? {
          _id: string
        }
      : IdentifiedSanityDocumentStub & DocumentShape
  >
  /**
   * Translate a target document based on a source.
   * @param request - translation request
   */
  translate<DocumentShape extends Record<string, Any>>(
    request: TranslateDocument<DocumentShape>,
  ): Promise<
    (typeof request)['async'] extends true
      ? {
          _id: string
        }
      : IdentifiedSanityDocumentStub & DocumentShape
  >
  /**
   * Run a raw instruction and return the result either as text or json
   * @param request - prompt request
   */
  prompt<const DocumentShape extends Record<string, Any>>(
    request: PromptRequest<DocumentShape>,
  ): Promise<(typeof request)['format'] extends 'json' ? DocumentShape : string>
  /**
   * Patch a document using a schema aware API.
   * Does not use an LLM, but uses the schema to ensure paths and values matches the schema.
   * @param request - instruction request
   */
  patch<DocumentShape extends Record<string, Any>>(
    request: PatchDocument<DocumentShape>,
  ): Promise<
    (typeof request)['async'] extends true
      ? {
          _id: string
        }
      : IdentifiedSanityDocumentStub & DocumentShape
  >
}

/** @beta */
declare interface AgentActionSync {
  /**
   * By default, noWrite: false.
   * Write enabled operations will mutate the target document, and emit AI presence in the studio.
   *
   * When noWrite: true, the api will not mutate any documents nor emit presence.
   * Ie, when true, no changes will be made to content-lake
   *
   * noWrite: true is incompatible with async: true,
   * as noWrite implies that you will use the return value of the operation
   */
  noWrite?: boolean
  /**
   * When async: true, requests responds with status 201 and \{_id\} as response body as soon as the request is validated.
   * The instruction operation will carry on in the background.
   *
   * When async: false (default), requests respond with status 200 and the document value after instruction has been applied.
   *
   * async: true is incompatible with noWrite: true, as async: true does not return the resulting document
   */
  async?: false
}

/**
 * @beta
 */
export declare interface AgentActionTarget {
  /**
   * Root target path.
   *
   * Use this to have the instruction only affect a part of the document.
   *
   * To further control the behavior of individual paths under the root, use `include`, `exclude`, `types.include`
   * and `types.exclude`.
   *
   * Example:
   *
   * `path: ['body', {_key: 'someKey'}, 'nestedObject']`
   *
   * Here, the instruction will only write to fields under the nestedObject.
   *
   * Default: [] = the document itself
   *
   * @see #AgentActionPathSegment
   * @see #AgentActionPath
   * */
  path?: AgentActionPathSegment | AgentActionPath
  /**
   * maxPathDepth controls how deep into the schema from the target root the instruction will affect.
   *
   * Depth is based on path segments:
   * - `title` has depth 1
   * - `array[_key="no"].title` has depth 3
   *
   * Be careful not to set this too high in studios with recursive document schemas, as it could have
   * negative impact on performance; both for runtime and quality of responses.
   *
   * Default: 4
   */
  maxPathDepth?: number
  /**
   * By default, all children up to `target.maxPathDepth` are included.
   * Fields or array items not on the exclude list, are implicitly included.
   */
  exclude?: AgentActionPathSegment[]
  /**
   * Types can be used to exclude array item types or all fields directly under the target path of a certain type.
   * If you do exclude: ['string'] all string fields under the target will be excluded, for instance.
   *
   * `types.include` and `types.exclude` are mutually exclusive.
   */
  types?: AgentActionTypeConfig
}

/**  @beta */
declare interface AgentActionTargetInclude {
  path: AgentActionPathSegment | AgentActionPath
  /**
   * By default, all children up to `target.maxPathDepth` are included.
   * Fields or array items not on the exclude list, are implicitly included.
   */
  exclude?: AgentActionPathSegment[]
  /**
   * Types can be used to exclude array item types or all fields directly under the target path of a certain type.
   * If you do exclude: ['string'] all string fields under the target will be excluded, for instance.
   *
   * `types.include` and `types.exclude` are mutually exclusive.
   */
  types?: AgentActionTypeConfig
}

/**  @beta */
declare type AgentActionTypeConfig =
  | {
      include: string[]
      exclude?: never
    }
  | {
      exclude: string[]
      include?: never
    }

/** @internal */
export declare type AllDocumentIdsMutationOptions = BaseMutationOptions & {
  returnFirst: false
  returnDocuments: false
}

/** @internal */
export declare type AllDocumentsMutationOptions = BaseMutationOptions & {
  returnFirst: false
  returnDocuments?: true
}

/**
 * Allowed animated image formats.
 * @public
 */
export declare type AnimatedImageFormat = 'gif' | 'webp'

/**
 * Animated preview rendition options (e.g. GIF / animated WebP).
 * @public
 */
export declare interface AnimatedTransformOptions {
  /** Pixel width of the animated output. Max 640 px. */
  width?: number
  /** Pixel height of the animated output. Max 640 px. */
  height?: number
  /** Start time in seconds (inclusive). */
  start?: number
  /** End time in seconds. */
  end?: number
  /** Frames per second (1–30). */
  fps?: number
  /** Output animated format. */
  format?: AnimatedImageFormat
}

/**
 * Used to tag types that is set to `any` as a temporary measure, but should be replaced with proper typings in the future
 * @internal
 */
export declare type Any = any

declare type AnyNonNullable = Exclude<any, null | undefined>

/** @internal */
export declare interface ApiError {
  error: string
  message: string
  statusCode: number
}

/**
 * Archives an `active` release, and deletes all the release documents.
 *
 * @public
 */
export declare interface ArchiveReleaseAction {
  actionType: 'sanity.action.release.archive'
  releaseId: string
}

/** @public */
export declare type AssetMetadataType =
  | 'location'
  | 'exif'
  | 'image'
  | 'palette'
  | 'lqip'
  | 'blurhash'
  | 'none'

/** @internal */
export declare class AssetsClient {
  #private
  constructor(client: SanityClient, httpRequest: HttpRequest)
  /**
   * Uploads a file asset to the configured dataset
   *
   * @param assetType - Asset type (file)
   * @param body - Asset content - can be a browser File instance, a Blob, a Node.js Buffer instance or a Node.js ReadableStream.
   * @param options - Options to use for the upload
   */
  upload(
    assetType: 'file',
    body: UploadBody,
    options?: UploadClientConfig,
  ): Promise<SanityAssetDocument>
  /**
   * Uploads an image asset to the configured dataset
   *
   * @param assetType - Asset type (image)
   * @param body - Asset content - can be a browser File instance, a Blob, a Node.js Buffer instance or a Node.js ReadableStream.
   * @param options - Options to use for the upload
   */
  upload(
    assetType: 'image',
    body: UploadBody,
    options?: UploadClientConfig,
  ): Promise<SanityImageAssetDocument>
  /**
   * Uploads a file or an image asset to the configured dataset
   *
   * @param assetType - Asset type (file/image)
   * @param body - Asset content - can be a browser File instance, a Blob, a Node.js Buffer instance or a Node.js ReadableStream.
   * @param options - Options to use for the upload
   */
  upload(
    assetType: 'file' | 'image',
    body: UploadBody,
    options?: UploadClientConfig,
  ): Promise<SanityAssetDocument | SanityImageAssetDocument>
}

/** @internal */
export declare type AttributeSet = {
  [key: string]: Any
}

/** @internal */
export declare interface AuthProvider {
  name: string
  title: string
  url: string
}

/** @internal */
export declare type AuthProviderResponse = {
  providers: AuthProvider[]
}

/** @internal */
export declare type BaseActionOptions = RequestOptions & {
  transactionId?: string
  skipCrossDatasetReferenceValidation?: boolean
  dryRun?: boolean
}

/** @internal */
export declare type BaseMutationOptions = RequestOptions & {
  visibility?: 'sync' | 'async' | 'deferred'
  returnDocuments?: boolean
  returnFirst?: boolean
  dryRun?: boolean
  autoGenerateArrayKeys?: boolean
  skipCrossDatasetReferenceValidation?: boolean
  transactionId?: string
}

/** @internal */
export declare class BasePatch {
  protected selection: PatchSelection
  protected operations: PatchOperations
  constructor(selection: PatchSelection, operations?: PatchOperations)
  /**
   * Sets the given attributes to the document. Does NOT merge objects.
   * The operation is added to the current patch, ready to be commited by `commit()`
   *
   * @param attrs - Attributes to set. To set a deep attribute, use JSONMatch, eg: \{"nested.prop": "value"\}
   */
  set(attrs: AttributeSet): this
  /**
   * Sets the given attributes to the document if they are not currently set. Does NOT merge objects.
   * The operation is added to the current patch, ready to be commited by `commit()`
   *
   * @param attrs - Attributes to set. To set a deep attribute, use JSONMatch, eg: \{"nested.prop": "value"\}
   */
  setIfMissing(attrs: AttributeSet): this
  /**
   * Performs a "diff-match-patch" operation on the string attributes provided.
   * The operation is added to the current patch, ready to be commited by `commit()`
   *
   * @param attrs - Attributes to perform operation on. To set a deep attribute, use JSONMatch, eg: \{"nested.prop": "dmp"\}
   */
  diffMatchPatch(attrs: AttributeSet): this
  /**
   * Unsets the attribute paths provided.
   * The operation is added to the current patch, ready to be commited by `commit()`
   *
   * @param attrs - Attribute paths to unset.
   */
  unset(attrs: string[]): this
  /**
   * Increment a numeric value. Each entry in the argument is either an attribute or a JSON path. The value may be a positive or negative integer or floating-point value. The operation will fail if target value is not a numeric value, or doesn't exist.
   *
   * @param attrs - Object of attribute paths to increment, values representing the number to increment by.
   */
  inc(attrs: {[key: string]: number}): this
  /**
   * Decrement a numeric value. Each entry in the argument is either an attribute or a JSON path. The value may be a positive or negative integer or floating-point value. The operation will fail if target value is not a numeric value, or doesn't exist.
   *
   * @param attrs - Object of attribute paths to decrement, values representing the number to decrement by.
   */
  dec(attrs: {[key: string]: number}): this
  /**
   * Provides methods for modifying arrays, by inserting, appending and replacing elements via a JSONPath expression.
   *
   * @param at - Location to insert at, relative to the given selector, or 'replace' the matched path
   * @param selector - JSONPath expression, eg `comments[-1]` or `blocks[_key=="abc123"]`
   * @param items - Array of items to insert/replace
   */
  insert(at: 'before' | 'after' | 'replace', selector: string, items: Any[]): this
  /**
   * Append the given items to the array at the given JSONPath
   *
   * @param selector - Attribute/path to append to, eg `comments` or `person.hobbies`
   * @param items - Array of items to append to the array
   */
  append(selector: string, items: Any[]): this
  /**
   * Prepend the given items to the array at the given JSONPath
   *
   * @param selector - Attribute/path to prepend to, eg `comments` or `person.hobbies`
   * @param items - Array of items to prepend to the array
   */
  prepend(selector: string, items: Any[]): this
  /**
   * Change the contents of an array by removing existing elements and/or adding new elements.
   *
   * @param selector - Attribute or JSONPath expression for array
   * @param start - Index at which to start changing the array (with origin 0). If greater than the length of the array, actual starting index will be set to the length of the array. If negative, will begin that many elements from the end of the array (with origin -1) and will be set to 0 if absolute value is greater than the length of the array.x
   * @param deleteCount - An integer indicating the number of old array elements to remove.
   * @param items - The elements to add to the array, beginning at the start index. If you don't specify any elements, splice() will only remove elements from the array.
   */
  splice(selector: string, start: number, deleteCount?: number, items?: Any[]): this
  /**
   * Adds a revision clause, preventing the document from being patched if the `_rev` property does not match the given value
   *
   * @param rev - Revision to lock the patch to
   */
  ifRevisionId(rev: string): this
  /**
   * Return a plain JSON representation of the patch
   */
  serialize(): PatchMutationOperation
  /**
   * Return a plain JSON representation of the patch
   */
  toJSON(): PatchMutationOperation
  /**
   * Clears the patch of all operations
   */
  reset(): this
  protected _assign(op: keyof PatchOperations, props: Any, merge?: boolean): this
  protected _set(op: keyof PatchOperations, props: Any): this
}

/** @internal */
export declare class BaseTransaction {
  protected operations: Mutation[]
  protected trxId?: string
  constructor(operations?: Mutation[], transactionId?: string)
  /**
   * Creates a new Sanity document. If `_id` is provided and already exists, the mutation will fail. If no `_id` is given, one will automatically be generated by the database.
   * The operation is added to the current transaction, ready to be commited by `commit()`
   *
   * @param doc - Document to create. Requires a `_type` property.
   */
  create<R extends Record<string, Any> = Record<string, Any>>(doc: SanityDocumentStub<R>): this
  /**
   * Creates a new Sanity document. If a document with the same `_id` already exists, the create operation will be ignored.
   * The operation is added to the current transaction, ready to be commited by `commit()`
   *
   * @param doc - Document to create if it does not already exist. Requires `_id` and `_type` properties.
   */
  createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(
    doc: IdentifiedSanityDocumentStub<R>,
  ): this
  /**
   * Creates a new Sanity document, or replaces an existing one if the same `_id` is already used.
   * The operation is added to the current transaction, ready to be commited by `commit()`
   *
   * @param doc - Document to create or replace. Requires `_id` and `_type` properties.
   */
  createOrReplace<R extends Record<string, Any> = Record<string, Any>>(
    doc: IdentifiedSanityDocumentStub<R>,
  ): this
  /**
   * Deletes the document with the given document ID
   * The operation is added to the current transaction, ready to be commited by `commit()`
   *
   * @param documentId - Document ID to delete
   */
  delete(documentId: string): this
  /**
   * Gets the current transaction ID, if any
   */
  transactionId(): string | undefined
  /**
   * Set the ID of this transaction.
   *
   * @param id - Transaction ID
   */
  transactionId(id: string): this
  /**
   * Return a plain JSON representation of the transaction
   */
  serialize(): Mutation[]
  /**
   * Return a plain JSON representation of the transaction
   */
  toJSON(): Mutation[]
  /**
   * Clears the transaction of all operations
   */
  reset(): this
  protected _add(mut: Mutation): this
}

/**
 * @public
 * The server sent a `channelError` message. Usually indicative of a bad or malformed request
 */
export declare class ChannelError extends Error {
  readonly name = 'ChannelError'
  readonly data?: unknown
  constructor(message: string, data: unknown)
}

/**
 * An error occurred. This is different from a network-level error (which will be emitted as 'error').
 * Possible causes are things such as malformed filters, non-existant datasets or similar.
 *
 * @public
 */
export declare type ChannelErrorEvent = {
  type: 'channelError'
  message: string
}

/** @public */
export declare interface ClientConfig {
  projectId?: string
  dataset?: string
  /** @defaultValue true */
  useCdn?: boolean
  token?: string
  /** @internal */
  '~experimental_resource'?: ClientConfigResource
  /**
   * What perspective to use for the client. See {@link https://www.sanity.io/docs/perspectives|perspective documentation}
   * @remarks
   * As of API version `v2025-02-19`, the default perspective has changed from `raw` to `published`. {@link https://www.sanity.io/changelog/676aaa9d-2da6-44fb-abe5-580f28047c10|Changelog}
   * @defaultValue 'published'
   */
  perspective?: ClientPerspective
  apiHost?: string
  /**
     @remarks
     * As of API version `v2025-02-19`, the default perspective has changed from `raw` to `published`. {@link https://www.sanity.io/changelog/676aaa9d-2da6-44fb-abe5-580f28047c10|Changelog}
     */
  apiVersion?: string
  proxy?: string
  /**
   * Optional request tag prefix for all request tags
   */
  requestTagPrefix?: string
  /**
   * Optional default headers to include with all requests
   *
   * @remarks request-specific headers will override any default headers with the same name.
   */
  headers?: Record<string, string>
  ignoreBrowserTokenWarning?: boolean
  /**
   * Ignore specific warning messages from the client.
   *
   * @remarks
   * - String values perform substring matching (not exact matching) against warning messages
   * - RegExp values are tested against the full warning message
   * - Array values allow multiple patterns to be specified
   *
   * @example
   * ```typescript
   * // Ignore warnings containing "experimental"
   * ignoreWarnings: 'experimental'
   *
   * // Ignore multiple warning types
   * ignoreWarnings: ['experimental', 'deprecated']
   *
   * // Use regex for exact matching
   * ignoreWarnings: /^This is an experimental API version$/
   *
   * // Mix strings and regex patterns
   * ignoreWarnings: ['rate limit', /^deprecated/i]
   * ```
   */
  ignoreWarnings?: string | RegExp | Array<string | RegExp>
  withCredentials?: boolean
  allowReconfigure?: boolean
  timeout?: number
  /** Number of retries for requests. Defaults to 5. */
  maxRetries?: number
  /**
   * The amount of time, in milliseconds, to wait before retrying, given an attemptNumber (starting at 0).
   *
   * Defaults to exponential back-off, starting at 100ms, doubling for each attempt, together with random
   * jitter between 0 and 100 milliseconds. More specifically the following algorithm is used:
   *
   *   Delay = 100 * 2^attemptNumber + randomNumberBetween0and100
   */
  retryDelay?: (attemptNumber: number) => number
  /**
   * @deprecated Don't use
   */
  useProjectHostname?: boolean
  /**
   * @deprecated Don't use
   */
  requester?: Requester
  /**
   * Adds a `resultSourceMap` key to the API response, with the type `ContentSourceMap`
   */
  resultSourceMap?: boolean | 'withKeyArraySelector'
  /**
   *@deprecated set `cache` and `next` options on `client.fetch` instead
   */
  fetch?:
    | {
        cache?: ResponseQueryOptions['cache']
        next?: ResponseQueryOptions['next']
      }
    | boolean
  /**
   * Options for how, if enabled, Content Source Maps are encoded into query results using steganography
   */
  stega?: StegaConfig | boolean
}

declare type ClientConfigResource =
  | {
      type: 'canvas'
      id: string
    }
  | {
      type: 'media-library'
      id: string
    }
  | {
      type: 'dataset'
      id: string
    }
  | {
      type: 'dashboard'
      id: string
    }

/** @public */
export declare class ClientError extends Error {
  response: ErrorProps['response']
  statusCode: ErrorProps['statusCode']
  responseBody: ErrorProps['responseBody']
  details: ErrorProps['details']
  constructor(res: Any, context?: HttpContext)
}

/** @public */
export declare type ClientPerspective =
  | DeprecatedPreviewDrafts
  | 'published'
  | 'drafts'
  | 'raw'
  | StackablePerspective[]

/** @public */
declare type ClientPerspective_2 =
  | DeprecatedPreviewDrafts_2
  | 'published'
  | 'drafts'
  | 'raw'
  | StackablePerspective_2[]

/** @public */
export declare type ClientReturn<
  GroqString extends string,
  Fallback = Any,
> = GroqString extends keyof SanityQueries ? SanityQueries[GroqString] : Fallback

/**
 * Sanity API specific EventSource handler shared between the listen and live APIs
 *
 * Since the `EventSource` API is not provided by all environments, this function enables custom initialization of the EventSource instance
 * for runtimes that requires polyfilling or custom setup logic (e.g. custom HTTP headers)
 * via the passed `initEventSource` function which must return an EventSource instance.
 *
 * Possible errors to be thrown on the returned observable are:
 * - {@link MessageError}
 * - {@link MessageParseError}
 * - {@link ChannelError}
 * - {@link DisconnectError}
 * - {@link ConnectionFailedError}
 *
 * @param initEventSource - A function that returns an EventSource instance or an Observable that resolves to an EventSource instance
 * @param events - an array of named events from the API to listen for.
 *
 * @internal
 */
export declare function connectEventSource<EventName extends string>(
  initEventSource: () => EventSourceInstance | Observable<EventSourceInstance>,
  events: EventName[],
): Observable<ServerSentEvent<EventName>>

/**
 * @public
 * Thrown if the EventSource connection could not be established.
 * Note that ConnectionFailedErrors are rare, and disconnects will normally be handled by the EventSource instance itself and emitted as `reconnect` events.
 */
export declare class ConnectionFailedError extends Error {
  readonly name = 'ConnectionFailedError'
}

/**
 * Include a string in the instruction: do not have to escape $ signs in the string.
 *
 * ```ts
 * client.agent.action.generate({
 *   schemaId,
 *   documentId,
 *   instruction: 'Give the following topic:\n $topic \n ---\nGenerate the full article.',
 *   instructionParams: {
 *     topic: {
 *       type: 'constant',
 *       value: 'Grapefruit'
 *     },
 *   },
 * })
 * ```
 *
 * `type: 'constant'` can also be provided directly as a string, as a shorthand:
 *
 * ```ts
 * client.agent.action.generate({
 *   schemaId,
 *   documentId,
 *   instruction: 'Give the following topic:\n $topic \n ---\nGenerate the full article.',
 *   instructionParams: {
 *     topic: 'Grapefruit'
 *   },
 * })
 * ```
 *
 * @beta
 * */
export declare interface ConstantAgentActionParam {
  type: 'constant'
  value: string
}

/** @public */
export declare interface ContentSourceMap {
  mappings: ContentSourceMapMappings
  documents: ContentSourceMapDocuments
  paths: ContentSourceMapPaths
}

/** @public */
export declare interface ContentSourceMapDocument extends ContentSourceMapDocumentBase {
  _projectId?: undefined
  _dataset?: undefined
}

/** @public */
export declare interface ContentSourceMapDocumentBase {
  _id: string
  _type: string
}

/** @public */
export declare type ContentSourceMapDocuments = (
  | ContentSourceMapDocument
  | ContentSourceMapRemoteDocument
)[]

/**
 * DocumentValueSource is a path to a value within a document
 * @public
 */
export declare interface ContentSourceMapDocumentValueSource {
  type: 'documentValue'
  document: number
  path: number
}

/**
 * When a value is not from a source, its a literal
 * @public
 */
export declare interface ContentSourceMapLiteralSource {
  type: 'literal'
}

/** @public */
export declare type ContentSourceMapMapping = ContentSourceMapValueMapping

/** @public */
export declare type ContentSourceMapMappings = Record<string, ContentSourceMapMapping>

export {ContentSourceMapParsedPath}

export {ContentSourceMapParsedPathKeyedSegment}

/** @public */
export declare type ContentSourceMapPaths = string[]

/** @public */
export declare interface ContentSourceMapRemoteDocument extends ContentSourceMapDocumentBase {
  _projectId: string
  _dataset: string
}

/** @public */
export declare type ContentSourceMapSource =
  | ContentSourceMapDocumentValueSource
  | ContentSourceMapLiteralSource
  | ContentSourceMapUnknownSource

/**
 * When a field source is unknown
 * @public
 */
export declare interface ContentSourceMapUnknownSource {
  type: 'unknown'
}

/**
 * ValueMapping is a mapping when for value that is from a single source value
 * It may refer to a field within a document or a literal value
 * @public
 */
export declare interface ContentSourceMapValueMapping {
  type: 'value'
  source: ContentSourceMapSource
}

/** @public */
export declare class CorsOriginError extends Error {
  projectId: string
  addOriginUrl?: URL
  constructor({projectId}: {projectId: string})
}

/**
 * Creates a new draft document. The published version of the document must not already exist.
 * If the draft version of the document already exists the action will fail by default, but
 * this can be adjusted to instead leave the existing document in place.
 *
 * @public
 */
export declare type CreateAction = {
  actionType: 'sanity.action.document.create'
  /**
   * ID of the published document to create a draft for.
   */
  publishedId: string
  /**
   * Document to create. Requires a `_type` property.
   */
  attributes: IdentifiedSanityDocumentStub
  /**
   * ifExists controls what to do if the draft already exists
   */
  ifExists: 'fail' | 'ignore'
}

/** @public */
export declare const createClient: (config: ClientConfig) => SanityClient

/**
 * Creates a new release under the given id, with metadata.
 *
 * @public
 */
export declare interface CreateReleaseAction {
  actionType: 'sanity.action.release.create'
  releaseId: string
  metadata?: Partial<ReleaseDocument['metadata']>
}

/**
 * Creates a new version of an existing document.
 *
 * If the `document` is provided, the version is created from the document
 * attached to the release as given by `document._id`
 *
 * If the `baseId` and `versionId` are provided, the version is created from the base document
 * and the version is attached to the release as given by `publishedId` and `versionId`
 *
 * @public
 */
export declare type CreateVersionAction = {
  actionType: 'sanity.action.document.version.create'
  publishedId: string
} & (
  | {
      document: IdentifiedSanityDocumentStub
    }
  | {
      baseId: string
      versionId: string
      ifBaseRevisionId?: string
    }
)

/** @public */
export declare interface CurrentSanityUser {
  id: string
  name: string
  email: string
  profileImage: string | null
  role: string
  provider: string
}

/** @public */
export declare type DatasetAclMode = 'public' | 'private' | 'custom'

/** @public */
export declare type DatasetResponse = {
  datasetName: string
  aclMode: DatasetAclMode
}

/** @internal */
export declare class DatasetsClient {
  #private
  constructor(client: SanityClient, httpRequest: HttpRequest)
  /**
   * Create a new dataset with the given name
   *
   * @param name - Name of the dataset to create
   * @param options - Options for the dataset
   */
  create(
    name: string,
    options?: {
      aclMode?: DatasetAclMode
    },
  ): Promise<DatasetResponse>
  /**
   * Edit a dataset with the given name
   *
   * @param name - Name of the dataset to edit
   * @param options - New options for the dataset
   */
  edit(
    name: string,
    options?: {
      aclMode?: DatasetAclMode
    },
  ): Promise<DatasetResponse>
  /**
   * Delete a dataset with the given name
   *
   * @param name - Name of the dataset to delete
   */
  delete(name: string): Promise<{
    deleted: true
  }>
  /**
   * Fetch a list of datasets for the configured project
   */
  list(): Promise<DatasetsResponse>
}

/** @public */
export declare type DatasetsResponse = {
  name: string
  aclMode: DatasetAclMode
  createdAt: string
  createdByUserId: string
  addonFor: string | null
  datasetProfile: string
  features: string[]
  tags: string[]
}[]

/**
 * Deletes the published version of a document and optionally some (likely all known) draft versions.
 * If any draft version exists that is not specified for deletion this is an error.
 * If the purge flag is set then the document history is also deleted.
 *
 * @public
 */
export declare type DeleteAction = {
  actionType: 'sanity.action.document.delete'
  /**
   * Published document ID to delete
   */
  publishedId: string
  /**
   * Draft document ID to delete
   */
  includeDrafts: string[]
  /**
   * Delete document history
   */
  purge?: boolean
}

/**
 * Deletes a `archived` or `published` release, and all the release documents versions.
 *
 * @public
 */
export declare interface DeleteReleaseAction {
  actionType: 'sanity.action.release.delete'
  releaseId: string
}

/**
 * @public
 * @deprecated Use the named export `createClient` instead of the `default` export
 */
declare const deprecatedCreateClient: (config: ClientConfig) => SanityClient
export default deprecatedCreateClient

/**
 * @deprecated use 'drafts' instead
 */
declare type DeprecatedPreviewDrafts = 'previewDrafts'

/**
 * @deprecated use 'drafts' instead
 */
declare type DeprecatedPreviewDrafts_2 = 'previewDrafts'

/**
 * Delete the draft version of a document.
 * It is an error if it does not exist. If the purge flag is set, the document history is also deleted.
 *
 * @public
 * @deprecated Use {@link DiscardVersionAction} instead
 */
export declare type DiscardAction = {
  actionType: 'sanity.action.document.discard'
  /**
   * Draft document ID to delete
   */
  draftId: string
  /**
   * Delete document history
   */
  purge?: boolean
}

/**
 * Delete a version of a document.
 *
 * @public
 */
export declare interface DiscardVersionAction {
  actionType: 'sanity.action.document.version.discard'
  versionId: string
  purge?: boolean
}

/**
 * The listener has been told to explicitly disconnect.
 *  This is a rare situation, but may occur if the API knows reconnect attempts will fail,
 *  eg in the case of a deleted dataset, a blocked project or similar events.
 * @public
 */
export declare class DisconnectError extends Error {
  readonly name = 'DisconnectError'
  readonly reason?: string
  constructor(message: string, reason?: string, options?: ErrorOptions)
}

/**
 * The listener has been told to explicitly disconnect and not reconnect.
 * This is a rare situation, but may occur if the API knows reconnect attempts will fail,
 * eg in the case of a deleted dataset, a blocked project or similar events.
 *
 * Note that this is not treated as an error on the observable, but will complete the observable.
 *
 * @public
 */
export declare type DisconnectEvent = {
  type: 'disconnect'
  reason: string
}

declare type DocIdParam<
  TParamConfig extends {
    docIdRequired: boolean
  } = {
    docIdRequired: false
  },
> = TParamConfig['docIdRequired'] extends true
  ? {
      documentId: string
    }
  : {
      /**
       * If omitted, implicitly uses the documentId of the instruction target
       */
      documentId?: string
    }

/**
 *
 * Includes a LLM-friendly version of the document in the instruction
 *
 * ```ts
 * client.agent.action.generate({
 *   schemaId,
 *   documentId,
 *   instruction: 'Give the following document value:\n $document \n ---\nGenerate keywords.',
 *   instructionParams: {
 *     document: {
 *       type: 'document',
 *     },
 *   },
 *   target: {path: 'keywords' }
 * })
 * ```
 *
 * @beta
 * */
export declare type DocumentAgentActionParam<
  TParamConfig extends {
    docIdRequired: boolean
  } = {
    docIdRequired: false
  },
> = {
  type: 'document'
} & DocIdParam<TParamConfig>

/** @internal */
export declare type EditableReleaseDocument = Omit<
  PartialExcept<ReleaseDocument, '_id'>,
  'metadata' | '_type'
> & {
  _id: string
  metadata: Partial<ReleaseDocument['metadata']>
}

/**
 * Modifies an existing draft document.
 * It applies the given patch to the document referenced by draftId.
 * If there is no such document then one is created using the current state of the published version and then that is updated accordingly.
 *
 * @public
 */
export declare type EditAction = {
  actionType: 'sanity.action.document.edit'
  /**
   * Draft document ID to edit
   */
  draftId: string
  /**
   * Published document ID to create draft from, if draft does not exist
   */
  publishedId: string
  /**
   * Patch operations to apply
   */
  patch: PatchOperations
}

/**
 * Edits an existing release, updating the metadata.
 *
 * @public
 */
export declare interface EditReleaseAction {
  actionType: 'sanity.action.release.edit'
  releaseId: string
  patch: PatchOperations
}

/** @public */
export declare interface ErrorProps {
  message: string
  response: Any
  statusCode: number
  responseBody: Any
  details: Any
}

/**
 * @internal
 */
export declare type EventSourceEvent<Name extends string> = ServerSentEvent<Name>

/**
 * @internal
 */
export declare type EventSourceInstance = InstanceType<typeof globalThis.EventSource>

/**
 * A string constant containing the experimental API version warning message.
 * Use this with the `ignoreWarnings` option to suppress warnings when using experimental API versions.
 *
 * @example
 * ```typescript
 * import { createClient, EXPERIMENTAL_API_WARNING } from '@sanity/client'
 *
 * const client = createClient({
 *   projectId: 'your-project-id',
 *   dataset: 'production',
 *   apiVersion: 'vX', // experimental version
 *   ignoreWarnings: EXPERIMENTAL_API_WARNING
 * })
 * ```
 *
 * @public
 */
export declare const EXPERIMENTAL_API_WARNING = 'This is an experimental API version'

/**
 *
 *
 * Includes a LLM-friendly version of the field value in the instruction
 *
 * ```ts
 * client.agent.action.generate({
 *   schemaId,
 *   documentId,
 *   instruction: 'Give the following field value:\n $pte \n ---\nGenerate keywords.',
 *   instructionParams: {
 *     pte: {
 *       type: 'field',
 *       path: ['pteField'],
 *     },
 *   },
 *   target: {path: 'keywords' }
 * })
 *
 * ```
 *
 * @beta
 * */
export declare type FieldAgentActionParam<
  TParamConfig extends {
    docIdRequired: boolean
  } = {
    docIdRequired: false
  },
> = {
  type: 'field'
  /**
   * Examples: 'title', ['array', \{_key: 'arrayItemKey'\}, 'field']
   */
  path: AgentActionPathSegment | AgentActionPath
} & DocIdParam<TParamConfig>

/** @public */
export declare type FilterDefault = (props: {
  /**
   * The path to the value in the source document, for example if you queried for a document like this:
   * `*[_type == "author"][0]{"slug": slug.current}`
   * Then the `sourcePath` for `result.slug` would be `['slug', 'current']`.
   *
   */
  sourcePath: ContentSourceMapParsedPath
  /**
   * If `sourcePath` alone isn't enough to tell you if it's safe to contain stega strings, then you can use `sourceDocument`
   * for additional metadata.
   * It'll always have a `_type` property, which can be used to trace it to the Studio Schema that were used initially.
   * It also has `_id` to help you debug and look at the whole document when troubleshooting.
   * Finally, if the document origins in a Cross Dataset Reference you'll also have `_projectId` and `_dataset` properties to help you trace it.
   */
  sourceDocument: ContentSourceMapDocuments_2[number]
  /**
   * If you don't colocate your Studio Schemas with your GROQ queries it might be hard to make sense of `sourcePath`,
   * as it operates on the original shape of a document.
   * In that case `resultPath` can be used, as it mirrors the path to the value in the result.
   * For example in a query like this:
   * `*[_type == "author"][0]{"slug": slug.current}`
   * The `resultPath` for `result.slug` would be `['slug']`, while `sourcePath` will be `['slug', 'current']`.
   */
  resultPath: ContentSourceMapParsedPath
  /**
   * You can also use your own string validation logic to determine if it's safe.
   */
  value: string
  /**
     * If you want to keep the default filtering behavior, but only override it for a specific path, you can use `filterDefault` to do that.
     * For example, here all "icon" documents in a Page Builder skips encoding:
     * ```ts
     {
     filter: (props) => {
     switch (props.sourceDocument._type) {
     case 'icon':
     return false
     default:
     return props.filterDefault(props)
     }
     }
     }
     * ```
     */
  filterDefault: FilterDefault
}) => boolean

/** @public */
export declare interface FilteredResponseQueryOptions extends ResponseQueryOptions {
  filterResponse?: true
}

/** @internal */
export declare type FirstDocumentIdMutationOptions = BaseMutationOptions & {
  returnFirst?: true
  returnDocuments: false
}

/** @internal */
export declare type FirstDocumentMutationOptions = BaseMutationOptions & {
  returnFirst?: true
  returnDocuments?: true
}

/**
 * Fit / resize modes accepted for thumbnail params.
 * @public
 */
export declare type FitMode = 'preserve' | 'stretch' | 'crop' | 'smartcrop' | 'pad'

/**
 * Formats a GROQ query parse error into a human-readable string.
 *
 * @param error - The error object containing details about the parse error.
 * @param tag - An optional tag to include in the error message.
 * @returns A formatted error message string.
 * @public
 */
export declare function formatQueryParseError(error: QueryParseError, tag?: string | null): string

/** @beta */
declare type GenerateAsyncInstruction<T extends Record<string, Any> = Record<string, Any>> = (
  | GenerateExistingDocumentRequest
  | GenerateTargetDocumentRequest<T>
) &
  GenerateRequestBase &
  AgentActionAsync

/**
 * Instruction for an existing document.
 * @beta
 */
declare interface GenerateExistingDocumentRequest {
  /**
   * @see #AgentActionSchema.forcePublishedWrite
   */
  documentId: string
  targetDocument?: never
}

/** @beta */
export declare type GenerateInstruction<T extends Record<string, Any> = Record<string, Any>> =
  | GenerateSyncInstruction<T>
  | GenerateAsyncInstruction<T>

/**  @beta */
export declare type GenerateOperation = 'set' | 'append' | 'mixed'

/**  @beta */
declare interface GenerateRequestBase extends AgentActionRequestBase {
  /** schemaId as reported by sanity deploy / sanity schema store */
  schemaId: string
  /**
   * Instruct the LLM how it should generate content. Be as specific and detailed as needed.
   *
   * The LLM only has access to information in the instruction, plus the target schema.
   *
   * String template with support for $variable from `instructionParams`.
   * */
  instruction: string
  /**
   * param values for the string template, keys are the variable name, ie if the template has "$variable", one key must be "variable"
   *
   * ### Examples
   *
   * #### Constant
   *
   * ##### Shorthand
   * ```ts
   * client.agent.action.generate({
   *   schemaId,
   *   documentId,
   *   instruction: 'Give the following topic:\n $topic \n ---\nGenerate the full article.',
   *   instructionParams: {
   *     topic: 'Grapefruit'
   *   },
   * })
   * ```
   * ##### Object-form
   *
   * ```ts
   * client.agent.action.generate({
   *   schemaId,
   *   documentId,
   *   instruction: 'Give the following topic:\n $topic \n ---\nGenerate the full article.',
   *   instructionParams: {
   *     topic: {
   *       type: 'constant',
   *       value: 'Grapefruit'
   *     },
   *   },
   * })
   * ```
   * #### Field
   * ```ts
   * client.agent.action.generate({
   *   schemaId,
   *   documentId,
   *   instruction: 'Give the following field value:\n $pte \n ---\nGenerate keywords.',
   *   instructionParams: {
   *     pte: {
   *       type: 'field',
   *       path: ['pteField'],
   *     },
   *   },
   *   target: {path: 'keywords' }
   * })
   * ```
   * #### Document
   * ```ts
   * client.agent.action.generate({
   *   schemaId,
   *   documentId,
   *   instruction: 'Give the following document value:\n $document \n ---\nGenerate keywords.',
   *   instructionParams: {
   *     document: {
   *       type: 'document',
   *     },
   *   },
   *   target: {path: 'keywords' }
   * })
   * ```
   *
   * #### GROQ
   * ```ts
   * client.agent.action.generate({
   *   schemaId,
   *   documentId,
   *   instruction: 'Give the following list of titles:\n $list \n ---\nGenerate a similar title.',
   *   instructionParams: {
   *     list: {
   *       type: 'groq',
   *       query: '* [_type==$type].title',
   *       params: {type: 'article'}
   *     },
   *   },
   *   target: {path: 'title' }
   * })
   * ```
   * */
  instructionParams?: AgentActionParams
  /**
   * Target defines which parts of the document will be affected by the instruction.
   * It can be an array, so multiple parts of the document can be separately configured in detail.
   *
   * Omitting target implies that the document itself is the root.
   *
   * Notes:
   * - instruction can only affect fields up to `maxPathDepth`
   * - when multiple targets are provided, they will be coalesced into a single target sharing a common target root.
   * It is therefor an error to provide conflicting include/exclude across targets (ie, include title in one, and exclude it in another)
   *
   * ## Generating images
   *
   * Generate will generate images the same was as AI Assist, for images that have been configured using
   * [AI Assist schema options](https://github.com/sanity-io/assist/tree/main/plugin#image-generation).
   *
   * To generate images _without_ changing the schema, directly target an image asset path.
   *
   * For example, all the following will generate an image into the provided asset:
   * * `target: {path: ['image', 'asset'] }`
   * * `target: {path: 'image', include: ['asset'] }`
   *
   * Image generation can be combined with regular content targets:
   * * `target: [{path: ['image', 'asset'] }, {include: ['title', 'description']}]`
   *
   * Since Generate happens in a single LLM pass, the image will be contextually related to other generated content.
   * @see AgentActionRequestBase#conditionalPaths
   */
  target?: GenerateTarget | GenerateTarget[]
}

/** @beta */
declare type GenerateSyncInstruction<T extends Record<string, Any> = Record<string, Any>> = (
  | GenerateExistingDocumentRequest
  | GenerateTargetDocumentRequest<T>
) &
  GenerateRequestBase &
  AgentActionSync

/**  @beta */
export declare interface GenerateTarget extends AgentActionTarget {
  /**
   * Sets the default operation for all paths in the target.
   * Generate runs in `'mixed'` operation mode by default:
   * Changes are set in all non-array fields, and append to all array fields.
   *
   * ### Operation types
   * - `'set'` – an *overwriting* operation, and replaces the full field value.
   * - `'append'`:
   *    – array fields: appends new items to the end of the array,
   *    - string fields: '"existing content" "new content"'
   *    - text fields: '"existing content"\\n"new content"'
   *    - number fields: existing + new
   *    - other field types not mentioned will set instead (dates, url)
   * - `'mixed'` – (default) sets non-array fields, and appends to array fields
   *
   * The default operation can be overridden on a per-path basis using `include`.
   *
   * Nested fields inherit the operation specified by their parent and falls back to the
   * top level target operation if not otherwise specified.
   *
   * Use `include` to change the `operation` of individual fields or items.
   *
   * #### Appending in the middle of arrays
   * `target: {path: ['array'], operation: 'append'}` will append the output of the instruction to the end of the array.
   *
   * To insert in the middle of the array, use `target: {path: ['array', {_key: 'appendAfterKey'}], operation: 'append'}`.
   * Here, the output of the instruction will be appended after the array item with key `'appendAfterKey'`.
   *
   * @see #AgentActionTargetInclude.operation
   * @see #include
   * @see #AgentActionTargetInclude.include
   * @see #AgentActionSchema.forcePublishedWrite
   */
  operation?: GenerateOperation
  /**
   * By default, all children up to `target.maxPathDepth` are included.
   *
   * When `include` is specified, only segments explicitly listed will be included.
   *
   * Fields or array items not on the include list, are implicitly excluded.
   */
  include?: (AgentActionPathSegment | GenerateTargetInclude)[]
}

/**  @beta */
export declare type GenerateTargetDocument<T extends Record<string, Any> = Record<string, Any>> =
  | {
      operation: 'edit'
      /**
       * @see #AgentActionSchema.forcePublishedWrite
       */
      _id: string
    }
  | {
      operation: 'create'
      /**
       * @see #AgentActionSchema.forcePublishedWrite
       */
      _id?: string
      _type: string
      initialValues?: T
    }
  | {
      operation: 'createIfNotExists'
      /**
       * @see #AgentActionSchema.forcePublishedWrite
       */
      _id: string
      _type: string
      initialValues?: T
    }
  | {
      operation: 'createOrReplace'
      /**
       * @see #AgentActionSchema.forcePublishedWrite
       */
      _id: string
      _type: string
      initialValues?: T
    }

/**
 * Instruction to create a new document
 * @beta
 */
declare interface GenerateTargetDocumentRequest<
  T extends Record<string, Any> = Record<string, Any>,
> {
  /**
   * @see #AgentActionSchema.forcePublishedWrite
   */
  targetDocument: GenerateTargetDocument<T>
  documentId?: never
}

/**  @beta */
export declare interface GenerateTargetInclude extends AgentActionTargetInclude {
  /**
   * Sets the operation for this path, and all its children.
   * This overrides any operation set parents or the root target.
   * @see #GenerateTarget.operation
   * @see #include
   */
  operation?: GenerateOperation
  /**
   * By default, all children up to `target.maxPathDepth` are included.
   *
   * When `include` is specified, only segments explicitly listed will be included.
   *
   * Fields or array items not on the include list, are implicitly excluded.
   */
  include?: (AgentActionPathSegment | GenerateTargetInclude)[]
}

/**
 * Includes a LLM-friendly version of GROQ query result in the instruction
 *
 * ```ts
 * client.agent.action.generate({
 *   schemaId,
 *   documentId,
 *   instruction: 'Give the following list of titles:\n $list \n ---\nGenerate a similar title.',
 *   instructionParams: {
 *     list: {
 *       type: 'groq',
 *       query: '* [_type==$type].title',
 *       params: {type: 'article'}
 *     },
 *   },
 *   target: {path: 'title' }
 * })
 * ```
 * @beta
 * */
export declare interface GroqAgentActionParam {
  type: 'groq'
  query: string
  params?: Record<string, string>
  perspective?: ClientPerspective_2
}

/**
 * Shared properties for HTTP errors (eg both ClientError and ServerError)
 * Use `isHttpError` for type narrowing and accessing response properties.
 *
 * @public
 */
export declare interface HttpError {
  statusCode: number
  message: string
  response: {
    body: unknown
    url: string
    method: string
    headers: Record<string, string>
    statusCode: number
    statusMessage: string | null
  }
}

/** @public */
export declare type HttpRequest = {
  (options: RequestOptions, requester: Requester): ReturnType<Requester>
}

/** @public */
export declare type HttpRequestEvent<T = unknown> = ResponseEvent<T> | ProgressEvent_2

/** @public */
export declare type IdentifiedSanityDocumentStub<
  T extends Record<string, Any> = Record<string, Any>,
> = {
  [P in keyof T]: T[P]
} & {
  _id: string
} & SanityDocumentStub

/**
 *
 * @see #TransformOperation
 * @beta
 */
export declare type ImageDescriptionOperation = {
  type: 'image-description'
  /**
   * When omitted, parent image value will be inferred from the arget path.
   *
   * When specified, the `sourcePath` should be a path to an image (or image asset) field:
   * - `['image']`
   * - `['wrapper', 'mainImage']`
   * - `['heroImage', 'asset'] // the asset segment is optional, but supported`
   */
  sourcePath?: AgentActionPath
} & (
  | {
      /**
       * When omitted, parent image value will be inferred from the target path.
       *
       * When specified, the `sourcePath` should be a path to an image (or image asset) field:
       * - `['image']`
       * - `['wrapper', 'mainImage']`
       * - `['heroImage', 'asset'] // the asset segment is optional, but supported`
       *
       * Incompatible with `imageUrl`
       *
       */
      sourcePath?: AgentActionPath
      imageUrl?: never
    }
  | {
      /**
       * When specified, the image source to be described will be fetched from the URL.
       *
       * Incompatible with `sourcePath`
       */
      imageUrl?: `https://${string}`
      sourcePath?: never
    }
)

/** @public */
export declare interface InitializedClientConfig extends ClientConfig {
  apiHost: string
  apiVersion: string
  useProjectHostname: boolean
  useCdn: boolean
  /**
   * @deprecated Internal, don't use
   */
  isDefaultApi: boolean
  /**
   * @deprecated Internal, don't use
   */
  url: string
  /**
   * @deprecated Internal, don't use
   */
  cdnUrl: string
  /**
   * The fully initialized stega config, can be used to check if stega is enabled
   */
  stega: InitializedStegaConfig
  /**
   * Default headers to include with all requests
   *
   * @remarks request-specific headers will override any default headers with the same name.
   */
  headers?: Record<string, string>
}

/** @public */
export declare type InitializedStegaConfig = Omit<StegaConfig, StegaConfigRequiredKeys> &
  Required<Pick<StegaConfig, StegaConfigRequiredKeys>>

/** @internal */
export declare type InsertPatch =
  | {
      before: string
      items: Any[]
    }
  | {
      after: string
      items: Any[]
    }
  | {
      replace: string
      items: Any[]
    }

/**
 * Checks if the provided error is an HTTP error.
 *
 * @param error - The error to check.
 * @returns `true` if the error is an HTTP error, `false` otherwise.
 * @public
 */
export declare function isHttpError(error: unknown): error is HttpError

/** @internal */
export declare function isQueryParseError(error: object): error is QueryParseError

/**
 * Set up a listener that will be notified when mutations occur on documents matching the provided query/filter.
 *
 * @param query - GROQ-filter to listen to changes for
 * @param params - Optional query parameters
 * @param options - Optional listener options
 * @public
 */
export declare function _listen<R extends Record<string, Any> = Record<string, Any>>(
  this: SanityClient | ObservableSanityClient,
  query: string,
  params?: ListenParams,
): Observable<MutationEvent<R>>

/**
 * Set up a listener that will be notified when mutations occur on documents matching the provided query/filter.
 *
 * @param query - GROQ-filter to listen to changes for
 * @param params - Optional query parameters
 * @param options - Optional listener options
 * @public
 */
export declare function _listen<R extends Record<string, Any> = Record<string, Any>>(
  this: SanityClient | ObservableSanityClient,
  query: string,
  params?: ListenParams,
  options?: ListenOptions,
): Observable<ListenEvent<R>>

/** @public */
export declare type ListenEvent<R extends Record<string, Any>> =
  | MutationEvent<R>
  | ChannelErrorEvent
  | DisconnectEvent
  | ReconnectEvent
  | WelcomeEvent
  | OpenEvent

/** @public */
export declare type ListenEventName =
  /** A mutation was performed */
  | 'mutation'
  /** The listener has been (re)established */
  | 'welcome'
  /** The listener has been disconnected, and a reconnect attempt is scheduled */
  | 'reconnect'

/** @public */
export declare interface ListenOptions {
  /**
   * Whether or not to include the resulting document in addition to the mutations performed.
   * If you do not need the actual document, set this to `false` to reduce bandwidth usage.
   * The result will be available on the `.result` property of the events.
   * @defaultValue `true`
   */
  includeResult?: boolean
  /**
   * Whether or not to include the mutations that was performed.
   * If you do not need the mutations, set this to `false` to reduce bandwidth usage.
   * @defaultValue `true`
   */
  includeMutations?: boolean
  /**
   * Whether or not to include the document as it looked before the mutation event.
   * The previous revision will be available on the `.previous` property of the events,
   * and may be `null` in the case of a new document.
   * @defaultValue `false`
   */
  includePreviousRevision?: boolean
  includeAllVersions?: boolean
  /**
   * Whether events should be sent as soon as a transaction has been committed (`transaction`, default),
   * or only after they are available for queries (query). Note that this is on a best-effort basis,
   * and listeners with `query` may in certain cases (notably with deferred transactions) receive events
   * that are not yet visible to queries.
   *
   * @defaultValue `'transaction'`
   */
  visibility?: 'transaction' | 'query'
  /**
   * Array of event names to include in the observable. By default, only mutation events are included.
   *
   * @defaultValue `['mutation']`
   */
  events?: ListenEventName[]
  /**
   * Format of "effects", eg the resulting changes of a mutation.
   * Currently only `mendoza` is supported, and (if set) will include `apply` and `revert` arrays
   * in the mutation events under the `effects` property.
   *
   * See {@link https://github.com/sanity-io/mendoza | The mendoza docs} for more info
   *
   * @defaultValue `undefined`
   */
  effectFormat?: 'mendoza'
  /**
   * Optional request tag for the listener. Use to identify the request in logs.
   *
   * @defaultValue `undefined`
   */
  tag?: string
}

/** @public */
export declare type ListenParams = {
  [key: string]: Any
}

/**
 * @public
 */
export declare class LiveClient {
  #private
  constructor(client: SanityClient | ObservableSanityClient)
  /**
   * Requires `apiVersion` to be `2021-03-25` or later.
   */
  events({
    includeDrafts,
    tag: _tag,
  }?: {
    includeDrafts?: boolean
    /**
     * Optional request tag for the listener. Use to identify the request in logs.
     *
     * @defaultValue `undefined`
     */
    tag?: string
  }): Observable<LiveEvent>
}

/** @public */
export declare type LiveEvent =
  | LiveEventRestart
  | LiveEventReconnect
  | LiveEventMessage
  | LiveEventWelcome
  | LiveEventGoAway

/**
 * The `id` field is the position at which the connection was rejected or closed.
 * The `reason` field will specify why the connection rejected/closed.
 * @public
 */
export declare interface LiveEventGoAway {
  type: 'goaway'
  id: string
  reason: string
}

/** @public */
export declare interface LiveEventMessage {
  type: 'message'
  id: string
  tags: SyncTag[]
}

/** @public */
export declare interface LiveEventReconnect {
  type: 'reconnect'
}

/** @public */
export declare interface LiveEventRestart {
  type: 'restart'
  id: string
}

/** @public */
export declare interface LiveEventWelcome {
  type: 'welcome'
}

/** @public */
export declare type Logger =
  | typeof console
  | Partial<
      Pick<typeof console, 'debug' | 'error' | 'groupCollapsed' | 'groupEnd' | 'log' | 'table'>
    >

/** @public */
export declare type MediaLibraryAssetInstanceIdentifier = string | SanityReference

/**
 * Options for requesting playback info (URLs + optional tokens) for a Media Library video asset.
 *
 * Removed: generic fallback parameters (width, height, fit, format). Supply per‑transformation values instead.
 * Animated transformations intentionally exclude any fit option (not supported by Mux).
 *
 * includeTokens is a client-side flag (not sent to the server) controlling whether
 * returned tokens should be appended to URLs when consumed.
 * @public
 */
export declare interface MediaLibraryPlaybackInfoOptions {
  /** Explicit per-video transformation options (thumbnail, animated, storyboard). */
  transformations?: MediaLibraryVideoPlaybackTransformations
  /** Expiration hint for secured/signed URLs (string or number, number will be stringified). */
  expiration?: string | number
}

/** @internal */
export declare class MediaLibraryVideoClient {
  #private
  constructor(client: SanityClient, httpRequest: HttpRequest)
  /**
   * Get video playback information for a media library asset
   *
   * @param assetIdentifier - Asset instance identifier (GDR, video-prefixed ID, or container ID)
   * @param options - Options for transformations and expiration
   */
  getPlaybackInfo(
    assetIdentifier: MediaLibraryAssetInstanceIdentifier,
    options?: MediaLibraryPlaybackInfoOptions,
  ): Promise<VideoPlaybackInfo>
}

/**
 * Video-specific playback transformation option groups.
 * Only explicitly provided values are serialized into query parameters.
 * @public
 */
export declare interface MediaLibraryVideoPlaybackTransformations {
  /** Static thumbnail (single frame) options. */
  thumbnail?: ThumbnailTransformOptions
  /** Animated preview options (GIF / animated WebP). */
  animated?: AnimatedTransformOptions
  /** Storyboard (contact sheet) options. */
  storyboard?: StoryboardTransformOptions
}

/**
 * @public
 * The server sent an `error`-event to tell the client that an unexpected error has happened.
 */
export declare class MessageError extends Error {
  readonly name = 'MessageError'
  readonly data?: unknown
  constructor(message: string, data: unknown, options?: ErrorOptions)
}

/**
 * @public
 * An error occurred while parsing the message sent by the server as JSON. Should normally not happen.
 */
export declare class MessageParseError extends Error {
  readonly name = 'MessageParseError'
}

/** @internal */
export declare interface MultipleActionResult {
  transactionId: string
}

/** @internal */
export declare interface MultipleMutationResult {
  transactionId: string
  documentIds: string[]
  results: {
    id: string
    operation: MutationOperation
  }[]
}

/** @public */
export declare type Mutation<R extends Record<string, Any> = Record<string, Any>> =
  | {
      create: SanityDocumentStub<R>
    }
  | {
      createOrReplace: IdentifiedSanityDocumentStub<R>
    }
  | {
      createIfNotExists: IdentifiedSanityDocumentStub<R>
    }
  | {
      delete: MutationSelection
    }
  | {
      patch: PatchMutationOperation
    }

/** @internal */
export declare interface MutationError {
  type: 'mutationError'
  description: string
  items?: MutationErrorItem[]
}

/** @internal */
export declare interface MutationErrorItem {
  error: {
    type: string
    description: string
    value?: unknown
  }
}

/**
 * A mutation was performed. Note that when updating multiple documents in a transaction,
 * each document affected will get a separate mutation event.
 *
 * @public
 */
export declare type MutationEvent<R extends Record<string, Any> = Record<string, Any>> = {
  type: 'mutation'
  /**
   * The ID of the document that was affected
   */
  documentId: string
  /**
   * A unique ID for this event
   */
  eventId: string
  /**
   * The user ID of the user that performed the mutation
   */
  identity: string
  /**
   * An array of mutations that were performed. Note that this can differ slightly from the
   * mutations sent to the server, as the server may perform some mutations automatically.
   */
  mutations: Mutation[]
  /**
   * The revision ID of the document before the mutation was performed
   */
  previousRev?: string
  /**
   * The revision ID of the document after the mutation was performed
   */
  resultRev?: string
  /**
   * The document as it looked after the mutation was performed. This is only included if
   * the listener was configured with `includeResult: true`.
   */
  result?: SanityDocument<R>
  /**
   * The document as it looked before the mutation was performed. This is only included if
   * the listener was configured with `includePreviousRevision: true`.
   */
  previous?: SanityDocument<R> | null
  /**
   * The effects of the mutation, if the listener was configured with `effectFormat: 'mendoza'`.
   * Object with `apply` and `revert` arrays, see {@link https://github.com/sanity-io/mendoza}.
   */
  effects?: {
    apply: unknown[]
    revert: unknown[]
  }
  /**
   * A timestamp for when the mutation was performed
   */
  timestamp: string
  /**
   * The transaction ID for the mutation
   */
  transactionId: string
  /**
   * The type of transition the document went through.
   *
   * - `update` means the document was previously part of the subscribed set of documents,
   *   and still is.
   * - `appear` means the document was not previously part of the subscribed set of documents,
   *   but is now. This can happen both on create or if updating to a state where it now matches
   *   the filter provided to the listener.
   * - `disappear` means the document was previously part of the subscribed set of documents,
   *   but is no longer. This can happen both on delete or if updating to a state where it no
   *   longer matches the filter provided to the listener.
   */
  transition: 'update' | 'appear' | 'disappear'
  /**
   * Whether the change that triggered this event is visible to queries (query) or only to
   * subsequent transactions (transaction). The listener client can specify a preferred visibility
   * through the `visibility` parameter on the listener, but this is only on a best-effort basis,
   * and may yet not be accurate.
   */
  visibility: 'query' | 'transaction'
  /**
   * The total number of events that will be sent for this transaction.
   * Note that this may differ from the amount of _documents_ affected by the transaction, as this
   * number only includes the documents that matches the given filter.
   *
   * This can be useful if you need to perform changes to all matched documents atomically,
   * eg you would wait for `transactionTotalEvents` events with the same `transactionId` before
   * applying the changes locally.
   */
  transactionTotalEvents: number
  /**
   * The index of this event within the transaction. Note that events may be delivered out of order,
   * and that the index is zero-based.
   */
  transactionCurrentEvent: number
}

/** @internal */
export declare type MutationOperation = 'create' | 'delete' | 'update' | 'none'

/** @internal */
export declare type MutationSelection =
  | {
      query: string
      params?: MutationSelectionQueryParams
    }
  | {
      id: string | string[]
    }

/** @internal */
export declare type MutationSelectionQueryParams = {
  [key: string]: Any
}

/** @public */
declare class ObservableAgentsActionClient {
  #private
  constructor(client: ObservableSanityClient, httpRequest: HttpRequest)
  /**
   * Run an instruction to generate content in a target document.
   * @param request - instruction request
   */
  generate<DocumentShape extends Record<string, Any>>(
    request: GenerateInstruction<DocumentShape>,
  ): Observable<
    (typeof request)['async'] extends true
      ? {
          _id: string
        }
      : IdentifiedSanityDocumentStub & DocumentShape
  >
  /**
   * Transform a target document based on a source.
   * @param request - translation request
   */
  transform<DocumentShape extends Record<string, Any>>(
    request: TransformDocument<DocumentShape>,
  ): Observable<
    (typeof request)['async'] extends true
      ? {
          _id: string
        }
      : IdentifiedSanityDocumentStub & DocumentShape
  >
  /**
   * Translate a target document based on a source.
   * @param request - translation request
   */
  translate<DocumentShape extends Record<string, Any>>(
    request: TranslateDocument<DocumentShape>,
  ): Observable<
    (typeof request)['async'] extends true
      ? {
          _id: string
        }
      : IdentifiedSanityDocumentStub & DocumentShape
  >
}

/** @internal */
export declare class ObservableAssetsClient {
  #private
  constructor(client: ObservableSanityClient, httpRequest: HttpRequest)
  /**
   * Uploads a file asset to the configured dataset
   *
   * @param assetType - Asset type (file)
   * @param body - Asset content - can be a browser File instance, a Blob, a Node.js Buffer instance or a Node.js ReadableStream.
   * @param options - Options to use for the upload
   */
  upload(
    assetType: 'file',
    body: UploadBody,
    options?: UploadClientConfig,
  ): Observable<
    HttpRequestEvent<{
      document: SanityAssetDocument
    }>
  >
  /**
   * Uploads an image asset to the configured dataset
   *
   * @param assetType - Asset type (image)
   * @param body - Asset content - can be a browser File instance, a Blob, a Node.js Buffer instance or a Node.js ReadableStream.
   * @param options - Options to use for the upload
   */
  upload(
    assetType: 'image',
    body: UploadBody,
    options?: UploadClientConfig,
  ): Observable<
    HttpRequestEvent<{
      document: SanityImageAssetDocument
    }>
  >
  /**
   * Uploads a file or an image asset to the configured dataset
   *
   * @param assetType - Asset type (file/image)
   * @param body - Asset content - can be a browser File instance, a Blob, a Node.js Buffer instance or a Node.js ReadableStream.
   * @param options - Options to use for the upload
   */
  upload(
    assetType: 'file' | 'image',
    body: UploadBody,
    options?: UploadClientConfig,
  ): Observable<
    HttpRequestEvent<{
      document: SanityAssetDocument | SanityImageAssetDocument
    }>
  >
}

/** @internal */
export declare class ObservableDatasetsClient {
  #private
  constructor(client: ObservableSanityClient, httpRequest: HttpRequest)
  /**
   * Create a new dataset with the given name
   *
   * @param name - Name of the dataset to create
   * @param options - Options for the dataset
   */
  create(
    name: string,
    options?: {
      aclMode?: DatasetAclMode
    },
  ): Observable<DatasetResponse>
  /**
   * Edit a dataset with the given name
   *
   * @param name - Name of the dataset to edit
   * @param options - New options for the dataset
   */
  edit(
    name: string,
    options?: {
      aclMode?: DatasetAclMode
    },
  ): Observable<DatasetResponse>
  /**
   * Delete a dataset with the given name
   *
   * @param name - Name of the dataset to delete
   */
  delete(name: string): Observable<{
    deleted: true
  }>
  /**
   * Fetch a list of datasets for the configured project
   */
  list(): Observable<DatasetsResponse>
}

/** @internal */
export declare class ObservableMediaLibraryVideoClient {
  #private
  constructor(client: ObservableSanityClient, httpRequest: HttpRequest)
  /**
   * Get video playback information for a media library asset
   *
   * @param assetIdentifier - Asset instance identifier (GDR, video-prefixed ID, or container ID)
   * @param options - Options for transformations and expiration
   */
  getPlaybackInfo(
    assetIdentifier: MediaLibraryAssetInstanceIdentifier,
    options?: MediaLibraryPlaybackInfoOptions,
  ): Observable<VideoPlaybackInfo>
}

/** @public */
export declare class ObservablePatch extends BasePatch {
  #private
  constructor(
    selection: PatchSelection,
    operations?: PatchOperations,
    client?: ObservableSanityClient,
  )
  /**
   * Clones the patch
   */
  clone(): ObservablePatch
  /**
   * Commit the patch, returning an observable that produces the first patched document
   *
   * @param options - Options for the mutation operation
   */
  commit<R extends Record<string, Any> = Record<string, Any>>(
    options: FirstDocumentMutationOptions,
  ): Observable<SanityDocument<R>>
  /**
   * Commit the patch, returning an observable that produces an array of the mutated documents
   *
   * @param options - Options for the mutation operation
   */
  commit<R extends Record<string, Any> = Record<string, Any>>(
    options: AllDocumentsMutationOptions,
  ): Observable<SanityDocument<R>[]>
  /**
   * Commit the patch, returning an observable that produces a mutation result object
   *
   * @param options - Options for the mutation operation
   */
  commit(options: FirstDocumentIdMutationOptions): Observable<SingleMutationResult>
  /**
   * Commit the patch, returning an observable that produces a mutation result object
   *
   * @param options - Options for the mutation operation
   */
  commit(options: AllDocumentIdsMutationOptions): Observable<MultipleMutationResult>
  /**
   * Commit the patch, returning an observable that produces the first patched document
   *
   * @param options - Options for the mutation operation
   */
  commit<R extends Record<string, Any> = Record<string, Any>>(
    options?: BaseMutationOptions,
  ): Observable<SanityDocument<R>>
}

/** @public */
export declare type ObservablePatchBuilder = (patch: ObservablePatch) => ObservablePatch

/** @internal */
export declare class ObservableProjectsClient {
  #private
  constructor(client: ObservableSanityClient, httpRequest: HttpRequest)
  /**
   * Fetch a list of projects the authenticated user has access to.
   *
   * @param options - Options for the list request
   *   - `includeMembers` - Whether to include members in the response (default: true)
   *   - `organizationId` - ID of the organization to fetch projects for
   */
  list(options?: {includeMembers?: true; organizationId?: string}): Observable<SanityProject[]>
  list(options?: {
    includeMembers?: false
    organizationId?: string
  }): Observable<Omit<SanityProject, 'members'>[]>
  /**
   * Fetch a project by project ID
   *
   * @param projectId - ID of the project to fetch
   */
  getById(projectId: string): Observable<SanityProject>
}

/** @public */
declare class ObservableReleasesClient {
  #private
  constructor(client: ObservableSanityClient, httpRequest: HttpRequest)
  /**
   * @public
   *
   * Retrieve a release by id.
   *
   * @category Releases
   *
   * @param params - Release action parameters:
   *   - `releaseId` - The id of the release to retrieve.
   * @param options - Additional query options including abort signal and query tag.
   * @returns An observable that resolves to the release document {@link ReleaseDocument}.
   *
   * @example Retrieving a release by id
   * ```ts
   * client.observable.releases.get({releaseId: 'my-release'}).pipe(
   *   tap((release) => console.log(release)),
   *   // {
   *   //   _id: '_.releases.my-release',
   *   //   name: 'my-release'
   *   //   _type: 'system.release',
   *   //   metadata: {releaseType: 'asap'},
   *   //   _createdAt: '2021-01-01T00:00:00.000Z',
   *   //   ...
   *   // }
   * ).subscribe()
   * ```
   */
  get(
    {
      releaseId,
    }: {
      releaseId: string
    },
    options?: {
      signal?: AbortSignal
      tag?: string
    },
  ): Observable<ReleaseDocument | undefined>
  /**
   * @public
   *
   * Creates a new release under the given id, with metadata.
   *
   * @remarks
   * * If no releaseId is provided, a release id will be generated.
   * * If no metadata is provided, then an `undecided` releaseType will be used.
   *
   * @category Releases
   *
   * @param params - Release action parameters:
   *   - `releaseId` - The id of the release to create.
   *   - `metadata` - The metadata to associate with the release {@link ReleaseDocument}.
   * @param options - Additional action options.
   * @returns An observable that resolves to the `transactionId` and the release id and metadata.
   *
   * @example Creating a release with a custom id and metadata
   * ```ts
   * const releaseId = 'my-release'
   * const metadata: ReleaseDocument['metadata'] = {
   *   releaseType: 'asap',
   * }
   *
   * client.observable.releases.create({releaseId, metadata}).pipe(
   *   tap(({transactionId, releaseId, metadata}) => console.log(transactionId, releaseId, metadata)),
   *   // {
   *   //   transactionId: 'transaction-id',
   *   //   releaseId: 'my-release',
   *   //   metadata: {releaseType: 'asap'},
   *   // }
   * ).subscribe()
   * ```
   *
   * @example Creating a release with generated id and metadata
   * ```ts
   * client.observable.releases.create().pipe(
   *   tap(({metadata}) => console.log(metadata)),
   *   // {
   *   //   metadata: {releaseType: 'undecided'},
   *   // }
   * ).subscribe()
   * ```
   *
   * @example Creating a release using a custom transaction id
   * ```ts
   * client.observable.releases.create({transactionId: 'my-transaction-id'}).pipe(
   *   tap(({transactionId, metadata}) => console.log(transactionId, metadata)),
   *   // {
   *   //   transactionId: 'my-transaction-id',
   *   //   metadata: {releaseType: 'undecided'},
   *   // }
   * ).subscribe()
   * ```
   */
  create(options: BaseActionOptions): Observable<
    SingleActionResult & {
      releaseId: string
      metadata: ReleaseDocument['metadata']
    }
  >
  create(
    release: {
      releaseId?: string
      metadata?: Partial<ReleaseDocument['metadata']>
    },
    options?: BaseActionOptions,
  ): Observable<
    SingleActionResult & {
      releaseId: string
      metadata: ReleaseDocument['metadata']
    }
  >
  /**
   * @public
   *
   * Edits an existing release, updating the metadata.
   *
   * @category Releases
   *
   * @param params - Release action parameters:
   *   - `releaseId` - The id of the release to edit.
   *   - `patch` - The patch operation to apply on the release metadata {@link PatchMutationOperation}.
   * @param options - Additional action options.
   * @returns An observable that resolves to the `transactionId`.
   */
  edit(
    {
      releaseId,
      patch,
    }: {
      releaseId: string
      patch: PatchOperations
    },
    options?: BaseActionOptions,
  ): Observable<SingleActionResult>
  /**
   * @public
   *
   * Publishes all documents in a release at once. For larger releases the effect of the publish
   * will be visible immediately when querying but the removal of the `versions.<releasesId>.*`
   * documents and creation of the corresponding published documents with the new content may
   * take some time.
   *
   * During this period both the source and target documents are locked and cannot be
   * modified through any other means.
   *
   * @category Releases
   *
   * @param params - Release action parameters:
   *   - `releaseId` - The id of the release to publish.
   * @param options - Additional action options.
   * @returns An observable that resolves to the `transactionId`.
   */
  publish(
    {
      releaseId,
    }: {
      releaseId: string
    },
    options?: BaseActionOptions,
  ): Observable<SingleActionResult>
  /**
   * @public
   *
   * An archive action removes an active release. The documents that comprise the release
   * are deleted and therefore no longer queryable.
   *
   * While the documents remain in retention the last version can still be accessed using document history endpoint.
   *
   * @category Releases
   *
   * @param params - Release action parameters:
   *   - `releaseId` - The id of the release to archive.
   * @param options - Additional action options.
   * @returns An observable that resolves to the `transactionId`.
   */
  archive(
    {
      releaseId,
    }: {
      releaseId: string
    },
    options?: BaseActionOptions,
  ): Observable<SingleActionResult>
  /**
   * @public
   *
   * An unarchive action restores an archived release and all documents
   * with the content they had just prior to archiving.
   *
   * @category Releases
   *
   * @param params - Release action parameters:
   *   - `releaseId` - The id of the release to unarchive.
   * @param options - Additional action options.
   * @returns An observable that resolves to the `transactionId`.
   */
  unarchive(
    {
      releaseId,
    }: {
      releaseId: string
    },
    options?: BaseActionOptions,
  ): Observable<SingleActionResult>
  /**
   * @public
   *
   * A schedule action queues a release for publishing at the given future time.
   * The release is locked such that no documents in the release can be modified and
   * no documents that it references can be deleted as this would make the publish fail.
   * At the given time, the same logic as for the publish action is triggered.
   *
   * @category Releases
   *
   * @param params - Release action parameters:
   *   - `releaseId` - The id of the release to schedule.
   *   - `publishAt` - The serialised date and time to publish the release. If the `publishAt` is in the past, the release will be published immediately.
   * @param options - Additional action options.
   * @returns An observable that resolves to the `transactionId`.
   */
  schedule(
    {
      releaseId,
      publishAt,
    }: {
      releaseId: string
      publishAt: string
    },
    options?: BaseActionOptions,
  ): Observable<SingleActionResult>
  /**
   * @public
   *
   * An unschedule action stops a release from being published.
   * The documents in the release are considered unlocked and can be edited again.
   * This may fail if another release is scheduled to be published after this one and
   * has a reference to a document created by this one.
   *
   * @category Releases
   *
   * @param params - Release action parameters:
   *   - `releaseId` - The id of the release to unschedule.
   * @param options - Additional action options.
   * @returns An observable that resolves to the `transactionId`.
   */
  unschedule(
    {
      releaseId,
    }: {
      releaseId: string
    },
    options?: BaseActionOptions,
  ): Observable<SingleActionResult>
  /**
   * @public
   *
   * A delete action removes a published or archived release.
   * The backing system document will be removed from the dataset.
   *
   * @category Releases
   *
   * @param params - Release action parameters:
   *   - `releaseId` - The id of the release to delete.
   * @param options - Additional action options.
   * @returns An observable that resolves to the `transactionId`.
   */
  delete(
    {
      releaseId,
    }: {
      releaseId: string
    },
    options?: BaseActionOptions,
  ): Observable<SingleActionResult>
  /**
   * @public
   *
   * Fetch the documents in a release by release id.
   *
   * @category Releases
   *
   * @param params - Release action parameters:
   *   - `releaseId` - The id of the release to fetch documents for.
   * @param options - Additional mutation options {@link BaseMutationOptions}.
   * @returns An observable that resolves to the documents in the release.
   */
  fetchDocuments(
    {
      releaseId,
    }: {
      releaseId: string
    },
    options?: BaseMutationOptions,
  ): Observable<RawQueryResponse<SanityDocument[]>>
}

/** @public */
export declare class ObservableSanityClient {
  #private
  assets: ObservableAssetsClient
  datasets: ObservableDatasetsClient
  live: LiveClient
  mediaLibrary: {
    video: ObservableMediaLibraryVideoClient
  }
  projects: ObservableProjectsClient
  users: ObservableUsersClient
  agent: {
    action: ObservableAgentsActionClient
  }
  releases: ObservableReleasesClient
  /**
   * Instance properties
   */
  listen: typeof _listen
  constructor(httpRequest: HttpRequest, config?: ClientConfig)
  /**
   * Clone the client - returns a new instance
   */
  clone(): ObservableSanityClient
  /**
   * Returns the current client configuration
   */
  config(): InitializedClientConfig
  /**
   * Reconfigure the client. Note that this _mutates_ the current client.
   */
  config(newConfig?: Partial<ClientConfig>): this
  /**
   * Clone the client with a new (partial) configuration.
   *
   * @param newConfig - New client configuration properties, shallowly merged with existing configuration
   */
  withConfig(newConfig?: Partial<ClientConfig>): ObservableSanityClient
  /**
   * Perform a GROQ-query against the configured dataset.
   *
   * @param query - GROQ-query to perform
   */
  fetch<
    R = Any,
    Q extends QueryWithoutParams = QueryWithoutParams,
    const G extends string = string,
  >(query: G, params?: Q | QueryWithoutParams): Observable<ClientReturn<G, R>>
  /**
   * Perform a GROQ-query against the configured dataset.
   *
   * @param query - GROQ-query to perform
   * @param params - Optional query parameters
   * @param options - Optional request options
   */
  fetch<
    R = Any,
    Q extends QueryWithoutParams | QueryParams = QueryParams,
    const G extends string = string,
  >(
    query: G,
    params: Q extends QueryWithoutParams ? QueryWithoutParams : Q,
    options?: FilteredResponseQueryOptions,
  ): Observable<ClientReturn<G, R>>
  /**
   * Perform a GROQ-query against the configured dataset.
   *
   * @param query - GROQ-query to perform
   * @param params - Optional query parameters
   * @param options - Request options
   */
  fetch<
    R = Any,
    Q extends QueryWithoutParams | QueryParams = QueryParams,
    const G extends string = string,
  >(
    query: string,
    params: Q extends QueryWithoutParams ? QueryWithoutParams : Q,
    options: UnfilteredResponseQueryOptions,
  ): Observable<RawQueryResponse<ClientReturn<G, R>>>
  /**
   * Perform a GROQ-query against the configured dataset.
   *
   * @param query - GROQ-query to perform
   * @param params - Optional query parameters
   * @param options - Request options
   */
  fetch<
    R = Any,
    Q extends QueryWithoutParams | QueryParams = QueryParams,
    const G extends string = string,
  >(
    query: G,
    params: Q extends QueryWithoutParams ? QueryWithoutParams : Q,
    options: UnfilteredResponseWithoutQuery,
  ): Observable<RawQuerylessQueryResponse<ClientReturn<G, R>>>
  /**
   * Fetch a single document with the given ID.
   *
   * @param id - Document ID to fetch
   * @param options - Request options
   */
  getDocument<R extends Record<string, Any> = Record<string, Any>>(
    id: string,
    options: {
      signal?: AbortSignal
      tag?: string
      releaseId?: string
      includeAllVersions: true
    },
  ): Observable<SanityDocument<R>[]>
  /**
   * Fetch a single document with the given ID.
   *
   * @param id - Document ID to fetch
   * @param options - Request options
   */
  getDocument<R extends Record<string, Any> = Record<string, Any>>(
    id: string,
    options?: {
      signal?: AbortSignal
      tag?: string
      releaseId?: string
      includeAllVersions?: false
    },
  ): Observable<SanityDocument<R> | undefined>
  /**
   * Fetch multiple documents in one request.
   * Should be used sparingly - performing a query is usually a better option.
   * The order/position of documents is preserved based on the original array of IDs.
   * If any of the documents are missing, they will be replaced by a `null` entry in the returned array
   *
   * @param ids - Document IDs to fetch
   * @param options - Request options
   */
  getDocuments<R extends Record<string, Any> = Record<string, Any>>(
    ids: string[],
    options?: {
      tag?: string
    },
  ): Observable<(SanityDocument<R> | null)[]>
  /**
   * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.
   * Returns an observable that resolves to the created document.
   *
   * @param document - Document to create
   * @param options - Mutation options
   */
  create<R extends Record<string, Any> = Record<string, Any>>(
    document: SanityDocumentStub<R>,
    options: FirstDocumentMutationOptions,
  ): Observable<SanityDocument<R>>
  /**
   * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.
   * Returns an observable that resolves to an array containing the created document.
   *
   * @param document - Document to create
   * @param options - Mutation options
   */
  create<R extends Record<string, Any> = Record<string, Any>>(
    document: SanityDocumentStub<R>,
    options: AllDocumentsMutationOptions,
  ): Observable<SanityDocument<R>[]>
  /**
   * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.
   * Returns an observable that resolves to a mutation result object containing the ID of the created document.
   *
   * @param document - Document to create
   * @param options - Mutation options
   */
  create<R extends Record<string, Any> = Record<string, Any>>(
    document: SanityDocumentStub<R>,
    options: FirstDocumentIdMutationOptions,
  ): Observable<SingleMutationResult>
  /**
   * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.
   * Returns an observable that resolves to a mutation result object containing the ID of the created document.
   *
   * @param document - Document to create
   * @param options - Mutation options
   */
  create<R extends Record<string, Any> = Record<string, Any>>(
    document: SanityDocumentStub<R>,
    options: AllDocumentIdsMutationOptions,
  ): Observable<MultipleMutationResult>
  /**
   * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.
   * Returns an observable that resolves to the created document.
   *
   * @param document - Document to create
   * @param options - Mutation options
   */
  create<R extends Record<string, Any> = Record<string, Any>>(
    document: SanityDocumentStub<R>,
    options?: BaseMutationOptions,
  ): Observable<SanityDocument<R>>
  /**
   * Create a document if no document with the same ID already exists.
   * Returns an observable that resolves to the created document.
   *
   * @param document - Document to create
   * @param options - Mutation options
   */
  createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(
    document: IdentifiedSanityDocumentStub<R>,
    options: FirstDocumentMutationOptions,
  ): Observable<SanityDocument<R>>
  /**
   * Create a document if no document with the same ID already exists.
   * Returns an observable that resolves to an array containing the created document.
   *
   * @param document - Document to create
   * @param options - Mutation options
   */
  createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(
    document: IdentifiedSanityDocumentStub<R>,
    options: AllDocumentsMutationOptions,
  ): Observable<SanityDocument<R>[]>
  /**
   * Create a document if no document with the same ID already exists.
   * Returns an observable that resolves to a mutation result object containing the ID of the created document.
   *
   * @param document - Document to create
   * @param options - Mutation options
   */
  createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(
    document: IdentifiedSanityDocumentStub<R>,
    options: FirstDocumentIdMutationOptions,
  ): Observable<SingleMutationResult>
  /**
   * Create a document if no document with the same ID already exists.
   * Returns an observable that resolves to a mutation result object containing the ID of the created document.
   *
   * @param document - Document to create
   * @param options - Mutation options
   */
  createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(
    document: IdentifiedSanityDocumentStub<R>,
    options: AllDocumentIdsMutationOptions,
  ): Observable<MultipleMutationResult>
  /**
   * Create a document if no document with the same ID already exists.
   * Returns an observable that resolves to the created document.
   *
   * @param document - Document to create
   * @param options - Mutation options
   */
  createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(
    document: IdentifiedSanityDocumentStub<R>,
    options?: BaseMutationOptions,
  ): Observable<SanityDocument<R>>
  /**
   * Create a document if it does not exist, or replace a document with the same document ID
   * Returns an observable that resolves to the created document.
   *
   * @param document - Document to either create or replace
   * @param options - Mutation options
   */
  createOrReplace<R extends Record<string, Any> = Record<string, Any>>(
    document: IdentifiedSanityDocumentStub<R>,
    options: FirstDocumentMutationOptions,
  ): Observable<SanityDocument<R>>
  /**
   * Create a document if it does not exist, or replace a document with the same document ID
   * Returns an observable that resolves to an array containing the created document.
   *
   * @param document - Document to either create or replace
   * @param options - Mutation options
   */
  createOrReplace<R extends Record<string, Any> = Record<string, Any>>(
    document: IdentifiedSanityDocumentStub<R>,
    options: AllDocumentsMutationOptions,
  ): Observable<SanityDocument<R>[]>
  /**
   * Create a document if it does not exist, or replace a document with the same document ID
   * Returns an observable that resolves to a mutation result object containing the ID of the created document.
   *
   * @param document - Document to either create or replace
   * @param options - Mutation options
   */
  createOrReplace<R extends Record<string, Any> = Record<string, Any>>(
    document: IdentifiedSanityDocumentStub<R>,
    options: FirstDocumentIdMutationOptions,
  ): Observable<SingleMutationResult>
  /**
   * Create a document if it does not exist, or replace a document with the same document ID
   * Returns an observable that resolves to a mutation result object containing the created document ID.
   *
   * @param document - Document to either create or replace
   * @param options - Mutation options
   */
  createOrReplace<R extends Record<string, Any> = Record<string, Any>>(
    document: IdentifiedSanityDocumentStub<R>,
    options: AllDocumentIdsMutationOptions,
  ): Observable<MultipleMutationResult>
  /**
   * Create a document if it does not exist, or replace a document with the same document ID
   * Returns an observable that resolves to the created document.
   *
   * @param document - Document to either create or replace
   * @param options - Mutation options
   */
  createOrReplace<R extends Record<string, Any> = Record<string, Any>>(
    document: IdentifiedSanityDocumentStub<R>,
    options?: BaseMutationOptions,
  ): Observable<SanityDocument<R>>
  /**
   * @public
   *
   * Creates a new version of a published document.
   *
   * @remarks
   * * Requires a document with a `_type` property.
   * * Creating a version with no `releaseId` will create a new draft version of the published document.
   * * If the `document._id` is defined, it should be a draft or release version ID that matches the version ID generated from `publishedId` and `releaseId`.
   * * If the `document._id` is not defined, it will be generated from `publishedId` and `releaseId`.
   * * To create a version of an unpublished document, use the `client.create` method.
   *
   * @category Versions
   *
   * @param params - Version action parameters:
   *   - `document` - The document to create as a new version (must include `_type`).
   *   - `publishedId` - The ID of the published document being versioned.
   *   - `releaseId` - The ID of the release to create the version for.
   * @param options - Additional action options.
   * @returns an observable that resolves to the `transactionId`.
   *
   * @example Creating a new version of a published document with a generated version ID
   * ```ts
   * client.observable.createVersion({
   *   // The document does not need to include an `_id` property since it will be generated from `publishedId` and `releaseId`
   *   document: {_type: 'myDocument', title: 'My Document'},
   *   publishedId: 'myDocument',
   *   releaseId: 'myRelease',
   * })
   *
   * // The following document will be created:
   * // {
   * //   _id: 'versions.myRelease.myDocument',
   * //   _type: 'myDocument',
   * //   title: 'My Document',
   * // }
   * ```
   *
   * @example Creating a new version of a published document with a specified version ID
   * ```ts
   * client.observable.createVersion({
   *   document: {_type: 'myDocument', _id: 'versions.myRelease.myDocument', title: 'My Document'},
   *   // `publishedId` and `releaseId` are not required since `document._id` has been specified
   * })
   *
   * // The following document will be created:
   * // {
   * //   _id: 'versions.myRelease.myDocument',
   * //   _type: 'myDocument',
   * //   title: 'My Document',
   * // }
   * ```
   *
   * @example Creating a new draft version of a published document
   * ```ts
   * client.observable.createVersion({
   *   document: {_type: 'myDocument', title: 'My Document'},
   *   publishedId: 'myDocument',
   * })
   *
   * // The following document will be created:
   * // {
   * //   _id: 'drafts.myDocument',
   * //   _type: 'myDocument',
   * //   title: 'My Document',
   * // }
   * ```
   */
  createVersion<R extends Record<string, Any>>(
    args: {
      document: SanityDocumentStub<R>
      publishedId: string
      releaseId?: string
    },
    options?: BaseActionOptions,
  ): Observable<SingleActionResult | MultipleActionResult>
  createVersion<R extends Record<string, Any>>(
    args: {
      document: IdentifiedSanityDocumentStub<R>
      publishedId?: string
      releaseId?: string
    },
    options?: BaseActionOptions,
  ): Observable<SingleActionResult | MultipleActionResult>
  createVersion(
    args: {
      baseId: string
      releaseId: string
      publishedId: string
      ifBaseRevisionId?: string
    },
    options?: BaseActionOptions,
  ): Observable<SingleActionResult | MultipleActionResult>
  /**
   * Deletes a document with the given document ID.
   * Returns an observable that resolves to the deleted document.
   *
   * @param id - Document ID to delete
   * @param options - Options for the mutation
   */
  delete<R extends Record<string, Any> = Record<string, Any>>(
    id: string,
    options: FirstDocumentMutationOptions,
  ): Observable<SanityDocument<R>>
  /**
   * Deletes a document with the given document ID.
   * Returns an observable that resolves to an array containing the deleted document.
   *
   * @param id - Document ID to delete
   * @param options - Options for the mutation
   */
  delete<R extends Record<string, Any> = Record<string, Any>>(
    id: string,
    options: AllDocumentsMutationOptions,
  ): Observable<SanityDocument<R>[]>
  /**
   * Deletes a document with the given document ID.
   * Returns an observable that resolves to a mutation result object containing the deleted document ID.
   *
   * @param id - Document ID to delete
   * @param options - Options for the mutation
   */
  delete(id: string, options: FirstDocumentIdMutationOptions): Observable<SingleMutationResult>
  /**
   * Deletes a document with the given document ID.
   * Returns an observable that resolves to a mutation result object containing the deleted document ID.
   *
   * @param id - Document ID to delete
   * @param options - Options for the mutation
   */
  delete(id: string, options: AllDocumentIdsMutationOptions): Observable<MultipleMutationResult>
  /**
   * Deletes a document with the given document ID.
   * Returns an observable that resolves to the deleted document.
   *
   * @param id - Document ID to delete
   * @param options - Options for the mutation
   */
  delete<R extends Record<string, Any> = Record<string, Any>>(
    id: string,
    options?: BaseMutationOptions,
  ): Observable<SanityDocument<R>>
  /**
   * Deletes one or more documents matching the given query or document ID.
   * Returns an observable that resolves to first deleted document.
   *
   * @param selection - An object with either an `id` or `query` key defining what to delete
   * @param options - Options for the mutation
   */
  delete<R extends Record<string, Any> = Record<string, Any>>(
    selection: MutationSelection,
    options: FirstDocumentMutationOptions,
  ): Observable<SanityDocument<R>>
  /**
   * Deletes one or more documents matching the given query or document ID.
   * Returns an observable that resolves to an array containing the deleted documents.
   *
   * @param selection - An object with either an `id` or `query` key defining what to delete
   * @param options - Options for the mutation
   */
  delete<R extends Record<string, Any> = Record<string, Any>>(
    selection: MutationSelection,
    options: AllDocumentsMutationOptions,
  ): Observable<SanityDocument<R>[]>
  /**
   * Deletes one or more documents matching the given query or document ID.
   * Returns an observable that resolves to a mutation result object containing the ID of the first deleted document.
   *
   * @param selection - An object with either an `id` or `query` key defining what to delete
   * @param options - Options for the mutation
   */
  delete(
    selection: MutationSelection,
    options: FirstDocumentIdMutationOptions,
  ): Observable<SingleMutationResult>
  /**
   * Deletes one or more documents matching the given query or document ID.
   * Returns an observable that resolves to a mutation result object containing the document IDs that were deleted.
   *
   * @param selection - An object with either an `id` or `query` key defining what to delete
   * @param options - Options for the mutation
   */
  delete(
    selection: MutationSelection,
    options: AllDocumentIdsMutationOptions,
  ): Observable<MultipleMutationResult>
  /**
   * Deletes one or more documents matching the given query or document ID.
   * Returns an observable that resolves to first deleted document.
   *
   * @param selection - An object with either an `id` or `query` key defining what to delete
   * @param options - Options for the mutation
   */
  delete<R extends Record<string, Any> = Record<string, Any>>(
    selection: MutationSelection,
    options?: BaseMutationOptions,
  ): Observable<SanityDocument<R>>
  /**
   * @public
   *
   * Deletes the draft or release version of a document.
   *
   * @remarks
   * * Discarding a version with no `releaseId` will discard the draft version of the published document.
   * * If the draft or release version does not exist, any error will throw.
   *
   * @param params - Version action parameters:
   *   - `releaseId` - The ID of the release to discard the document from.
   *   - `publishedId` - The published ID of the document to discard.
   * @param purge - if `true` the document history is also discarded.
   * @param options - Additional action options.
   * @returns an observable that resolves to the `transactionId`.
   *
   * @example Discarding a release version of a document
   * ```ts
   * client.observable.discardVersion({publishedId: 'myDocument', releaseId: 'myRelease'})
   * // The document with the ID `versions.myRelease.myDocument` will be discarded.
   * ```
   *
   * @example Discarding a draft version of a document
   * ```ts
   * client.observable.discardVersion({publishedId: 'myDocument'})
   * // The document with the ID `drafts.myDocument` will be discarded.
   * ```
   */
  discardVersion(
    {
      releaseId,
      publishedId,
    }: {
      releaseId?: string
      publishedId: string
    },
    purge?: boolean,
    options?: BaseActionOptions,
  ): Observable<SingleActionResult | MultipleActionResult>
  /**
   * @public
   *
   * Replaces an existing version document.
   *
   * @remarks
   * * Requires a document with a `_type` property.
   * * If the `document._id` is defined, it should be a draft or release version ID that matches the version ID generated from `publishedId` and `releaseId`.
   * * If the `document._id` is not defined, it will be generated from `publishedId` and `releaseId`.
   * * Replacing a version with no `releaseId` will replace the draft version of the published document.
   * * At least one of the **version** or **published** documents must exist.
   *
   * @param params - Version action parameters:
   *   - `document` - The new document to replace the version with.
   *   - `releaseId` - The ID of the release where the document version is replaced.
   *   - `publishedId` - The ID of the published document to replace.
   * @param options - Additional action options.
   * @returns an observable that resolves to the `transactionId`.
   *
   * @example Replacing a release version of a published document with a generated version ID
   * ```ts
   * client.observable.replaceVersion({
   *   document: {_type: 'myDocument', title: 'My Document'},
   *   publishedId: 'myDocument',
   *   releaseId: 'myRelease',
   * })
   *
   * // The following document will be patched:
   * // {
   * //   _id: 'versions.myRelease.myDocument',
   * //   _type: 'myDocument',
   * //   title: 'My Document',
   * // }
   * ```
   *
   * @example Replacing a release version of a published document with a specified version ID
   * ```ts
   * client.observable.replaceVersion({
   *   document: {_type: 'myDocument', _id: 'versions.myRelease.myDocument', title: 'My Document'},
   *   // `publishedId` and `releaseId` are not required since `document._id` has been specified
   * })
   *
   * // The following document will be patched:
   * // {
   * //   _id: 'versions.myRelease.myDocument',
   * //   _type: 'myDocument',
   * //   title: 'My Document',
   * // }
   * ```
   *
   * @example Replacing a draft version of a published document
   * ```ts
   * client.observable.replaceVersion({
   *   document: {_type: 'myDocument', title: 'My Document'},
   *   publishedId: 'myDocument',
   * })
   *
   * // The following document will be patched:
   * // {
   * //   _id: 'drafts.myDocument',
   * //   _type: 'myDocument',
   * //   title: 'My Document',
   * // }
   * ```
   */
  replaceVersion<R extends Record<string, Any>>(
    args: {
      document: SanityDocumentStub<R>
      publishedId: string
      releaseId?: string
    },
    options?: BaseActionOptions,
  ): Observable<SingleActionResult | MultipleActionResult>
  replaceVersion<R extends Record<string, Any>>(
    args: {
      document: IdentifiedSanityDocumentStub<R>
      publishedId?: string
      releaseId?: string
    },
    options?: BaseActionOptions,
  ): Observable<SingleActionResult | MultipleActionResult>
  /**
   * @public
   *
   * Used to indicate when a document within a release should be unpublished when
   * the release is run.
   *
   * @remarks
   * * If the published document does not exist, an error will be thrown.
   *
   * @param params - Version action parameters:
   *   - `releaseId` - The ID of the release to unpublish the document from.
   *   - `publishedId` - The published ID of the document to unpublish.
   * @param options - Additional action options.
   * @returns an observable that resolves to the `transactionId`.
   *
   * @example Unpublishing a release version of a published document
   * ```ts
   * client.observable.unpublishVersion({publishedId: 'myDocument', releaseId: 'myRelease'})
   * // The document with the ID `versions.myRelease.myDocument` will be unpublished. when `myRelease` is run.
   * ```
   */
  unpublishVersion(
    {
      releaseId,
      publishedId,
    }: {
      releaseId: string
      publishedId: string
    },
    options?: BaseActionOptions,
  ): Observable<SingleActionResult | MultipleActionResult>
  /**
   * Perform mutation operations against the configured dataset
   * Returns an observable that resolves to the first mutated document.
   *
   * @param operations - Mutation operations to execute
   * @param options - Mutation options
   */
  mutate<R extends Record<string, Any> = Record<string, Any>>(
    operations: Mutation<R>[] | ObservablePatch | ObservableTransaction,
    options: FirstDocumentMutationOptions,
  ): Observable<SanityDocument<R>>
  /**
   * Perform mutation operations against the configured dataset.
   * Returns an observable that resolves to an array of the mutated documents.
   *
   * @param operations - Mutation operations to execute
   * @param options - Mutation options
   */
  mutate<R extends Record<string, Any> = Record<string, Any>>(
    operations: Mutation<R>[] | ObservablePatch | ObservableTransaction,
    options: AllDocumentsMutationOptions,
  ): Observable<SanityDocument<R>[]>
  /**
   * Perform mutation operations against the configured dataset
   * Returns an observable that resolves to a mutation result object containing the document ID of the first mutated document.
   *
   * @param operations - Mutation operations to execute
   * @param options - Mutation options
   */
  mutate<R extends Record<string, Any> = Record<string, Any>>(
    operations: Mutation<R>[] | ObservablePatch | ObservableTransaction,
    options: FirstDocumentIdMutationOptions,
  ): Observable<SingleMutationResult>
  /**
   * Perform mutation operations against the configured dataset
   * Returns an observable that resolves to a mutation result object containing the mutated document IDs.
   *
   * @param operations - Mutation operations to execute
   * @param options - Mutation options
   */
  mutate<R extends Record<string, Any> = Record<string, Any>>(
    operations: Mutation<R>[] | ObservablePatch | ObservableTransaction,
    options: AllDocumentIdsMutationOptions,
  ): Observable<MultipleMutationResult>
  /**
   * Perform mutation operations against the configured dataset
   * Returns an observable that resolves to the first mutated document.
   *
   * @param operations - Mutation operations to execute
   * @param options - Mutation options
   */
  mutate<R extends Record<string, Any> = Record<string, Any>>(
    operations: Mutation<R>[] | ObservablePatch | ObservableTransaction,
    options?: BaseMutationOptions,
  ): Observable<SanityDocument<R>>
  /**
   * Create a new buildable patch of operations to perform
   *
   * @param documentId - Document ID to patch
   * @param operations - Optional object of patch operations to initialize the patch instance with
   * @returns Patch instance - call `.commit()` to perform the operations defined
   */
  patch(documentId: string, operations?: PatchOperations): ObservablePatch
  /**
   * Create a new buildable patch of operations to perform
   *
   * @param documentIds - Array of document IDs to patch
   * @param operations - Optional object of patch operations to initialize the patch instance with
   * @returns Patch instance - call `.commit()` to perform the operations defined
   */
  patch(documentIds: string[], operations?: PatchOperations): ObservablePatch
  /**
   * Create a new buildable patch of operations to perform
   *
   * @param selection - An object with `query` and optional `params`, defining which document(s) to patch
   * @param operations - Optional object of patch operations to initialize the patch instance with
   * @returns Patch instance - call `.commit()` to perform the operations defined
   */
  patch(selection: MutationSelection, operations?: PatchOperations): ObservablePatch
  /**
   * Create a new transaction of mutations
   *
   * @param operations - Optional array of mutation operations to initialize the transaction instance with
   */
  transaction<R extends Record<string, Any> = Record<string, Any>>(
    operations?: Mutation<R>[],
  ): ObservableTransaction
  /**
   * Perform action operations against the configured dataset
   *
   * @param operations - Action operation(s) to execute
   * @param options - Action options
   */
  action(
    operations: Action | Action[],
    options?: BaseActionOptions,
  ): Observable<SingleActionResult | MultipleActionResult>
  /**
   * Perform an HTTP request against the Sanity API
   *
   * @param options - Request options
   */
  request<R = Any>(options: RawRequestOptions): Observable<R>
  /**
   * Get a Sanity API URL for the URI provided
   *
   * @param uri - URI/path to build URL for
   * @param canUseCdn - Whether or not to allow using the API CDN for this route
   */
  getUrl(uri: string, canUseCdn?: boolean): string
  /**
   * Get a Sanity API URL for the data operation and path provided
   *
   * @param operation - Data operation (eg `query`, `mutate`, `listen` or similar)
   * @param path - Path to append after the operation
   */
  getDataUrl(operation: string, path?: string): string
}

/** @public */
export declare class ObservableTransaction extends BaseTransaction {
  #private
  constructor(operations?: Mutation[], client?: ObservableSanityClient, transactionId?: string)
  /**
   * Clones the transaction
   */
  clone(): ObservableTransaction
  /**
   * Commit the transaction, returning an observable that produces the first mutated document
   *
   * @param options - Options for the mutation operation
   */
  commit<R extends Record<string, Any>>(
    options: TransactionFirstDocumentMutationOptions,
  ): Observable<SanityDocument<R>>
  /**
   * Commit the transaction, returning an observable that produces an array of the mutated documents
   *
   * @param options - Options for the mutation operation
   */
  commit<R extends Record<string, Any>>(
    options: TransactionAllDocumentsMutationOptions,
  ): Observable<SanityDocument<R>[]>
  /**
   * Commit the transaction, returning an observable that produces a mutation result object
   *
   * @param options - Options for the mutation operation
   */
  commit(options: TransactionFirstDocumentIdMutationOptions): Observable<SingleMutationResult>
  /**
   * Commit the transaction, returning an observable that produces a mutation result object
   *
   * @param options - Options for the mutation operation
   */
  commit(options: TransactionAllDocumentIdsMutationOptions): Observable<MultipleMutationResult>
  /**
   * Commit the transaction, returning an observable that produces a mutation result object
   *
   * @param options - Options for the mutation operation
   */
  commit(options?: BaseMutationOptions): Observable<MultipleMutationResult>
  /**
   * Performs a patch on the given document ID. Can either be a builder function or an object of patch operations.
   * The operation is added to the current transaction, ready to be commited by `commit()`
   *
   * @param documentId - Document ID to perform the patch operation on
   * @param patchOps - Operations to perform, or a builder function
   */
  patch(documentId: string, patchOps?: ObservablePatchBuilder | PatchOperations): this
  /**
   * Adds the given patch instance to the transaction.
   * The operation is added to the current transaction, ready to be commited by `commit()`
   *
   * @param patch - ObservablePatch to execute
   */
  patch(patch: ObservablePatch): this
}

/** @public */
export declare class ObservableUsersClient {
  #private
  constructor(client: ObservableSanityClient, httpRequest: HttpRequest)
  /**
   * Fetch a user by user ID
   *
   * @param id - User ID of the user to fetch. If `me` is provided, a minimal response including the users role is returned.
   */
  getById<T extends 'me' | string>(
    id: T,
  ): Observable<T extends 'me' ? CurrentSanityUser : SanityUser>
}

/**
 * The listener connection has been established
 * note: it's usually a better option to use the 'welcome' event
 * @public
 */
export declare type OpenEvent = {
  type: 'open'
}

/** @internal */
export declare type PartialExcept<T, K extends keyof T> = Pick<T, K> & Partial<Omit<T, K>>

/** @public */
export declare class Patch extends BasePatch {
  #private
  constructor(selection: PatchSelection, operations?: PatchOperations, client?: SanityClient)
  /**
   * Clones the patch
   */
  clone(): Patch
  /**
   * Commit the patch, returning a promise that resolves to the first patched document
   *
   * @param options - Options for the mutation operation
   */
  commit<R extends Record<string, Any> = Record<string, Any>>(
    options: FirstDocumentMutationOptions,
  ): Promise<SanityDocument<R>>
  /**
   * Commit the patch, returning a promise that resolves to an array of the mutated documents
   *
   * @param options - Options for the mutation operation
   */
  commit<R extends Record<string, Any> = Record<string, Any>>(
    options: AllDocumentsMutationOptions,
  ): Promise<SanityDocument<R>[]>
  /**
   * Commit the patch, returning a promise that resolves to a mutation result object
   *
   * @param options - Options for the mutation operation
   */
  commit(options: FirstDocumentIdMutationOptions): Promise<SingleMutationResult>
  /**
   * Commit the patch, returning a promise that resolves to a mutation result object
   *
   * @param options - Options for the mutation operation
   */
  commit(options: AllDocumentIdsMutationOptions): Promise<MultipleMutationResult>
  /**
   * Commit the patch, returning a promise that resolves to the first patched document
   *
   * @param options - Options for the mutation operation
   */
  commit<R extends Record<string, Any> = Record<string, Any>>(
    options?: BaseMutationOptions,
  ): Promise<SanityDocument<R>>
}

/** @public */
export declare type PatchBuilder = (patch: Patch) => Patch

/** @beta */
export declare type PatchDocument<T extends Record<string, Any> = Record<string, Any>> =
  | PatchDocumentSync<T>
  | PatchDocumentAsync<T>

/** @beta */
declare type PatchDocumentAsync<T extends Record<string, Any> = Record<string, Any>> = (
  | PatchExistingDocumentRequest
  | PatchTargetDocumentRequest<T>
) &
  PatchRequestBase &
  AgentActionAsync

/** @beta */
declare type PatchDocumentSync<T extends Record<string, Any> = Record<string, Any>> = (
  | PatchExistingDocumentRequest
  | PatchTargetDocumentRequest<T>
) &
  PatchRequestBase &
  AgentActionSync

/**
 * Patches an existing document
 * @beta
 */
declare interface PatchExistingDocumentRequest {
  /**
   * @see #AgentActionSchema.forcePublishedWrite
   */
  documentId: string
  targetDocument?: never
}

/** @internal */
export declare type PatchMutationOperation = PatchOperations & MutationSelection

/**  @beta */
export declare type PatchOperation = 'set' | 'append' | 'mixed' | 'unset'

/** @internal */
export declare interface PatchOperations {
  set?: {
    [key: string]: Any
  }
  setIfMissing?: {
    [key: string]: Any
  }
  diffMatchPatch?: {
    [key: string]: Any
  }
  unset?: string[]
  inc?: {
    [key: string]: number
  }
  dec?: {
    [key: string]: number
  }
  insert?: InsertPatch
  ifRevisionID?: string
}

/**  @beta */
declare interface PatchRequestBase extends AgentActionSchema {
  /**
   * Target defines which parts of the document will be affected by the instruction.
   * It can be an array, so multiple parts of the document can be separately configured in detail.
   *
   * Omitting target implies that the document itself is the root.
   *
   * Notes:
   * - instruction can only affect fields up to `maxPathDepth`
   * - when multiple targets are provided, they will be coalesced into a single target sharing a common target root.
   * It is therefore an error to provide conflicting include/exclude across targets (ie, include title in one, and exclude it in another)
   *
   * @see AgentActionRequestBase#conditionalPaths
   */
  target: PatchTarget | PatchTarget[]
}

/** @internal */
export declare type PatchSelection = string | string[] | MutationSelection

/**  @beta */
export declare type PatchTarget = {
  /**
   * Determines how the target path will be patched.
   *
   * ### Operation types
   * - `'set'` – an *overwriting* operation: sets the full field value for primitive targets, and merges the provided value with existing values for objects
   * - `'append'`:
   *    – array fields: appends new items to the end of the array,
   *    - string fields: '"existing content" "new content"'
   *    - text fields: '"existing content"\\n"new content"'
   *    - number fields: existing + new
   *    - other field types not mentioned will set instead (dates, url)
   * - `'mixed'` –  sets non-array fields, and appends to array fields
   * - `'unset'` – removes whatever value is on the target path
   *
   * All operations except unset requires a `value`.
   *
   * #### Appending in the middle of arrays
   * To append to an array, use the 'append' operation, and provide an array value with one or more array items.
   *
   * `target: {path: ['array'], operation: 'append', value: [{_type: 'item' _key: 'a'}]}` will append the items in the value to the existing array.
   *
   * To insert in the middle of the array, use `target: {path: ['array', {_key: 'appendAfterKey'}], operation: 'append', value: [{_type: 'item' _key: 'a'}]}`.
   * Here, `{_type: 'item' _key: 'a'}` will be appended after the array item with key `'appendAfterKey'`
   *
   * It is optional to provide a _key for inserted array items; if one isn't provided, it will be generated.
   */
  operation: PatchOperation
  path: AgentActionPathSegment | AgentActionPath
} & (
  | {
      operation: 'unset'
      value?: never
    }
  | {
      operation: Exclude<PatchOperation, 'unset'>
      value: AnyNonNullable
    }
)

/**
 * Create a new document, then patch it
 * @beta
 */
declare interface PatchTargetDocumentRequest<T extends Record<string, Any> = Record<string, Any>> {
  /**
   * @see #AgentActionSchema.forcePublishedWrite
   */
  targetDocument: GenerateTargetDocument<T>
  documentId?: never
}

/** @public */
declare interface ProgressEvent_2 {
  type: 'progress'
  stage: 'upload' | 'download'
  percent: number
  total?: number
  loaded?: number
  lengthComputable: boolean
}
export {ProgressEvent_2 as ProgressEvent}

/** @internal */
export declare class ProjectsClient {
  #private
  constructor(client: SanityClient, httpRequest: HttpRequest)
  /**
   * Fetch a list of projects the authenticated user has access to.
   *
   * @param options - Options for the list request
   *   - `includeMembers` - Whether to include members in the response (default: true)
   *   - `organizationId` - ID of the organization to fetch projects for
   */
  list(options?: {includeMembers?: true; organizationId?: string}): Promise<SanityProject[]>
  list(options?: {
    includeMembers?: false
    organizationId?: string
  }): Promise<Omit<SanityProject, 'members'>[]>
  /**
   * Fetch a project by project ID
   *
   * @param projectId - ID of the project to fetch
   */
  getById(projectId: string): Promise<SanityProject>
}

/**
 * @beta
 */
declare interface PromptJsonResponse<T extends Record<string, Any> = Record<string, Any>> {
  /**
   *
   * When format is 'json', the response will be json according to the instruction.
   * Note: In addition to setting this to 'json',  `instruction` MUST include the word 'JSON', or 'json' for this to work.
   */
  format: 'json'
}

/** @beta */
export declare type PromptRequest<T extends Record<string, Any> = Record<string, Any>> = (
  | PromptTextResponse
  | PromptJsonResponse<T>
) &
  PromptRequestBase

/**  @beta */
declare interface PromptRequestBase {
  /**
   * Instruct the LLM how it should generate content. Be as specific and detailed as needed.
   *
   * The LLM only has access to information in the instruction, plus the target schema.
   *
   * String template with support for $variable from `instructionParams`.
   * */
  instruction: string
  /**
   * param values for the string template, keys are the variable name, ie if the template has "$variable", one key must be "variable"
   *
   * ### Examples
   *
   * #### Constant
   *
   * ##### Shorthand
   * ```ts
   * client.agent.action.prompt({
   *   instruction: 'Give the following topic:\n $topic \n ---\nReturns some facts about it',
   *   instructionParams: {
   *     topic: 'Grapefruit'
   *   },
   * })
   * ```
   * ##### Object-form
   *
   * ```ts
   * client.agent.action.prompt({
   *   instruction: 'Give the following topic:\n $topic \n ---\nReturns some facts about it.',
   *   instructionParams: {
   *     topic: {
   *       type: 'constant',
   *       value: 'Grapefruit'
   *     },
   *   },
   * })
   * ```
   * #### Field
   * ```ts
   * client.agent.action.prompt({
   *   instruction: 'Give the following field value:\n $pte \n ---\nGenerate keywords.',
   *   instructionParams: {
   *     pte: {
   *       type: 'field',
   *       path: ['pteField'],
   *       documentId: 'someSanityDocId'
   *     },
   *   },
   * })
   * ```
   * #### Document
   * ```ts
   * client.agent.action.prompt({
   *   json: true,
   *   instruction: 'Given the following document:$document\nCreate a JSON string[] array with keywords describing it.',
   *   instructionParams: {
   *     document: {
   *       type: 'document',
   *       documentId: 'someSanityDocId'
   *     },
   *   },
   * })
   * ```
   *
   * #### GROQ
   * ```ts
   * client.agent.action.prompt({
   *   instruction: 'Return the best title amongst these: $titles.',
   *   instructionParams: {
   *     titles: {
   *       type: 'groq',
   *       query: '* [_type==$type].title',
   *       params: {type: 'article'}
   *     },
   *   },
   * })
   * ```
   * */
  instructionParams?: AgentActionParams<{
    docIdRequired: true
  }>
  /**
   * Controls how much variance the instructions will run with.
   *
   * Value must be in the range [0, 1] (inclusive).
   *
   * Default: 0.3
   */
  temperature?: number
}

declare interface PromptTextResponse {
  /**
   * When format is 'string', the response will be a raw text response to the instruction.
   */
  format?: 'string'
}

/**
 * Publishes a draft document.
 * If a published version of the document already exists this is replaced by the current draft document.
 * In either case the draft document is deleted.
 * The optional revision id parameters can be used for optimistic locking to ensure
 * that the draft and/or published versions of the document have not been changed by another client.
 *
 * @public
 */
export declare type PublishAction = {
  actionType: 'sanity.action.document.publish'
  /**
   * Draft document ID to publish
   */
  draftId: string
  /**
   * Draft revision ID to match
   */
  ifDraftRevisionId?: string
  /**
   * Published document ID to replace
   */
  publishedId: string
  /**
   * Published revision ID to match
   */
  ifPublishedRevisionId?: string
}

/**
 * Publishes all documents in a release at once.
 *
 * @public
 */
export declare interface PublishReleaseAction {
  actionType: 'sanity.action.release.publish'
  releaseId: string
}

/** @public */
export declare type QueryOptions =
  | FilteredResponseQueryOptions
  | UnfilteredResponseQueryOptions
  | UnfilteredResponseWithoutQuery

/** @public */
export declare interface QueryParams {
  [key: string]: any
  /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */
  body?: never
  /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */
  cache?: 'next' extends keyof RequestInit ? never : any
  /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */
  filterResponse?: never
  /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */
  headers?: never
  /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */
  method?: never
  /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */
  next?: 'next' extends keyof RequestInit ? never : any
  /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */
  perspective?: never
  /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */
  query?: never
  /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */
  resultSourceMap?: never
  /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */
  returnQuery?: never
  /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */
  signal?: never
  /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */
  stega?: never
  /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */
  tag?: never
  /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */
  timeout?: never
  /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */
  token?: never
  /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */
  useCdn?: never
  /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */
  lastLiveEventId?: never
  /** @deprecated you're using a fetch option as a GROQ parameter, this is likely a mistake */
  cacheMode?: never
}

/**
 * Returned from the Content Lake API when a query is malformed, usually with a start
 * and end column to indicate where the error occurred, but not always. Can we used to
 * provide a more structured error message to the user.
 *
 * This will be located under the response `error` property.
 *
 * @public
 */
export declare interface QueryParseError {
  type: 'queryParseError'
  description: string
  start?: number
  end?: number
  query?: string
}

/**
 * This type can be used with `client.fetch` to indicate that the query has no GROQ parameters.
 * @public
 */
export declare type QueryWithoutParams = Record<string, never> | undefined

/** @public */
export declare type RawQuerylessQueryResponse<R> = Omit<RawQueryResponse<R>, 'query'>

/** @public */
export declare interface RawQueryResponse<R> {
  query: string
  ms: number
  result: R
  resultSourceMap?: ContentSourceMap
  /** Requires `apiVersion` to be `2021-03-25` or later. */
  syncTags?: SyncTag[]
}

/** @internal */
export declare interface RawRequestOptions {
  url?: string
  uri?: string
  method?: string
  token?: string
  json?: boolean
  tag?: string
  useGlobalApi?: boolean
  withCredentials?: boolean
  query?: {
    [key: string]: string | string[]
  }
  headers?: {
    [key: string]: string
  }
  timeout?: number
  proxy?: string
  body?: Any
  maxRedirects?: number
  signal?: AbortSignal
}

/**
 * The listener has been disconnected, and a reconnect attempt is scheduled.
 *
 * @public
 */
export declare type ReconnectEvent = {
  type: 'reconnect'
}

/** @public */
export declare type ReleaseAction =
  | CreateReleaseAction
  | EditReleaseAction
  | PublishReleaseAction
  | ArchiveReleaseAction
  | UnarchiveReleaseAction
  | ScheduleReleaseAction
  | UnscheduleReleaseAction
  | DeleteReleaseAction

/** @public */
export declare type ReleaseCardinality = 'many' | 'one' | undefined

/** @internal */
export declare interface ReleaseDocument extends SanityDocument {
  /**
   * typically
   * `_.releases.<name>`
   */
  _id: string
  /**
   * where a release has _id `_.releases.foo`, the name is `foo`
   */
  name: string
  _type: 'system.release'
  _createdAt: string
  _updatedAt: string
  _rev: string
  state: ReleaseState
  error?: {
    message: string
  }
  finalDocumentStates?: {
    /** Document ID */
    id: string
  }[]
  /**
   * If defined, it takes precedence over the intendedPublishAt, the state should be 'scheduled'
   */
  publishAt?: string
  /**
   * If defined, it provides the time the release was actually published
   */
  publishedAt?: string
  metadata: {
    title?: string
    description?: string
    intendedPublishAt?: string
    releaseType: ReleaseType
    cardinality?: ReleaseCardinality
  }
}

/**
 * @public
 * @deprecated – The `r`-prefix is not required, use `string` instead
 */
export declare type ReleaseId = `r${string}`

/** @public */
declare class ReleasesClient {
  #private
  constructor(client: SanityClient, httpRequest: HttpRequest)
  /**
   * @public
   *
   * Retrieve a release by id.
   *
   * @category Releases
   *
   * @param params - Release action parameters:
   *   - `releaseId` - The id of the release to retrieve.
   * @param options - Additional query options including abort signal and query tag.
   * @returns A promise that resolves to the release document {@link ReleaseDocument}.
   *
   * @example Retrieving a release by id
   * ```ts
   * const release = await client.releases.get({releaseId: 'my-release'})
   * console.log(release)
   * // {
   * //   _id: '_.releases.my-release',
   * //   name: 'my-release'
   * //   _type: 'system.release',
   * //   metadata: {releaseType: 'asap'},
   * //   _createdAt: '2021-01-01T00:00:00.000Z',
   * //   ...
   * // }
   * ```
   */
  get(
    {
      releaseId,
    }: {
      releaseId: string
    },
    options?: {
      signal?: AbortSignal
      tag?: string
    },
  ): Promise<ReleaseDocument | undefined>
  /**
   * @public
   *
   * Creates a new release under the given id, with metadata.
   *
   * @remarks
   * * If no releaseId is provided, a release id will be generated.
   * * If no metadata is provided, then an `undecided` releaseType will be used.
   *
   * @category Releases
   *
   * @param params - Release action parameters:
   *   - `releaseId` - The id of the release to create.
   *   - `metadata` - The metadata to associate with the release {@link ReleaseDocument}.
   * @param options - Additional action options.
   * @returns A promise that resolves to the `transactionId` and the release id and metadata.
   *
   * @example Creating a release with a custom id and metadata
   * ```ts
   * const releaseId = 'my-release'
   * const releaseMetadata: ReleaseDocument['metadata'] = {
   *   releaseType: 'asap',
   * }
   *
   * const result =
   *   await client.releases.create({releaseId, metadata: releaseMetadata})
   * console.log(result)
   * // {
   * //   transactionId: 'transaction-id',
   * //   releaseId: 'my-release',
   * //   metadata: {releaseType: 'asap'},
   * // }
   * ```
   *
   * @example Creating a release with generated id and metadata
   * ```ts
   * const {metadata} = await client.releases.create()
   * console.log(metadata.releaseType) // 'undecided'
   * ```
   *
   * @example Creating a release with a custom transaction id
   * ```ts
   * const {transactionId, metadata} = await client.releases.create({transactionId: 'my-transaction-id'})
   * console.log(metadata.releaseType) // 'undecided'
   * console.log(transactionId) // 'my-transaction-id'
   * ```
   */
  create(options: BaseActionOptions): Promise<
    SingleActionResult & {
      releaseId: string
      metadata: ReleaseDocument['metadata']
    }
  >
  create(
    release: {
      releaseId?: string
      metadata?: Partial<ReleaseDocument['metadata']>
    },
    options?: BaseActionOptions,
  ): Promise<
    SingleActionResult & {
      releaseId: string
      metadata: ReleaseDocument['metadata']
    }
  >
  /**
   * @public
   *
   * Edits an existing release, updating the metadata.
   *
   * @category Releases
   *
   * @param params - Release action parameters:
   *   - `releaseId` - The id of the release to edit.
   *   - `patch` - The patch operation to apply on the release metadata {@link PatchMutationOperation}.
   * @param options - Additional action options.
   * @returns A promise that resolves to the `transactionId`.
   */
  edit(
    {
      releaseId,
      patch,
    }: {
      releaseId: string
      patch: PatchOperations
    },
    options?: BaseActionOptions,
  ): Promise<SingleActionResult>
  /**
   * @public
   *
   * Publishes all documents in a release at once. For larger releases the effect of the publish
   * will be visible immediately when querying but the removal of the `versions.<releasesId>.*`
   * documents and creation of the corresponding published documents with the new content may
   * take some time.
   *
   * During this period both the source and target documents are locked and cannot be
   * modified through any other means.
   *
   * @category Releases
   *
   * @param params - Release action parameters:
   *   - `releaseId` - The id of the release to publish.
   * @param options - Additional action options.
   * @returns A promise that resolves to the `transactionId`.
   */
  publish(
    {
      releaseId,
    }: {
      releaseId: string
    },
    options?: BaseActionOptions,
  ): Promise<SingleActionResult>
  /**
   * @public
   *
   * An archive action removes an active release. The documents that comprise the release
   * are deleted and therefore no longer queryable.
   *
   * While the documents remain in retention the last version can still be accessed using document history endpoint.
   *
   * @category Releases
   *
   * @param params - Release action parameters:
   *   - `releaseId` - The id of the release to archive.
   * @param options - Additional action options.
   * @returns A promise that resolves to the `transactionId`.
   */
  archive(
    {
      releaseId,
    }: {
      releaseId: string
    },
    options?: BaseActionOptions,
  ): Promise<SingleActionResult>
  /**
   * @public
   *
   * An unarchive action restores an archived release and all documents
   * with the content they had just prior to archiving.
   *
   * @category Releases
   *
   * @param params - Release action parameters:
   *   - `releaseId` - The id of the release to unarchive.
   * @param options - Additional action options.
   * @returns A promise that resolves to the `transactionId`.
   */
  unarchive(
    {
      releaseId,
    }: {
      releaseId: string
    },
    options?: BaseActionOptions,
  ): Promise<SingleActionResult>
  /**
   * @public
   *
   * A schedule action queues a release for publishing at the given future time.
   * The release is locked such that no documents in the release can be modified and
   * no documents that it references can be deleted as this would make the publish fail.
   * At the given time, the same logic as for the publish action is triggered.
   *
   * @category Releases
   *
   * @param params - Release action parameters:
   *   - `releaseId` - The id of the release to schedule.
   *   - `publishAt` - The serialised date and time to publish the release. If the `publishAt` is in the past, the release will be published immediately.
   * @param options - Additional action options.
   * @returns A promise that resolves to the `transactionId`.
   */
  schedule(
    {
      releaseId,
      publishAt,
    }: {
      releaseId: string
      publishAt: string
    },
    options?: BaseActionOptions,
  ): Promise<SingleActionResult>
  /**
   * @public
   *
   * An unschedule action stops a release from being published.
   * The documents in the release are considered unlocked and can be edited again.
   * This may fail if another release is scheduled to be published after this one and
   * has a reference to a document created by this one.
   *
   * @category Releases
   *
   * @param params - Release action parameters:
   *   - `releaseId` - The id of the release to unschedule.
   * @param options - Additional action options.
   * @returns A promise that resolves to the `transactionId`.
   */
  unschedule(
    {
      releaseId,
    }: {
      releaseId: string
    },
    options?: BaseActionOptions,
  ): Promise<SingleActionResult>
  /**
   * @public
   *
   * A delete action removes a published or archived release.
   * The backing system document will be removed from the dataset.
   *
   * @category Releases
   *
   * @param params - Release action parameters:
   *   - `releaseId` - The id of the release to delete.
   * @param options - Additional action options.
   * @returns A promise that resolves to the `transactionId`.
   */
  delete(
    {
      releaseId,
    }: {
      releaseId: string
    },
    options?: BaseActionOptions,
  ): Promise<SingleActionResult>
  /**
   * @public
   *
   * Fetch the documents in a release by release id.
   *
   * @category Releases
   *
   * @param params - Release action parameters:
   *   - `releaseId` - The id of the release to fetch documents for.
   * @param options - Additional mutation options {@link BaseMutationOptions}.
   * @returns A promise that resolves to the documents in the release.
   */
  fetchDocuments(
    {
      releaseId,
    }: {
      releaseId: string
    },
    options?: BaseMutationOptions,
  ): Promise<RawQueryResponse<SanityDocument[]>>
}

/** @beta */
export declare type ReleaseState =
  | 'active'
  | 'archiving'
  | 'unarchiving'
  | 'archived'
  | 'published'
  | 'publishing'
  | 'scheduled'
  | 'scheduling'

/** @internal */
export declare type ReleaseType = 'asap' | 'scheduled' | 'undecided'

/**
 * Replaces an existing draft document.
 * At least one of the draft or published versions of the document must exist.
 *
 * @public
 * @deprecated Use {@link ReplaceVersionAction} instead
 */
export declare type ReplaceDraftAction = {
  actionType: 'sanity.action.document.replaceDraft'
  /**
   * Published document ID to create draft from, if draft does not exist
   */
  publishedId: string
  /**
   * Document to create if it does not already exist. Requires `_id` and `_type` properties.
   */
  attributes: IdentifiedSanityDocumentStub
}

/**
 * Replace an existing version of a document.
 *
 * @public
 */
export declare interface ReplaceVersionAction {
  actionType: 'sanity.action.document.version.replace'
  document: IdentifiedSanityDocumentStub
}

/** @public */
export declare const requester: Requester

/** @internal */
export declare interface RequestObservableOptions extends Omit<RequestOptions, 'url'> {
  url?: string
  uri?: string
  canUseCdn?: boolean
  useCdn?: boolean
  tag?: string
  returnQuery?: boolean
  resultSourceMap?: boolean | 'withKeyArraySelector'
  perspective?: ClientPerspective
  lastLiveEventId?: string
  cacheMode?: 'noStale'
}

/** @public */
export declare interface RequestOptions {
  timeout?: number
  token?: string
  tag?: string
  headers?: Record<string, string>
  method?: string
  query?: Any
  body?: Any
  signal?: AbortSignal
}

export {ResolveStudioUrl}

/** @public */
export declare interface ResponseEvent<T = unknown> {
  type: 'response'
  body: T
  url: string
  method: string
  statusCode: number
  statusMessage?: string
  headers: Record<string, string>
}

/** @public */
export declare interface ResponseQueryOptions extends RequestOptions {
  perspective?: ClientPerspective
  resultSourceMap?: boolean | 'withKeyArraySelector'
  returnQuery?: boolean
  useCdn?: boolean
  stega?: boolean | StegaConfig
  cache?: 'next' extends keyof RequestInit ? RequestInit['cache'] : never
  next?: ('next' extends keyof RequestInit ? RequestInit : never)['next']
  lastLiveEventId?: string | string[] | null
  /**
   * When set to `noStale`, APICDN will not return a cached response if the content is stale.
   * Tradeoff between latency and freshness of content.
   *
   * Only to be used with live content queries and when useCdn is true.
   */
  cacheMode?: 'noStale'
}

/** @internal */
export declare interface SanityAssetDocument extends SanityDocument {
  url: string
  path: string
  size: number
  assetId: string
  mimeType: string
  sha1hash: string
  extension: string
  uploadId?: string
  originalFilename?: string
}

/** @public */
export declare class SanityClient {
  #private
  assets: AssetsClient
  datasets: DatasetsClient
  live: LiveClient
  mediaLibrary: {
    video: MediaLibraryVideoClient
  }
  projects: ProjectsClient
  users: UsersClient
  agent: {
    action: AgentActionsClient
  }
  releases: ReleasesClient
  /**
   * Observable version of the Sanity client, with the same configuration as the promise-based one
   */
  observable: ObservableSanityClient
  /**
   * Instance properties
   */
  listen: typeof _listen
  constructor(httpRequest: HttpRequest, config?: ClientConfig)
  /**
   * Clone the client - returns a new instance
   */
  clone(): SanityClient
  /**
   * Returns the current client configuration
   */
  config(): InitializedClientConfig
  /**
   * Reconfigure the client. Note that this _mutates_ the current client.
   */
  config(newConfig?: Partial<ClientConfig>): this
  /**
   * Clone the client with a new (partial) configuration.
   *
   * @param newConfig - New client configuration properties, shallowly merged with existing configuration
   */
  withConfig(newConfig?: Partial<ClientConfig>): SanityClient
  /**
   * Perform a GROQ-query against the configured dataset.
   *
   * @param query - GROQ-query to perform
   */
  fetch<
    R = Any,
    Q extends QueryWithoutParams = QueryWithoutParams,
    const G extends string = string,
  >(query: G, params?: Q | QueryWithoutParams): Promise<ClientReturn<G, R>>
  /**
   * Perform a GROQ-query against the configured dataset.
   *
   * @param query - GROQ-query to perform
   * @param params - Optional query parameters
   * @param options - Optional request options
   */
  fetch<
    R = Any,
    Q extends QueryWithoutParams | QueryParams = QueryParams,
    const G extends string = string,
  >(
    query: G,
    params: Q extends QueryWithoutParams ? QueryWithoutParams : Q,
    options?: FilteredResponseQueryOptions,
  ): Promise<ClientReturn<G, R>>
  /**
   * Perform a GROQ-query against the configured dataset.
   *
   * @param query - GROQ-query to perform
   * @param params - Optional query parameters
   * @param options - Request options
   */
  fetch<
    R = Any,
    Q extends QueryWithoutParams | QueryParams = QueryParams,
    const G extends string = string,
  >(
    query: G,
    params: Q extends QueryWithoutParams ? QueryWithoutParams : Q,
    options: UnfilteredResponseQueryOptions,
  ): Promise<RawQueryResponse<ClientReturn<G, R>>>
  /**
   * Perform a GROQ-query against the configured dataset.
   *
   * @param query - GROQ-query to perform
   * @param params - Optional query parameters
   * @param options - Request options
   */
  fetch<
    R = Any,
    Q extends QueryWithoutParams | QueryParams = QueryParams,
    const G extends string = string,
  >(
    query: G,
    params: Q extends QueryWithoutParams ? QueryWithoutParams : Q,
    options: UnfilteredResponseWithoutQuery,
  ): Promise<RawQuerylessQueryResponse<ClientReturn<G, R>>>
  /**
   * Fetch a single document with the given ID.
   *
   * @param id - Document ID to fetch
   * @param options - Request options
   */
  getDocument<R extends Record<string, Any> = Record<string, Any>>(
    id: string,
    options: {
      signal?: AbortSignal
      tag?: string
      releaseId?: string
      includeAllVersions: true
    },
  ): Promise<SanityDocument<R>[]>
  /**
   * Fetch a single document with the given ID.
   *
   * @param id - Document ID to fetch
   * @param options - Request options
   */
  getDocument<R extends Record<string, Any> = Record<string, Any>>(
    id: string,
    options?: {
      signal?: AbortSignal
      tag?: string
      releaseId?: string
      includeAllVersions?: false
    },
  ): Promise<SanityDocument<R> | undefined>
  /**
   * Fetch multiple documents in one request.
   * Should be used sparingly - performing a query is usually a better option.
   * The order/position of documents is preserved based on the original array of IDs.
   * If any of the documents are missing, they will be replaced by a `null` entry in the returned array
   *
   * @param ids - Document IDs to fetch
   * @param options - Request options
   */
  getDocuments<R extends Record<string, Any> = Record<string, Any>>(
    ids: string[],
    options?: {
      signal?: AbortSignal
      tag?: string
    },
  ): Promise<(SanityDocument<R> | null)[]>
  /**
   * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.
   * Returns a promise that resolves to the created document.
   *
   * @param document - Document to create
   * @param options - Mutation options
   */
  create<R extends Record<string, Any> = Record<string, Any>>(
    document: SanityDocumentStub<R>,
    options: FirstDocumentMutationOptions,
  ): Promise<SanityDocument<R>>
  /**
   * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.
   * Returns a promise that resolves to an array containing the created document.
   *
   * @param document - Document to create
   * @param options - Mutation options
   */
  create<R extends Record<string, Any> = Record<string, Any>>(
    document: SanityDocumentStub<R>,
    options: AllDocumentsMutationOptions,
  ): Promise<SanityDocument<R>[]>
  /**
   * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.
   * Returns a promise that resolves to a mutation result object containing the ID of the created document.
   *
   * @param document - Document to create
   * @param options - Mutation options
   */
  create<R extends Record<string, Any> = Record<string, Any>>(
    document: SanityDocumentStub<R>,
    options: FirstDocumentIdMutationOptions,
  ): Promise<SingleMutationResult>
  /**
   * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.
   * Returns a promise that resolves to a mutation result object containing the ID of the created document.
   *
   * @param document - Document to create
   * @param options - Mutation options
   */
  create<R extends Record<string, Any> = Record<string, Any>>(
    document: SanityDocumentStub<R>,
    options: AllDocumentIdsMutationOptions,
  ): Promise<MultipleMutationResult>
  /**
   * Create a document. Requires a `_type` property. If no `_id` is provided, it will be generated by the database.
   * Returns a promise that resolves to the created document.
   *
   * @param document - Document to create
   * @param options - Mutation options
   */
  create<R extends Record<string, Any> = Record<string, Any>>(
    document: SanityDocumentStub<R>,
    options?: BaseMutationOptions,
  ): Promise<SanityDocument<R>>
  /**
   * Create a document if no document with the same ID already exists.
   * Returns a promise that resolves to the created document.
   *
   * @param document - Document to create
   * @param options - Mutation options
   */
  createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(
    document: IdentifiedSanityDocumentStub<R>,
    options: FirstDocumentMutationOptions,
  ): Promise<SanityDocument<R>>
  /**
   * Create a document if no document with the same ID already exists.
   * Returns a promise that resolves to an array containing the created document.
   *
   * @param document - Document to create
   * @param options - Mutation options
   */
  createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(
    document: IdentifiedSanityDocumentStub<R>,
    options: AllDocumentsMutationOptions,
  ): Promise<SanityDocument<R>[]>
  /**
   * Create a document if no document with the same ID already exists.
   * Returns a promise that resolves to a mutation result object containing the ID of the created document.
   *
   * @param document - Document to create
   * @param options - Mutation options
   */
  createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(
    document: IdentifiedSanityDocumentStub<R>,
    options: FirstDocumentIdMutationOptions,
  ): Promise<SingleMutationResult>
  /**
   * Create a document if no document with the same ID already exists.
   * Returns a promise that resolves to a mutation result object containing the ID of the created document.
   *
   * @param document - Document to create
   * @param options - Mutation options
   */
  createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(
    document: IdentifiedSanityDocumentStub<R>,
    options: AllDocumentIdsMutationOptions,
  ): Promise<MultipleMutationResult>
  /**
   * Create a document if no document with the same ID already exists.
   * Returns a promise that resolves to the created document.
   *
   * @param document - Document to create
   * @param options - Mutation options
   */
  createIfNotExists<R extends Record<string, Any> = Record<string, Any>>(
    document: IdentifiedSanityDocumentStub<R>,
    options?: BaseMutationOptions,
  ): Promise<SanityDocument<R>>
  /**
   * Create a document if it does not exist, or replace a document with the same document ID
   * Returns a promise that resolves to the created document.
   *
   * @param document - Document to either create or replace
   * @param options - Mutation options
   */
  createOrReplace<R extends Record<string, Any> = Record<string, Any>>(
    document: IdentifiedSanityDocumentStub<R>,
    options: FirstDocumentMutationOptions,
  ): Promise<SanityDocument<R>>
  /**
   * Create a document if it does not exist, or replace a document with the same document ID
   * Returns a promise that resolves to an array containing the created document.
   *
   * @param document - Document to either create or replace
   * @param options - Mutation options
   */
  createOrReplace<R extends Record<string, Any> = Record<string, Any>>(
    document: IdentifiedSanityDocumentStub<R>,
    options: AllDocumentsMutationOptions,
  ): Promise<SanityDocument<R>[]>
  /**
   * Create a document if it does not exist, or replace a document with the same document ID
   * Returns a promise that resolves to a mutation result object containing the ID of the created document.
   *
   * @param document - Document to either create or replace
   * @param options - Mutation options
   */
  createOrReplace<R extends Record<string, Any> = Record<string, Any>>(
    document: IdentifiedSanityDocumentStub<R>,
    options: FirstDocumentIdMutationOptions,
  ): Promise<SingleMutationResult>
  /**
   * Create a document if it does not exist, or replace a document with the same document ID
   * Returns a promise that resolves to a mutation result object containing the created document ID.
   *
   * @param document - Document to either create or replace
   * @param options - Mutation options
   */
  createOrReplace<R extends Record<string, Any> = Record<string, Any>>(
    document: IdentifiedSanityDocumentStub<R>,
    options: AllDocumentIdsMutationOptions,
  ): Promise<MultipleMutationResult>
  /**
   * Create a document if it does not exist, or replace a document with the same document ID
   * Returns a promise that resolves to the created document.
   *
   * @param document - Document to either create or replace
   * @param options - Mutation options
   */
  createOrReplace<R extends Record<string, Any> = Record<string, Any>>(
    document: IdentifiedSanityDocumentStub<R>,
    options?: BaseMutationOptions,
  ): Promise<SanityDocument<R>>
  /**
   * @public
   *
   * Creates a new version of a published document.
   *
   * @remarks
   * * The preferred approach is to use `baseId` to refer to the existing published document, but it is also possible to provide a complete `document` instead.
   * * If `document` is provided, it must have a `_type` property.
   * * Creating a version with no `releaseId` will create a new draft version of the published document.
   * * If the `document._id` is defined, it should be a draft or release version ID that matches the version ID generated from `publishedId` and `releaseId`.
   * * If the `document._id` is not defined, it will be generated from `publishedId` and `releaseId`.
   * * To create a version of an unpublished document, use the `client.create` method.
   *
   * @category Versions
   *
   * @param params - Version action parameters:
   *   - `baseId` - The ID of the published document from which to create a new version from.
   *   - `ifBaseRevisionId` - If `baseId` is provided, this ensures the `baseId`'s revision Id is as expected before creating the new version from it.
   *   - `document` - The document to create as a new version (must include `_type`).
   *   - `publishedId` - The ID of the published document being versioned.
   *   - `releaseId` - The ID of the release to create the version for.
   * @param options - Additional action options.
   * @returns A promise that resolves to the `transactionId`.
   *
   * @example Creating a new version of a published document
   * ```ts
   * const transactionId = await client.createVersion({
   *   baseId: 'myDocument',
   *   publishedId: 'myDocument',
   *   releaseId: 'myRelease',
   * })
   *
   * // The following document will be created:
   * // {
   * //   _id: 'versions.myRelease.myDocument',
   * //   _type: 'myDocument',
   * //   title: 'My Document',
   * // }
   * ```
   *
   *
   * @example Creating a new draft version of a published document
   * ```ts
   * const transactionId = await client.createVersion({
   *   baseId: 'myDocument',
   *   publishedId: 'myDocument',
   * })
   *
   * // The following document will be created:
   * // {
   * //   _id: 'drafts.myDocument',
   * //   _type: 'myDocument',
   * //   title: 'My Document',
   * // }
   * ```
   */
  createVersion<R extends Record<string, Any>>(
    args: {
      document: SanityDocumentStub<R>
      publishedId: string
      releaseId?: string
    },
    options?: BaseActionOptions,
  ): Promise<SingleActionResult | MultipleActionResult>
  createVersion<R extends Record<string, Any>>(
    args: {
      document: IdentifiedSanityDocumentStub<R>
      publishedId?: string
      releaseId?: string
    },
    options?: BaseActionOptions,
  ): Promise<SingleActionResult | MultipleActionResult>
  createVersion(
    args: {
      publishedId: string
      baseId: string
      releaseId: string
      ifBaseRevisionId?: string
    },
    options?: BaseActionOptions,
  ): Promise<SingleActionResult | MultipleActionResult>
  /**
   * Deletes a document with the given document ID.
   * Returns a promise that resolves to the deleted document.
   *
   * @param id - Document ID to delete
   * @param options - Options for the mutation
   */
  delete<R extends Record<string, Any> = Record<string, Any>>(
    id: string,
    options: FirstDocumentMutationOptions,
  ): Promise<SanityDocument<R>>
  /**
   * Deletes a document with the given document ID.
   * Returns a promise that resolves to an array containing the deleted document.
   *
   * @param id - Document ID to delete
   * @param options - Options for the mutation
   */
  delete<R extends Record<string, Any> = Record<string, Any>>(
    id: string,
    options: AllDocumentsMutationOptions,
  ): Promise<SanityDocument<R>[]>
  /**
   * Deletes a document with the given document ID.
   * Returns a promise that resolves to a mutation result object containing the deleted document ID.
   *
   * @param id - Document ID to delete
   * @param options - Options for the mutation
   */
  delete(id: string, options: FirstDocumentIdMutationOptions): Promise<SingleMutationResult>
  /**
   * Deletes a document with the given document ID.
   * Returns a promise that resolves to a mutation result object containing the deleted document ID.
   *
   * @param id - Document ID to delete
   * @param options - Options for the mutation
   */
  delete(id: string, options: AllDocumentIdsMutationOptions): Promise<MultipleMutationResult>
  /**
   * Deletes a document with the given document ID.
   * Returns a promise that resolves to the deleted document.
   *
   * @param id - Document ID to delete
   * @param options - Options for the mutation
   */
  delete<R extends Record<string, Any> = Record<string, Any>>(
    id: string,
    options?: BaseMutationOptions,
  ): Promise<SanityDocument<R>>
  /**
   * Deletes one or more documents matching the given query or document ID.
   * Returns a promise that resolves to first deleted document.
   *
   * @param selection - An object with either an `id` or `query` key defining what to delete
   * @param options - Options for the mutation
   */
  delete<R extends Record<string, Any> = Record<string, Any>>(
    selection: MutationSelection,
    options: FirstDocumentMutationOptions,
  ): Promise<SanityDocument<R>>
  /**
   * Deletes one or more documents matching the given query or document ID.
   * Returns a promise that resolves to an array containing the deleted documents.
   *
   * @param selection - An object with either an `id` or `query` key defining what to delete
   * @param options - Options for the mutation
   */
  delete<R extends Record<string, Any> = Record<string, Any>>(
    selection: MutationSelection,
    options: AllDocumentsMutationOptions,
  ): Promise<SanityDocument<R>[]>
  /**
   * Deletes one or more documents matching the given query or document ID.
   * Returns a promise that resolves to a mutation result object containing the ID of the first deleted document.
   *
   * @param selection - An object with either an `id` or `query` key defining what to delete
   * @param options - Options for the mutation
   */
  delete(
    selection: MutationSelection,
    options: FirstDocumentIdMutationOptions,
  ): Promise<SingleMutationResult>
  /**
   * Deletes one or more documents matching the given query or document ID.
   * Returns a promise that resolves to a mutation result object containing the document IDs that were deleted.
   *
   * @param selection - An object with either an `id` or `query` key defining what to delete
   * @param options - Options for the mutation
   */
  delete(
    selection: MutationSelection,
    options: AllDocumentIdsMutationOptions,
  ): Promise<MultipleMutationResult>
  /**
   * Deletes one or more documents matching the given query or document ID.
   * Returns a promise that resolves to first deleted document.
   *
   * @param selection - An object with either an `id` or `query` key defining what to delete
   * @param options - Options for the mutation
   */
  delete<R extends Record<string, Any> = Record<string, Any>>(
    selection: MutationSelection,
    options?: BaseMutationOptions,
  ): Promise<SanityDocument<R>>
  /**
   * @public
   *
   * Deletes the draft or release version of a document.
   *
   * @remarks
   * * Discarding a version with no `releaseId` will discard the draft version of the published document.
   * * If the draft or release version does not exist, any error will throw.
   *
   * @param params - Version action parameters:
   *   - `releaseId` - The ID of the release to discard the document from.
   *   - `publishedId` - The published ID of the document to discard.
   * @param purge - if `true` the document history is also discarded.
   * @param options - Additional action options.
   * @returns a promise that resolves to the `transactionId`.
   *
   * @example Discarding a release version of a document
   * ```ts
   * client.discardVersion({publishedId: 'myDocument', releaseId: 'myRelease'})
   * // The document with the ID `versions.myRelease.myDocument` will be discarded.
   * ```
   *
   * @example Discarding a draft version of a document
   * ```ts
   * client.discardVersion({publishedId: 'myDocument'})
   * // The document with the ID `drafts.myDocument` will be discarded.
   * ```
   */
  discardVersion(
    {
      releaseId,
      publishedId,
    }: {
      releaseId?: string
      publishedId: string
    },
    purge?: boolean,
    options?: BaseActionOptions,
  ): Promise<SingleActionResult | MultipleActionResult>
  /**
   * @public
   *
   * Replaces an existing version document.
   *
   * @remarks
   * * Requires a document with a `_type` property.
   * * If the `document._id` is defined, it should be a draft or release version ID that matches the version ID generated from `publishedId` and `releaseId`.
   * * If the `document._id` is not defined, it will be generated from `publishedId` and `releaseId`.
   * * Replacing a version with no `releaseId` will replace the draft version of the published document.
   * * At least one of the **version** or **published** documents must exist.
   *
   * @param params - Version action parameters:
   *   - `document` - The new document to replace the version with.
   *   - `releaseId` - The ID of the release where the document version is replaced.
   *   - `publishedId` - The ID of the published document to replace.
   * @param options - Additional action options.
   * @returns a promise that resolves to the `transactionId`.
   *
   * @example Replacing a release version of a published document with a generated version ID
   * ```ts
   * await client.replaceVersion({
   *   document: {_type: 'myDocument', title: 'My Document'},
   *   publishedId: 'myDocument',
   *   releaseId: 'myRelease',
   * })
   *
   * // The following document will be patched:
   * // {
   * //   _id: 'versions.myRelease.myDocument',
   * //   _type: 'myDocument',
   * //   title: 'My Document',
   * // }
   * ```
   *
   * @example Replacing a release version of a published document with a specified version ID
   * ```ts
   * await client.replaceVersion({
   *   document: {_type: 'myDocument', _id: 'versions.myRelease.myDocument', title: 'My Document'},
   *   // `publishedId` and `releaseId` are not required since `document._id` has been specified
   * })
   *
   * // The following document will be patched:
   * // {
   * //   _id: 'versions.myRelease.myDocument',
   * //   _type: 'myDocument',
   * //   title: 'My Document',
   * // }
   * ```
   *
   * @example Replacing a draft version of a published document
   * ```ts
   * await client.replaceVersion({
   *   document: {_type: 'myDocument', title: 'My Document'},
   *   publishedId: 'myDocument',
   * })
   *
   * // The following document will be patched:
   * // {
   * //   _id: 'drafts.myDocument',
   * //   _type: 'myDocument',
   * //   title: 'My Document',
   * // }
   * ```
   */
  replaceVersion<R extends Record<string, Any>>(
    args: {
      document: SanityDocumentStub<R>
      publishedId: string
      releaseId?: string
    },
    options?: BaseActionOptions,
  ): Promise<SingleActionResult | MultipleActionResult>
  replaceVersion<R extends Record<string, Any>>(
    args: {
      document: IdentifiedSanityDocumentStub<R>
      publishedId?: string
      releaseId?: string
    },
    options?: BaseActionOptions,
  ): Promise<SingleActionResult | MultipleActionResult>
  /**
   * @public
   *
   * Used to indicate when a document within a release should be unpublished when
   * the release is run.
   *
   * @remarks
   * * If the published document does not exist, an error will be thrown.
   *
   * @param params - Version action parameters:
   *   - `releaseId` - The ID of the release to unpublish the document from.
   *   - `publishedId` - The published ID of the document to unpublish.
   * @param options - Additional action options.
   * @returns a promise that resolves to the `transactionId`.
   *
   * @example Unpublishing a release version of a published document
   * ```ts
   * await client.unpublishVersion({publishedId: 'myDocument', releaseId: 'myRelease'})
   * // The document with the ID `versions.myRelease.myDocument` will be unpublished. when `myRelease` is run.
   * ```
   */
  unpublishVersion(
    {
      releaseId,
      publishedId,
    }: {
      releaseId: string
      publishedId: string
    },
    options?: BaseActionOptions,
  ): Promise<SingleActionResult | MultipleActionResult>
  /**
   * Perform mutation operations against the configured dataset
   * Returns a promise that resolves to the first mutated document.
   *
   * @param operations - Mutation operations to execute
   * @param options - Mutation options
   */
  mutate<R extends Record<string, Any> = Record<string, Any>>(
    operations: Mutation<R>[] | Patch | Transaction,
    options: FirstDocumentMutationOptions,
  ): Promise<SanityDocument<R>>
  /**
   * Perform mutation operations against the configured dataset.
   * Returns a promise that resolves to an array of the mutated documents.
   *
   * @param operations - Mutation operations to execute
   * @param options - Mutation options
   */
  mutate<R extends Record<string, Any> = Record<string, Any>>(
    operations: Mutation<R>[] | Patch | Transaction,
    options: AllDocumentsMutationOptions,
  ): Promise<SanityDocument<R>[]>
  /**
   * Perform mutation operations against the configured dataset
   * Returns a promise that resolves to a mutation result object containing the document ID of the first mutated document.
   *
   * @param operations - Mutation operations to execute
   * @param options - Mutation options
   */
  mutate<R extends Record<string, Any> = Record<string, Any>>(
    operations: Mutation<R>[] | Patch | Transaction,
    options: FirstDocumentIdMutationOptions,
  ): Promise<SingleMutationResult>
  /**
   * Perform mutation operations against the configured dataset
   * Returns a promise that resolves to a mutation result object containing the mutated document IDs.
   *
   * @param operations - Mutation operations to execute
   * @param options - Mutation options
   */
  mutate<R extends Record<string, Any> = Record<string, Any>>(
    operations: Mutation<R>[] | Patch | Transaction,
    options: AllDocumentIdsMutationOptions,
  ): Promise<MultipleMutationResult>
  /**
   * Perform mutation operations against the configured dataset
   * Returns a promise that resolves to the first mutated document.
   *
   * @param operations - Mutation operations to execute
   * @param options - Mutation options
   */
  mutate<R extends Record<string, Any> = Record<string, Any>>(
    operations: Mutation<R>[] | Patch | Transaction,
    options?: BaseMutationOptions,
  ): Promise<SanityDocument<R>>
  /**
   * Create a new buildable patch of operations to perform
   *
   * @param documentId - Document ID to patch
   * @param operations - Optional object of patch operations to initialize the patch instance with
   * @returns Patch instance - call `.commit()` to perform the operations defined
   */
  patch(documentId: string, operations?: PatchOperations): Patch
  /**
   * Create a new buildable patch of operations to perform
   *
   * @param documentIds - Array of document IDs to patch
   * @param operations - Optional object of patch operations to initialize the patch instance with
   * @returns Patch instance - call `.commit()` to perform the operations defined
   */
  patch(documentIds: string[], operations?: PatchOperations): Patch
  /**
   * Create a new buildable patch of operations to perform
   *
   * @param selection - An object with `query` and optional `params`, defining which document(s) to patch
   * @param operations - Optional object of patch operations to initialize the patch instance with
   * @returns Patch instance - call `.commit()` to perform the operations defined
   */
  patch(selection: MutationSelection, operations?: PatchOperations): Patch
  /**
   * Create a new transaction of mutations
   *
   * @param operations - Optional array of mutation operations to initialize the transaction instance with
   */
  transaction<R extends Record<string, Any> = Record<string, Any>>(
    operations?: Mutation<R>[],
  ): Transaction
  /**
   * Perform action operations against the configured dataset
   * Returns a promise that resolves to the transaction result
   *
   * @param operations - Action operation(s) to execute
   * @param options - Action options
   */
  action(
    operations: Action | Action[],
    options?: BaseActionOptions,
  ): Promise<SingleActionResult | MultipleActionResult>
  /**
   * Perform a request against the Sanity API
   * NOTE: Only use this for Sanity API endpoints, not for your own APIs!
   *
   * @param options - Request options
   * @returns Promise resolving to the response body
   */
  request<R = Any>(options: RawRequestOptions): Promise<R>
  /**
   * Perform an HTTP request a `/data` sub-endpoint
   * NOTE: Considered internal, thus marked as deprecated. Use `request` instead.
   *
   * @deprecated - Use `request()` or your own HTTP library instead
   * @param endpoint - Endpoint to hit (mutate, query etc)
   * @param body - Request body
   * @param options - Request options
   * @internal
   */
  dataRequest(endpoint: string, body: unknown, options?: BaseMutationOptions): Promise<Any>
  /**
   * Get a Sanity API URL for the URI provided
   *
   * @param uri - URI/path to build URL for
   * @param canUseCdn - Whether or not to allow using the API CDN for this route
   */
  getUrl(uri: string, canUseCdn?: boolean): string
  /**
   * Get a Sanity API URL for the data operation and path provided
   *
   * @param operation - Data operation (eg `query`, `mutate`, `listen` or similar)
   * @param path - Path to append after the operation
   */
  getDataUrl(operation: string, path?: string): string
}

/** @internal */
export declare type SanityDocument<T extends Record<string, Any> = Record<string, Any>> = {
  [P in keyof T]: T[P]
} & {
  _id: string
  _rev: string
  _type: string
  _createdAt: string
  _updatedAt: string
  /**
   * Present when `perspective` is set to `previewDrafts`
   */
  _originalId?: string
}

/** @public */
export declare type SanityDocumentStub<T extends Record<string, Any> = Record<string, Any>> = {
  [P in keyof T]: T[P]
} & {
  _type: string
}

/** @internal */
export declare interface SanityImageAssetDocument extends SanityAssetDocument {
  metadata: {
    _type: 'sanity.imageMetadata'
    hasAlpha: boolean
    isOpaque: boolean
    lqip?: string
    blurHash?: string
    dimensions: {
      _type: 'sanity.imageDimensions'
      aspectRatio: number
      height: number
      width: number
    }
    palette?: {
      _type: 'sanity.imagePalette'
      darkMuted?: SanityImagePalette
      darkVibrant?: SanityImagePalette
      dominant?: SanityImagePalette
      lightMuted?: SanityImagePalette
      lightVibrant?: SanityImagePalette
      muted?: SanityImagePalette
      vibrant?: SanityImagePalette
    }
    image?: {
      _type: 'sanity.imageExifTags'
      [key: string]: Any
    }
    exif?: {
      _type: 'sanity.imageExifMetadata'
      [key: string]: Any
    }
  }
}

/** @internal */
export declare interface SanityImagePalette {
  background: string
  foreground: string
  population: number
  title: string
}

/** @public */
export declare interface SanityProject {
  id: string
  displayName: string
  /**
   * @deprecated Use the `/user-applications` endpoint instead, which lists all deployed studios/applications
   * @see https://www.sanity.io/help/studio-host-user-applications
   */
  studioHost: string | null
  organizationId: string | null
  isBlocked: boolean
  isDisabled: boolean
  isDisabledByUser: boolean
  createdAt: string
  pendingInvites?: number
  maxRetentionDays?: number
  members: SanityProjectMember[]
  metadata: {
    cliInitializedAt?: string
    color?: string
    /**
     * @deprecated Use the `/user-applications` endpoint instead, which lists all deployed studios/applications
     * @see https://www.sanity.io/help/studio-host-user-applications
     */
    externalStudioHost?: string
  }
}

/** @public */
export declare interface SanityProjectMember {
  id: string
  role: string
  isRobot: boolean
  isCurrentUser: boolean
}

/** @public */
export declare interface SanityQueries {}

/** @internal */
export declare interface SanityReference {
  _ref: string
}

/** @public */
export declare interface SanityUser {
  id: string
  projectId: string
  displayName: string
  familyName: string | null
  givenName: string | null
  middleName: string | null
  imageUrl: string | null
  createdAt: string
  updatedAt: string
  isCurrentUser: boolean
}

/**
 * Queues release for publishing at the given future time.
 *
 * @public
 */
export declare interface ScheduleReleaseAction {
  actionType: 'sanity.action.release.schedule'
  releaseId: string
  publishAt: string
}

/** @public */
export declare class ServerError extends Error {
  response: ErrorProps['response']
  statusCode: ErrorProps['statusCode']
  responseBody: ErrorProps['responseBody']
  details: ErrorProps['details']
  constructor(res: Any)
}

/**
 * @public
 */
export declare interface ServerSentEvent<Name extends string> {
  type: Name
  id?: string
  data?: unknown
}

/** @internal */
export declare interface SingleActionResult {
  transactionId: string
}

/** @internal */
export declare interface SingleMutationResult {
  transactionId: string
  documentId: string
  results: {
    id: string
    operation: MutationOperation
  }[]
}

/** @public */
export declare type StackablePerspective = ('published' | 'drafts' | string) & {}

/** @public */
declare type StackablePerspective_2 = ('published' | 'drafts' | string) & {}

/** @public */
export declare interface StegaConfig {
  /**
     * Enable or disable stega encoded strings in query results
     * ```ts
     {
     enabled: process.env.VERCEL_ENV !== 'production'
     }
     * ```
     * @defaultValue `false`
     */
  enabled?: boolean
  /**
   * Where the Studio is hosted.
   * If it's embedded in the app, use the base path for example `/studio`.
   * Otherwise provide the full URL to where the Studio is hosted, for example: `https://blog.sanity.studio`.
   *
   */
  studioUrl?: StudioUrl | ResolveStudioUrl
  filter?: FilterDefault
  /**
   * Specify a `console.log` compatible logger to see debug logs, which keys are encoded and which are not.
   */
  logger?: Logger
  /**
   * Set to `true` to omit cross dataset reference specific data from encoded strings
   */
  omitCrossDatasetReferenceData?: boolean
}

/** @public */
export declare type StegaConfigRequiredKeys = Extract<keyof StegaConfig, 'enabled'>

/**
 * Allowed still image formats (thumbnail + storyboard).
 * @public
 */
export declare type StillImageFormat = 'jpg' | 'png' | 'webp'

/**
 * Storyboard (contact sheet) options.
 * @public
 */
export declare interface StoryboardTransformOptions {
  /** Output image format for the storyboard. */
  format?: StillImageFormat
}

export {StudioBaseRoute}

export {StudioBaseUrl}

export {StudioUrl}

/** @public */
export declare type SyncTag = `s1:${string}`

/**
 * Thumbnail rendition (single frame) options.
 * @public
 */
export declare interface ThumbnailTransformOptions {
  /** Pixel width of the thumbnail frame. */
  width?: number
  /** Pixel height of the thumbnail frame. */
  height?: number
  /** Timestamp (seconds) from which to grab the frame. */
  time?: number
  /** Resize / fit mode applied to the extracted frame. */
  fit?: FitMode
  /** Output image format. */
  format?: StillImageFormat
}

/** @public */
export declare class Transaction extends BaseTransaction {
  #private
  constructor(operations?: Mutation[], client?: SanityClient, transactionId?: string)
  /**
   * Clones the transaction
   */
  clone(): Transaction
  /**
   * Commit the transaction, returning a promise that resolves to the first mutated document
   *
   * @param options - Options for the mutation operation
   */
  commit<R extends Record<string, Any>>(
    options: TransactionFirstDocumentMutationOptions,
  ): Promise<SanityDocument<R>>
  /**
   * Commit the transaction, returning a promise that resolves to an array of the mutated documents
   *
   * @param options - Options for the mutation operation
   */
  commit<R extends Record<string, Any>>(
    options: TransactionAllDocumentsMutationOptions,
  ): Promise<SanityDocument<R>[]>
  /**
   * Commit the transaction, returning a promise that resolves to a mutation result object
   *
   * @param options - Options for the mutation operation
   */
  commit(options: TransactionFirstDocumentIdMutationOptions): Promise<SingleMutationResult>
  /**
   * Commit the transaction, returning a promise that resolves to a mutation result object
   *
   * @param options - Options for the mutation operation
   */
  commit(options: TransactionAllDocumentIdsMutationOptions): Promise<MultipleMutationResult>
  /**
   * Commit the transaction, returning a promise that resolves to a mutation result object
   *
   * @param options - Options for the mutation operation
   */
  commit(options?: BaseMutationOptions): Promise<MultipleMutationResult>
  /**
   * Performs a patch on the given document ID. Can either be a builder function or an object of patch operations.
   * The operation is added to the current transaction, ready to be commited by `commit()`
   *
   * @param documentId - Document ID to perform the patch operation on
   * @param patchOps - Operations to perform, or a builder function
   */
  patch(documentId: string, patchOps?: PatchBuilder | PatchOperations): this
  /**
   * Performs a patch on the given selection. Can either be a builder function or an object of patch operations.
   *
   * @param selection - An object with `query` and optional `params`, defining which document(s) to patch
   * @param patchOps - Operations to perform, or a builder function
   */
  patch(patch: MutationSelection, patchOps?: PatchBuilder | PatchOperations): this
  /**
   * Adds the given patch instance to the transaction.
   * The operation is added to the current transaction, ready to be commited by `commit()`
   *
   * @param patch - Patch to execute
   */
  patch(patch: Patch): this
}

/** @internal */
export declare type TransactionAllDocumentIdsMutationOptions = BaseMutationOptions & {
  returnFirst?: false
  returnDocuments?: false
}

/** @internal */
export declare type TransactionAllDocumentsMutationOptions = BaseMutationOptions & {
  returnFirst?: false
  returnDocuments: true
}

/** @internal */
export declare type TransactionFirstDocumentIdMutationOptions = BaseMutationOptions & {
  returnFirst: true
  returnDocuments?: false
}

/** @internal */
export declare type TransactionFirstDocumentMutationOptions = BaseMutationOptions & {
  returnFirst: true
  returnDocuments: true
}

/** @internal */
export declare type TransactionMutationOptions =
  | TransactionFirstDocumentMutationOptions
  | TransactionFirstDocumentIdMutationOptions
  | TransactionAllDocumentsMutationOptions
  | TransactionAllDocumentIdsMutationOptions

/** @beta */
export declare type TransformDocument<T extends Record<string, Any> = Record<string, Any>> =
  | TransformDocumentSync<T>
  | TransformDocumentAsync

/** @beta */
declare type TransformDocumentAsync = TransformRequestBase & AgentActionAsync

/** @beta */
declare type TransformDocumentSync<T extends Record<string, Any> = Record<string, Any>> =
  TransformRequestBase & AgentActionSync

/**
 *
 * ## `set` by default
 * By default, Transform will change the value of every target field in place using a set operation.
 *
 * ## Image description
 *
 * ### Targeting image fields
 * Images can be transformed to a textual description by targeting a `string`, `text` or Portable Text field (`array` with `block`)
 * with `operation: {type: 'image-description'}`.
 *
 * Custom instructions for image description targets will be used to generate the description.
 *
 * Such targets must be a descendant field of an image object.
 *
 * For example:
 * - `target: {path: ['image', 'description'], operation: {type: 'image-description'} }`
 * - `target: {path: ['array', {_key: 'abc'}, 'alt'], operation: {type: 'image-description'} } //assuming the item in the array on the key-ed path is an image`
 * - `target: {path: ['image'], include: ['portableTextField'], operation: {type: 'image-description'}, instruction: 'Use formatting and headings to describe the image in great detail' }`
 *
 * ### Targeting non-image fields
 * If the target image description lives outside an image object, use the `sourcePath` option to specify the path to the image field.
 * `sourcePath` must be an image or image asset field.
 *
 * For example:
 * - `target: {path: ['description'], operation: operation: {type: 'image-description', sourcePath: ['image', 'asset'] }`
 * - `target: {path: ['wrapper', 'title'], operation: {type: 'image-description', sourcePath: ['array', {_key: 'abc'}, 'image'] }`
 * - `target: {path: ['wrapper'], include: ['portableTextField'], operation: {type: 'image-description', sourcePath: ['image', 'asset'] }, instruction: 'Use formatting and headings to describe the image in great detail' }`
 *
 * ### Targeting images outside the document (URL)
 * If the source image is available on a https URL outside the target document, it is possible to get a description for it using `imageUrl`.
 *
 * Example:
 * - `target: {path: ['description'], operation: operation: {type: 'image-description', imageUrL: 'https://www.sanity.io/static/images/favicons/android-icon-192x192.png?v=2' }`
 * @beta
 */
export declare type TransformOperation = 'set' | ImageDescriptionOperation

/** @beta */
declare interface TransformRequestBase extends AgentActionRequestBase {
  /** schemaId as reported by sanity deploy / sanity schema store */
  schemaId: string
  /**
   * The source document the transformation will use as input.
   *
   * @see #AgentActionSchema.forcePublishedWrite
   */
  documentId: string
  /**
   * The source document's content is first copied to the target,
   * then it is transformed according to the instruction.
   *
   * When omitted, the source document (documentId) is also the target document.
   *
   *  @see #AgentActionSchema.forcePublishedWrite
   */
  targetDocument?: TransformTargetDocument
  /**
   * Instruct the LLM how to transform the input to th output.
   *
   * String template with support for $variable from `instructionParams`.
   *
   * Capped to 2000 characters, after variables has been injected.
   * */
  instruction: string
  /**
   *
   * param values for the string template, keys are the variable name, ie if the template has "$variable", one key must be "variable"
   *
   * ### Examples
   *
   * #### Constant
   *
   * ##### Shorthand
   * ```ts
   * client.agent.action.generate({
   *   schemaId,
   *   documentId,
   *   instruction: 'Give the following topic:\n $topic \n ---\nGenerate the full article.',
   *   instructionParams: {
   *     topic: 'Grapefruit'
   *   },
   * })
   * ```
   * ##### Object-form
   *
   * ```ts
   * client.agent.action.transform({
   *   schemaId,
   *   documentId,
   *   instruction: 'Give the following topic:\n $topic \n ---\nGenerate the full article.',
   *   instructionParams: {
   *     topic: {
   *       type: 'constant',
   *       value: 'Grapefruit'
   *     },
   *   },
   * })
   * ```
   * #### Field
   * ```ts
   * client.agent.action.transform({
   *   schemaId,
   *   documentId,
   *   instruction: 'Give the following field value:\n $pte \n ---\nGenerate keywords.',
   *   instructionParams: {
   *     pte: {
   *       type: 'field',
   *       path: ['pteField'],
   *     },
   *   },
   *   target: {path: 'keywords' }
   * })
   * ```
   * #### Document
   * ```ts
   * client.agent.action.transform({
   *   schemaId,
   *   documentId,
   *   instruction: 'Give the following document value:\n $document \n ---\nGenerate keywords.',
   *   instructionParams: {
   *     document: {
   *       type: 'document',
   *     },
   *   },
   *   target: {path: 'keywords' }
   * })
   * ```
   *
   * #### GROQ
   * ```ts
   * client.agent.action.transform({
   *   schemaId,
   *   documentId,
   *   instruction: 'Give the following list of titles:\n $list \n ---\nGenerate a similar title.',
   *   instructionParams: {
   *     list: {
   *       type: 'groq',
   *       query: '* [_type==$type].title',
   *       params: {type: 'article'}
   *     },
   *   },
   *   target: {path: 'title'}
   * })
   * ```
   * */
  instructionParams?: AgentActionParams
  /**
   * Target defines which parts of the document will be affected by the instruction.
   * It can be an array, so multiple parts of the document can be separately configured in detail.
   *
   * Omitting target implies that the document itself is the root.
   *
   * Notes:
   * - instruction can only affect fields up to `maxPathDepth`
   * - when multiple targets are provided, they will be coalesced into a single target sharing a common target root.
   * It is therefor an error to provide conflicting include/exclude across targets (ie, include title in one, and exclude it in another)
   *
   * Default max depth for transform: 12
   *
   * ## Transforming images
   *
   * To transform an existing image, directly target an image asset path.
   *
   * For example, all the following will transform the image into the provided asset:
   * * `target: {path: ['image', 'asset'] }`
   * * `target: {path: 'image', include: ['asset'] }`
   *
   * Image transform can be combined with regular content targets:
   * * `target: [{path: ['image', 'asset'] }, {include: ['title', 'description']}]`
   *
   * Image transform can have per-path instructions, just like any other target paths:
   * * `target: [{path: ['image', 'asset'], instruction: 'Make the sky blue' }`
   *
   * @see AgentActionRequestBase#conditionalPaths
   */
  target?: TransformTarget | TransformTarget[]
}

/**
 * @see #TransformOperation
 * @beta
 * */
export declare interface TransformTarget extends AgentActionTarget {
  /**
   * Specifies a tailored instruction of this target.
   *
   * String template with support for $variable from `instructionParams`.
   * */
  instruction?: string
  /**
   * By default, all children up to `target.maxPathDepth` are included.
   *
   * When `include` is specified, only segments explicitly listed will be included.
   *
   * Fields or array items not on the include list, are implicitly excluded.
   */
  include?: (AgentActionPathSegment | TransformTargetInclude)[]
  /**
   * Default: `set`
   * @see #TransformOperation
   */
  operation?: TransformOperation
}

/**
 * @see #AgentActionSchema.forcePublishedWrite
 *
 * @beta
 */
export declare type TransformTargetDocument =
  | {
      operation: 'edit'
      _id: string
    }
  | {
      operation: 'create'
      _id?: string
    }
  | {
      operation: 'createIfNotExists'
      _id: string
    }
  | {
      operation: 'createOrReplace'
      _id: string
    }

/**
 * @see #TransformOperation
 * @beta
 * */
export declare interface TransformTargetInclude extends AgentActionTargetInclude {
  /**
   * Specifies a tailored instruction of this target.
   *
   * String template with support for $variable from `instructionParams`.  */
  instruction?: string
  /**
   * By default, all children up to `target.maxPathDepth` are included.
   *
   * When `include` is specified, only segments explicitly listed will be included.
   *
   * Fields or array items not on the include list, are implicitly excluded.
   */
  include?: (AgentActionPathSegment | TransformTargetInclude)[]
  /**
   * Default: `set`
   * @see #TransformOperation
   */
  operation?: TransformOperation
}

/** @beta */
export declare type TranslateDocument<T extends Record<string, Any> = Record<string, Any>> =
  | TranslateDocumentSync<T>
  | TranslateDocumentAsync

/** @beta */
declare type TranslateDocumentAsync = TranslateRequestBase & AgentActionAsync

/** @beta */
declare type TranslateDocumentSync<T extends Record<string, Any> = Record<string, Any>> =
  TranslateRequestBase & AgentActionSync

/**  @beta */
declare interface TranslateLanguage {
  /**
   * Language code
   */
  id: string
  /**
   * While optional, it is recommended to provide a language title
   */
  title?: string
}

/**  @beta */
declare interface TranslateRequestBase extends AgentActionRequestBase {
  /** schemaId as reported by sanity deploy / sanity schema store */
  schemaId: string
  /**
   * The source document the transformation will use as input.
   * @see #AgentActionSchema.forcePublishedWrite
   */
  documentId: string
  /**
   * The target document will first get content copied over from the source,
   * then it is translated according to the instruction.
   *
   * When omitted, the source document (documentId) is also the target document.
   *
   * @see #AgentActionSchema.forcePublishedWrite
   */
  targetDocument?: TransformTargetDocument
  /**
   * While optional, it is recommended
   */
  fromLanguage?: TranslateLanguage
  toLanguage: TranslateLanguage
  /**
   * `styleGuide` can be used to tailor how the translation should be preformed.
   *
   * String template using $variable from styleGuideParams.
   *
   * Capped to 2000 characters, after variables has been injected.
   *
   * @see #protectedPhrases
   */
  styleGuide?: string
  /** param values for the string template, keys are the variable name, ie if the template has "$variable", one key must be "variable" */
  styleGuideParams?: AgentActionParams
  /**
   * When the input string contains any phrase from `protectedPhrases`, the LLM will be instructed not
   * to translate them.
   *
   * It is recommended to use `protectedPhrases` instead of `styleGuide` for deny-list words and phrases,
   * since it keeps token cost low, resulting in faster responses, and limits how much information the LLM
   * has to process, since only phrases that are actually in the input string will be included in the final prompt.
   */
  protectedPhrases?: string[]
  /**
   * When specified, the `toLanguage.id` will be stored in the specified path in the target document.
   *
   * The file _can_ be hidden: true (unlike other fields in the target, which will be ignored)
   */
  languageFieldPath?: AgentActionPathSegment | AgentActionPath
  /**
   * Target defines which parts of the document will be affected by the instruction.
   * It can be an array, so multiple parts of the document can be separately configured in detail.
   *
   * Omitting target implies that the document itself is the root.
   *
   * Notes:
   * - instruction can only affect fields up to `maxPathDepth`
   * - when multiple targets are provided, they will be coalesced into a single target sharing a common target root.
   * It is therefor an error to provide conflicting include/exclude across targets (ie, include title in one, and exclude it in another)
   *
   * @see AgentActionRequestBase#conditionalPaths
   */
  target?: TranslateTarget | TranslateTarget[]
}

/**  @beta */
export declare interface TranslateTarget extends AgentActionTarget {
  /** String template using $variable from styleGuideParams.  */
  styleGuide?: string
  /**
   * By default, all children up to `target.maxPathDepth` are included.
   *
   * When `include` is specified, only segments explicitly listed will be included.
   *
   * Fields or array items not on the include list, are implicitly excluded.
   */
  include?: (AgentActionPathSegment | TranslateTargetInclude)[]
}

/**  @beta */
export declare interface TranslateTargetInclude extends AgentActionTargetInclude {
  /** String template using $variable from styleGuideParams.  */
  styleGuide?: string
  /**
   * By default, all children up to `target.maxPathDepth` are included.
   *
   * When `include` is specified, only segments explicitly listed will be included.
   *
   * Fields or array items not on the include list, are implicitly excluded.
   */
  include?: (AgentActionPathSegment | TranslateTargetInclude)[]
}

/**
 * Unarchived an `archived` release, and restores all the release documents.
 *
 * @public
 */
export declare interface UnarchiveReleaseAction {
  actionType: 'sanity.action.release.unarchive'
  releaseId: string
}

/** @public */
export declare interface UnfilteredResponseQueryOptions extends ResponseQueryOptions {
  filterResponse: false
  /**
   * When `filterResponse` is `false`, `returnQuery` also defaults to `true` for
   * backwards compatibility (on the client side, not from the content lake API).
   * Can also explicitly be set to `true`.
   */
  returnQuery?: true
}

/**
 * When using `filterResponse: false`, but you do not wish to receive back the query from
 * the content lake API.
 *
 * @public
 */
export declare interface UnfilteredResponseWithoutQuery extends ResponseQueryOptions {
  filterResponse: false
  returnQuery: false
}

/**
 * Retract a published document.
 * If there is no draft version then this is created from the published version.
 * In either case the published version is deleted.
 *
 * @public
 */
export declare type UnpublishAction = {
  actionType: 'sanity.action.document.unpublish'
  /**
   * Draft document ID to replace the published document with
   */
  draftId: string
  /**
   * Published document ID to delete
   */
  publishedId: string
}

/**
 * Identify that a version of a document should be unpublished when
 * the release that version is contained within is published.
 *
 * @public
 */
export declare interface UnpublishVersionAction {
  actionType: 'sanity.action.document.version.unpublish'
  versionId: string
  publishedId: string
}

/**
 * Unschedules a `scheduled` release, stopping it from being published.
 *
 * @public
 */
export declare interface UnscheduleReleaseAction {
  actionType: 'sanity.action.release.unschedule'
  releaseId: string
}

export {unstable__adapter}

export {unstable__environment}

/** @public */
export declare type UploadBody = File | Blob | Buffer | NodeJS.ReadableStream

/** @public */
export declare interface UploadClientConfig {
  /**
   * Optional request tag for the upload
   */
  tag?: string
  /**
   * Whether or not to preserve the original filename (default: true)
   */
  preserveFilename?: boolean
  /**
   * Filename for this file (optional)
   */
  filename?: string
  /**
   * Milliseconds to wait before timing the request out
   */
  timeout?: number
  /**
   * Mime type of the file
   */
  contentType?: string
  /**
   * Array of metadata parts to extract from asset
   */
  extract?: AssetMetadataType[]
  /**
   * Optional freeform label for the asset. Generally not used.
   */
  label?: string
  /**
   * Optional title for the asset
   */
  title?: string
  /**
   * Optional description for the asset
   */
  description?: string
  /**
   * The credit to person(s) and/or organization(s) required by the supplier of the asset to be used when published
   */
  creditLine?: string
  /**
   * Source data (when the asset is from an external service)
   */
  source?: {
    /**
     * The (u)id of the asset within the source, i.e. 'i-f323r1E'
     */
    id: string
    /**
     * The name of the source, i.e. 'unsplash'
     */
    name: string
    /**
     * A url to where to find the asset, or get more info about it in the source
     */
    url?: string
  }
}

/** @public */
export declare class UsersClient {
  #private
  constructor(client: SanityClient, httpRequest: HttpRequest)
  /**
   * Fetch a user by user ID
   *
   * @param id - User ID of the user to fetch. If `me` is provided, a minimal response including the users role is returned.
   */
  getById<T extends 'me' | string>(id: T): Promise<T extends 'me' ? CurrentSanityUser : SanityUser>
}

/**
 * @internal - it may have breaking changes in any release
 */
export declare function validateApiPerspective(
  perspective: unknown,
): asserts perspective is ClientPerspective

/** @public */
export declare type VersionAction =
  | CreateVersionAction
  | DiscardVersionAction
  | ReplaceVersionAction
  | UnpublishVersionAction

/** @public */
export declare interface VideoPlaybackInfo<
  T extends VideoPlaybackInfoItem = VideoPlaybackInfoItem,
> {
  id: string
  thumbnail: T
  animated: T
  storyboard: T
  stream: T
  duration: number
  aspectRatio: number
}

/** @public */
export declare type VideoPlaybackInfoItem =
  | VideoPlaybackInfoItemPublic
  | VideoPlaybackInfoItemSigned

/** @public */
export declare interface VideoPlaybackInfoItemPublic {
  url: string
}

/** @public */
export declare interface VideoPlaybackInfoItemSigned extends VideoPlaybackInfoItemPublic {
  token: string
}

/** @public */
export declare type VideoPlaybackInfoPublic = VideoPlaybackInfo<VideoPlaybackInfoItemPublic>

/** @public */
export declare type VideoPlaybackInfoSigned = VideoPlaybackInfo<VideoPlaybackInfoItemSigned>

/** @public */
export declare interface VideoPlaybackTokens {
  stream?: string
  thumbnail?: string
  storyboard?: string
  animated?: string
}

/**
 * The listener has been established, and will start receiving events.
 * Note that this is also emitted upon _reconnection_.
 *
 * @public
 */
export declare type WelcomeEvent = {
  type: 'welcome'
  listenerName: string
}

export {}
