import { b as AuthConfig, c as DocumentTypeHandle, d as ProjectHandle, f as ReleaseHandle, i as DatasetHandle, o as DocumentHandle, s as DocumentResource, t as SanityInstance, u as PerspectiveHandle, x as AuthProvider } from "./createSanityInstance--Lrldto8.js";
import { i as StoreAction, n as StateSource, r as BoundStoreAction } from "./createStateSourceAction-CICvr0ZE.js";
import { ClientConfig, DatasetsResponse, ListenEvent, MultipleMutationResult, ReleaseDocument, ReleaseDocument as ReleaseDocument$1, ResponseQueryOptions, SanityClient, SanityDocument, SanityProject, SanityProjectionsByResource, SanityQueriesByResource, SanitySchemasByResource } from "@sanity/client";
import { Observable, Subject } from "rxjs";
import { CurrentUser, CurrentUser as CurrentUser$1, InsertPatch, Mutation, PatchOperations, Path, PortableTextBlock, Role, SanityDocument as SanityDocument$1, SanityDocument as SanityDocument$3, SanityDocumentLike } from "@sanity/types";
import { getIndexForKey as getIndexForKey$1, getPathDepth, joinPaths, jsonMatch as jsonMatch$1, slicePath as slicePath$1, stringifyPath as stringifyPath$1 } from "@sanity/json-match";
import { PatchMutation } from "@sanity/mutate/_unstable_store";
import { SanityDocument as SanityDocument$2, SanityProjectionResult, SanityProjections as SanityProjections$1, SanityQueries as SanityQueries$1, SanityQueryResult } from "groq";
import { ExprNode } from "groq-js";
import { CanvasResource, MediaResource, StudioResource } from "@sanity/message-protocol";
/**
 * Identifies cached data for invalidation, matched across the whole store.
 * A fetcher declares the tags each of its entries carries (via
 * {@link FetcherDefinition.tags}); a mutation declares the tags it invalidates
 * (via {@link MutationDefinition.invalidates}).
 *
 * When invalidating,`{type: 'organization'}` matches every entry carrying any `organization` tag;
 * `{type: 'organization', id: 'abc'}` matches only entries carrying that exact pair.
 * List entries carry a `{type, id: 'LIST'}` sentinel plus one tag per item, so a
 * "create" mutation can refetch lists without touching unrelated detail entries.
 *
 * @internal
 */
interface CacheTag {
  type: string;
  /** Specific id, or the `'LIST'` sentinel for list entries */
  id?: string | number;
}
/**
 * The reactive value of one cache entry, as exposed by
 * {@link Fetcher.getState}. React hooks consume this envelope directly.
 * Discriminated on `status`, so narrowing gives correctly-typed `data`:
 * `'success'` is the only arm carrying data, and a background failure while
 * data still renders surfaces on the `'success'` arm's `error`.
 *
 * `isFetching` is common to all arms: a fetch for this entry is in flight
 * (initial load, revalidation, or poll).
 *
 * @internal
 */
type FetcherSnapshot<TData> = {
  /** No data yet — initial fetch in flight or not started */
  status: 'pending';
  data: undefined;
  error: undefined;
  isFetching: boolean;
  dataUpdatedAt: undefined;
} | {
  /** Data available — possibly stale, possibly revalidating */
  status: 'success';
  data: TData;
  /** Most recent background-fetch failure, cleared by the next successful fetch */
  error: unknown;
  isFetching: boolean;
  /** Epoch ms of the fetch that produced `data` */
  dataUpdatedAt: number;
} | {
  /** The last fetch failed and no data exists to serve */
  status: 'error';
  data: undefined;
  error: unknown;
  isFetching: boolean;
  dataUpdatedAt: undefined;
};
/**
 * A typed description of one cached, parameterised read of an API response —
 * here is a single cache per {@link SanityInstance}; every definition registers
 * into it and its `name` namespaces its keys. A list and a detail read are two
 * definitions over the one cache, not two caches.
 *
 * Entry lifecycle: fresh → stale → collected. Fresh entries are served from
 * cache with no fetch; stale entries are served immediately and revalidated in
 * the background (stale-while-revalidate); collected entries are removed once
 * their `gcTime` elapses after the last unsubscribe, so the next subscriber
 * suspends.
 *
 * @internal
 */
interface FetcherDefinition<TParams extends unknown[], TData> {
  /** Namespaces this fetcher's keys in the shared cache; used for devtools and request-tag derivation */
  name: string;
  /**
   * Fetches the data once. Return an observable that emits the result and
   * completes.
   */
  fetch: (instance: SanityInstance) => (...params: TParams) => Observable<TData>;
  /** Converts params into the cache key that identifies an entry (unique within `name`) */
  getKey: (instance: SanityInstance, ...params: TParams) => string;
  /**
   * Cache tags each entry carries, for cache-wide invalidation. A static array,
   * or a function of the fetched data when tags depend on the response (e.g. one
   * tag per list item).
   */
  tags?: CacheTag[] | ((data: TData, ...params: TParams) => CacheTag[]);
  /**
   * How long fetched data is fresh, in ms. Fresh entries never refetch;
   * stale entries serve cached data and revalidate in the background.
   * @defaultValue 30_000
   */
  staleTime?: number;
  /**
   * How long an entry survives after its last unsubscribe before it is garbage
   * collected, in ms. The clock starts at the last unsubscribe — entries with
   * active subscribers are never collected.
   * @defaultValue 300_000
   */
  gcTime?: number;
  /**
   * Refetch on this interval (ms) while the entry has at least one subscriber,
   * independent of staleness. Ticks are skipped while `document.hidden`. Off by default.
   */
  refetchInterval?: number;
  /**
   * Consulted once, when an entry is being created and no cached data exists for
   * it. Return data pulled from another fetcher in the same cache — read via its
   * ordinary `getState(instance, ...).getCurrent()`, e.g. a detail entry pulling
   * its item out of the cached list — to skip or soften the initial fetch.
   * `dataUpdatedAt` must be when the source data was fetched, not "now": staleness
   * is measured from it. Return `undefined` to fetch as normal.
   */
  initialData?: (instance: SanityInstance, ...params: TParams) => {
    data: TData;
    dataUpdatedAt: number;
  } | undefined;
}
/**
 * A typed handle over the shared fetcher cache, returned by
 * {@link defineFetcher}. It is a view onto the entries under its definition's
 * `name`, not a cache of its own.
 *
 * @internal
 */
interface Fetcher<TParams extends unknown[], TData> {
  /** Reactive envelope for one entry. Subscribing triggers fetching per staleness rules. */
  getState: (instance: SanityInstance, ...params: TParams) => StateSource<FetcherSnapshot<TData>>;
  /**
   * Resolves with the entry's first available data — the promise a suspending
   * component throws. Rejects if the initial fetch fails.
   */
  resolveState: (instance: SanityInstance, ...params: TParams) => Promise<TData>;
  /**
   * Marks the entry stale. If it has active subscribers it refetches immediately;
   * otherwise it refetches on next subscribe.
   */
  invalidate: (instance: SanityInstance, ...params: TParams) => void;
  /** {@link Fetcher.invalidate} for every entry under this fetcher's `name`. */
  invalidateAll: (instance: SanityInstance) => void;
  /**
   * Imperative fetch, bypassing staleness. Dedupes against an in-flight fetch.
   * Resolves with the entry's data as held by the cache once the fetch settles.
   */
  refetch: (instance: SanityInstance, ...params: TParams) => Promise<TData>;
  /**
   * Writes an entry's data directly. Returns an undo handle — inside a
   * mutation's `onMutate` these writes are recorded and rolled back automatically
   * on failure.
   */
  setData: (instance: SanityInstance, params: TParams, updater: TData | ((current: TData | undefined) => TData)) => {
    undo: () => void;
  };
}
/**
 * Writes an entry's data in any fetcher. Passed to {@link MutationDefinition}
 * callbacks — mutations are the only holders of arbitrary write access; read
 * fetchers pull their data (see {@link FetcherDefinition.initialData}). Inside
 * `onMutate`, every write is recorded and undone automatically if the mutation
 * fails.
 *
 * @internal
 */
type CacheWriter = <TParams extends unknown[], TData>(fetcher: Fetcher<TParams, TData>, params: TParams, updater: TData | ((current: TData | undefined) => TData)) => void;
/**
 * Resolves when the mutation settles on the server. `invalidated` tracks the
 * background reconciliation — the refetches triggered by
 * {@link MutationDefinition.invalidates} — for the rare caller that must wait for
 * full reconvergence rather than server settlement.
 *
 * @internal
 */
interface MutationResult<TResult> {
  /** The server response */
  data: TResult;
  /** Settles when the refetches of matched active entries complete */
  invalidated: Promise<void>;
}
/**
 * Defines a mutation with optimistic cache updates. Lifecycle:
 *
 * 1. `onMutate` applies optimistic writes synchronously — the UI updates before
 *    the request leaves. Each entry carries a version counter that increments on
 *    every write. An optimistic write bumps the counter, so a revalidation already
 *    in flight lands "out of date" and is discarded rather than clobbering the
 *    optimistic write.
 * 2. The request runs. On failure, recorded writes are rolled back automatically
 *    — the cache is restored exactly, so failure ends the lifecycle here.
 * 3. On success, `onSuccess` may write the server response into the cache directly.
 * 4. On success, `invalidates` tags mark matching entries across the cache
 *    stale (active entries refetch), so the cache reconverges on server truth
 *    even if the optimistic shape was wrong.
 *
 * @internal
 */
interface MutationDefinition<TInput, TResult> {
  /** Unique mutation name, used for devtools and request-tag derivation */
  name: string;
  /** Creates the observable that performs the server mutation */
  mutationFn: (instance: SanityInstance) => (input: TInput) => Observable<TResult>;
  /** Optimistic cache writes, applied synchronously before the request */
  onMutate?: (write: CacheWriter, input: TInput) => void;
  /** Reconcile the cache with the server response, avoiding a refetch round-trip */
  onSuccess?: (write: CacheWriter, result: TResult, input: TInput) => void;
  /**
   * Cache tags to invalidate on success. Failure invalidates nothing: recorded
   * optimistic writes roll back to the exact pre-mutation cache, and any
   * server-side ambiguity (e.g. timeout after commit) heals via `staleTime`.
   * A static array, or a function of the result/input.
   */
  invalidates?: CacheTag[] | ((result: TResult, input: TInput) => CacheTag[]);
}
/**
 * Registers a fetcher definition against the shared cache and returns its typed
 * handle.
 *
 * @internal
 */
declare function defineFetcher<TParams extends unknown[], TData>(definition: FetcherDefinition<TParams, TData>): Fetcher<TParams, TData>;
/**
 * Creates a bound mutation from its definition. The returned action resolves at
 * server settlement — not after invalidation refetches, which run as background
 * reconciliation (see {@link MutationResult.invalidated}).
 *
 * @internal
 */
declare function defineMutation<TInput, TResult>(definition: MutationDefinition<TInput, TResult>): (instance: SanityInstance, input: TInput) => Promise<MutationResult<TResult>>;
/**
 * The resource types the Access API can scope a permission check to.
 *
 * @see https://www.sanity.io/docs/http-reference/access-api
 * @public
 */
type AccessResourceType = 'organization' | 'project' | 'media-library' | 'canvas' | 'dashboard' | 'view';
/**
 * Fetcher checking whether the current user holds the given permissions on a
 * resource (`GET /access/:resourceType/:resourceId/user-permissions/me/check`),
 * on the shared fetcher cache. Resolves to a map of each requested permission
 * to whether the user has it. The key sorts the permission list, so permission
 * order doesn't create distinct cache entries.
 *
 * @see https://www.sanity.io/docs/http-reference/access-api
 * @internal
 */
declare const checkPermissions: Fetcher<[resourceType: AccessResourceType, resourceId: string, permissions: string[]], Record<string, boolean>>;
/**
 * Represents the various states the authentication type can be in.
 *
 * @public
 */
declare enum AuthStateType {
  LOGGED_IN = "logged-in",
  LOGGING_IN = "logging-in",
  ERROR = "error",
  LOGGED_OUT = "logged-out"
}
/**
 * OAuth tokens issued by Sanity's OAuth token endpoint.
 *
 * @public
 */
interface OAuthTokens {
  accessToken: string;
  tokenType: 'bearer';
  expiresIn: number;
  expiresAt: Date;
  refreshToken?: string;
}
/**
 * Represents the various states the authentication can be in.
 *
 * @public
 */
type AuthState = LoggedInAuthState | LoggedOutAuthState | LoggingInAuthState | ErrorAuthState;
/**
 * Logged-in state from the auth state.
 * @public
 */
type LoggedInAuthState = {
  type: AuthStateType.LOGGED_IN;
  token: string;
  currentUser: CurrentUser | null;
  lastTokenRefresh?: number;
};
/**
 * Logged-out state from the auth state.
 * @public
 */
type LoggedOutAuthState = {
  type: AuthStateType.LOGGED_OUT;
  isDestroyingSession: boolean;
};
/**
 * Logging-in state from the auth state.
 * @public
 */
type LoggingInAuthState = {
  type: AuthStateType.LOGGING_IN;
  isExchangingToken: boolean;
};
/**
 * Error state from the auth state.
 * @public
 */
type ErrorAuthState = {
  type: AuthStateType.ERROR;
  error: unknown;
};
/**
 * Represents the various states the authentication can be in.
 *
 * @public
 */
interface DashboardContext {
  mode?: string;
  env?: string;
  orgId?: string;
}
/**
 * The method of authentication used.
 * @internal
 */
type AuthMethodOptions = 'localstorage' | 'cookie' | undefined;
/**
 * @public
 */
interface AuthStoreState {
  authState: AuthState;
  providers?: AuthProvider[];
  options: {
    initialLocationHref: string;
    clientFactory: (config: ClientConfig) => SanityClient;
    customProviders: AuthConfig['providers'];
    storageKey: string;
    storageArea: Storage | undefined;
    apiHost: string | undefined;
    loginUrl: string;
    callbackUrl: string | undefined;
    providedToken: string | undefined;
    authMethod: AuthMethodOptions;
    oauth: AuthConfig['oauth'];
  };
  dashboardContext?: DashboardContext;
  oauthTokens?: OAuthTokens;
}
/**
 * @public
 */
declare const getCurrentUserState: BoundStoreAction<AuthStoreState, [], StateSource<CurrentUser | null>>;
/**
 * @public
 */
declare const getTokenState: BoundStoreAction<AuthStoreState, [], StateSource<string | null>>;
/**
 * @public
 */
declare const getLoginUrlState: BoundStoreAction<AuthStoreState, [], StateSource<string>>;
/**
 * @public
 */
declare const getAuthState: BoundStoreAction<AuthStoreState, [], StateSource<AuthState>>;
/**
 * Returns a state source indicating if the SDK is running within a dashboard context.
 * @public
 */
declare const getIsInDashboardState: BoundStoreAction<AuthStoreState, [], StateSource<boolean>>;
/**
 * Action to explicitly set the authentication token.
 * Used internally by the Comlink token refresh.
 * @internal
 */
declare const setAuthToken: BoundStoreAction<AuthStoreState, [token: string | null], void>;
/**
 * Error message returned by the organization verification
 * @public
 */
interface OrgVerificationResult {
  error: string | null;
}
/**
 * Creates an observable that emits the organization verification state for a given instance.
 * It combines the dashboard organization ID (from the message bus or `_context`) with the
 * project's actual organization ID (fetched via the project fetcher) and compares them.
 * @public
 */
declare function observeOrganizationVerificationState(instance: SanityInstance, projectIds: string[]): Observable<OrgVerificationResult>;
/**
 * Handles the auth redirect callback. In OAuth mode this delegates to
 * {@link handleOAuthCallback}; otherwise it exchanges the legacy `sid` for a
 * long-lived token.
 *
 * @public
 */
declare const handleAuthCallback: BoundStoreAction<AuthStoreState, [locationHref?: string | undefined], Promise<string | false>>;
/**
 * Logs the current user out. In OAuth mode this revokes the OAuth tokens
 * instead of calling the legacy `/auth/logout` endpoint; revocation is
 * best-effort, so the OAuth path resolves even if the revoke request fails,
 * whereas the legacy path rejects when `/auth/logout` fails. Local state and
 * storage are cleared in both cases.
 *
 * @public
 */
declare const logout: BoundStoreAction<AuthStoreState, [], Promise<void>>;
/**
 * Starts the OAuth authorization-code + PKCE flow: generates a `code_verifier`,
 * `code_challenge` and `state`, persists the verifier and state to
 * `sessionStorage`, then navigates the browser to the authorize endpoint.
 *
 * @public
 */
declare const startOAuthAuthorization: BoundStoreAction<AuthStoreState, [], Promise<void>>;
/**
 * Handles the OAuth redirect callback: validates `state`, surfaces `error`
 * responses, exchanges the authorization `code` for tokens, persists them, and
 * transitions to `LOGGED_IN`.
 *
 * Returns the URL for the caller to `history.replaceState` to when a callback
 * was processed: on success, the same-origin location the user was on when
 * the flow started (if any), otherwise the callback URL cleaned of OAuth
 * params. Returns `false` when there was nothing to handle (no code, or an
 * exchange already in progress). A callback that fails validation while a
 * session is already `LOGGED_IN` (e.g. a remount before the params were
 * stripped) is ignored with a warning and still returns the cleaned URL, so a
 * string result does not imply an exchange ran.
 *
 * @public
 */
declare const handleOAuthCallback: BoundStoreAction<AuthStoreState, [locationHref?: string | undefined], Promise<string | false>>;
/**
 * Refreshes the OAuth tokens using the `refresh_token` grant. Concurrent
 * callers share a single in-flight request. An unrecoverable failure (a 4xx
 * rejecting the refresh token) clears the tokens and transitions to
 * `LOGGED_OUT`; transient failures (network, 5xx, rate limits) leave the
 * session intact and rethrow so the caller can retry. The resolved tokens omit
 * the refresh token, which core retains internally for subsequent refreshes.
 *
 * @public
 */
declare const refreshOAuthTokens: BoundStoreAction<AuthStoreState, [], Promise<Omit<OAuthTokens, "refreshToken"> | null>>;
/**
 * Revokes the OAuth tokens then clears local storage and transitions to `LOGGED_OUT`.
 * Local state is cleared even if the revoke request fails.
 *
 * @public
 */
declare const revokeOAuthTokens: BoundStoreAction<AuthStoreState, [], Promise<void>>;
/**
 * A state source exposing the current OAuth tokens (including expiry), or
 * `null` when not logged in via OAuth. The refresh token is omitted — it is a
 * long-lived credential held internally by core for `refreshOAuthTokens`, not
 * part of the app-facing token view.
 *
 * @public
 */
declare const getOAuthTokensState: BoundStoreAction<AuthStoreState, [], StateSource<Omit<OAuthTokens, "refreshToken"> | null>>;
/**
 * Identifiers from a `projectUserNotFoundError` response. Each field is
 * optional because older API responses only carry a description.
 *
 * @internal
 */
interface ProjectAccessErrorDetails {
  /** The project the failed request was made against. */
  projectId?: string;
  /** The global ID of the signed-in user, which has no membership in the project. */
  userId?: string;
  /** The trace ID of the failed request. Support uses it to find the request in logs. */
  traceId?: string;
}
/**
 * Reads the identifiers from the 401 `projectUserNotFoundError` that the
 * Content Lake returns when the signed-in user is not a member of the project.
 * Accepts the `ClientError` itself or an error that wraps it as its `cause`,
 * such as the React package's `AuthError`.
 *
 * @returns The identifiers, or `null` when the error is not a
 *   `projectUserNotFoundError`.
 * @internal
 */
declare function getProjectAccessErrorDetails(error: unknown): ProjectAccessErrorDetails | null;
/**
 * Returns the ID of the project that rejected a request because the signed-in
 * user isn't a member of it. The Content Lake reports this as a 401
 * `projectUserNotFoundError`. It usually means the user signed in with a
 * different account than the one that has access, for example Google instead
 * of SSO with the same email address.
 *
 * When this error reaches the SDK's `AuthBoundary`, the boundary replaces the
 * whole app with a screen that explains the problem. An app-level error
 * boundary inside `AuthBoundary` catches the error first, so it decides where
 * the error goes. Rethrow it when the app can't work without the rejected
 * project. Handle it in place when only part of the app reads from that
 * project, so a user who can access the app's other projects can keep using
 * them.
 *
 * @param error - The value to inspect. A `ClientError`, or an error that wraps
 *   one as its `cause`.
 * @returns The rejected project's ID, or `null` when the error isn't a
 *   `projectUserNotFoundError` or the response doesn't name the project.
 *
 * @example Rethrowing only for the project the whole app needs
 * ```tsx
 * const MAIN_PROJECT_ID = 'abc123'
 *
 * function Fallback({error}: FallbackProps) {
 *   const projectId = getProjectAccessErrorProjectId(error)
 *   // The app can't work without its main project, so let AuthBoundary
 *   // replace it with the project access screen.
 *   if (projectId === MAIN_PROJECT_ID) throw error
 *   if (projectId) return <p>You don't have access to project {projectId}.</p>
 *   return <p>Something went wrong.</p>
 * }
 * ```
 *
 * @category Authentication
 * @public
 */
declare function getProjectAccessErrorProjectId(error: unknown): string | null;
/**
 * Returns a user-facing name for a `/users/me` `provider` value, such as
 * `Google` for `google` or `SSO` for any `saml-*` provider.
 *
 * @returns The label, or `undefined` for an unknown or missing provider.
 * @internal
 */
declare function getSignInMethodLabel(provider: string | undefined): string | undefined;
type AllowedClientConfigKey = 'useCdn' | 'token' | 'perspective' | 'apiHost' | 'proxy' | 'withCredentials' | 'timeout' | 'maxRetries' | 'dataset' | 'projectId' | 'requestTagPrefix' | 'useProjectHostname';
/**
 * States tracked by the client store
 * @public
 */
interface ClientStoreState {
  token: string | null;
  clients: { [TKey in string]?: SanityClient; };
  authMethod?: 'localstorage' | 'cookie';
}
/**
 * Options used when retrieving a client instance from the client store.
 *
 * This interface extends the base {@link ClientConfig} and adds:
 *
 * - **apiVersion:** A required string indicating the API version for the client.
 * - **scope:** An optional flag to choose between the project-specific client
 *   ('project') and the global client ('global'). When set to `'global'`, the
 *   global client is used.
 *
 * These options are utilized by `getClient` and `getClientState` to configure and
 * return appropriate client instances that automatically handle authentication
 * updates and configuration changes.
 *
 * @public
 */
interface ClientOptions extends Pick<ClientConfig, AllowedClientConfigKey> {
  /**
   * An optional flag to choose between the default client (typically project-level)
   * and the global client ('global'). When set to `'global'`, the global client
   * is used.
   */
  scope?: 'default' | 'global';
  /**
   * A required string indicating the API version for the client.
   */
  apiVersion: string;
  /**
   * @internal
   * The SDK resource to use for the client -- this will get transformed into a ClientConfig resource.
   */
  resource?: DocumentResource;
}
/**
 * Retrieves a Sanity client instance configured with the provided options.
 *
 * This function returns a client instance configured for the project or as a
 * global client based on the options provided. It ensures efficient reuse of
 * client instances by returning the same instance for the same options.
 * For automatic handling of authentication token updates, consider using
 * `getClientState`.
 *
 * @public
 */
declare const getClient: BoundStoreAction<ClientStoreState, [options: ClientOptions], SanityClient>;
/**
 * Returns a state source for the Sanity client instance.
 *
 * This function provides a subscribable state source that emits updated client
 * instances whenever relevant configurations change (such as authentication tokens).
 * Use this when you need to react to client configuration changes in your application.
 *
 * @public
 */
declare const getClientState: BoundStoreAction<ClientStoreState, [options: ClientOptions], StateSource<SanityClient>>;
/**
 * Whether a thread is still being discussed or has been closed out.
 * @beta
 */
type CommentStatus = 'open' | 'resolved';
/**
 * The body of a comment, as Portable Text.
 *
 * Mentions appear here as inline objects of type `mention` carrying a `userId`.
 * The SDK stores and returns them untouched, so a mention written in the Studio
 * survives a round trip, but there is no API for composing one yet.
 * @beta
 */
type CommentMessage = PortableTextBlock[] | null;
/**
 * One block touched by a text selection, and that block's text with the
 * selection boundaries marked.
 *
 * `text` is the block's *entire* plain text with two private-use sentinel
 * characters (U+F000 and U+F001) inserted where the selection starts and ends.
 * Storing marked-up text rather than character offsets is what lets a highlight
 * survive edits elsewhere in the same block.
 * @beta
 */
interface CommentTextSelectionItem {
  _key: string;
  text: string;
}
/**
 * A comment anchored to a run of text inside a Portable Text field.
 *
 * The SDK passes this through untouched. Resolving it back to a position in a
 * live editor needs the editor's current value, so that lives in
 * `@portabletext/plugin-sdk-value` rather than here.
 * @beta
 */
interface CommentTextSelection {
  type: 'text';
  value: CommentTextSelectionItem[];
}
/**
 * An emoji reaction on a comment.
 *
 * Read only for now: a reaction added in the Studio shows up here, but there is
 * no action for adding or removing one.
 * @beta
 */
interface CommentReaction {
  shortName: string;
  userId: string;
  addedAt: string;
}
/**
 * Why a comment is not yet on the server.
 *
 * Local only, never written. Present on a comment whose create request failed,
 * so an app can offer a retry.
 * @beta
 */
type CommentLocalState = {
  type: 'createError';
  error: Error;
} | {
  type: 'createRetrying';
};
/**
 * A single comment.
 *
 * Deliberately not the stored document. Comments are moving from per-dataset
 * addon datasets to an organization-level store, and the two disagree on the
 * document type, on how the commented document is referenced, and on where the
 * author is recorded. Everything here reads the same on both sides, so an app
 * written against this survives the move.
 *
 * Threads are flat: every comment in a thread shares a `threadId`, the thread's
 * first comment has no `parentCommentId`, and replies carry that first comment's
 * `id`. Use {@link CommentThread} to work with them grouped.
 *
 * @beta
 */
interface Comment {
  id: string;
  createdAt: string;
  /**
   * Who wrote it.
   *
   * Absent when the server carries the author instead of the document. The
   * Studio's comments dataset stores it on the document, so it is present on
   * everything written today, but an agent-authored comment records
   * attribution elsewhere. Render a fallback rather than assuming a user id.
   */
  authorId?: string;
  message: CommentMessage;
  threadId: string;
  /** Absent on the comment that starts a thread. */
  parentCommentId?: string;
  status: CommentStatus;
  /** Set once the message has been rewritten. */
  lastEditedAt?: string;
  /** The document the thread hangs on, always the published id. */
  documentId: string;
  documentType: string;
  /** The field the thread hangs off, for example `title`. */
  fieldPath: string;
  /** Set when the comment is anchored to a run of text in a Portable Text field. */
  selection?: CommentTextSelection;
  /** A copy of the content the comment was written about. */
  contentSnapshot?: unknown;
  reactions: CommentReaction[];
  /** Local only. Present while a create is failing or being retried. */
  state?: CommentLocalState;
}
/**
 * A thread: one comment plus its replies.
 *
 * Unlike the Studio, the SDK returns every thread it finds. The Studio hides
 * threads whose field is gone from the schema or hidden by a conditional, which
 * it can do because it has the schema. Check `fieldPath` yourself if your app
 * needs the same behaviour.
 * @beta
 */
interface CommentThread {
  threadId: string;
  /** The field the thread hangs off, taken from its first comment. */
  fieldPath: string;
  parentComment: Comment;
  /** Oldest first. */
  replies: Comment[];
  /** The parent plus its replies. */
  commentsCount: number;
  /** Taken from the parent comment; replies follow it. */
  status: CommentStatus;
  /** `createdAt` of the most recent comment in the thread. */
  lastActivityAt: string;
}
/** @beta */
interface CreateCommentOptions extends DocumentHandle {
  message: CommentMessage;
  /**
   * Which field the thread hangs off, for example `title` or
   * `body[_key=="intro"].content`.
   *
   * Required, and it has to resolve to a real path. There is no such thing as a
   * comment on a document as a whole: the Studio only ever creates field
   * comments, and its comment inspector throws on an empty path rather than
   * ignoring it, so a pathless comment takes the inspector down for everyone
   * looking at that document.
   */
  fieldPath: string | Path;
  /**
   * Anchors the comment to a run of text inside a Portable Text field. Building
   * one needs a live editor, so this comes from
   * `@portabletext/plugin-sdk-value` rather than being constructed by hand.
   */
  selection?: CommentTextSelection;
  /** Reuse the id of a failed comment to retry it. Defaults to a new id. */
  commentId?: string;
  /** Defaults to a new id, which starts a new thread. */
  threadId?: string;
  /** @defaultValue `'open'` */
  status?: CommentStatus;
  /**
   * The `_rev` of the document when the comment was written.
   *
   * Not filled in automatically: the SDK's local document revision is replaced
   * by a transaction id while an edit is in flight, so it can name a revision
   * that never reached the server. Nothing in the Studio reads this today.
   */
  documentRevisionId?: string;
  /**
   * Ambient information stored alongside the comment, merged over the defaults.
   *
   * The Studio writes `tool`, `payload`, `intent`, and `notification` here for
   * its notification backend. The SDK has no source for any of them, so
   * mentions in comments created this way do not send email unless you supply
   * `notification` yourself. Deliberately loose: the organization-level store
   * treats this as free-form, so no shape is worth promising.
   */
  context?: Record<string, unknown>;
  /** A copy of the content being discussed. References in it are weakened. */
  contentSnapshot?: unknown;
}
/** @beta */
interface ReplyToCommentOptions extends DocumentHandle {
  /** The comment being replied to. Replies to a reply join the same thread. */
  parentCommentId: string;
  message: CommentMessage;
  commentId?: string;
  /** Only needed when the parent is not loaded, such as following a deep link. */
  threadId?: string;
  /** Only needed when the parent is not loaded. */
  fieldPath?: string | Path;
  /** Required when the parent is not loaded. */
  status?: CommentStatus;
}
/** @beta */
interface UpdateCommentOptions extends DatasetHandle {
  commentId: string;
  message: CommentMessage;
}
/** @beta */
interface SetCommentStatusOptions extends DatasetHandle {
  /** The thread's first comment. Replies follow their parent. */
  commentId: string;
  status: CommentStatus;
}
/** @beta */
interface RemoveCommentOptions extends DatasetHandle {
  commentId: string;
}
/**
 * Starts a thread on a document, or on one of its fields.
 *
 * Creates the project's comments dataset if this is the first comment anywhere
 * in it. The comment appears locally before the server confirms it; if the
 * write fails it stays, carrying `_state.createError`, and retrying with the
 * same `commentId` replaces it.
 *
 * @beta
 */
declare const createComment: (instance: SanityInstance, options: CreateCommentOptions) => Promise<Comment>;
/**
 * Adds a reply to an existing thread.
 *
 * The thread and field are taken from the parent comment, so a reply always
 * matches the same list as the comment it answers. Supply them only when the
 * parent is not loaded.
 *
 * @beta
 */
declare const replyToComment: (instance: SanityInstance, options: ReplyToCommentOptions) => Promise<Comment>;
/**
 * Rewrites a comment's message and stamps `lastEditedAt`.
 * @beta
 */
declare const updateComment: (instance: SanityInstance, options: UpdateCommentOptions) => Promise<void>;
/**
 * Resolves or reopens a thread.
 *
 * Pass the thread's first comment: replies follow it, patched server-side in
 * one query so a reply created by someone else at the same moment is caught
 * too.
 *
 * @beta
 */
declare const setCommentStatus: (instance: SanityInstance, options: SetCommentStatusOptions) => Promise<void>;
/**
 * Deletes a comment, and its replies when it starts a thread.
 * @beta
 */
declare const removeComment: (instance: SanityInstance, options: RemoveCommentOptions) => Promise<void>;
/**
 * Which comments to read.
 * @beta
 */
interface CommentsOptions extends DocumentHandle {
  /**
   * Narrow to one field. Omit to get every comment on the document.
   */
  fieldPath?: string | Path;
  /** Narrow to open or resolved threads. Omit for both. */
  status?: CommentStatus;
}
/** @beta */
interface ResolveCommentsOptions extends CommentsOptions {
  signal?: AbortSignal;
}
/**
 * A stable string standing for one set of read options.
 *
 * Only React needs this: it holds one state source steady across renders and
 * defers swapping to a new one while the previous list is still on screen.
 * `fieldPath` is normalised on the way in, so a path array and the equivalent
 * string address the same list.
 *
 * @internal
 */
declare function getCommentsOptionsKey(options: CommentsOptions): string;
/** @internal */
declare function parseCommentsOptionsKey(key: string): CommentsOptions;
/**
 * Every comment on a document, newest first.
 *
 * `undefined` until the first snapshot arrives. Replies are included; use
 * {@link getCommentThreadsState} to read them grouped.
 *
 * @beta
 */
declare const getCommentsState: (instance: SanityInstance, options: CommentsOptions) => StateSource<Comment[] | undefined>;
/**
 * Threads on a document, newest thread first, each with its replies oldest first.
 *
 * A thread's `status` and `fieldPath` come from its first comment, so filtering
 * by either selects whole threads rather than individual replies.
 *
 * @beta
 */
declare const getCommentThreadsState: (instance: SanityInstance, options: CommentsOptions) => StateSource<CommentThread[] | undefined>;
/**
 * Waits for a document's comments to load.
 *
 * Holds a subscriber only while resolving, so a component that suspends on this
 * and then errors before mounting does not strand the list. Throw the promise
 * for Suspense, then read through {@link getCommentsState}.
 *
 * @beta
 */
declare const resolveComments: (instance: SanityInstance, options: ResolveCommentsOptions) => Promise<Comment[]>;
/**
 * Waits for a document's comments to load, grouped into threads.
 * @beta
 */
declare const resolveCommentThreads: (instance: SanityInstance, options: ResolveCommentsOptions) => Promise<CommentThread[]>;
/**
 * Creates or validates a `DocumentHandle` object.
 * Ensures the provided object conforms to the `DocumentHandle` interface.
 *
 * This signature applies when the handle passes both `projectId` and `dataset` as strings. The
 * returned handle keeps both fields required and typed as the values passed, so
 * `createDocumentHandle({projectId: 'abc123', dataset: 'production', ...}).projectId` is typed
 * `'abc123'` instead of `'abc123' | undefined`. A field typed `string | undefined`, such as one
 * spread from a `SanityConfig`, uses the next signature and stays optional. `TDataset` and
 * `TProjectId` are `const` so a call written where a typed handle is expected, such as an
 * annotated variable or a prop typed `DocumentHandle<'book', 'production', 'abc123'>`, keeps the
 * literals instead of inferring `string`.
 * @param handle - The object containing document identification properties.
 * @returns The validated `DocumentHandle` object, with `projectId` and `dataset` required.
 * @public
 */
declare function createDocumentHandle<TDocumentType extends string = string, const TDataset extends string = string, const TProjectId extends string = string>(handle: DocumentHandle<TDocumentType, TDataset, TProjectId> & {
  dataset: TDataset;
  projectId: TProjectId;
}): DocumentHandle<TDocumentType, TDataset, TProjectId> & {
  dataset: TDataset;
  projectId: TProjectId;
};
/**
 * Creates or validates a `DocumentHandle` object.
 * Ensures the provided object conforms to the `DocumentHandle` interface.
 * @param handle - The object containing document identification properties.
 * @returns The validated `DocumentHandle` object.
 * @public
 */
declare function createDocumentHandle<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string>(handle: DocumentHandle<TDocumentType, TDataset, TProjectId>): DocumentHandle<TDocumentType, TDataset, TProjectId>;
/**
 * Creates or validates a `DocumentTypeHandle` object.
 * Ensures the provided object conforms to the `DocumentTypeHandle` interface.
 *
 * This signature applies when the handle passes both `projectId` and `dataset` as strings. The
 * returned handle keeps both fields required and typed as the values passed.
 * @param handle - The object containing document type identification properties.
 * @returns The validated `DocumentTypeHandle` object, with `projectId` and `dataset` required.
 * @public
 */
declare function createDocumentTypeHandle<TDocumentType extends string = string, const TDataset extends string = string, const TProjectId extends string = string>(handle: DocumentTypeHandle<TDocumentType, TDataset, TProjectId> & {
  dataset: TDataset;
  projectId: TProjectId;
}): DocumentTypeHandle<TDocumentType, TDataset, TProjectId> & {
  dataset: TDataset;
  projectId: TProjectId;
};
/**
 * Creates or validates a `DocumentTypeHandle` object.
 * Ensures the provided object conforms to the `DocumentTypeHandle` interface.
 * @param handle - The object containing document type identification properties.
 * @returns The validated `DocumentTypeHandle` object.
 * @public
 */
declare function createDocumentTypeHandle<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string>(handle: DocumentTypeHandle<TDocumentType, TDataset, TProjectId>): DocumentTypeHandle<TDocumentType, TDataset, TProjectId>;
/**
 * Creates or validates a `ProjectHandle` object.
 * Ensures the provided object conforms to the `ProjectHandle` interface.
 * @param handle - The object containing project identification properties.
 * @returns The validated `ProjectHandle` object.
 * @public
 */
declare function createProjectHandle<TProjectId extends string = string>(handle: ProjectHandle<TProjectId>): ProjectHandle<TProjectId>;
/**
 * Creates or validates a `DatasetHandle` object.
 * Ensures the provided object conforms to the `DatasetHandle` interface.
 *
 * This signature applies when the handle passes both `projectId` and `dataset` as strings. The
 * returned handle keeps both fields required and typed as the values passed.
 * @param handle - The object containing dataset identification properties.
 * @returns The validated `DatasetHandle` object, with `projectId` and `dataset` required.
 * @public
 */
declare function createDatasetHandle<const TDataset extends string = string, const TProjectId extends string = string>(handle: DatasetHandle<TDataset, TProjectId> & {
  dataset: TDataset;
  projectId: TProjectId;
}): DatasetHandle<TDataset, TProjectId> & {
  dataset: TDataset;
  projectId: TProjectId;
};
/**
 * Creates or validates a `DatasetHandle` object.
 * Ensures the provided object conforms to the `DatasetHandle` interface.
 * @param handle - The object containing dataset identification properties.
 * @returns The validated `DatasetHandle` object.
 * @public
 */
declare function createDatasetHandle<TDataset extends string = string, TProjectId extends string = string>(handle: DatasetHandle<TDataset, TProjectId>): DatasetHandle<TDataset, TProjectId>;
/**
 * Logging infrastructure for the Sanity SDK
 *
 * Provides multi-level, namespace-based logging for both SDK users and maintainers.
 * In production builds, all logging can be stripped via tree-shaking.
 *
 * @example SDK User
 * ```ts
 * import {configureLogging} from '@sanity/sdk'
 *
 * configureLogging({
 *   level: 'info',
 *   namespaces: ['auth', 'document']
 * })
 * ```
 *
 * @example SDK Maintainer
 * ```ts
 * configureLogging({
 *   level: 'trace',
 *   namespaces: ['*'],
 *   internal: true
 * })
 * ```
 */
/**
 * Log levels in order of verbosity (least to most)
 * - error: Critical failures that prevent operation
 * - warn: Issues that may cause problems but don't stop execution
 * - info: High-level informational messages (SDK user level)
 * - debug: Detailed debugging information (maintainer level)
 * - trace: Very detailed tracing (maintainer level, includes RxJS streams)
 * @public
 */
type LogLevel = 'error' | 'warn' | 'info' | 'debug' | 'trace';
/**
 * Log namespaces organize logs by functional domain
 *
 * @remarks
 * This is an extensible string type. As logging is added to more modules,
 * additional namespaces will be recognized. Currently implemented namespaces
 * will be documented as they are added.
 * @internal
 */
type LogNamespace = string;
/**
 * Configuration for the logging system
 * @public
 */
interface LoggerConfig {
  /**
   * Minimum log level to output
   * @defaultValue 'warn'
   */
  level?: LogLevel;
  /**
   * Namespaces to enable. Use ['*'] for all namespaces
   * @defaultValue []
   * @remarks
   * Available namespaces depend on which modules have logging integrated.
   * Check the SDK documentation for the current list of instrumented modules.
   * @example ['auth', 'document']
   */
  namespaces?: string[];
  /**
   * Enable internal/maintainer-level logging
   * Shows RxJS streams, store internals, etc.
   * @defaultValue false
   */
  internal?: boolean;
  /**
   * Custom log handler (for testing or custom output)
   * @defaultValue console methods
   */
  handler?: LogHandler;
  /**
   * Enable timestamps in log output
   * @defaultValue true
   */
  timestamps?: boolean;
  /**
   * Enable in production builds
   * @defaultValue false
   */
  enableInProduction?: boolean;
}
/**
 * Custom log handler interface
 *
 * @internal
 */
interface LogHandler {
  error: (message: string, context?: LogContext) => void;
  warn: (message: string, context?: LogContext) => void;
  info: (message: string, context?: LogContext) => void;
  debug: (message: string, context?: LogContext) => void;
  trace: (message: string, context?: LogContext) => void;
}
/**
 * Context object attached to log messages
 *
 * This interface allows you to attach arbitrary contextual data to log messages.
 * The index signature `[key: string]: unknown` enables you to add any custom
 * properties relevant to your log entry (e.g., `userId`, `documentId`, `action`, etc.).
 *
 * **Sensitive data sanitization:**
 * Top-level keys containing sensitive names (`token`, `password`, `secret`, `apiKey`,
 * `authorization`) are automatically redacted to `[REDACTED]` in log output.
 *
 * @example
 * ```ts
 * logger.info('User logged in', {
 *   userId: '123',          // Custom context
 *   action: 'login',        // Custom context
 *   token: 'secret'         // Will be redacted to [REDACTED]
 * })
 * ```
 *
 * @internal
 */
interface LogContext {
  /**
   * Custom context properties that provide additional information about the log entry.
   * Any key-value pairs can be added here (e.g., userId, documentId, requestId, etc.).
   * Keys with sensitive names (token, password, secret, apiKey, authorization) are
   * automatically sanitized.
   */
  [key: string]: unknown;
  /** Error object if logging an error */
  error?: Error | unknown;
  /** Duration in milliseconds for timed operations */
  duration?: number;
  /** Stack trace for debugging */
  stack?: string;
  /** Instance context (automatically added when available) */
  instanceContext?: InstanceContext;
}
/**
 * Instance context information automatically added to logs
 * @internal
 */
interface InstanceContext {
  /** Unique instance ID */
  instanceId?: string;
  /** Project ID */
  projectId?: string;
  /** Dataset name */
  dataset?: string;
}
/**
 * Logger instance for a specific namespace
 * @internal
 */
interface Logger {
  readonly namespace: string;
  error: (message: string, context?: LogContext) => void;
  warn: (message: string, context?: LogContext) => void;
  info: (message: string, context?: LogContext) => void;
  debug: (message: string, context?: LogContext) => void;
  trace: (message: string, context?: LogContext) => void;
  /** Check if a log level is enabled (for performance-sensitive code) */
  isLevelEnabled: (level: LogLevel) => boolean;
  /** Create a child logger with extended context */
  child: (context: LogContext) => Logger;
  /** Get the instance context if available */
  getInstanceContext: () => InstanceContext | undefined;
}
/**
 * Create a logger for a specific namespace
 * @param namespace - A string identifier for the logging domain (e.g., 'auth', 'document')
 * @param baseContext - Optional base context to include in all log messages
 * @remarks
 * If baseContext includes an `instanceContext` property (with projectId, dataset, instanceId),
 * it will be automatically formatted into the log output for easier debugging of
 * multi-instance scenarios.
 * @public
 */
declare function createLogger(namespace: string, baseContext?: LogContext): Logger;
/**
 * Configure logging for the Sanity SDK
 *
 * This function allows you to control what logs are output by the SDK,
 * making it easier to debug issues in development or production.
 *
 * @remarks
 * **Zero-Config via Environment Variable (Recommended):**
 *
 * The SDK automatically reads the `DEBUG` environment variable, making it
 * easy to enable logging without code changes:
 *
 * ```bash
 * # Enable all SDK logging at debug level
 * DEBUG=sanity:* npm start
 *
 * # Enable specific namespaces
 * DEBUG=sanity:auth,sanity:document npm start
 *
 * # Enable trace level for all namespaces
 * DEBUG=sanity:trace:* npm start
 *
 * # Enable internal/maintainer logs
 * DEBUG=sanity:*:internal npm start
 * ```
 *
 * This matches the pattern used by Sanity CLI and Studio, making it familiar
 * and easy for support teams to help troubleshoot issues.
 *
 * **Programmatic Configuration (Advanced):**
 *
 * For more control (custom handlers, dynamic configuration), call this function
 * explicitly. Programmatic configuration overrides environment variables.
 *
 * **For Application Developers:**
 * Use `info`, `warn`, or `error` levels to see high-level SDK activity
 * without being overwhelmed by internal details.
 *
 * **For SDK Maintainers:**
 * Use `debug` or `trace` levels with `internal: true` to see detailed
 * information about store operations, RxJS streams, and state transitions.
 *
 * **Instance Context:**
 * Logs automatically include instance information (projectId, dataset, instanceId)
 * when available, making it easier to debug multi-instance scenarios:
 * ```
 * [INFO] [auth] [project:abc] [dataset:production] User logged in
 * ```
 *
 * **Available Namespaces:**
 * - `sdk` - SDK initialization, configuration, and lifecycle
 * - `auth` - Authentication and authorization (when instrumented in the future)
 * - And more as logging is added to modules
 *
 * @example Zero-config via environment variable (recommended for debugging)
 * ```bash
 * # Just set DEBUG and run your app - no code changes needed!
 * DEBUG=sanity:* npm start
 * ```
 *
 * @example Programmatic configuration (application developer)
 * ```ts
 * import {configureLogging} from '@sanity/sdk'
 *
 * // Log warnings and errors for auth and document operations
 * configureLogging({
 *   level: 'warn',
 *   namespaces: ['auth', 'document']
 * })
 * ```
 *
 * @example Programmatic configuration (SDK maintainer)
 * ```ts
 * import {configureLogging} from '@sanity/sdk'
 *
 * // Enable all logs including internal traces
 * configureLogging({
 *   level: 'trace',
 *   namespaces: ['*'],
 *   internal: true
 * })
 * ```
 *
 * @example Custom handler (for testing)
 * ```ts
 * import {configureLogging} from '@sanity/sdk'
 *
 * const logs: string[] = []
 * configureLogging({
 *   level: 'info',
 *   namespaces: ['*'],
 *   handler: {
 *     error: (msg) => logs.push(msg),
 *     warn: (msg) => logs.push(msg),
 *     info: (msg) => logs.push(msg),
 *     debug: (msg) => logs.push(msg),
 *     trace: (msg) => logs.push(msg),
 *   }
 * })
 * ```
 *
 * @public
 */
declare function configureLogging(config: LoggerConfig): void;
/**
 * A response field that the API embeds only when its `include` token was
 * requested. Given the full set of tokens `All`, the token `Key` this field
 * maps to, and the tokens actually `Requested`, it resolves to:
 *
 * - `unknown` (field absent) when nothing — or nothing matching `Key` — was requested
 * - `Field` (present, as declared) when a literal request list contains `Key`
 * - `Partial<Field>` (optional) when `Requested` is the wide `All` union, i.e.
 *   an `include` array whose members aren't known at the type level
 *
 * Absent arms return `unknown` so they vanish under intersection. Mirrors the
 * `boolean extends Flag` trick the organization/project types use, but for an
 * include-token union rather than a boolean flag.
 *
 * @internal
 */
type Included<All extends string, Key extends All, Requested extends All, Field> = [All] extends [Requested] ? Partial<Field> : [Key] extends [Requested] ? Field : unknown;
/**
 * Whether the requested include tokens intersect a given set — used to decide
 * whether a parent field (e.g. an application's `activeDeployment`) is present,
 * when requesting any of several tokens forces it in.
 *
 * @internal
 */
type IncludesAny<Requested extends string, Set extends string> = [Requested & Set] extends [never] ? false : true;
/**
 * Related data the Installations API can embed in a response. Each token adds
 * a top-level field to the {@link Installation} item.
 *
 * @see https://www.sanity.io/docs/http-reference/applications-api
 * @public
 */
type InstallationInclude = 'activeConfig' | 'access' | 'interfaces' | 'config.mfManifest';
/**
 * A resource an installation accesses, embedded when `access` is included.
 *
 * @see https://www.sanity.io/docs/http-reference/applications-api
 * @public
 */
interface InstallationAccess {
  id: string;
  resourceType: 'datasets' | 'canvases' | 'dashboards' | 'media-libraries';
  resourceId: string;
}
/**
 * The active config of an installation, embedded when `activeConfig` is
 * included. `null` when nothing is deployed.
 *
 * @see https://www.sanity.io/docs/http-reference/applications-api
 * @public
 */
interface InstallationActiveConfig {
  id: string;
  installationId: string;
  deployedBy: string | null;
  version: string;
  isActive: boolean;
  createdAt: string;
}
/**
 * The always-present fields of an active singleton installation returned by the
 * Installations API (`/installations`), before any {@link InstallationInclude}.
 *
 * @see https://www.sanity.io/docs/http-reference/applications-api
 * @public
 */
interface InstallationBase {
  id: string;
  applicationId: string;
  organizationId: string;
  installedBy: string | null;
  createdAt: string;
  updatedAt: string;
  application: {
    title: string;
    /** Stable, immutable identity of the installed singleton, distinct from `slug`. */
    name: string;
    /** Qualified, globally-unique handle of the installed singleton (e.g. `sanity/<name>`). */
    reference: string;
    slug: string | null;
    /** Sanitized SVG icon markup, or `null` when the singleton has no icon. */
    icon: string | null;
    /** The singleton's publishing organization; the top-level `organizationId` is the installing one. */
    organizationId: string;
  };
}
/**
 * An active singleton installation as returned by the Installations API
 * (`/installations`). `activeConfig`, `access` and `interfaces` are top-level
 * fields, each present only when the matching {@link InstallationInclude} token
 * was requested.
 *
 * @see https://www.sanity.io/docs/http-reference/applications-api
 * @public
 */
type Installation<Include extends InstallationInclude = never> = InstallationBase & Included<InstallationInclude, 'config.mfManifest', Include, {
  application: InstallationBase['application'] & ([InstallationInclude] extends [Include] ? Partial<Pick<Application<'config.mfManifest'>, 'config'>> : Pick<Application<'config.mfManifest'>, 'config'>);
}> & Included<InstallationInclude, 'activeConfig', Include, {
  activeConfig: InstallationActiveConfig | null;
}> & Included<InstallationInclude, 'access', Include, {
  access: InstallationAccess[];
}> & Included<InstallationInclude, 'interfaces', Include, {
  interfaces: ApplicationInterface[];
}>;
/**
 * Options for listing an organization's installations.
 *
 * @see https://www.sanity.io/docs/http-reference/applications-api
 * @public
 */
interface InstallationsOptions<Include extends InstallationInclude = InstallationInclude> {
  organizationId: string;
  include?: Include[];
  /** Page size (1-100, default 50), or `'none'` to disable pagination */
  limit?: number | 'none';
  /** Cursor from a previous response's `nextCursor` */
  cursor?: string;
}
/**
 * The cursor-paginated envelope returned by `GET /installations`.
 *
 * @see https://www.sanity.io/docs/http-reference/applications-api
 * @public
 */
interface InstallationsResponse<Include extends InstallationInclude = never> {
  nextCursor: string | null;
  data: Installation<Include>[];
}
/**
 * Fetcher for an organization's installations (`GET /installations`), on the
 * shared fetcher cache.
 *
 * @see https://www.sanity.io/docs/http-reference/applications-api
 * @internal
 */
declare const installations: Fetcher<[options: InstallationsOptions<InstallationInclude>], InstallationsResponse<InstallationInclude>>;
/**
 * Fetcher for a single installation (`GET /installations/:id`), on the shared
 * fetcher cache. No pre-seeding from {@link installations}: its list keys
 * include the organization, which this fetcher's params can't reconstruct.
 *
 * @see https://www.sanity.io/docs/http-reference/applications-api
 * @internal
 */
declare const installation: Fetcher<[installationId: string, options?: {
  include?: InstallationInclude[];
} | undefined], Installation<InstallationInclude>>;
/** @public */
interface OrganizationMember {
  sanityUserId: string;
  isCurrentUser: boolean;
  user: {
    id: string;
    displayName: string;
    familyName: string;
    givenName: string;
    middleName: string | null;
    imageUrl: string | null;
    email: string;
    loginProvider: string;
  };
  roles: Array<{
    name: string;
    title: string;
    description?: string;
  }>;
}
/**
 * The base fields returned from `/organizations/<id>` for every organization.
 * @public
 */
interface OrganizationBase {
  id: string;
  name: string;
  slug: string | null;
  createdAt: string;
  createdByUserId: string;
  updatedAt: string;
  deletedAt: string | null;
  dashboardStatus: 'enabled' | 'disabled';
  aiFeaturesStatus: 'enabled' | 'disabled';
  mediaLibraryStatus: 'enabled' | 'disabled';
  requestAccessStatus: 'allowed' | 'disabled';
  telemetryConsentStatus: 'allowed' | 'msa_denied' | 'customer_denied';
  oauthAppsStatus: 'allowed' | 'blocked';
  defaultRoleName: string;
  domains: string[] | null;
}
/** @public */
interface OrganizationOptions<IncludeMembers extends boolean = false, IncludeFeatures extends boolean = false> {
  includeMembers?: IncludeMembers;
  includeFeatures?: IncludeFeatures;
  organizationId: string;
}
/**
 * An `Organization` with `members` and/or `features` conditionally included
 * based on the query options used to fetch it.
 * @public
 */
type Organization<IncludeMembers extends boolean = false, IncludeFeatures extends boolean = false> = OrganizationBase & (boolean extends IncludeMembers ? {
  members?: OrganizationMember[];
} : IncludeMembers extends true ? {
  members: OrganizationMember[];
} : unknown) & (boolean extends IncludeFeatures ? {
  features?: string[];
} : IncludeFeatures extends true ? {
  features: string[];
} : unknown);
/**
 * Fetcher for a single organization (`GET /organizations/:id`), on the shared
 * fetcher cache. No pre-seeding from the organizations list: it returns a
 * subset of the detail fields, and a partial seed would serve as fresh for
 * the whole stale window.
 *
 * @internal
 */
declare const organization: Fetcher<[options?: OrganizationOptions<boolean, boolean> | undefined], Organization<boolean, boolean>>;
/**
 * Identifies a module federation expose and the manifest that serves it.
 * @public
 * @category Remote Modules
 */
interface RemoteModuleRef {
  readonly entry: string;
  readonly moduleId: string;
  readonly version: string;
}
/**
 * Application types that can receive configuration modules.
 *
 * The dashboard supplies this value over the message bus, so any string is accepted; known
 * types are listed for autocomplete. `& {}` keeps the literal from collapsing into `string`.
 * @public
 * @category Types
 * @category Message Bus
 */
type ApplicationConfigAppType = 'media-library' | (string & {});
/**
 * Identifies a configuration module for an application or application type.
 * @public
 * @category Types
 * @category Message Bus
 */
interface ApplicationConfig$1 extends RemoteModuleRef {
  readonly appId?: Application['id'];
  readonly appType: ApplicationConfigAppType;
}
/**
 * The capabilities a host can provide.
 *
 * Reuses the Studio's rendering-context identifiers so an application can hide its own
 * implementation of anything the host provides.
 * @public
 * @category Message Bus
 */
declare const capabilities: readonly ["globalUserMenu", "favorites", "history"];
/**
 * A capability a host can provide.
 * @public
 * @category Message Bus
 */
type Capability = (typeof capabilities)[number];
/**
 * The capabilities the host provides. A missing key means the host does not provide it.
 * @public
 * @category Message Bus
 */
type CapabilityRecord = Partial<Record<Capability, boolean>>;
/**
 * A document a user viewed, edited, created, or deleted in an application.
 * @public
 * @category Types
 * @category Message Bus
 */
interface DocumentActivity {
  readonly kind: 'document';
  readonly eventType: 'viewed' | 'edited' | 'created' | 'deleted';
  readonly document: {
    readonly id: string;
    readonly type: string;
    readonly resource: {
      readonly id: string;
      readonly type: 'dataset' | 'media-library' | 'canvas';
      /** Schema collection the document belongs to; the workspace name for studios. */
      readonly schemaName?: string;
    };
  };
}
/**
 * Activity an application reports to the host. Discriminated on `kind`.
 * @public
 * @category Types
 * @category Message Bus
 */
type ApplicationActivity = DocumentActivity;
/**
 * A document a user favorited, addressed like {@link DocumentActivity}'s document.
 * @public
 * @category Types
 * @category Message Bus
 */
type FavoriteDocument = DocumentActivity['document'];
/**
 * A label rendered for an application interface; `null` clears it.
 * @internal
 */
type ApplicationStatus = {
  label: string | null;
};
/**
 * Updates the status rendered for an application interface.
 * @internal
 */
type ApplicationStatusUpdate = {
  /** The application interface name. */
  name: string;
  /** The status to render. */
  value: ApplicationStatus;
};
/**
 * What an application is currently showing: the Comlink agent resource context, made generic.
 * @public
 * @category Types
 * @category Message Bus
 */
interface ApplicationContext {
  /** The resource the application is working in. Types follow `@sanity/client`'s resource config. */
  readonly resource: {
    readonly id: string;
    readonly type: 'dataset' | 'media-library' | 'canvas';
  };
  /** The open document, or `null` when none is open. */
  readonly document: {
    readonly id: string;
  } | null;
}
/**
 * An application served by a CLI dev server. The workbench publishes it in the same shape as a
 * deployed application; `local` marks it and names the dev server it is served from.
 * @public
 * @category Types
 * @category Message Bus
 */
type LocalApplication = Application<ApplicationInclude> & {
  readonly local: {
    readonly host: string;
    readonly port: number;
  };
};
/**
 * Declares a topic that stores and replays its current value.
 * @public
 * @category Message Bus
 */
type StateTopicDef<T> = {
  kind: 'state';
  value: T;
};
/**
 * Declares a topic that delivers events and an optional reply.
 * @public
 * @category Message Bus
 */
type EventTopicDef<P, R = never> = {
  kind: 'event';
  payload: P;
  reply?: R;
};
/**
 * Represents a successful topic value or a failed topic operation.
 * @public
 * @category Message Bus
 */
type TopicResult<T> = {
  ok: true;
  value: T;
} | {
  ok: false;
};
/**
 * Identifies a dashboard application and a route within it.
 * @public
 * @category Types
 * @category Message Bus
 */
type NavigationTarget = {
  /** The application ID, or `null` for dashboard-level routes. */
  appId: Application['id'] | null;
  /** The route path, including its query string and fragment. */
  path: string;
};
/**
 * Describes the current dashboard location and an active navigation.
 * @public
 * @category Types
 * @category Message Bus
 */
type NavigationLocation = NavigationTarget & {
  /** The active navigation, or `null` when navigation is idle. */
  transition: {
    /** Whether the navigation pushes or replaces browser history. */
    navigationType: 'push' | 'replace';
    /** The requested destination. */
    to: NavigationTarget;
  } | null;
};
/**
 * Declares the topics provided by the dashboard.
 * @public
 * @category Message Bus
 */
interface DashboardTopics {
  /**
   * Asks the dashboard to show its access request prompt for a resource the user can't access,
   * scoped like the Access API's `/access/{resourceType}/{resourceId}/requests`. Replies once the
   * prompt is shown. The prompt handles the Access API outcome (SSO enforcement, pending or
   * declined requests, request limits), so the reply doesn't report it.
   *
   * `ok: false` reasons:
   * - `unsupported`: the dashboard doesn't show access requests for the sending application
   * - `already-has-access`: the user already has access to the resource, so there is nothing to request
   */
  'access.request': EventTopicDef<{
    resourceType: Extract<AccessResourceType, 'organization' | 'project'>;
    resourceId: string;
  }, {
    ok: true;
  } | {
    ok: false;
    reason: 'unsupported' | 'already-has-access';
  }>;
  /** Reports user activity in an application, e.g. for the recents feed. Fire-and-forget. */
  'applications.activity': EventTopicDef<ApplicationActivity>;
  /**
   * The base path for an application.
   *
   * An unknown application returns `{ok: false}`.
   */
  'applications.base-path': StateTopicDef<TopicResult<string>>;
  /** The capabilities the host provides. A missing key means the host does not provide it. */
  'applications.capabilities': StateTopicDef<CapabilityRecord>;
  /** The available application configuration modules. */
  'applications.config': StateTopicDef<ApplicationConfig$1[] | null>;
  /** The foreground application's context, or `null` when it has published none. */
  'applications.context': StateTopicDef<(ApplicationContext & {
    readonly appId: Application['id'];
  }) | null>;
  /** Publishes the sending application's context. `null` clears it. Fire-and-forget. */
  'applications.context.update': EventTopicDef<ApplicationContext | null>;
  /** The foreground application ID, or `null` on dashboard-level routes. */
  'applications.foreground': StateTopicDef<Application['id'] | null>;
  /**
   * The dashboard applications and installations available to the current user. Each member
   * publishes its own raw serialised record, so the kinds are distinguished by shape: an
   * {@link Application} has a `type` of `'studio' | 'coreApp'`, a {@link LocalApplication} adds
   * `local`, and an {@link Installation} has no `type` and carries `applicationId` with a nested
   * `application` object.
   */
  'applications.list': StateTopicDef<TopicResult<(Application<ApplicationInclude> | LocalApplication | Installation<InstallationInclude>)[]> | null>;
  'applications.status.update': EventTopicDef<ApplicationStatusUpdate>;
  /**
   * The session token for the reading connection, or `null` while signed out. The host
   * writes it to each connection separately, so one application never sees another's token.
   */
  'auth.token': StateTopicDef<string | null>;
  /** Requests a dashboard session token. */
  'auth.token.refresh': EventTopicDef<void, string>;
  /** The signed-in user's favorited documents, published while the host provides `favorites`. */
  'favorites.documents': StateTopicDef<FavoriteDocument[]>;
  /**
   * Favorites or unfavorites a document. The host replies once `favorites.documents` reflects
   * the change, so a read after the reply sees it. A favorite is identified by its published
   * document ID, type, resource and `schemaName` (workspace).
   */
  'favorites.update': EventTopicDef<{
    document: FavoriteDocument;
    favorited: boolean;
  }, void>;
  /** The current dashboard location and active navigation. */
  'navigation.location': StateTopicDef<NavigationLocation | null>;
  /**
   * Requests navigation and replies when the location commits.
   *
   * `ok: false` reasons:
   * - `not-navigable`: the URL cannot be handled by a dashboard application
   * - `interrupted`: another navigation superseded the request
   * - `failed`: the router rejected or did not commit the request
   */
  'navigation.location.update': EventTopicDef<{
    url: string;
    history?: 'push' | 'replace';
  }, {
    ok: true;
  } | {
    ok: false;
    reason: 'not-navigable' | 'interrupted' | 'failed';
  }>;
  /** The current organization, or `null` without an active organization. */
  'organizations.current': StateTopicDef<Pick<OrganizationBase, 'id' | 'name' | 'slug'> | null>;
  /** The open panel, its application, display mode, and optional width in pixels. */
  'panels.mode': StateTopicDef<TopicResult<{
    appId: string;
    name: string;
    mode: 'aside';
    size?: number;
  } | {
    appId: string;
    name: string;
    mode: 'full';
  } | null> | null>;
  /** Opens, updates, resizes, or closes an application's panel. */
  'panels.mode.set': EventTopicDef<{
    name: string;
    mode: 'aside' | 'full';
  } | {
    name: string;
    size: number;
  } | null>;
  /** The resolved dashboard color scheme. */
  'preferences.color-scheme': StateTopicDef<'light' | 'dark'>;
  /** Whether the dashboard dock is pinned open. */
  'preferences.dock-locked': StateTopicDef<boolean>;
  /** The signed-in user, or `null` while signed out. */
  'users.current': StateTopicDef<CurrentUser | null>;
}
/**
 * Declares every topic available through the message bus.
 * @public
 * @category Message Bus
 */
interface Topics extends DashboardTopics {}
/**
 * Hides provisional topics from the public message bus methods.
 * @internal
 */
type MessageBusTopics = Omit<Topics, 'applications.status.update'>;
/**
 * Every declared topic name.
 * @public
 * @category Message Bus
 */
type TopicName<TTopics = Topics> = keyof TTopics;
type StateTopicsOf<T> = { [K in keyof T]: T[K] extends {
  kind: 'state';
} ? K : never; }[keyof T];
/**
 * Names of state topics exposed by message bus methods.
 * @public
 * @category Message Bus
 */
type StateTopic<TTopics = MessageBusTopics> = StateTopicsOf<TTopics>;
/**
 * Names of event topics exposed by message bus methods.
 * @public
 * @category Message Bus
 */
type EventTopic<TTopics = MessageBusTopics> = { [K in keyof TTopics]: TTopics[K] extends {
  kind: 'event';
} ? K : never; }[keyof TTopics];
/**
 * The value type of a state topic.
 * @public
 * @category Message Bus
 */
type ValueOf<K extends StateTopic<TTopics>, TTopics = Topics> = TTopics[K] extends StateTopicDef<infer T> ? T : never;
/**
 * The payload type of an event topic.
 * @public
 * @category Message Bus
 */
type PayloadOf<K extends EventTopic<TTopics>, TTopics = Topics> = TTopics[K] extends EventTopicDef<infer P, infer _R> ? P : never;
/**
 * The reply type of an event topic (`never` if it declares none).
 * @public
 * @category Message Bus
 */
type ReplyOf<K extends EventTopic<TTopics>, TTopics = Topics> = TTopics[K] extends EventTopicDef<infer _P, infer R> ? R : never;
/**
 * An error raised when a dashboard state topic reports failure.
 * @public
 * @category Message Bus
 */
declare class TopicError extends Error {
  /** The topic that failed. */
  readonly topic: StateTopic;
  /** Creates an error for a failed topic. */
  constructor(topic: StateTopic);
}
/**
 * The value of a state topic, with `TopicResult` wrappers unwrapped to their success value.
 * @public
 * @category Message Bus
 */
type TopicData<K extends StateTopic> = ValueOf<K> extends (infer Value) ? Value extends {
  ok: true;
  value: infer Success;
} ? Success : Value extends {
  ok: false;
} ? never : Value : never;
interface TopicEntry {
  /** Why the first-value query failed. Dropped with the entry when its last subscriber leaves. */
  error?: unknown;
  /** The in-flight first-value query, shared by every suspended render of the topic. */
  pending?: Promise<void>;
  subscribers: number;
}
interface DashboardTopicsState {
  topics: {
    [topic: string]: TopicEntry;
  };
}
/**
 * A state source for a dashboard state topic, with `TopicResult` wrappers unwrapped.
 *
 * @remarks
 * Returns `undefined` until the topic publishes; use {@link resolveTopic} to wait for that
 * first value. While the topic is still unpublished, reading throws the failure that
 * {@link resolveTopic} recorded. A published value takes precedence over a recorded failure,
 * and a {@link TopicError} is thrown when the topic itself reports failure. A thrown failure
 * ends the subscription, so a reader recovers by subscribing again.
 * @internal
 */
declare const getTopicState: BoundStoreAction<DashboardTopicsState, [topic: StateTopic], StateSource<unknown>>;
/**
 * Resolves once a dashboard state topic has published, or records the failure for
 * {@link getTopicState} to throw. Repeated calls for a pending topic share one query.
 *
 * @remarks
 * Holds a temporary subscriber while the query is in flight so a failure recorded after the
 * reading component has gone is dropped with it, rather than thrown at the next mount.
 * @internal
 */
declare const resolveTopic: BoundStoreAction<DashboardTopicsState, [topic: StateTopic], Promise<void>>;
/**
 * Returns the organization the dashboard has selected: the `organizations.current` topic on a
 * message bus, or the `_context` URL param in a Comlink dashboard.
 * @public
 */
declare function getDashboardOrganizationId(instance: SanityInstance): StateSource<string | undefined>;
/**
 * Fetcher for a project's datasets (`GET /datasets`), on the shared fetcher
 * cache.
 *
 * @internal
 */
declare const datasets: Fetcher<[options?: ProjectHandle<string> | undefined], DatasetsResponse>;
/**
 * Augments `groq` with the type surface of `groq@3.88.1-typegen-experimental.0`, the fork
 * this package depended on before GA `groq`.
 *
 * A `sanity.types.ts` from the experimental Typegen flow imports these helpers from
 * `groq` and augments these interfaces. GA `groq` exports only `defineQuery` and the
 * template tag, so those files stop typechecking without this one.
 *
 * `defineProjection` is absent: it is a runtime function, and declaring it in a
 * type-only augmentation turns a compile error into `undefined is not a function`.
 * `@sanity/sdk` exports it instead.
 *
 * Keep these declarations while the SDK supports existing experimental generated files.
 */
declare module 'groq' {
  /**
   * Brands a type with the resource it came from so one flat interface can hold entries
   * from more than one schema; {@link PickSchema} narrows it back out.
   */
  type SchemaOrigin<TBase, TSchemaId extends string> = TBase & {
    /**
     * @internal
     * @deprecated typescript helper only
     */
    __schemaId?: TSchemaId;
  };
  /**
   * Brands a projection result with the document type it was evaluated against;
   * {@link PickProjectionResult} narrows it back out.
   */
  type ProjectionBase<TBase, TProjectionBaseTypeName extends string> = TBase & {
    /**
     * @internal
     * @deprecated typescript helper only
     */
    __schemaTypeName?: TProjectionBaseTypeName;
  };
  /** Extracts the members of `T` that came from the schema `TSchemaId`. */
  type PickSchema<T, TSchemaId extends string = string> = Extract<T, SchemaOrigin<T, TSchemaId>>;
  /** Extracts the members of `T` projected from the document type `TProjectionBaseTypeName`. */
  type PickProjectionResult<T, TProjectionBaseTypeName extends string = string> = Extract<T, ProjectionBase<T, TProjectionBaseTypeName>>;
  /** Augmented by generated files: resource key to the union of that schema's types. */
  interface SanitySchemas {}
  /** Augmented by generated files: query string to its result type. */
  interface SanityQueries {}
  /** Augmented by generated files: projection string to its result type. */
  interface SanityProjections {}
  /**
   * Indexes an augmented interface, falling back to the union of every registered value
   * when the key is absent. Code generated against the fork relies on that fallback, so
   * narrowing it to `never` changes what existing apps infer.
   */
  type SafeAccess<T, K extends string> = K extends keyof T ? T[K] : T[keyof T];
  /** Fields Sanity adds to every document. */
  interface SanityDocumentShape {
    _id: string;
    _type: string;
    _createdAt: string;
    _updatedAt: string;
    _rev: string;
    [key: string]: unknown;
  }
  /** All types registered for one resource. */
  type SanitySchema<TSchemaId extends string = string> = PickSchema<SafeAccess<SanitySchemas, TSchemaId>, TSchemaId>;
  /** One schema type, selected by its `_type` and its resource. */
  type SanitySchemaType<TSchemaTypeName extends string = string, TSchemaId extends string = string> = Extract<SanitySchema<TSchemaId>, {
    _type: TSchemaTypeName;
  }>;
  /** One document type, selected by its `_type` and its resource. */
  type SanityDocument<TDocumentType extends string = string, TSchemaId extends string = string> = Extract<Extract<SanitySchema<TSchemaId>, SanityDocumentShape> | SanityDocumentShape, {
    _type: TDocumentType;
  }>;
  /** The result of a registered query, for one resource. */
  type SanityQueryResult<TQuery extends string = string, TSchemaId extends string = string> = Extract<SafeAccess<SanityQueries, TQuery>, SchemaOrigin<SafeAccess<SanityQueries, TQuery>, TSchemaId>>;
  /** The result of a registered projection, for one document type and one resource. */
  type SanityProjectionResult<TProjection extends string = string, TProjectionBaseTypeName extends string = string, TSchemaId extends string = string> = PickSchema<PickProjectionResult<SafeAccess<SanityProjections, TProjection>, TProjectionBaseTypeName>, TSchemaId>;
}
/**
 * Indexes `T` by `K`, or `never` when `K` is not a key of `T`.
 *
 * Deliberately exact. The legacy `groq` lookup falls back to the union of every registered
 * value on a miss, which lets a query resolve to another dataset's result type.
 */
type At<T, K> = K extends keyof T ? T[K] : never;
/**
 * Fields Sanity adds to every document. A resource's schema union also carries object types
 * such as `slug`, which lack these, so this separates documents from the rest.
 * No index signature is required, so both type aliases and interfaces are supported.
 */
interface DocumentFields {
  _id: string;
  _type: string;
  _createdAt: string;
  _updatedAt: string;
  _rev: string;
}
/**
 * Copies document fields into a type alias so interface registrations satisfy the
 * record constraints used by document actions without adding an index signature.
 */
type DocumentRecord<T> = { [K in keyof T]: T[K]; };
/**
 * A registered document as it is when it already satisfies those constraints, as the type
 * aliases Typegen generates do, so editors show the generated name, such as `Movie`. Only an
 * interface registration, which lacks the index signature, goes through {@link DocumentRecord}.
 */
type RegisteredDocument<T> = T extends {
  [key: string]: unknown;
} ? T : DocumentRecord<T>;
/**
 * The registered keys that a resource key known only as a pattern can stand for. A handle typed
 * without its project and dataset carries `${string}.${string}`, which matches every registered
 * key; `${string}.production` matches only production datasets; an unregistered literal key
 * matches none.
 */
type MatchingKeys<TRegistry, TSchemaId extends string> = Extract<keyof TRegistry, TSchemaId>;
/**
 * True when a lookup should use the legacy path instead of a union across registered resources:
 * when the resource key matches no registration, or when the key or the thing looked up (the
 * document type, query or projection) is only `string`. The SDK's own default generics produce
 * that unspecific form to mean any document or action, so it must not narrow to the app's
 * registered types.
 */
type UsesLegacyLookup<TSchemaId extends string, TRegistry, TLookup extends string> = string extends TSchemaId ? true : string extends TLookup ? true : [MatchingKeys<TRegistry, TSchemaId>] extends [never] ? true : false;
type DocumentIn<TSchemaId, TDocumentType extends string> = TSchemaId extends keyof SanitySchemasByResource ? RegisteredDocument<Extract<Extract<SanitySchemasByResource[TSchemaId], DocumentFields>, {
  _type: TDocumentType;
}>> : never;
type QueryIn<TSchemaId, TQuery extends string> = TSchemaId extends keyof SanityQueriesByResource ? At<SanityQueriesByResource[TSchemaId], TQuery> : never;
type ProjectionIn<TSchemaId, TDocumentType extends string, TProjection extends string> = TSchemaId extends keyof SanityProjectionsByResource ? Extract<ProjectionForDocumentType<SanityProjectionsByResource[TSchemaId], TDocumentType, TProjection>, object> : never;
/**
 * The saved experimental result for exactly this query text, or `never`. The legacy lookup
 * itself answers a missing query with the union of every saved result, which would add
 * unrelated results to a union across resources.
 */
type LegacyQueryIn<TSchemaId extends string, TQuery extends string> = TQuery extends keyof SanityQueries$1 ? SanityQueryResult<TQuery, TSchemaId> : never;
/** The saved experimental result for exactly this projection text, or `never`. */
type LegacyProjectionIn<TSchemaId extends string, TDocumentType extends string, TProjection extends string> = TProjection extends keyof SanityProjections$1 ? SanityProjectionResult<TProjection, TDocumentType, TSchemaId> : never;
/**
 * Resolves a document type for one resource.
 *
 * A resource registered in `SanitySchemasByResource` is answered from there and only there:
 * a document type absent from a registered resource is `never`, never the legacy union,
 * because an unrelated union looks precise while describing the wrong dataset.
 *
 * A key known only as a pattern, such as `${string}.${string}` from a `DocumentHandle<'post'>`
 * prop or a resource chosen at runtime, resolves to the union of the document type across the
 * registered resources it can match: the document is one of those. A key that matches no
 * registration, or a lookup whose document type is also only `string`, uses the experimental
 * Typegen declarations as before, which is what keeps saved generated files working.
 *
 * @beta
 */
type ResolveDocument<TDocumentType extends string = string, TSchemaId extends string = string> = TSchemaId extends keyof SanitySchemasByResource ? DocumentIn<TSchemaId, TDocumentType> : UsesLegacyLookup<TSchemaId, SanitySchemasByResource, TDocumentType> extends true ? SanityDocument$2<TDocumentType, TSchemaId> : DocumentIn<MatchingKeys<SanitySchemasByResource, TSchemaId>, TDocumentType> | SanityDocument$2<TDocumentType, TSchemaId>;
/**
 * Resolves a query result for one resource, selected by the exact query text.
 *
 * A key known only as a pattern gets the union of the query's result across the registered
 * resources it can match, plus the result saved by experimental Typegen for the same query
 * text, if any. See {@link ResolveDocument} for why a registered resource does not fall
 * through, and when the experimental Typegen declarations apply.
 *
 * @beta
 */
type ResolveQueryResult<TQuery extends string = string, TSchemaId extends string = string> = TSchemaId extends keyof SanityQueriesByResource ? QueryIn<TSchemaId, TQuery> : UsesLegacyLookup<TSchemaId, SanityQueriesByResource, TQuery> extends true ? SanityQueryResult<TQuery, TSchemaId> : QueryIn<MatchingKeys<SanityQueriesByResource, TSchemaId>, TQuery> | LegacyQueryIn<TSchemaId, TQuery>;
/**
 * Resolves a projection result for one resource and document type.
 *
 * A projection runs against the document its handle names, so the same projection text
 * resolves differently per document type as well as per resource. A resource key known only as
 * a pattern gets the union across the registered resources it can match, plus the result saved
 * by experimental Typegen for the same projection text, as in {@link ResolveDocument}.
 *
 * @beta
 */
type ResolveProjectionResult<TProjection extends string = string, TDocumentType extends string = string, TSchemaId extends string = string> = TSchemaId extends keyof SanityProjectionsByResource ? ProjectionIn<TSchemaId, TDocumentType, TProjection> : UsesLegacyLookup<TSchemaId, SanityProjectionsByResource, TProjection> extends true ? SanityProjectionResult<TProjection, TDocumentType, TSchemaId> : ProjectionIn<MatchingKeys<SanityProjectionsByResource, TSchemaId>, TDocumentType, TProjection> | LegacyProjectionIn<TSchemaId, TDocumentType, TProjection>;
/**
 * Looks up a projection under one document type. A handle whose document type is only known as
 * `string`, as with handles from a document list, gets the union of the projection's result
 * across every document type it was generated for.
 */
type ProjectionForDocumentType<TProjections, TDocumentType extends string, TProjection extends string> = string extends TDocumentType ? { [K in keyof TProjections]: At<TProjections[K], TProjection>; }[keyof TProjections] : At<At<TProjections, TDocumentType>, TProjection>;
/**
 * Represents an action to create a new document.
 * Specifies the document type and optionally a document ID (which will be treated as the published ID).
 * @beta
 */
interface CreateDocumentAction<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string> extends DocumentTypeHandle<TDocumentType, TDataset, TProjectId> {
  type: 'document.create';
  /**
   * Optional initial field values for the document.
   * These values will be set when the document is created.
   * System fields (_id, _type, _rev, _createdAt, _updatedAt) are omitted as they are set automatically.
   */
  initialValue?: Partial<Omit<ResolveDocument<TDocumentType, `${TProjectId}.${TDataset}`>, '_id' | '_type' | '_rev' | '_createdAt' | '_updatedAt'>>;
}
/**
 * Represents an action to delete an existing document.
 * Requires the full document handle including the document ID.
 * @beta
 */
interface DeleteDocumentAction<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string> extends DocumentHandle<TDocumentType, TDataset, TProjectId> {
  type: 'document.delete';
}
/**
 * Represents an action to edit an existing document using patches.
 * Requires the full document handle and an array of patch operations.
 * @beta
 */
interface EditDocumentAction<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string> extends DocumentHandle<TDocumentType, TDataset, TProjectId> {
  type: 'document.edit';
  patches?: PatchOperations[];
  /**
   * When `true`, the given `patches` are forwarded verbatim to the server and
   * applied as-is locally, instead of being re-derived by diffing document
   * snapshots. This preserves the operational intent of the patches (e.g.
   * keyed array inserts/unsets), which lets concurrent edits from other
   * clients interleave coherently instead of being overwritten by
   * position-based patches computed from a stale snapshot.
   *
   * Use this when the patches were produced by an editor that tracks its own
   * operations (e.g. a collaborative text editor). During a rebase onto a
   * changed remote document, preserved patches are re-applied operationally;
   * if a patch can no longer apply, the transaction is skipped and reported
   * as a `rebase-error` document event.
   */
  preserveOperations?: boolean;
}
/**
 * Represents an action to publish the draft version of a document.
 * Requires the full document handle.
 * @beta
 */
interface PublishDocumentAction<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string> extends DocumentHandle<TDocumentType, TDataset, TProjectId> {
  type: 'document.publish';
}
/**
 * Represents an action to unpublish a document, moving its published content to a draft.
 * Requires the full document handle.
 * @beta
 */
interface UnpublishDocumentAction<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string> extends DocumentHandle<TDocumentType, TDataset, TProjectId> {
  type: 'document.unpublish';
}
/**
 * Represents an action to discard the draft changes of a document.
 * Requires the full document handle.
 * @beta
 */
interface DiscardDocumentAction<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string> extends DocumentHandle<TDocumentType, TDataset, TProjectId> {
  type: 'document.discard';
}
/**
 * Union type representing all possible document actions within the SDK.
 * @beta
 */
type DocumentAction<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string> = CreateDocumentAction<TDocumentType, TDataset, TProjectId> | DeleteDocumentAction<TDocumentType, TDataset, TProjectId> | EditDocumentAction<TDocumentType, TDataset, TProjectId> | PublishDocumentAction<TDocumentType, TDataset, TProjectId> | UnpublishDocumentAction<TDocumentType, TDataset, TProjectId> | DiscardDocumentAction<TDocumentType, TDataset, TProjectId>;
/**
 * Union of every action accepted by `applyDocumentActions` — both document-
 * level actions and release-lifecycle actions.
 * @beta
 */
type Action<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string> = DocumentAction<TDocumentType, TDataset, TProjectId> | ReleaseAction;
/**
 * Creates a `CreateDocumentAction` object.
 * @param doc - A handle identifying the document type, dataset, and project. An optional `documentId` can be provided.
 * @param initialValue - Optional initial field values for the document. (System fields are omitted as they are set automatically.)
 * @returns A `CreateDocumentAction` object ready for dispatch.
 * @beta
 */
declare function createDocument<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string>(doc: DocumentTypeHandle<TDocumentType, TDataset, TProjectId>, initialValue?: Partial<Omit<ResolveDocument<TDocumentType, `${TProjectId}.${TDataset}`>, '_id' | '_type' | '_rev' | '_createdAt' | '_updatedAt'>>): CreateDocumentAction<TDocumentType, TDataset, TProjectId>;
/**
 * Creates a `DeleteDocumentAction` object.
 * @param doc - A handle uniquely identifying the document to be deleted.
 * @returns A `DeleteDocumentAction` object ready for dispatch.
 * @beta
 */
declare function deleteDocument<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string>(doc: DocumentHandle<TDocumentType, TDataset, TProjectId>): DeleteDocumentAction<TDocumentType, TDataset, TProjectId>;
/**
 * Options for creating an `EditDocumentAction`.
 * @beta
 */
interface EditDocumentOptions {
  /**
   * Forward the given patches verbatim instead of re-deriving them by
   * diffing document snapshots. See {@link EditDocumentAction.preserveOperations}.
   */
  preserveOperations?: boolean;
}
/**
 * Creates an `EditDocumentAction` object with patches for modifying a document.
 * Accepts patches in either the standard `PatchOperations` format or as a `SanityMutatePatchMutation` from `@sanity/mutate`.
 *
 * @param doc - A handle uniquely identifying the document to be edited.
 * @param sanityMutatePatch - A patch mutation object from `@sanity/mutate`.
 * @param options - Options controlling how the patches are processed.
 * @returns An `EditDocumentAction` object ready for dispatch.
 * @beta
 */
declare function editDocument<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string>(doc: DocumentHandle<TDocumentType, TDataset, TProjectId>, sanityMutatePatch: PatchMutation, options?: EditDocumentOptions): EditDocumentAction<TDocumentType, TDataset, TProjectId>;
/**
 * Creates an `EditDocumentAction` object with patches for modifying a document.
 *
 * @param doc - A handle uniquely identifying the document to be edited.
 * @param patches - A single patch operation or an array of patch operations.
 * @param options - Options controlling how the patches are processed.
 * @returns An `EditDocumentAction` object ready for dispatch.
 * @beta
 */
declare function editDocument<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string>(doc: DocumentHandle<TDocumentType, TDataset, TProjectId>, patches?: PatchOperations | PatchOperations[], options?: EditDocumentOptions): EditDocumentAction<TDocumentType, TDataset, TProjectId>;
/**
 * Creates a `PublishDocumentAction` object.
 * @param doc - A handle uniquely identifying the document to be published.
 * @returns A `PublishDocumentAction` object ready for dispatch.
 * @beta
 */
declare function publishDocument<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string>(doc: DocumentHandle<TDocumentType, TDataset, TProjectId>): PublishDocumentAction<TDocumentType, TDataset, TProjectId>;
/**
 * Creates an `UnpublishDocumentAction` object.
 * @param doc - A handle uniquely identifying the document to be unpublished.
 * @returns An `UnpublishDocumentAction` object ready for dispatch.
 * @beta
 */
declare function unpublishDocument<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string>(doc: DocumentHandle<TDocumentType, TDataset, TProjectId>): UnpublishDocumentAction<TDocumentType, TDataset, TProjectId>;
/**
 * Creates a `DiscardDocumentAction` object.
 * @param doc - A handle uniquely identifying the document whose draft changes are to be discarded.
 * @returns A `DiscardDocumentAction` object ready for dispatch.
 * @beta
 */
declare function discardDocument<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string>(doc: DocumentHandle<TDocumentType, TDataset, TProjectId>): DiscardDocumentAction<TDocumentType, TDataset, TProjectId>;
/**
 * Creates a new release. The `releaseId` must be unique within the current
 * retention period.
 * @beta
 */
interface CreateReleaseAction extends ReleaseHandle {
  type: 'release.create';
  metadata: ReleaseDocument['metadata'];
}
/**
 * Patches the metadata of an existing release.
 * @beta
 */
interface EditReleaseAction extends ReleaseHandle {
  type: 'release.edit';
  patch: PatchOperations;
}
/**
 * Publishes all version documents in a release.
 * @beta
 */
interface PublishReleaseAction extends ReleaseHandle {
  type: 'release.publish';
}
/**
 * Schedules a release to be published at the given UTC time. Locks the
 * version documents server-side until the release is unscheduled or published.
 * @beta
 */
interface ScheduleReleaseAction extends ReleaseHandle {
  type: 'release.schedule';
  publishAt: string;
}
/**
 * Unschedules a release that was previously scheduled, returning it to the
 * active editable state.
 * @beta
 */
interface UnscheduleReleaseAction extends ReleaseHandle {
  type: 'release.unschedule';
}
/**
 * Archives an active release. Version documents within the release are
 * removed and no longer queryable, though still recoverable through history
 * during the retention period.
 * @beta
 */
interface ArchiveReleaseAction extends ReleaseHandle {
  type: 'release.archive';
}
/**
 * Restores an archived release. Only possible during the retention period.
 * @beta
 */
interface UnarchiveReleaseAction extends ReleaseHandle {
  type: 'release.unarchive';
}
/**
 * Permanently deletes an archived or published release. To remove an active
 * release, use the archive action first.
 * @beta
 */
interface DeleteReleaseAction extends ReleaseHandle {
  type: 'release.delete';
}
/**
 * Union of all release actions that can be dispatched alongside document
 * actions through `applyDocumentActions`.
 * @beta
 */
type ReleaseAction = CreateReleaseAction | EditReleaseAction | PublishReleaseAction | ScheduleReleaseAction | UnscheduleReleaseAction | ArchiveReleaseAction | UnarchiveReleaseAction | DeleteReleaseAction;
/** @beta */
declare function createRelease(handle: ReleaseHandle, metadata?: ReleaseDocument['metadata']): CreateReleaseAction;
/** @beta */
declare function editRelease(handle: ReleaseHandle, patch: PatchOperations): EditReleaseAction;
/** @beta */
declare function publishRelease(handle: ReleaseHandle): PublishReleaseAction;
/** @beta */
declare function scheduleRelease(handle: ReleaseHandle, publishAt: string): ScheduleReleaseAction;
/** @beta */
declare function unscheduleRelease(handle: ReleaseHandle): UnscheduleReleaseAction;
/** @beta */
declare function archiveRelease(handle: ReleaseHandle): ArchiveReleaseAction;
/** @beta */
declare function unarchiveRelease(handle: ReleaseHandle): UnarchiveReleaseAction;
/** @beta */
declare function deleteRelease(handle: ReleaseHandle): DeleteReleaseAction;
/**
 * Split the entire path string on dots "outside" of any brackets.
 *
 * For example:
 * ```
 * "friends[0].name"
 * ```
 *
 * becomes:
 *
 * ```
 * [...ParseSegment<"friends[0]">, ...ParseSegment<"name">]
 * ```
 *
 * (We use a simple recursion that splits on the first dot.)
 */
type PathParts<TPath extends string> = TPath extends `${infer Head}.${infer Tail}` ? [Head, ...PathParts<Tail>] : TPath extends '' ? [] : [TPath];
/**
 * Given a type T and an array of "access keys" Parts, recursively index into T.
 *
 * If a part is a key, it looks up that property.
 * If T is an array and the part is a number, it "indexes" into the element type.
 */
type DeepGet<TValue, TPath extends readonly (string | number)[]> = TPath extends [] ? TValue : TPath extends readonly [infer THead, ...infer TTail] ? DeepGet<TValue extends undefined | null ? undefined : THead extends keyof TValue ? TValue[THead] : THead extends number ? TValue extends readonly (infer TElement)[] ? TElement | undefined : undefined : undefined // Key/index doesn't exist
, TTail extends readonly (string | number)[] ? TTail : []> : never;
/**
 * Given a document type TDocument and a JSON Match path string TPath,
 * compute the type found at that path.
 * @beta
 */
type JsonMatch<TDocument, TPath extends string> = DeepGet<TDocument, PathParts<TPath>>;
/**
 * Given an input object and a record of path expressions to values, this
 * function will set each match with the given value.
 *
 * ```js
 * const output = set(
 *   {name: {first: 'initial', last: 'initial'}},
 *   {'name.first': 'changed'}
 * );
 *
 * // { name: { first: 'changed', last: 'initial' } }
 * console.log(output);
 * ```
 */
declare function set<R>(input: unknown, pathExpressionValues: Record<string, unknown>): R;
/**
 * Given an input object and a record of path expressions to values, this
 * function will set each match with the given value **if the value at the current
 * path is missing** (i.e. `null` or `undefined`).
 *
 * ```js
 * const output = setIfMissing(
 *   {items: [null, 'initial']},
 *   {'items[:]': 'changed'}
 * );
 *
 * // { items: ['changed', 'initial'] }
 * console.log(output);
 * ```
 */
declare function setIfMissing<R>(input: unknown, pathExpressionValues: Record<string, unknown>): R;
/**
 * Given an input object and an array of path expressions, this function will
 * remove each match from the input object.
 *
 * ```js
 * const output = unset(
 *   {name: {first: 'one', last: 'two'}},
 *   ['name.last']
 * );
 *
 * // { name: { first: 'one' } }
 * console.log(output);
 * ```
 */
declare function unset<R>(input: unknown, pathExpressions: string[]): R;
/**
 * Given an input object, a path expression (inside the insert patch object), and an array of items,
 * this function will insert or replace the matched items.
 *
 * **Insert before:**
 *
 * ```js
 * const input = {some: {array: ['a', 'b', 'c']}}
 * const output = insert(
 *   input,
 *   {
 *     before: 'some.array[1]',
 *     items: ['!']
 *   }
 * );
 * // { some: { array: ['a', '!', 'b', 'c'] } }
 * console.log(output);
 * ```
 *
 * **Insert before with negative index (append):**
 *
 * ```js
 * const input = {some: {array: ['a', 'b', 'c']}}
 * const output = insert(
 *   input,
 *   {
 *     before: 'some.array[-1]',
 *     items: ['!']
 *   }
 * );
 * // { some: { array: ['a', 'b', 'c', '!'] } }
 * console.log(output);
 * ```
 *
 * **Insert after:**
 *
 * ```js
 * const input = {some: {array: ['a', 'b', 'c']}}
 * const output = insert(
 *   input,
 *   {
 *     after: 'some.array[1]',
 *     items: ['!']
 *   }
 * );
 * // { some: { array: ['a', 'b', '!', 'c'] } }
 * console.log(output);
 * ```
 *
 * **Replace:**
 *
 * ```js
 * const output = insert(
 *   { some: { array: ['a', 'b', 'c'] } },
 *   {
 *     replace: 'some.array[1]',
 *     items: ['!']
 *   }
 * );
 * // { some: { array: ['a', '!', 'c'] } }
 * console.log(output);
 * ```
 *
 * **Replace many:**
 *
 * ```js
 * const input = {some: {array: ['a', 'b', 'c', 'd']}}
 * const output = insert(
 *   input,
 *   {
 *     replace: 'some.array[1:3]',
 *     items: ['!', '?']
 *   }
 * );
 * // { some: { array: ['a', '!', '?', 'd'] } }
 * console.log(output);
 * ```
 */
declare function insert<R>(input: unknown, insertPatch: InsertPatch): R;
/**
 * Given an input object and a record of path expressions to numeric values,
 * this function will increment each match with the given value.
 *
 * ```js
 * const output = inc(
 *   {foo: {first: 3, second: 4.5}},
 *   {'foo.first': 3, 'foo.second': 4}
 * );
 *
 * // { foo: { first: 6, second: 8.5 } }
 * console.log(output);
 * ```
 */
declare function inc<R>(input: unknown, pathExpressionValues: Record<string, number>): R;
/**
 * Given an input object and a record of path expressions to numeric values,
 * this function will decrement each match with the given value.
 *
 * ```js
 * const output = dec(
 *   {foo: {first: 3, second: 4.5}},
 *   {'foo.first': 3, 'foo.second': 4}
 * );
 *
 * // { foo: { first: 0, second: 0.5 } }
 * console.log(output);
 * ```
 */
declare function dec<R>(input: unknown, pathExpressionValues: Record<string, number>): R;
/**
 * Given an input object and a record of paths to [diff match patches][0], this
 * function will apply the diff match patch for the string at each match.
 *
 * [0]: https://www.sanity.io/docs/http-patches#aTbJhlAJ
 *
 * ```js
 * const output = diffMatchPatch(
 *   {foo: 'the quick brown fox'},
 *   {'foo': '@@ -13,7 +13,7 @@\n own \n-fox\n+cat\n'}
 * );
 *
 * // { foo: 'the quick brown cat' }
 * console.log(output);
 * ```
 */
declare function diffMatchPatch<R>(input: unknown, pathExpressionValues: Record<string, string>): R;
/**
 * Simply checks if the given document input has a `_rev` that matches the given
 * `revisionId` and throws otherwise.
 *
 * (No code example provided.)
 */
declare function ifRevisionID<R>(input: unknown, revisionId: string): R;
/**
 * Maps document IDs to documents, using `null` for documents that do not exist.
 *
 * @beta
 */
type DocumentSet<TDocument extends SanityDocument$1 = SanityDocument$1> = { [TDocumentId in string]?: TDocument | null; };
/**
 * Exposes the patch operations used by {@link processMutations}.
 *
 * @remarks
 * Property order determines execution order in {@link processMutations}:
 * `ifRevisionID`, `set`, `setIfMissing`, `unset`, `inc`, `dec`, `insert`,
 * then `diffMatchPatch`. Reordering the properties changes mutation results.
 * Freezes the collection to prevent callers from replacing the functions
 * used by the SDK's mutation evaluator.
 *
 * @see https://www.sanity.io/docs/http-mutations#5b4db1396e56
 *
 * @example
 * ```ts
 * const document = {items: [{_key: 'a', title: 'Before'}]}
 * const updated = patchOperations.set<typeof document>(document, {
 *   'items[_key=="a"].title': 'After',
 * })
 * ```
 *
 * @internal
 */
declare const patchOperations: Readonly<{
  ifRevisionID: typeof ifRevisionID;
  set: typeof set;
  setIfMissing: typeof setIfMissing;
  unset: typeof unset;
  inc: typeof inc;
  dec: typeof dec;
  insert: typeof insert;
  diffMatchPatch: typeof diffMatchPatch;
}>;
/**
 * Configures {@link processMutations}.
 *
 * @internal
 */
interface ProcessMutationsOptions {
  /**
   * The transaction ID that will become the next `_rev` for documents mutated
   * by the given mutations.
   */
  transactionId: string;
  /**
   * The input document set that the mutations will be applied to.
   */
  documents: DocumentSet;
  /**
   * A list of mutations to apply to the given document set.
   */
  mutations: Mutation[];
  /**
   * Supplies the default `_createdAt` and `_updatedAt` timestamps.
   * Uses the current time when omitted or empty.
   */
  timestamp?: string;
}
/**
 * Applies mutations to an in-memory set of Sanity documents.
 * Deleted documents remain in the returned set with a value of `null`.
 *
 * Include every document affected by `mutations` in `documents`, using `null`
 * for documents that do not exist.
 *
 * Returns `documents` itself when `mutations` is empty. Otherwise, returns a
 * shallow copy of that object. The result can reuse document objects and
 * nested objects from `documents`. Mutating a reused object through the
 * result also changes the input.
 *
 * Sets `_rev` to `transactionId` on created, replaced, and patched documents.
 * Uses `timestamp` for timestamps unless the mutation preserves them.
 * Ignores `merge` patches; `inc` and `dec` skip values that are not numbers.
 * Generates document IDs when omitted or ending in `.`.
 * Patch operations can generate missing array keys.
 *
 * Does not persist documents or run Content Lake's server validation.
 *
 * @throws If a selection uses a query, a `create` targets an existing document,
 * or a `patch` targets a document that does not exist.
 * @throws If a patch operation fails, including a revision check failure or
 * `diffMatchPatch` applied to a value other than a string or `undefined`.
 *
 * @internal
 */
declare function processMutations({ documents, mutations, transactionId, timestamp }: ProcessMutationsOptions): DocumentSet;
type Grant = 'read' | 'update' | 'create' | 'history';
/** @beta */
interface PermissionDeniedReason {
  type: 'precondition' | 'access';
  message: string;
  documentId?: string;
}
/** @beta */
type DocumentPermissionsResult = {
  allowed: false;
  message: string;
  reasons: PermissionDeniedReason[];
} | {
  allowed: true;
  message?: undefined;
  reasons?: undefined;
};
interface SharedListener {
  events: Observable<ListenEvent<SanityDocument>>;
  dispose: () => void;
}
interface DocumentStoreState {
  documentStates: { [TDocumentId in string]?: DocumentState; };
  queued: QueuedTransaction[];
  applied: AppliedTransaction[];
  outgoing?: OutgoingTransaction;
  grants?: Record<Grant, ExprNode>;
  /**
   * The current user's identity (their user ID).
   */
  identity?: string;
  error?: unknown;
  sharedListener: SharedListener;
  fetchDocument: (documentId: string) => Observable<ResolveDocument | null>;
  events: Subject<DocumentEvent>;
}
interface DocumentState {
  id: string;
  error?: unknown;
  /**
   * the "remote" local copy that matches the server. represents the last known
   * server state. this gets updated every time we confirm remote patches
   */
  remote?: ResolveDocument | null;
  /**
   * the current ephemeral working copy that includes local optimistic changes
   * that have not yet been confirmed by the server
   */
  local?: ResolveDocument | null;
  /**
   * the revision that our remote document is at
   */
  remoteRev?: string | null;
  /**
   * Array of subscription IDs. This document state will be deleted if there are
   * no subscribers.
   */
  subscriptions: string[];
  /**
   * An object keyed by transaction ID of revisions sent out but that have not
   * yet been verified yet. When an applied transaction is transitioned to an
   * outgoing transaction, it also adds unverified revisions for each document
   * that is part of that outgoing transaction. Transactions are submitted to
   * the server with a locally generated transaction ID. This way we can observe
   * when our transaction comes back through the shared listener. Each listener
   * event that comes back contains a `previousRev`. If we see our own
   * transaction with a different `previousRev` than expected, we can rebase our
   * local transactions on top of this new remote.
   */
  unverifiedRevisions?: { [TTransactionId in string]?: UnverifiedDocumentRevision; };
  /**
   * transaction IDs recently submitted by this client for this document,
   * newest last. used to label `remote-patches` events with the correct
   * `origin` even after the corresponding `unverifiedRevisions` entry has
   * been pruned (e.g. by a sync event that raced the listener echo). capped
   * to the most recent entries.
   */
  recentOwnTransactionIds?: string[];
}
/**
 * @beta
 * Options for specifying a document and optionally a path within it.
 */
interface DocumentOptions<TPath extends string | undefined = undefined, TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string> extends DocumentHandle<TDocumentType, TDataset, TProjectId> {
  path?: TPath;
}
/** @beta */
declare function getDocumentState<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string>(instance: SanityInstance, options: DocumentOptions<undefined, TDocumentType, TDataset, TProjectId>): StateSource<ResolveDocument<TDocumentType, `${TProjectId}.${TDataset}`> | undefined | null>;
/** @beta */
declare function getDocumentState<TPath extends string = string, TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string>(instance: SanityInstance, options: DocumentOptions<TPath, TDocumentType, TDataset, TProjectId>): StateSource<JsonMatch<ResolveDocument<TDocumentType, `${TProjectId}.${TDataset}`>, TPath> | undefined>;
/** @beta */
declare function getDocumentState<TData>(instance: SanityInstance, options: DocumentOptions<string | undefined>): StateSource<TData | undefined | null>;
/** @beta */
declare function resolveDocument<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string>(instance: SanityInstance, docHandle: DocumentHandle<TDocumentType, TDataset, TProjectId>): Promise<ResolveDocument<TDocumentType, `${TProjectId}.${TDataset}`> | null>;
/** @beta */
declare function resolveDocument<TData extends ResolveDocument>(instance: SanityInstance, docHandle: DocumentHandle<string, string, string>): Promise<TData | null>;
/** @beta */
declare const getDocumentSyncStatus: BoundStoreAction<DocumentStoreState, [doc: DocumentHandle<string, string, string>], StateSource<boolean | undefined>>;
type PermissionsStateOptions = {
  resource?: DocumentResource;
  actions: DocumentAction[];
};
/** @beta */
declare const getPermissionsState: BoundStoreAction<DocumentStoreState, [PermissionsStateOptions], StateSource<DocumentPermissionsResult>>;
/** @beta */
declare const resolvePermissions: BoundStoreAction<DocumentStoreState, [options: PermissionsStateOptions], Promise<DocumentPermissionsResult>>;
/** @beta */
declare const subscribeDocumentEvents: BoundStoreAction<DocumentStoreState, [options: {
  resource?: DocumentResource;
  eventHandler: (e: DocumentEvent) => void;
}], () => void>;
type ActionMap = {
  create: 'sanity.action.document.version.create';
  discard: 'sanity.action.document.version.discard';
  unpublish: 'sanity.action.document.unpublish';
  delete: 'sanity.action.document.delete';
  edit: 'sanity.action.document.edit';
  publish: 'sanity.action.document.publish';
  releaseCreate: 'sanity.action.release.create';
  releaseEdit: 'sanity.action.release.edit';
  releasePublish: 'sanity.action.release.publish';
  releaseSchedule: 'sanity.action.release.schedule';
  releaseUnschedule: 'sanity.action.release.unschedule';
  releaseArchive: 'sanity.action.release.archive';
  releaseUnarchive: 'sanity.action.release.unarchive';
  releaseDelete: 'sanity.action.release.delete';
};
type OptimisticLock = {
  ifDraftRevisionId?: string;
  ifPublishedRevisionId?: string;
};
interface ReleaseMetadataPayload {
  title?: string;
  description?: string;
  intendedPublishAt?: string;
  releaseType?: 'asap' | 'scheduled' | 'undecided';
  cardinality?: 'one' | 'many';
}
type HttpAction = {
  actionType: ActionMap['create'];
  publishedId: string;
  attributes: SanityDocumentLike;
} | {
  actionType: ActionMap['discard'];
  versionId: string;
  purge?: boolean;
} | {
  actionType: ActionMap['unpublish'];
  draftId: string;
  publishedId: string;
} | {
  actionType: ActionMap['delete'];
  publishedId: string;
  includeDrafts?: string[];
} | {
  actionType: ActionMap['edit'];
  draftId: string;
  publishedId: string;
  patch: PatchOperations;
} | ({
  actionType: ActionMap['publish'];
  draftId: string;
  publishedId: string;
} & OptimisticLock) | {
  actionType: ActionMap['releaseCreate'];
  releaseId: string;
  metadata?: ReleaseMetadataPayload;
} | {
  actionType: ActionMap['releaseEdit'];
  releaseId: string;
  patch: PatchOperations;
} | {
  actionType: ActionMap['releasePublish'];
  releaseId: string;
} | {
  actionType: ActionMap['releaseSchedule'];
  releaseId: string;
  publishAt: string;
} | {
  actionType: ActionMap['releaseUnschedule'];
  releaseId: string;
} | {
  actionType: ActionMap['releaseArchive'];
  releaseId: string;
} | {
  actionType: ActionMap['releaseUnarchive'];
  releaseId: string;
} | {
  actionType: ActionMap['releaseDelete'];
  releaseId: string;
};
/**
 * Represents a transaction that is queued to be applied but has not yet been
 * applied. A transaction will remain in a queued state until all required
 * documents for the transactions are available locally.
 */
interface QueuedTransaction {
  /**
   * the ID of this transaction. this is generated client-side.
   */
  transactionId: string;
  /**
   * the high-level actions associated with this transaction. note that these
   * actions don't mention draft IDs and is meant to abstract away the draft
   * model from users.
   */
  actions: Action[];
  /**
   * An optional flag set to disable this transaction from being batched with
   * other transactions.
   */
  disableBatching?: boolean;
}
/**
 * Represents a transaction that has been applied locally but has not been
 * committed/transitioned-to-outgoing. These transactions are visible to the
 * user but may be rebased upon a new working document set. Applied transactions
 * also contain the resulting `outgoingActions` that will be submitted to
 * Content Lake. These `outgoingActions` depend on the state of the working
 * documents so they are recomputed on rebase and are only relevant to applied
 * actions (we cannot compute `outgoingActions` for queued transactions because
 * we haven't resolved the set of documents the actions are dependent on yet).
 *
 * In order to support better conflict resolution, the original `previous` set
 * is saved as the `base` set.
 */
interface AppliedTransaction extends QueuedTransaction {
  /**
   * the resulting set of documents after the actions have been applied
   */
  working: DocumentSet;
  /**
   * the previous set of documents before the action was applied
   */
  previous: DocumentSet;
  /**
   * the original `previous` document set captured when this action was
   * originally applied. this is used as a reference point to do a 3-way merge
   * if this applied transaction ever needs to be reapplied on a different
   * set of documents.
   */
  base: DocumentSet;
  /**
   * the `_rev`s from `previous` document set
   */
  previousRevs: { [TDocumentId in string]?: string; };
  /**
   * a timestamp for when this transaction was applied locally
   */
  timestamp: string;
  /**
   * the resulting HTTP actions derived from the state of the `working` document
   * set. these are sent to Content Lake as-is when this transaction is batched
   * and transitioned into an outgoing transaction.
   */
  outgoingActions: HttpAction[];
  /**
   * similar to `outgoingActions` but comprised of mutations instead of actions.
   * Useful for debugging, and is also used by liveEdit documents to send mutations,
   * since they can't use the Actions API which is pretty dependent on the draft model.
   */
  outgoingMutations: Mutation[];
}
/**
 * Represents a set of applied transactions batched into a single outgoing
 * transaction. An outgoing transaction is the result of batching many applied
 * actions. An outgoing transaction may be reverted locally if the server
 * does not accept it.
 */
interface OutgoingTransaction extends AppliedTransaction {
  disableBatching: boolean;
  batchedTransactionIds: string[];
}
interface UnverifiedDocumentRevision {
  transactionId: string;
  documentId: string;
  previousRev: string | undefined;
  timestamp: string;
}
/** @beta Response body from submitting an outgoing transaction (actions or mutations API). */
type DocumentTransactionSubmissionResult = Awaited<ReturnType<SanityClient['action']>> | MultipleMutationResult;
/** @beta */
type DocumentEvent = ActionErrorEvent | TransactionRevertedEvent | TransactionSubmissionFailedEvent | TransactionAcceptedEvent | DocumentRebaseErrorEvent | DocumentEditedEvent | DocumentCreatedEvent | DocumentDeletedEvent | DocumentPublishedEvent | DocumentUnpublishedEvent | DocumentDiscardedEvent | DocumentRemotePatchesEvent;
/**
 * @beta
 * Event emitted when a precondition to applying an action fails.
 * (For example: when trying to edit a document that no longer exists.)
 */
interface ActionErrorEvent {
  type: 'error';
  documentId: string;
  transactionId: string;
  message: string;
  error: unknown;
}
/**
 * @beta
 * Event emitted when a transaction is accepted.
 */
interface TransactionAcceptedEvent {
  type: 'accepted';
  outgoing: OutgoingTransaction;
  result: DocumentTransactionSubmissionResult;
}
/**
 * @beta
 * Event emitted when a transaction is reverted.
 */
interface TransactionRevertedEvent {
  type: 'reverted';
  message: string;
  error: unknown;
  outgoing: OutgoingTransaction;
}
/**
 * @beta
 * Event emitted when submitting a transaction fails with an error the store
 * retries: a network failure, a 5xx, 408 or 429 response, a 401 (for example
 * an expired session), or a 409 `transactionConflictError` (contention while
 * committing). The transaction and its local changes are kept
 * and submitted again, so the document stays out of sync until an attempt
 * succeeds. Emitted once per failed attempt; `attempt` starts at 1.
 */
interface TransactionSubmissionFailedEvent {
  type: 'submission-failed';
  message: string;
  error: unknown;
  outgoing: OutgoingTransaction;
  attempt: number;
}
/**
 * @beta
 * Event emitted when an attempt to apply local changes to a modified remote document fails.
 */
interface DocumentRebaseErrorEvent {
  type: 'rebase-error';
  documentId: string;
  transactionId: string;
  message: string;
  error: unknown;
}
/**
 * @beta
 * Event emitted when a document is edited.
 */
interface DocumentEditedEvent {
  type: 'edited';
  documentId: string;
  outgoing: OutgoingTransaction;
}
/**
 * @beta
 * Event emitted when a document is created.
 */
interface DocumentCreatedEvent {
  type: 'created';
  documentId: string;
  outgoing: OutgoingTransaction;
}
/**
 * @beta
 * Event emitted when a document is deleted.
 */
interface DocumentDeletedEvent {
  type: 'deleted';
  documentId: string;
  outgoing: OutgoingTransaction;
}
/**
 * @beta
 * Event emitted when a document is published.
 */
interface DocumentPublishedEvent {
  type: 'published';
  documentId: string;
  outgoing: OutgoingTransaction;
}
/**
 * @beta
 * Event emitted when a document is unpublished.
 */
interface DocumentUnpublishedEvent {
  type: 'unpublished';
  documentId: string;
  outgoing: OutgoingTransaction;
}
/**
 * @beta
 * Event emitted when a document version is discarded.
 */
interface DocumentDiscardedEvent {
  type: 'discarded';
  documentId: string;
  outgoing: OutgoingTransaction;
}
/**
 * @beta
 * Event emitted when patches for a document are observed through the listener.
 *
 * Unlike the whole-document snapshots the store keeps, these are the raw patch
 * operations from the transaction that produced the change, preserving the
 * operational intent of the edit (e.g. keyed array inserts/unsets). Consumers
 * that maintain their own local state, like collaborative text editors, can
 * apply these directly instead of diffing document snapshots.
 *
 * `origin` is `'local'` when the transaction was submitted by this document
 * store instance (an own edit observed back through the listener) and
 * `'remote'` when it came from another client.
 */
interface DocumentRemotePatchesEvent {
  type: 'remote-patches';
  /** The ID of the document version the patches apply to (e.g. a draft ID). */
  documentId: string;
  /** The transaction ID that carried these patches. */
  transactionId: string;
  /** The revision the document was at before this transaction. */
  previousRev?: string;
  /** The timestamp of the transaction. */
  timestamp: string;
  /** The patch operations, rooted at the document. */
  patches: PatchOperations[];
  /** Whether the transaction originated from this client or another one. */
  origin: 'local' | 'remote';
}
/** @beta */
interface ActionsResult<TDocument extends ResolveDocument = ResolveDocument> {
  transactionId: string;
  documents: DocumentSet<TDocument>;
  previous: DocumentSet<TDocument>;
  previousRevs: {
    [documentId: string]: string | undefined;
  };
  appeared: string[];
  updated: string[];
  disappeared: string[];
  submitted: () => Promise<DocumentTransactionSubmissionResult>;
}
/** @beta */
interface ApplyDocumentActionsOptions {
  /**
   * List of actions to apply. Accepts both document actions and release
   * lifecycle actions because they share the same transaction pipeline.
   */
  actions: Action[];
  /**
   * The resource to which the documents being acted on belong.
   */
  resource?: DocumentResource;
  /**
   * Optionally provide an ID to be used as this transaction ID
   */
  transactionId?: string;
  /**
   * Set this to true to prevent this action from being batched with others.
   */
  disableBatching?: boolean;
}
/** @beta */
declare function applyDocumentActions<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string>(instance: SanityInstance, options: ApplyDocumentActionsOptions): Promise<ActionsResult<ResolveDocument<TDocumentType, `${TProjectId}.${TDataset}`>>>;
/** @beta */
declare function applyDocumentActions(instance: SanityInstance, options: ApplyDocumentActionsOptions): Promise<ActionsResult>;
/**
 * Returns the full release document ID for the given release name.
 * e.g. `getReleaseDocumentId('my-release') === '_.releases.my-release'`
 * @beta
 */
declare function getReleaseDocumentId(releaseId: string): string;
/**
 * @public
 */
interface FavoriteStatusResponse {
  isFavorited: boolean;
}
/**
 * @public
 */
interface FavoriteDocumentContext extends DocumentHandle {
  resourceId: string;
  resourceType: StudioResource['type'] | MediaResource['type'] | CanvasResource['type'];
  schemaName?: string;
}
/**
 * Fetcher for a document's favorite status, read from the dashboard over
 * comlink, on the shared fetcher cache.
 *
 * @internal
 */
declare const favorites: Fetcher<[context: FavoriteDocumentContext], FavoriteStatusResponse>;
/**
 * Input for {@link setFavorite}: the document context plus the desired state.
 *
 * @public
 */
type SetFavoriteInput = FavoriteDocumentContext & {
  /** The favorite state to move to: `true` to favorite, `false` to unfavorite. */
  isFavorited: boolean;
};
/**
 * Sets a document's favorite state over comlink. Writes the new state into the
 * cached {@link favorites} status before the request (rolled back on failure),
 * then invalidates it so active readers reconverge on server truth. The
 * write-side counterpart to {@link favorites}.
 *
 * @internal
 */
declare const setFavorite: (instance: SanityInstance, input: SetFavoriteInput) => Promise<MutationResult<FavoriteStatusResponse>>;
/**
 * The list shape returned from `/organizations`, with `members` and/or
 * `features` conditionally included based on the query options used.
 * @public
 */
type Organizations<IncludeMembers extends boolean = false, IncludeFeatures extends boolean = false> = (Pick<OrganizationBase, 'id' | 'name' | 'slug' | 'createdAt' | 'updatedAt' | 'defaultRoleName' | 'dashboardStatus' | 'aiFeaturesStatus'> & (boolean extends IncludeMembers ? {
  members?: OrganizationMember[];
} : IncludeMembers extends true ? {
  members: OrganizationMember[];
} : unknown) & (boolean extends IncludeFeatures ? {
  features?: string[];
} : IncludeFeatures extends true ? {
  features: string[];
} : unknown))[];
/** @public */
interface OrganizationsOptions<IncludeMembers extends boolean = false, IncludeFeatures extends boolean = false> extends Omit<OrganizationOptions<IncludeMembers, IncludeFeatures>, 'organizationId'> {
  /**
   * When `true`, includes organisations the user has access to via
   * project-level grants, not just direct organisation memberships.
   */
  includeImplicitMemberships?: boolean;
}
/**
 * Fetcher for the current user's organizations (`GET /organizations`), on the
 * shared fetcher cache.
 *
 * @internal
 */
declare const organizations: Fetcher<[options?: OrganizationsOptions<boolean, boolean> | undefined], Organizations<boolean, boolean>>;
/**
 * @public
 */
interface SanityUser {
  sanityUserId: string;
  profile: UserProfile;
  memberships: Membership[];
}
/**
 * @public
 */
interface Membership {
  addedAt?: string;
  resourceType: string;
  resourceId: string;
  roleNames: Array<string>;
  lastSeenAt?: string | null;
}
/**
 * @public
 */
interface UserProfile {
  id: string;
  displayName: string;
  email: string;
  familyName?: string;
  givenName?: string;
  middleName?: string | null;
  imageUrl?: string;
  provider: string;
  tosAcceptedAt?: string;
  createdAt: string;
  updatedAt?: string;
  isCurrentUser?: boolean;
  providerId?: string;
}
/**
 * @public
 */
interface GetUsersOptions extends ProjectHandle {
  resourceType?: 'organization' | 'project';
  batchSize?: number;
  organizationId?: string;
  userId?: string;
}
/**
 * @public
 */
interface UsersGroupState {
  subscriptions: string[];
  totalCount?: number;
  nextCursor?: string | null;
  lastLoadMoreRequest?: string;
  users?: SanityUser[];
  error?: unknown;
}
/**
 * @public
 */
interface SanityUserResponse {
  data: SanityUser[];
  totalCount: number;
  nextCursor: string | null;
}
/**
 * @public
 */
interface UsersStoreState {
  users: { [TUsersKey in string]?: UsersGroupState; };
  error?: unknown;
}
/**
 * @public
 */
interface ResolveUsersOptions extends GetUsersOptions {
  signal?: AbortSignal;
}
/**
 * @public
 */
interface GetUserOptions extends ProjectHandle {
  userId: string;
  resourceType?: 'organization' | 'project';
  organizationId?: string;
}
/**
 * @public
 */
interface ResolveUserOptions extends GetUserOptions {
  signal?: AbortSignal;
}
/**
 * One end of a text selection: a Portable Text path plus a character offset
 * within the span it addresses.
 * @public
 */
interface PresenceSelectionPoint {
  path: Path;
  offset: number;
}
/**
 * A Portable Text caret or selected range, as exchanged with the Studio.
 *
 * Structurally identical to `EditorSelection` from `@portabletext/editor`, and
 * declared separately so that `@sanity/sdk` stays free of React dependencies. A
 * value from the editor can be passed straight through, and vice versa.
 *
 * `offset` is a character offset within the span that `path` addresses.
 * @public
 */
type PresenceSelection = {
  anchor: PresenceSelectionPoint;
  focus: PresenceSelectionPoint;
  backward?: boolean;
} | null;
/**
 * Somewhere a participant is, as it arrives over the wire.
 *
 * Prefer {@link DocumentPresence} from `getDocumentPresence`, which is scoped to one
 * document, flattened for rendering, and types `path` accurately.
 * @public
 */
interface PresenceLocation {
  type: 'document';
  /**
   * The specific document the participant is in, so a draft, published, or version
   * id rather than a bare document id.
   */
  documentId: string;
  /**
   * The focused field path, empty when they are in the document but not a field.
   *
   * Declared as `string[]`, but segments can also be numbers or `{_key: string}`
   * objects when the focus is inside an array or a Portable Text field, because
   * that is what other clients send. Guard for those rather than assuming strings.
   * Widening the declared type is a breaking change, so it waits for the next major;
   * {@link DocumentPresence.path} is typed correctly today.
   */
  path: string[];
  /**
   * When the participant said they were last active, on *their* clock.
   *
   * Fine for display, unreliable for deciding whether someone is still here: it is
   * subject to clock skew between machines. Presence already drops participants that
   * stop announcing, so a session appearing here is one the SDK still considers
   * live.
   */
  lastActiveAt: string;
  /** A Portable Text caret, when the focused field is a Portable Text field. */
  selection?: PresenceSelection;
}
/**
 * Which specific document a presence id resolves to.
 *
 * Presence compares exact document ids, so a client in a draft and a client in the
 * published document are in different places even for the same `documentId`. Pass
 * the perspective you are editing under and the SDK resolves it; the React hooks
 * take it from `ResourceProvider` when you do not pass one.
 * @public
 */
interface PresencePerspectiveOptions extends PerspectiveHandle {
  /** Live-edit documents have no draft, so presence resolves to the published id. */
  liveEdit?: boolean;
}
/**
 * What an app reports about where the current user is.
 *
 * Omit `path` for document-level presence, or pass one for field-level presence.
 * @public
 */
interface ReportPresenceOptions extends PresencePerspectiveOptions {
  /**
   * The document the user is in.
   *
   * Pass the plain document id; the perspective decides which specific document that
   * resolves to. An already-specific id is accepted and re-resolved, so passing
   * `drafts.abc` while the perspective is `published` reports the published document.
   */
  documentId: string;
  /**
   * The focused field path. Supports keyed and numeric segments, so array items
   * and Portable Text spans can be addressed.
   */
  path?: Path;
  /** A Portable Text caret, when the focused field is a Portable Text field. */
  selection?: PresenceSelection;
}
/**
 * One participant's session and everywhere it currently is.
 *
 * Keyed by session, not by user: the same person in two tabs is two entries with
 * the same `user`.
 * @public
 */
interface UserPresence {
  user: SanityUser;
  locations: PresenceLocation[];
  /** Identifies one tab. Stable while that tab is open, and not reused. */
  sessionId: string;
}
/**
 * One participant at one location within a single document, flattened so it can
 * be rendered directly against a field.
 *
 * Unlike {@link PresenceLocation.path}, `path` here is typed as a full `Path`, so
 * keyed and numeric segments are described rather than cast away.
 * @beta
 */
interface DocumentPresence {
  user: SanityUser;
  /** Identifies one tab, so the same person in two tabs appears twice. */
  sessionId: string;
  /**
   * The specific document id this participant is in: a draft, published, or
   * version id, depending on which perspective they are editing.
   */
  documentId: string;
  /** The focused field path. Empty when they are in the document but no field. */
  path: Path;
  /**
   * When they said they were last active, on *their* clock. Fine for display,
   * unreliable for liveness. See {@link PresenceLocation.lastActiveAt}.
   */
  lastActiveAt: string;
  /** The Portable Text caret, when they are focused in a Portable Text field. */
  selection?: PresenceSelection;
}
/** @beta */
interface DocumentPresenceOptions extends PresencePerspectiveOptions {
  /**
   * The document to look at. Resolved through the perspective exactly as
   * {@link ReportPresenceOptions.documentId} is, so reads match writes.
   */
  documentId: string;
  /**
   * Narrows to participants at or below this field path. Omit it for everyone in
   * the document.
   */
  path?: Path;
  /**
   * By default a draft, its published version, and any release versions are
   * treated as the same document, which is what document lists want. Set this to
   * compare ids exactly, which is what field-level indicators want so that a
   * draft and a release version do not bleed into each other.
   */
  excludeVersions?: boolean;
}
/** @public */
type TransportEvent = RollCallEvent | StateEvent | DisconnectEvent;
/** @public */
interface RollCallEvent {
  type: 'rollCall';
  userId: string;
  sessionId: string;
}
/** @public */
interface StateEvent {
  type: 'state';
  userId: string;
  sessionId: string;
  timestamp: string;
  locations: PresenceLocation[];
}
/** @public */
interface DisconnectEvent {
  type: 'disconnect';
  userId: string;
  sessionId: string;
  timestamp: string;
}
/** @beta */
declare function getPresence(instance: SanityInstance, params?: {
  resource?: DocumentResource;
}): StateSource<UserPresence[]>;
/**
 * Presence within a single document, flattened to one entry per participant per
 * location so it can be rendered directly against a field.
 *
 * Reading presence never announces anything. Use `reportPresence` to make the
 * current user visible to others.
 *
 * @param instance - the Sanity instance
 * @param params - the document to look at, its perspective, an optional `path` to
 *   narrow to a field subtree, and `excludeVersions` to compare document ids exactly
 *
 * @beta
 */
declare function getDocumentPresence(instance: SanityInstance, params: {
  resource?: DocumentResource;
} & DocumentPresenceOptions): StateSource<DocumentPresence[]>;
/**
 * Announces where the current user is, so other clients in the same project and
 * dataset can show them. Reading presence never announces anything, so this is
 * the only way an app becomes visible to others.
 *
 * Call it again whenever the user moves. Announcements are collapsed over a short
 * window and then repeated every 30 seconds while idle, which is what tells peers
 * the session is still alive.
 *
 * Announcements only go out while the presence connection is open, which is
 * while something subscribes to `getPresence` or `getDocumentPresence`. Keep a
 * subscription for as long as the user should appear present.
 *
 * Which specific document each location resolves to depends on its perspective, and
 * that matters for interoperability: other clients, the Studio included, compare
 * exact document ids for field-level presence. Pass the perspective you are editing
 * under rather than building a draft or version id yourself.
 *
 * @param instance - the Sanity instance
 * @param params - the resource to announce on, plus the locations to report.
 *   Pass one location with a `documentId` for document-level presence, add a
 *   `path` for field-level presence, and pass an empty array to appear present
 *   without being in any document.
 *
 * @beta
 */
declare function reportPresence(instance: SanityInstance, params: {
  resource?: DocumentResource;
  locations: ReportPresenceOptions[];
}): void;
/**
 * @public
 * The result of a projection query
 */
interface ProjectionValuePending<TValue extends object> {
  data: TValue | null;
  isPending: boolean;
}
interface DocumentStatus {
  lastEditedDraftAt?: string;
  lastEditedPublishedAt?: string;
  lastEditedVersionAt?: string;
}
/**
 *
 * @internal
 */
interface PreviewQueryResult {
  _id: string;
  _type: string;
  _updatedAt: string;
  titleCandidates: Record<string, unknown>;
  subtitleCandidates: Record<string, unknown>;
  media?: PreviewMedia | null;
  _status?: DocumentStatus;
}
/**
 * Represents a media asset in a preview.
 *
 * @public
 */
interface PreviewMedia {
  type: 'image-asset';
  _ref: string;
  url: string;
}
/**
 * Represents the set of values displayed as a preview for a given Sanity document.
 * This includes a primary title, a secondary subtitle, an optional piece of media associated
 * with the document, and the document's status.
 *
 * @public
 */
interface PreviewValue {
  /**
   * The primary text displayed for the document preview.
   */
  title: string;
  /**
   * A secondary line of text providing additional context about the document.
   */
  subtitle?: string;
  /**
   * An optional piece of media representing the document within its preview.
   * Currently, only image assets are available.
   */
  media?: PreviewMedia | null;
  /**
   * The status of the document.
   */
  _status?: {
    /** The date of the last published edit */
    lastEditedPublishedAt?: string;
    /** The date of the last draft edit */
    lastEditedDraftAt?: string;
  };
}
/** @public */
interface ProjectMemberRole {
  name: string;
  title: string;
  description: string;
}
/** @public */
interface ProjectMember {
  id: string;
  createdAt: string;
  updatedAt: string;
  isCurrentUser: boolean;
  isRobot: boolean;
  roles: ProjectMemberRole[];
}
/** @public */
interface ProjectMetadata {
  color?: string;
  externalStudioHost?: string;
  initialTemplate?: string;
  cliInitializedAt?: string;
  integration: 'manage' | 'cli';
}
/**
 * The base fields returned from `/projects` for every project.
 * @public
 */
interface ProjectBase {
  id: string;
  displayName: string;
  studioHost: string | null;
  organizationId: string;
  metadata: ProjectMetadata;
  isBlocked: boolean;
  isDisabled: boolean;
  isDisabledByUser: boolean;
  activityFeedEnabled: boolean;
  createdAt: string;
  updatedAt: string;
}
/**
 * A `Project` with `members` and/or `features` conditionally included
 * based on the query options used to fetch it.
 * @public
 */
type Project<IncludeMembers extends boolean = true, IncludeFeatures extends boolean = true> = ProjectBase & (boolean extends IncludeMembers ? {
  members?: ProjectMember[];
} : IncludeMembers extends true ? {
  members: ProjectMember[];
} : unknown) & (boolean extends IncludeFeatures ? {
  features?: string[];
} : IncludeFeatures extends true ? {
  features: string[];
} : unknown);
/** @public */
interface ProjectOptions<IncludeMembers extends boolean = true, IncludeFeatures extends boolean = true> extends ProjectHandle {
  includeMembers?: IncludeMembers;
  includeFeatures?: IncludeFeatures;
}
/**
 * Fetcher for a single project (`GET /projects/:id`), on the shared fetcher
 * cache. Pre-seeds from the default {@link projects} list entry when it can
 * satisfy the read — the default list carries features but not members, so
 * only `includeMembers: false` reads seed.
 *
 * @internal
 */
declare const project: Fetcher<[options?: ProjectOptions<boolean, boolean> | undefined], Project<boolean, boolean>>;
interface ProjectionOptions<TProjection extends string = string, TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string> extends DocumentHandle<TDocumentType, TDataset, TProjectId> {
  projection: TProjection;
}
/**
 * @beta
 */
declare function getProjectionState<TProjection extends string = string, TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string>(instance: SanityInstance, options: ProjectionOptions<TProjection, TDocumentType, TDataset, TProjectId>): StateSource<ProjectionValuePending<ResolveProjectionResult<TProjection, TDocumentType, `${TProjectId}.${TDataset}`>> | undefined>;
/**
 * @beta
 */
declare function getProjectionState<TData extends object>(instance: SanityInstance, options: ProjectionOptions): StateSource<ProjectionValuePending<TData> | undefined>;
/**
 * @beta
 */
declare function getProjectionState(instance: SanityInstance, options: ProjectionOptions): StateSource<ProjectionValuePending<Record<string, unknown>> | undefined>;
/** @beta */
declare function resolveProjection<TProjection extends string = string, TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string>(instance: SanityInstance, options: ProjectionOptions<TProjection, TDocumentType, TDataset, TProjectId>): Promise<ProjectionValuePending<ResolveProjectionResult<TProjection, TDocumentType, `${TProjectId}.${TDataset}`>>>;
/** @beta */
declare function resolveProjection<TData extends object>(instance: SanityInstance, options: ProjectionOptions): Promise<ProjectionValuePending<TData>>;
/** @public */
interface ProjectsOptions<IncludeMembers extends boolean = false, IncludeFeatures extends boolean = true> {
  organizationId?: string;
  includeMembers?: IncludeMembers;
  includeFeatures?: IncludeFeatures;
  onlyExplicitMembership?: boolean;
}
/**
 * Fetcher for the current user's projects (`GET /projects`), on the shared
 * fetcher cache.
 *
 * @internal
 */
declare const projects: Fetcher<[options?: ProjectsOptions<boolean, boolean> | undefined], Project<boolean, boolean>[]>;
/**
 * @beta
 */
interface QueryOptions<TQuery extends string = string, TDataset extends string = string, TProjectId extends string = string> extends Pick<ResponseQueryOptions, 'useCdn' | 'cache' | 'next' | 'cacheMode' | 'tag'>, DatasetHandle<TDataset, TProjectId> {
  query: TQuery;
  params?: Record<string, unknown>;
}
/**
 * @beta
 */
interface ResolveQueryOptions<TQuery extends string = string, TDataset extends string = string, TProjectId extends string = string> extends QueryOptions<TQuery, TDataset, TProjectId> {
  signal?: AbortSignal;
}
/** @internal */
declare const getQueryKey: (instance: SanityInstance, options: QueryOptions) => string;
/** @internal */
declare const parseQueryKey: (key: string) => QueryOptions;
/**
 * Returns the state source for a query.
 *
 * This function returns a state source that represents the current result of a GROQ query.
 * Subscribing to the state source will instruct the SDK to fetch the query (if not already fetched)
 * and will keep the query live using the Live content API (considering sync tags) to provide up-to-date results.
 * When the last subscriber is removed, the query state is automatically cleaned up from the store.
 *
 * Note: This functionality is for advanced users who want to build their own framework integrations.
 * Our SDK also provides a React integration (useQuery hook) for convenient usage.
 *
 * Note: Automatic cleanup can interfere with React Suspense because if a component suspends while being the only subscriber,
 * cleanup might occur unexpectedly. In such cases, consider using `resolveQuery` instead.
 *
 * @beta
 */
declare function getQueryState<TQuery extends string = string, TDataset extends string = string, TProjectId extends string = string>(instance: SanityInstance, queryOptions: QueryOptions<TQuery, TDataset, TProjectId>): StateSource<ResolveQueryResult<TQuery, `${TProjectId}.${TDataset}`> | undefined>;
/** @beta */
declare function getQueryState<TData>(instance: SanityInstance, queryOptions: QueryOptions): StateSource<TData | undefined>;
/** @beta */
declare function getQueryState(instance: SanityInstance, queryOptions: QueryOptions): StateSource<unknown>;
/**
 * Resolves the result of a query without registering a lasting subscriber.
 *
 * This function fetches the result of a GROQ query and returns a promise that resolves with the query result.
 * It registers a temporary subscriber for the lifetime of the resolution (released shortly after the promise
 * settles), so the query state participates in normal cleanup even when no lasting subscriber ever attaches —
 * e.g. when a suspended component errors before committing. This makes it ideal for use with React Suspense,
 * where the returned promise is thrown to delay rendering until the query result becomes available.
 * Once the promise resolves, it is expected that a real subscriber will be added via `getQueryState` to manage ongoing updates.
 *
 * Additionally, an optional AbortSignal can be provided to cancel the query and immediately clear the associated state
 * if there are no other active subscribers.
 *
 * @beta
 */
declare function resolveQuery<TQuery extends string = string, TDataset extends string = string, TProjectId extends string = string>(instance: SanityInstance, queryOptions: ResolveQueryOptions<TQuery, TDataset, TProjectId>): Promise<ResolveQueryResult<TQuery, `${TProjectId}.${TDataset}`>>;
/** @beta */
declare function resolveQuery<TData>(instance: SanityInstance, queryOptions: ResolveQueryOptions): Promise<TData>;
/**
 * Lifecycle states a release document can be in. Mirrors the server's
 * `ReleaseState`.
 * @beta
 */
type ReleaseState = 'active' | 'archiving' | 'unarchiving' | 'archived' | 'published' | 'publishing' | 'scheduled' | 'scheduling';
interface ReleasesStoreState {
  activeReleases?: ReleaseDocument[];
  allReleases?: ReleaseDocument[];
  error?: unknown;
}
/**
 * Get the active releases from the store.
 * @internal
 */
declare const getActiveReleasesState: (instance: SanityInstance, options?: {
  resource?: DocumentResource;
}) => StateSource<ReleaseDocument[] | undefined>;
/**
 * Get every release in the store, including archived and published.
 * @internal
 */
declare const getAllReleasesState: (instance: SanityInstance, options?: {
  resource?: DocumentResource;
}) => StateSource<ReleaseDocument[] | undefined>;
declare const _getPerspectiveStateSelector: StoreAction<ReleasesStoreState, [_?: (PerspectiveHandle & {
  projectId?: string;
  dataset?: string;
  resource?: DocumentResource;
}) | undefined], StateSource<string[] | "previewDrafts" | "published" | "drafts" | "raw" | undefined>, unknown>;
type OmitFirst<T extends unknown[]> = T extends [unknown, ...infer R] ? R : never;
type SelectorParams = OmitFirst<Parameters<typeof _getPerspectiveStateSelector>>;
type BoundGetPerspectiveState = BoundStoreAction<ReleasesStoreState, SelectorParams, ReturnType<typeof _getPerspectiveStateSelector>>;
/**
 * Provides a subscribable state source for a "perspective" for the Sanity client,
 * which is used to fetch documents as though certain Content Releases are active.
 *
 * @param instance - The Sanity instance to get the perspective for
 * @param options - The options for the perspective -- usually a release name
 *
 * @returns A subscribable perspective value, usually a list of applicable release names,
 * or a single release name / default perspective (such as 'drafts').
 *
 * @public
 */
declare const getPerspectiveState: BoundGetPerspectiveState;
/**
 * Marks a projection for Typegen and returns the projection string unchanged, with its literal
 * type. `useDocumentProjection` matches that literal against the generated projection types.
 *
 * Pass the document type first so Typegen evaluates the projection for that type only. A
 * projection passed alone is evaluated for every document type in the schema, which generates
 * a result type for each.
 *
 * @example
 * ```ts
 * const preview = defineProjection('book', '{title, "author": author->name}')
 * ```
 *
 * @beta
 */
declare function defineProjection<const TProjection extends string>(documentType: string, projection: TProjection): TProjection;
/**
 * Marks a projection for Typegen and returns it unchanged. Typegen evaluates a projection
 * passed alone for every document type in the schema; pass the document type first to limit it
 * to one.
 *
 * @beta
 */
declare function defineProjection<const TProjection extends string>(projection: TProjection): TProjection;
/**
 * Returns the state source for users associated with a specific resource.
 *
 * This function returns a state source that represents the current list of users for a given
 * resource. Subscribing to the state source will instruct the SDK to fetch the users (if not
 * already fetched) and will load more from this state source as well. When the last subscriber is
 * removed, the users state is automatically cleaned up from the store after a delay.
 *
 * Note: This functionality is for advanced users who want to build their own framework
 * integrations. Our SDK also provides a React integration for convenient usage.
 *
 * @beta
 */
declare const getUsersState: BoundStoreAction<UsersStoreState, [options?: GetUsersOptions | undefined], StateSource<{
  data: SanityUser[];
  totalCount: number;
  hasMore: boolean;
} | undefined>>;
/**
 * Resolves the users for a specific resource without registering a lasting subscriber.
 *
 * This function fetches the users for a given resource and returns a promise that resolves with
 * the users result. Unlike `getUsersState`, which registers subscribers to keep the data live and
 * performs automatic cleanup, `resolveUsers` does not track subscribers. This makes it ideal for
 * use with React Suspense, where the returned promise is thrown to delay rendering until the users
 * result becomes available. Once the promise resolves, it is expected that a real subscriber will
 * be added via `getUsersState` to manage ongoing updates.
 *
 * Additionally, an optional AbortSignal can be provided to cancel the request and immediately
 * clear the associated state if there are no active subscribers.
 *
 * @beta
 */
declare const resolveUsers: BoundStoreAction<UsersStoreState, [ResolveUsersOptions], Promise<{
  data: SanityUser[];
  totalCount: number;
  hasMore: boolean;
}>>;
/**
 * Loads more users for a specific resource.
 *
 * This function triggers a request to fetch the next page of users for a given resource. It
 * requires that users have already been loaded for the resource (via `resolveUsers` or
 * `getUsersState`), and that there are more users available to load (as indicated by the `hasMore`
 * property).
 *
 * The function returns a promise that resolves when the next page of users has been loaded.
 *
 * @beta
 */
declare const loadMoreUsers: BoundStoreAction<UsersStoreState, [options?: GetUsersOptions | undefined], Promise<{
  data: SanityUser[];
  totalCount: number;
  hasMore: boolean;
}>>;
/**
 * @beta
 */
declare const getUserState: BoundStoreAction<UsersStoreState, [GetUserOptions], Observable<SanityUser | undefined>>;
/**
 * @beta
 */
declare const resolveUser: BoundStoreAction<UsersStoreState, [ResolveUserOptions], Promise<SanityUser>>;
/**
 * @public
 * Extracts the project ID from a CorsOriginError message.
 * @param error - The error to extract the project ID from.
 * @returns The project ID or null if the error is not a CorsOriginError.
 */
declare function getCorsErrorProjectId(error: Error): string | null;
/**
 * Returns true when the given error looks like a dynamic-import or
 * code-split chunk-loading failure.
 *
 * These errors typically surface when a user has a tab open against a
 * previously-deployed version of an app and the JavaScript or CSS chunk
 * filenames have since changed: a fresh deployment removes the hashed assets
 * the open tab still references. Detecting them lets the SDK trigger an
 * automatic reload so the user gets the new build without manual intervention.
 *
 * Recognized shapes (webpack ChunkLoadError, Vite "Failed to fetch
 * dynamically imported module", Firefox "error loading dynamically imported
 * module", Safari "Importing a module script failed", and Vite "Unable to
 * preload CSS").
 *
 * @param error - The value to inspect. Anything that is not an Error
 *   instance returns false.
 * @returns True if the error matches a known import/chunk-load failure.
 *
 * @public
 */
declare function isImportError(error: unknown): boolean;
/**
 * This version is provided by pkg-utils at build time
 * @internal
 */
declare const CORE_SDK_VERSION: {};
/**
 * @public
 */
type SanityProject$1 = SanityProject;
/**
 * Related data the Applications API can embed in a response. `interfaces`,
 * `workspaces` and `access` are children of the active deployment and are
 * embedded under {@link Application.activeDeployment}; `config.studio` and
 * `config.mfManifest` are embedded under {@link Application.config}.
 *
 * @see https://www.sanity.io/docs/http-reference/applications-api
 * @public
 */
type ApplicationInclude = 'interfaces' | 'workspaces' | 'access' | 'config.studio' | 'config.mfManifest' | 'activeDeployment';
type ApplicationInterfaceBase = {
  id: string;
  name: string;
  title: string;
  version: string;
  /** Module federation module ID; resolved from the host mf-manifest at runtime */
  moduleId: string;
};
/**
 * Placement metadata for application and panel interfaces.
 *
 * @see https://www.sanity.io/docs/http-reference/applications-api
 * @public
 */
type ApplicationInterfacePlacementMetadata = {
  dock?: {
    group?: string;
    order?: number;
  };
};
/**
 * An interface exposed by a deployment, embedded when `interfaces` is included.
 *
 * @see https://www.sanity.io/docs/http-reference/applications-api
 * @public
 */
type ApplicationInterface = ApplicationInterfaceBase & ({
  type: 'app';
  metadata: ApplicationInterfacePlacementMetadata | null;
} | {
  type: 'panel';
  metadata: ApplicationInterfacePlacementMetadata | null;
} | {
  type: 'asset_source';
  metadata: null;
} | {
  type: 'worker';
  metadata: null;
} | {
  type: 'tile';
  metadata: {
    order?: number;
    size: 'small' | 'large' | 'banner';
  };
});
/**
 * A studio workspace of a deployment, embedded when `workspaces` is included.
 * Studio applications only.
 *
 * @see https://www.sanity.io/docs/http-reference/applications-api
 * @public
 */
interface ApplicationWorkspace {
  id: string;
  name: string;
  title: string | null;
  subtitle: string | null;
  projectId: string;
  dataset: string;
  schemaDescriptorId: string | null;
  basePath: string | null;
  /** Sanitized SVG icon markup */
  icon: string | null;
}
/**
 * A resource an application accesses, embedded when `access` is included.
 *
 * @see https://www.sanity.io/docs/http-reference/applications-api
 * @public
 */
interface ApplicationAccess {
  id: string;
  resourceType: 'datasets' | 'canvases' | 'dashboards' | 'media-libraries';
  resourceId: string;
}
/**
 * Studio configuration, embedded under `config` when `config.studio` is included.
 *
 * @see https://www.sanity.io/docs/http-reference/applications-api
 * @public
 */
interface ApplicationStudioConfig {
  projectId: string;
  /** Release channel (`next`, `stable`, `latest`) or a pinned semver; null if unset */
  autoUpdatingVersion: string | null;
}
/**
 * The active deployment as embedded under {@link Application.activeDeployment}.
 * Its `interfaces`, `workspaces` and `access` children are each present only
 * when the matching {@link ApplicationInclude} token was requested. `workspaces`
 * is omitted (not `null`) for non-studio applications even when requested.
 *
 * @see https://www.sanity.io/docs/http-reference/applications-api
 * @public
 */
type ApplicationDeployment<Include extends ApplicationInclude = never> = {
  id: string;
  applicationId: string;
  size: number | null;
  version: string | null;
  isAutoUpdating: boolean | null;
  isActiveDeployment: boolean;
  deployedBy: string | null;
  createdAt: string;
  updatedAt: string;
} & Included<ApplicationInclude, 'interfaces', Include, {
  interfaces: ApplicationInterface[];
}> & Included<ApplicationInclude, 'workspaces', Include, {
  workspaces?: ApplicationWorkspace[];
}> & Included<ApplicationInclude, 'access', Include, {
  access: ApplicationAccess[];
}>;
/**
 * The always-present fields of an org-owned application returned by the
 * Applications API (`/applications`), before any {@link ApplicationInclude}.
 *
 * @see https://www.sanity.io/docs/http-reference/applications-api
 * @public
 */
interface ApplicationBase {
  id: string;
  type: 'studio' | 'coreApp';
  title: string;
  /** Stable, immutable identity, distinct from the mutable `slug` address. */
  name: string;
  /** Qualified, globally-unique handle: `sanity/<name>` for singletons, `<organizationId>/<name>` otherwise. */
  reference: string;
  icon: string | null;
  isSingleton: boolean;
  visibility: 'default' | 'unlisted' | 'disabled';
  slug: string | null;
  externalUrl: string | null;
  organizationId: string;
  createdAt: string;
  updatedAt: string;
}
type DeploymentToken = 'activeDeployment' | 'interfaces' | 'workspaces' | 'access';
type ConfigToken = 'config.studio' | 'config.mfManifest';
type ApplicationConfig<Include extends ApplicationInclude> = Included<ApplicationInclude, 'config.studio', Include, {
  studio?: ApplicationStudioConfig;
}> & Included<ApplicationInclude, 'config.mfManifest', Include, {
  mfManifest?: unknown;
}>;
type ApplicationConfigShape<Include extends ApplicationInclude> = [ApplicationInclude] extends [Include] ? {
  config?: ApplicationConfig<Include>;
} : IncludesAny<Include, ConfigToken> extends true ? {
  config: ApplicationConfig<Include>;
} : unknown;
type ApplicationDeploymentShape<Include extends ApplicationInclude> = [ApplicationInclude] extends [Include] ? {
  activeDeployment?: ApplicationDeployment<Include> | null;
} : IncludesAny<Include, DeploymentToken> extends true ? {
  activeDeployment: ApplicationDeployment<Include> | null;
} : unknown;
/**
 * An org-owned application as returned by the Applications API
 * (`/applications`). `config` and `activeDeployment` (with its
 * `interfaces`/`workspaces`/`access` children) are present only when the
 * corresponding {@link ApplicationInclude} tokens were requested.
 *
 * @see https://www.sanity.io/docs/http-reference/applications-api
 * @public
 */
type Application<Include extends ApplicationInclude = never> = ApplicationBase & ApplicationConfigShape<Include> & ApplicationDeploymentShape<Include>;
/**
 * Options for listing an organization's applications.
 *
 * @see https://www.sanity.io/docs/http-reference/applications-api
 * @public
 */
interface ApplicationsOptions<Include extends ApplicationInclude = ApplicationInclude> {
  organizationId: string;
  /** Filter by application type */
  type?: string;
  include?: Include[];
  /** Page size (1-100, default 50), or `'none'` to disable pagination */
  limit?: number | 'none';
  /** Cursor from a previous response's `nextCursor` */
  cursor?: string;
}
/**
 * The cursor-paginated envelope returned by `GET /applications`.
 *
 * @see https://www.sanity.io/docs/http-reference/applications-api
 * @public
 */
interface ApplicationsResponse<Include extends ApplicationInclude = never> {
  nextCursor: string | null;
  data: Application<Include>[];
}
/**
 * Fetcher for an organization's applications (`GET /applications`), on the
 * shared fetcher cache.
 *
 * @see https://www.sanity.io/docs/http-reference/applications-api
 * @internal
 */
declare const applications: Fetcher<[options: ApplicationsOptions<ApplicationInclude>], ApplicationsResponse<ApplicationInclude>>;
/**
 * Fetcher for a single application (`GET /applications/:id`), on the shared
 * fetcher cache. No pre-seeding from {@link applications}: its list keys
 * include the organization, which this fetcher's params can't reconstruct.
 *
 * @see https://www.sanity.io/docs/http-reference/applications-api
 * @internal
 */
declare const application: Fetcher<[applicationId: string, options?: {
  include?: ApplicationInclude[];
} | undefined], Application<ApplicationInclude>>;
/**
 * Confirmation returned by the API's soft-delete endpoints.
 *
 * @see https://www.sanity.io/docs/http-reference/applications-api
 * @internal
 */
interface DeletedResult {
  deleted: boolean;
}
/**
 * Dashboard visibility for an application.
 *
 * @see https://www.sanity.io/docs/http-reference/applications-api
 * @internal
 */
type ApplicationVisibility = ApplicationBase['visibility'];
/**
 * Mutable properties of an application (`PATCH /applications/:id`) — the
 * writable subset of {@link ApplicationBase}, each optional, keyed by id.
 *
 * @see https://www.sanity.io/docs/http-reference/applications-api
 * @internal
 */
type UpdateApplicationInput = {
  applicationId: string;
} & Partial<Pick<ApplicationBase, 'title' | 'icon' | 'visibility'>>;
/**
 * Mutation to update an application (`PATCH /applications/:id`). Invalidates the
 * updated application and the list so active entries reconverge on server truth.
 *
 * @see https://www.sanity.io/docs/http-reference/applications-api
 * @internal
 */
declare const updateApplication: (instance: SanityInstance, input: UpdateApplicationInput) => Promise<MutationResult<ApplicationBase>>;
/**
 * Input for {@link deleteApplication}.
 *
 * @internal
 */
interface DeleteApplicationInput {
  applicationId: string;
}
/**
 * Mutation to soft-delete an application (`DELETE /applications/:id`).
 * Invalidates the deleted application and the list.
 *
 * @see https://www.sanity.io/docs/http-reference/applications-api
 * @internal
 */
declare const deleteApplication: (instance: SanityInstance, input: DeleteApplicationInput) => Promise<MutationResult<DeletedResult>>;
export { Project as $, LoggedOutAuthState as $i, ResolveProjectionResult as $n, Logger as $r, DocumentPublishedEvent as $t, stringifyPath$1 as A, CommentTextSelectionItem as Ai, EditReleaseAction as An, TopicResult as Ar, SanityUser as At, getPerspectiveState as B, getOAuthTokensState as Bi, createRelease as Bn, InstallationAccess as Br, SetFavoriteInput as Bt, SanityDocument$3 as C, updateComment as Ci, CreateReleaseAction as Cn, NavigationTarget as Cr, TransportEvent as Ct, joinPaths as D, CommentReaction as Di, DocumentAction as Dn, StateTopic as Dr, Membership as Dt, getPathDepth as E, CommentMessage as Ei, DiscardDocumentAction as En, ReplyOf as Er, GetUsersOptions as Et, getUsersState as F, getClientState as Fi, UnarchiveReleaseAction as Fn, OrganizationBase as Fr, Organizations as Ft, getQueryKey as G, logout as Gi, editRelease as Gn, InstallationsResponse as Gr, ApplyDocumentActionsOptions as Gt, getActiveReleasesState as H, refreshOAuthTokens as Hi, deleteRelease as Hn, InstallationBase as Hr, setFavorite as Ht, loadMoreUsers as I, ProjectAccessErrorDetails as Ii, UnpublishDocumentAction as In, OrganizationMember as Ir, OrganizationsOptions as It, resolveQuery as J, OrgVerificationResult as Ji, scheduleRelease as Jn, configureLogging as Jr, DocumentCreatedEvent as Jt, getQueryState as K, handleAuthCallback as Ki, publishDocument as Kn, installation as Kr, applyDocumentActions as Kt, resolveUser as L, getProjectAccessErrorDetails as Li, UnscheduleReleaseAction as Ln, OrganizationOptions as Lr, organizations as Lt, isImportError as M, ClientOptions as Mi, PublishReleaseAction as Mn, ValueOf as Mr, UserProfile as Mt, getCorsErrorProjectId as N, ClientStoreState as Ni, ReleaseAction as Nn, capabilities as Nr, UsersGroupState as Nt, jsonMatch$1 as O, CommentStatus as Oi, EditDocumentAction as On, StateTopicDef as Or, ResolveUserOptions as Ot, getUserState as P, getClient as Pi, ScheduleReleaseAction as Pn, Organization as Pr, UsersStoreState as Pt, getProjectionState as Q, LoggedInAuthState as Qi, ResolveDocument as Qn, LogNamespace as Qr, DocumentEvent as Qt, resolveUsers as R, getProjectAccessErrorProjectId as Ri, archiveRelease as Rn, organization as Rr, FavoriteDocumentContext as Rt, Role as S, setCommentStatus as Si, CreateDocumentAction as Sn, NavigationLocation as Sr, StateEvent as St, getIndexForKey$1 as T, CommentLocalState as Ti, DeleteReleaseAction as Tn, RemoteModuleRef as Tr, GetUserOptions as Tt, getAllReleasesState as U, revokeOAuthTokens as Ui, discardDocument as Un, InstallationInclude as Ur, getReleaseDocumentId as Ut, ReleaseState as V, handleOAuthCallback as Vi, deleteDocument as Vn, InstallationActiveConfig as Vr, favorites as Vt, QueryOptions as W, startOAuthAuthorization as Wi, editDocument as Wn, InstallationsOptions as Wr, ActionsResult as Wt, projects as X, AuthStoreState as Xi, unpublishDocument as Xn, LogContext as Xr, DocumentDiscardedEvent as Xt, ProjectsOptions as Y, AuthState as Yi, unarchiveRelease as Yn, InstanceContext as Yr, DocumentDeletedEvent as Yt, resolveProjection as Z, ErrorAuthState as Zi, unscheduleRelease as Zn, LogLevel as Zr, DocumentEditedEvent as Zt, applications as _, MutationResult as _a, SetCommentStatusOptions as _i, patchOperations as _n, EventTopic as _r, PresencePerspectiveOptions as _t, ApplicationInclude as a, getTokenState as aa, createProjectHandle as ai, TransactionSubmissionFailedEvent as an, getTopicState as ar, project as at, CurrentUser$1 as b, removeComment as bi, Action as bn, LocalApplication as br, ReportPresenceOptions as bt, ApplicationStudioConfig as c, AuthStateType as ca, getCommentThreadsState as ci, getDocumentSyncStatus as cn, ApplicationConfig$1 as cr, PreviewValue as ct, ApplicationsOptions as d, CacheTag as da, parseCommentsOptionsKey as di, resolvePermissions as dn, ApplicationStatus as dr, getPresence as dt, LoggingInAuthState as ea, LoggerConfig as ei, DocumentRemotePatchesEvent as en, ResolveQueryResult as er, ProjectBase as et, ApplicationsResponse as f, CacheWriter as fa, resolveCommentThreads as fi, subscribeDocumentEvents as fn, ApplicationStatusUpdate as fr, reportPresence as ft, application as g, MutationDefinition as ga, ReplyToCommentOptions as gi, ProcessMutationsOptions as gn, DocumentActivity as gr, PresenceLocation as gt, UpdateApplicationInput as h, FetcherSnapshot as ha, RemoveCommentOptions as hi, DocumentSet as hn, DashboardTopics as hr, DocumentPresenceOptions as ht, ApplicationDeployment as i, getLoginUrlState as ia, createDocumentTypeHandle as ii, TransactionRevertedEvent as in, getDashboardOrganizationId as ir, ProjectOptions as it, CORE_SDK_VERSION as j, CommentThread as ji, PublishDocumentAction as jn, Topics as jr, SanityUserResponse as jt, slicePath$1 as k, CommentTextSelection as ki, EditDocumentOptions as kn, TopicName as kr, ResolveUsersOptions as kt, ApplicationVisibility as l, AccessResourceType as la, getCommentsOptionsKey as li, getPermissionsState as ln, ApplicationConfigAppType as lr, ProjectionValuePending as lt, DeletedResult as m, FetcherDefinition as ma, CreateCommentOptions as mi, PermissionDeniedReason as mn, CapabilityRecord as mr, DocumentPresence as mt, ApplicationAccess as n, getCurrentUserState as na, createDatasetHandle as ni, DocumentUnpublishedEvent as nn, TopicData as nr, ProjectMemberRole as nt, ApplicationInterface as o, setAuthToken as oa, CommentsOptions as oi, DocumentOptions as on, resolveTopic as or, PreviewMedia as ot, DeleteApplicationInput as p, Fetcher as pa, resolveComments as pi, DocumentPermissionsResult as pn, Capability as pr, DisconnectEvent as pt, parseQueryKey as q, observeOrganizationVerificationState as qi, publishRelease as qn, installations as qr, ActionErrorEvent as qt, ApplicationBase as r, getIsInDashboardState as ra, createDocumentHandle as ri, TransactionAcceptedEvent as rn, TopicError as rr, ProjectMetadata as rt, ApplicationInterfacePlacementMetadata as s, OAuthTokens as sa, ResolveCommentsOptions as si, getDocumentState as sn, ApplicationActivity as sr, PreviewQueryResult as st, Application as t, getAuthState as ta, createLogger as ti, DocumentTransactionSubmissionResult as tn, datasets as tr, ProjectMember as tt, ApplicationWorkspace as u, checkPermissions as ua, getCommentsState as ui, resolveDocument as un, ApplicationContext as ur, getDocumentPresence as ut, deleteApplication as v, defineFetcher as va, UpdateCommentOptions as vi, processMutations as vn, EventTopicDef as vr, PresenceSelection as vt, SanityProject$1 as w, Comment as wi, DeleteDocumentAction as wn, PayloadOf as wr, UserPresence as wt, ReleaseDocument$1 as x, replyToComment as xi, ArchiveReleaseAction as xn, MessageBusTopics as xr, RollCallEvent as xt, updateApplication as y, defineMutation as ya, createComment as yi, JsonMatch as yn, FavoriteDocument as yr, PresenceSelectionPoint as yt, defineProjection as z, getSignInMethodLabel as zi, createDocument as zn, Installation as zr, FavoriteStatusResponse as zt };
//# sourceMappingURL=applications-DowvM7CN.d.ts.map