import * as _sanity_client12 from "@sanity/client"; import { ClientConfig, ClientError, ClientPerspective, ListenEvent, ResponseQueryOptions, SanityClient, SanityDocument as SanityDocument$1, SanityProject as SanityProject$1, StackablePerspective } from "@sanity/client"; import { Observable, Subject } from "rxjs"; import { CurrentUser, CurrentUser as CurrentUser$1, Mutation, PatchOperations, Role, SanityDocument, SanityDocument as SanityDocument$2, SanityDocumentLike } from "@sanity/types"; import * as _sanity_comlink3 from "@sanity/comlink"; import { ChannelInput, ChannelInstance, Controller, Message, Node, NodeInput, Status } from "@sanity/comlink"; import { PatchMutation } from "@sanity/mutate/_unstable_store"; import { SanityDocument as SanityDocument$3, SanityProjectionResult, SanityQueryResult } from "groq"; import { ExprNode } from "groq-js"; import { CanvasResource, MediaResource, StudioResource } from "@sanity/message-protocol"; import { getIndexForKey, getPathDepth, joinPaths, jsonMatch, slicePath, stringifyPath } from "@sanity/json-match"; /** * Configuration for an authentication provider * @public */ interface AuthProvider { /** * Unique identifier for the auth provider (e.g., 'google', 'github') */ name: string; /** * Display name for the auth provider in the UI */ title: string; /** * Complete authentication URL including callback and token parameters */ url: string; /** * Optional URL for direct sign-up flow */ signUpUrl?: string; } /** * Configuration options for creating an auth store. * * @public */ interface AuthConfig { /** * The initial location href to use when handling auth callbacks. * Defaults to the current window location if available. */ initialLocationHref?: string; /** * Factory function to create a SanityClient instance. * Defaults to the standard Sanity client factory if not provided. */ clientFactory?: (config: ClientConfig) => SanityClient; /** * Custom authentication providers to use instead of or in addition to the default ones. * Can be an array of providers or a function that takes the default providers and returns * a modified array or a Promise resolving to one. */ providers?: AuthProvider[] | ((prev: AuthProvider[]) => AuthProvider[] | Promise); /** * The API hostname for requests. Usually leave this undefined, but it can be set * if using a custom domain or CNAME for the API endpoint. */ apiHost?: string; /** * Storage implementation to persist authentication state. * Defaults to `localStorage` if available. */ storageArea?: Storage; /** * A callback URL for your application. * If none is provided, the auth API will redirect back to the current location (`location.href`). * When handling callbacks, this URL's pathname is checked to ensure it matches the callback. */ callbackUrl?: string; /** * A static authentication token to use instead of handling the OAuth flow. * When provided, the auth store will remain in a logged-in state with this token, * ignoring any storage or callback handling. */ token?: string; } /** * A minimal Observable-compatible interface for subscribing to token changes. * Any object with a `subscribe` method that follows this contract will work, * including RxJS Observables. This avoids coupling the SDK to a specific * reactive library. * * @public */ interface TokenSource { /** Subscribe to token emissions. Emits `null` when logged out. */ subscribe(observer: { next: (token: string | null) => void; }): { unsubscribe(): void; }; } /** * Studio-specific configuration for the SDK. * When present, the SDK operates in studio mode and derives auth from the * provided token source instead of discovering tokens independently. * * @public */ interface StudioConfig { /** Reactive auth token source from the Studio's auth store. */ auth?: { /** * A reactive token source. The SDK subscribes and stays in sync — the * Studio is the single authority for auth and handles token refresh. * * Optional because older Studios may not expose it. When absent, the * SDK falls back to localStorage/cookie discovery. */ token?: TokenSource; }; } /** * Represents the minimal configuration required to identify a Sanity project. * @public */ interface ProjectHandle { projectId?: TProjectId; } /** * @public */ type ReleasePerspective = { releaseName: string; excludedPerspectives?: StackablePerspective[]; }; /** * @public */ interface PerspectiveHandle { perspective?: ClientPerspective | ReleasePerspective; } /** * @public */ interface DatasetHandle extends ProjectHandle, PerspectiveHandle { dataset?: TDataset; /** * @beta * Explicit source object to use for this operation. */ source?: DocumentSource; } /** * Identifies a specific document type within a Sanity dataset and project. * Includes `projectId`, `dataset`, and `documentType`. * Optionally includes a `documentId` and `liveEdit` flag. * @public */ interface DocumentTypeHandle extends DatasetHandle { documentId?: string; documentType: TDocumentType; /** * Indicates whether this document uses liveEdit mode. * When `true`, the document does not use the draft/published model and edits are applied directly to the document. * @see https://www.sanity.io/docs/content-lake/drafts#ca0663a8f002 */ liveEdit?: boolean; } /** * Uniquely identifies a specific document within a Sanity dataset and project. * Includes `projectId`, `dataset`, `documentType`, and the required `documentId`. * Commonly used by document-related hooks and components to reference a document without fetching its full content initially. * @public */ interface DocumentHandle extends DocumentTypeHandle { documentId: string; } /** * Represents the complete configuration for a Sanity SDK instance * @public */ interface SanityConfig extends DatasetHandle, PerspectiveHandle { /** * Authentication configuration for the instance * @remarks Merged with parent configurations when using createChild */ auth?: AuthConfig; /** * Studio configuration provided by a Sanity Studio workspace. * When present, the SDK operates in studio mode and derives auth from the * workspace's reactive token source — no manual configuration needed. * * @remarks Typically set automatically by `SanityApp` when it detects an * `SDKStudioContext` provider. Can also be set explicitly for programmatic use. */ studio?: StudioConfig; /** * Studio mode configuration for use of the SDK in a Sanity Studio. * @remarks Controls whether studio mode features are enabled. * @deprecated Use `studio` instead, which provides richer integration * with the Studio's workspace (auth token sync, etc.). */ studioMode?: { enabled: boolean; }; /** * @beta * A list of named sources to use for this instance. */ sources?: Record; } /** * A document source can be used for querying. * This will soon be the default way to identify where you are querying from. * * @beta */ type DocumentSource = DatasetSource | MediaLibrarySource | CanvasSource; /** * @beta */ type DatasetSource = { projectId: string; dataset: string; }; /** * @beta */ type MediaLibrarySource = { mediaLibraryId: string; }; /** * @beta */ type CanvasSource = { canvasId: string; }; /** * @beta */ declare function isDatasetSource(source: DocumentSource): source is DatasetSource; /** * @beta */ declare function isMediaLibrarySource(source: DocumentSource): source is MediaLibrarySource; /** * @beta */ declare function isCanvasSource(source: DocumentSource): source is CanvasSource; /** * Represents a Sanity.io resource instance with its own configuration and lifecycle * @remarks Instances form a hierarchy through parent/child relationships * * @public */ interface SanityInstance { /** * Unique identifier for this instance * @remarks Generated using crypto.randomUUID() */ readonly instanceId: string; /** * Resolved configuration for this instance * @remarks Merges values from parent instances where appropriate */ readonly config: SanityConfig; /** * Checks if the instance has been disposed * @returns true if dispose() has been called */ isDisposed(): boolean; /** * Disposes the instance and cleans up associated resources * @remarks Triggers all registered onDispose callbacks */ dispose(): void; /** * Registers a callback to be invoked when the instance is disposed * @param cb - Callback to execute on disposal * @returns Function to unsubscribe the callback */ onDispose(cb: () => void): () => void; /** * Gets the parent instance in the hierarchy * @returns Parent instance or undefined if this is the root */ getParent(): SanityInstance | undefined; /** * Creates a child instance with merged configuration * @param config - Configuration to merge with parent values * @remarks Child instances inherit parent configuration but can override values */ createChild(config: SanityConfig): SanityInstance; /** * Traverses the instance hierarchy to find the first instance whose configuration * matches the given target config using a shallow comparison. * @param targetConfig - A partial configuration object containing key-value pairs to match. * @returns The first matching instance or undefined if no match is found. */ match(targetConfig: Partial): SanityInstance | undefined; } /** * Creates a new Sanity resource instance * @param config - Configuration for the instance (optional) * @returns A configured SanityInstance * @remarks When creating child instances, configurations are merged with parent values * * @public */ declare function createSanityInstance(config?: SanityConfig): SanityInstance; /** @alpha */ type AgentGenerateOptions = Parameters[0]; /** @alpha */ type AgentTransformOptions = Parameters[0]; /** @alpha */ type AgentTranslateOptions = Parameters[0]; /** @alpha */ type AgentPromptOptions = Parameters[0]; /** @alpha */ type AgentPatchOptions = Parameters[0]; /** @alpha */ type AgentGenerateResult = Awaited>; /** @alpha */ type AgentTransformResult = Awaited>; /** @alpha */ type AgentTranslateResult = Awaited>; /** @alpha */ type AgentPromptResult = Awaited>; /** @alpha */ type AgentPatchResult = Awaited>; /** * Generates a new document using the agent. * @param instance - The Sanity instance. * @param options - The options for the agent generate action. See the [Agent Actions API](https://www.sanity.io/docs/agent-actions/introduction) for more details. * @returns An Observable emitting the result of the agent generate action. * @alpha */ declare function agentGenerate(instance: SanityInstance, options: AgentGenerateOptions): AgentGenerateResult; /** * Transforms a document using the agent. * @param instance - The Sanity instance. * @param options - The options for the agent transform action. See the [Agent Actions API](https://www.sanity.io/docs/agent-actions/introduction) for more details. * @returns An Observable emitting the result of the agent transform action. * @alpha */ declare function agentTransform(instance: SanityInstance, options: AgentTransformOptions): AgentTransformResult; /** * Translates a document using the agent. * @param instance - The Sanity instance. * @param options - The options for the agent translate action. See the [Agent Actions API](https://www.sanity.io/docs/agent-actions/introduction) for more details. * @returns An Observable emitting the result of the agent translate action. * @alpha */ declare function agentTranslate(instance: SanityInstance, options: AgentTranslateOptions): AgentTranslateResult; /** * Prompts the agent using the same instruction template format as the other actions, but returns text or json instead of acting on a document. * @param instance - The Sanity instance. * @param options - The options for the agent prompt action. See the [Agent Actions API](https://www.sanity.io/docs/agent-actions/introduction) for more details. * @returns An Observable emitting the result of the agent prompt action. * @alpha */ declare function agentPrompt(instance: SanityInstance, options: AgentPromptOptions): Observable; /** * Patches a document using the agent. * @param instance - The Sanity instance. * @param options - The options for the agent patch action. See the [Agent Actions API](https://www.sanity.io/docs/agent-actions/introduction) for more details. * @returns An Observable emitting the result of the agent patch action. * @alpha */ declare function agentPatch(instance: SanityInstance, options: AgentPatchOptions): Observable; /** * Returns `true` when the config indicates the SDK is running inside a Studio. * Checks the new `studio` field first, then falls back to the deprecated * `studioMode.enabled` for backwards compatibility. * * @internal */ declare function isStudioConfig(config: SanityConfig): 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", } /** * Represents a reactive store state container with multiple access patterns */ interface StoreState { /** * Gets the current state value * * @remarks * This is a direct synchronous accessor that doesn't trigger subscriptions */ get: () => TState; /** * Updates the store state * @param name - Action name for devtools tracking * @param updatedState - New state value or updater function * * @remarks * When providing a partial object, previous top-level keys not included in * the update will be preserved. */ set: (name: string, updatedState: Partial | ((s: TState) => Partial)) => void; /** * Observable stream of state changes * @remarks * - Emits immediately with current state on subscription * - Shares underlying subscription between observers * - Only emits when state reference changes * - Completes when store is disposed */ observable: Observable; } /** * Context object provided to store initialization functions */ interface StoreContext { /** * Sanity instance associated with this store * * @remarks * Provides access to the Sanity configuration and instance lifecycle methods */ instance: SanityInstance; /** * Reactive store state management utilities * * @remarks * Contains methods for getting/setting state and observing changes */ state: StoreState; /** * The key used to instantiate the store. */ key: TKey; } /** * Defines a store action that operates on a specific state type */ type StoreAction = (context: StoreContext, ...params: TParams) => TReturn; /** * Represents a store action that has been bound to a specific store instance */ type BoundStoreAction<_TState, TParams extends unknown[], TReturn> = (instance: SanityInstance, ...params: TParams) => TReturn; /** * 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$1 | 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; }; dashboardContext?: DashboardContext; } /** * @public */ declare const getCurrentUserState: BoundStoreAction>; /** * @public */ declare const getTokenState: BoundStoreAction>; /** * @public */ declare const getLoginUrlState: BoundStoreAction>; /** * @public */ declare const getAuthState: BoundStoreAction>; /** * @public */ declare const getDashboardOrganizationId: BoundStoreAction>; /** * Returns a state source indicating if the SDK is running within a dashboard context. * @public */ declare const getIsInDashboardState: BoundStoreAction>; /** * Action to explicitly set the authentication token. * Used internally by the Comlink token refresh. * @internal */ declare const setAuthToken: BoundStoreAction; /** * 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 auth context) with the * project's actual organization ID (fetched via getProjectState) and compares them. * @public */ declare function observeOrganizationVerificationState(instance: SanityInstance, projectIds: string[]): Observable; /** * @public */ declare const handleAuthCallback: BoundStoreAction>; /** * @public */ declare const logout: BoundStoreAction>; /** @internal */ type ApiErrorBody = { error?: { type?: string; description?: string; }; type?: string; description?: string; message?: string; }; /** @internal Extracts the structured API error body from a ClientError, if present. */ declare function getClientErrorApiBody(error: ClientError): ApiErrorBody | undefined; /** @internal Returns the error type string from an API error body, if available. */ declare function getClientErrorApiType(error: ClientError): string | undefined; /** @internal Returns the error description string from an API error body, if available. */ declare function getClientErrorApiDescription(error: ClientError): string | undefined; /** @internal True if the error represents a projectUserNotFoundError. */ declare function isProjectUserNotFoundClientError(error: ClientError): boolean; 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 { /** * 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 */ '~experimental_resource'?: ClientConfig['~experimental_resource']; /** * @internal */ 'source'?: DocumentSource; } /** * 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; /** * 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>; /** * Message sent from a containing app to an iframe * @public */ type FrameMessage = Message; /** * Message sent from an iframe to a containing app * @public */ type WindowMessage = Message; /** * Message from SDK (iframe) to Parent (dashboard) to request a new token * @internal */ type RequestNewTokenMessage = { type: 'dashboard/v1/auth/tokens/create'; payload?: undefined; }; /** * Message from Parent (dashboard) to SDK (iframe) with the new token * @internal */ type NewTokenResponseMessage = { type: 'dashboard/v1/auth/tokens/create'; payload: { token: string | null; error?: string; }; }; /** * Individual channel with its relevant options * @public */ interface ChannelEntry { channel: ChannelInstance; options: ChannelInput; refCount: number; } /** * Internal state tracking comlink connections * @public */ interface ComlinkControllerState { controller: Controller | null; controllerOrigin: string | null; channels: Map; } /** * Calls the destroy method on the controller and resets the controller state. * @public */ declare const destroyController: BoundStoreAction; /** * Retrieve or create a channel to be used for communication between * an application and the controller. * @public */ declare const getOrCreateChannel: BoundStoreAction>; /** * Initializes or fetches a controller to handle communication * between an application and iframes. * @public */ declare const getOrCreateController: BoundStoreAction; /** * Signals to the store that the consumer has stopped using the channel * @public */ declare const releaseChannel: BoundStoreAction; /** * Individual node with its relevant options * @public */ interface NodeEntry { node: Node; options: NodeInput; status: Status; statusUnsub?: () => void; } /** * Internal state tracking comlink connections * @public */ interface ComlinkNodeState { nodes: Map; subscriptions: Map>; } /** * Signals to the store that the consumer has stopped using the node * @public */ declare const releaseNode: BoundStoreAction; /** * Retrieve or create a node to be used for communication between * an application and the controller -- specifically, a node should * be created within a frame / window to communicate with the controller. * @public */ declare const getOrCreateNode: BoundStoreAction>; /** * @public */ interface NodeState { node: Node; status: Status | undefined; } /** * Provides a subscribable state source for a node by name * @param instance - The Sanity instance to get the node state for * @param nodeInput - The configuration for the node to get the state for * @returns A subscribable state source for the node * @public */ declare const getNodeState: BoundStoreAction>; /** * 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(handle: DocumentHandle): DocumentHandle; /** * 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(handle: DocumentTypeHandle): DocumentTypeHandle; /** * 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(handle: ProjectHandle): ProjectHandle; /** * 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(handle: DatasetHandle): DatasetHandle; /** * 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; } /** * 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; /** @public */ declare const getDatasetsState: BoundStoreAction | undefined], _sanity_client12.DatasetsResponse>, [options?: ProjectHandle | undefined], StateSource<_sanity_client12.DatasetsResponse | undefined>>; /** @public */ declare const resolveDatasets: BoundStoreAction | undefined], _sanity_client12.DatasetsResponse>, [options?: ProjectHandle | undefined], Promise<_sanity_client12.DatasetsResponse>>; /** * 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 extends DocumentTypeHandle { 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, '_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 extends DocumentHandle { 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 extends DocumentHandle { type: 'document.edit'; patches?: PatchOperations[]; } /** * Represents an action to publish the draft version of a document. * Requires the full document handle. * @beta */ interface PublishDocumentAction extends DocumentHandle { 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 extends DocumentHandle { type: 'document.unpublish'; } /** * Represents an action to discard the draft changes of a document. * Requires the full document handle. * @beta */ interface DiscardDocumentAction extends DocumentHandle { type: 'document.discard'; } /** * Union type representing all possible document actions within the SDK. * @beta */ type DocumentAction = CreateDocumentAction | DeleteDocumentAction | EditDocumentAction | PublishDocumentAction | UnpublishDocumentAction | DiscardDocumentAction; /** * 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(doc: DocumentTypeHandle, initialValue?: Partial, '_id' | '_type' | '_rev' | '_createdAt' | '_updatedAt'>>): CreateDocumentAction; /** * 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(doc: DocumentHandle): DeleteDocumentAction; /** * 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`. * @returns An `EditDocumentAction` object ready for dispatch. * @beta */ declare function editDocument(doc: DocumentHandle, sanityMutatePatch: PatchMutation): EditDocumentAction; /** * 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. * @returns An `EditDocumentAction` object ready for dispatch. * @beta */ declare function editDocument(doc: DocumentHandle, patches?: PatchOperations | PatchOperations[]): EditDocumentAction; /** * 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(doc: DocumentHandle): PublishDocumentAction; /** * 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(doc: DocumentHandle): UnpublishDocumentAction; /** * 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(doc: DocumentHandle): DiscardDocumentAction; /** * Represents a set of document that will go into `applyMutations`. Before * applying a mutation, it's expected that all relevant documents that the * mutations affect are included, including those that do not exist yet. * Documents that don't exist have a `null` value. */ type DocumentSet = { [TDocumentId in string]?: TDocument | null }; /** @beta */ interface ActionsResult { transactionId: string; documents: DocumentSet; previous: DocumentSet; previousRevs: { [documentId: string]: string | undefined; }; appeared: string[]; updated: string[]; disappeared: string[]; submitted: () => ReturnType; } /** @beta */ interface ApplyDocumentActionsOptions { /** * List of actions to apply. */ actions: DocumentAction[]; /** * 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(instance: SanityInstance, options: ApplyDocumentActionsOptions): Promise>>; /** @beta */ declare function applyDocumentActions(instance: SanityInstance, options: ApplyDocumentActionsOptions): Promise; /** * Represents a reactive state source that provides synchronized access to store data * * @remarks * Designed to work with React's useSyncExternalStore hook. Provides three ways to access data: * 1. `getCurrent()` for synchronous current value access * 2. `subscribe()` for imperative change notifications * 3. `observable` for reactive stream access * * @public */ interface StateSource { /** * Subscribes to state changes with optional callback * @param onStoreChanged - Called whenever relevant state changes occur * @returns Unsubscribe function to clean up the subscription */ subscribe: (onStoreChanged?: () => void) => () => void; /** * Gets the current derived state value * * @remarks * Safe to call without subscription. Will always return the latest value * based on the current store state and selector parameters. */ getCurrent: () => T; /** * Observable stream of state values * * @remarks * Shares a single underlying subscription between all observers. Emits: * - Immediately with current value on subscription * - On every relevant state change * - Errors if selector throws */ observable: Observable; } /** * Context passed to selectors when deriving state * * @remarks * Provides access to both the current state value and the Sanity instance, * allowing selectors to use configuration values when computing derived state. * The context is memoized for each state object and instance combination * to optimize performance and prevent unnecessary recalculations. * * @example * ```ts * // Using both state and instance in a selector (psuedo example) * const getUserByProjectId = createStateSourceAction( * ({ state, instance }: SelectorContext, options?: ProjectHandle) => { * const allUsers = state.users * const projectId = options?.projectId ?? instance.config.projectId * return allUsers.filter(user => user.projectId === projectId) * } * ) * ``` */ interface SelectorContext { /** * The current state object from the store */ state: TState; /** * The Sanity instance associated with this state */ instance: SanityInstance; } /** * Function type for selecting derived state from store state and parameters * @public */ type Selector = (context: SelectorContext, ...params: TParams) => TReturn; type ActionMap = { create: 'sanity.action.document.version.create'; createLiveEdit: 'sanity.action.document.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'; }; type OptimisticLock = { ifDraftRevisionId?: string; ifPublishedRevisionId?: string; }; type HttpAction = { actionType: ActionMap['create']; publishedId: string; attributes: SanityDocumentLike; } | { actionType: ActionMap['createLiveEdit']; 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); /** * 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: DocumentAction[]; /** * 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 action. * this left here for debugging purposes but could be used to send mutations * to Content Lake instead of actions. */ 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; } 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; }; /** @beta */ type DocumentEvent = ActionErrorEvent | TransactionRevertedEvent | TransactionAcceptedEvent | DocumentRebaseErrorEvent | DocumentEditedEvent | DocumentCreatedEvent | DocumentDeletedEvent | DocumentPublishedEvent | DocumentUnpublishedEvent | DocumentDiscardedEvent; /** * @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: Awaited>; } /** * @beta * Event emitted when a transaction is reverted. */ interface TransactionRevertedEvent { type: 'reverted'; message: string; error: unknown; outgoing: OutgoingTransaction; } /** * @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; } /** * 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 `${infer Head}.${infer Tail}` ? [Head, ...PathParts] : 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 = TPath extends [] ? TValue : TPath extends readonly [infer THead, ...infer TTail] ? DeepGet : never; /** * Given a document type TDocument and a JSON Match path string TPath, * compute the type found at that path. * @beta */ type JsonMatch = DeepGet>; interface SharedListener { events: Observable>; dispose: () => void; } interface DocumentStoreState { documentStates: { [TDocumentId in string]?: DocumentState }; queued: QueuedTransaction[]; applied: AppliedTransaction[]; outgoing?: OutgoingTransaction; grants?: Record; error?: unknown; sharedListener: SharedListener; fetchDocument: (documentId: string) => Observable; events: Subject; } interface DocumentState { id: string; /** * the "remote" local copy that matches the server. represents the last known * server state. this gets updated every time we confirm remote patches */ remote?: SanityDocument$3 | null; /** * the current ephemeral working copy that includes local optimistic changes * that have not yet been confirmed by the server */ local?: SanityDocument$3 | 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 }; } /** * @beta * Options for specifying a document and optionally a path within it. */ interface DocumentOptions extends DocumentHandle { path?: TPath; } /** @beta */ declare function getDocumentState(instance: SanityInstance, options: DocumentOptions): StateSource | undefined | null>; /** @beta */ declare function getDocumentState(instance: SanityInstance, options: DocumentOptions): StateSource, TPath> | undefined>; /** @beta */ declare function getDocumentState(instance: SanityInstance, options: DocumentOptions): StateSource; /** @beta */ declare function resolveDocument(instance: SanityInstance, docHandle: DocumentHandle): Promise | null>; /** @beta */ declare function resolveDocument(instance: SanityInstance, docHandle: DocumentHandle): Promise; /** @beta */ declare const getDocumentSyncStatus: BoundStoreAction], StateSource>; type PermissionsStateOptions = { actions: DocumentAction[]; }; /** @beta */ declare const getPermissionsState: BoundStoreAction>; /** @beta */ declare const resolvePermissions: BoundStoreAction>; /** @beta */ declare const subscribeDocumentEvents: BoundStoreAction void], () => void>; /** * @public */ interface FavoriteStatusResponse { isFavorited: boolean; } /** * @public */ interface FavoriteDocumentContext extends DocumentHandle { resourceId: string; resourceType: StudioResource['type'] | MediaResource['type'] | CanvasResource['type']; schemaName?: string; } /** * Gets a StateSource for the favorite status of a document. * @param instance - The Sanity instance. * @param context - The document context including ID, type, and resource information. * @returns A StateSource emitting `{ isFavorited: boolean }`. * @public */ declare const getFavoritesState: BoundStoreAction, [FavoriteDocumentContext], StateSource>; /** * Resolves the favorite status for a document. * @param instance - The Sanity instance. * @param context - The document context including ID, type, and resource information. * @returns A Promise resolving to `{ isFavorited: boolean }`. * @public */ declare const resolveFavoritesState: BoundStoreAction, [FavoriteDocumentContext], Promise>; /** * @public */ interface SanityUser { sanityUserId: string; profile: UserProfile; memberships: Membership[]; } /** * @public */ interface Membership { addedAt?: string; resourceType: string; resourceId: string; roleNames: Array; 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; } /** @public */ interface PresenceLocation { type: 'document'; documentId: string; path: string[]; lastActiveAt: string; } /** @public */ interface UserPresence { user: SanityUser; locations: PresenceLocation[]; sessionId: string; } /** @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; } type PresenceStoreState = { locations: Map; users: Record; }; /** @public */ /** @public */ declare const getPresence: BoundStoreAction>; /** * 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; }; } /** * Represents the current state of a preview value along with a flag indicating whether * the preview data is still being fetched or is fully resolved. * * The tuple contains a preview value or null, and a boolean indicating if the data is * pending. A `true` value means a fetch is ongoing; `false` indicates that the * currently provided preview value is up-to-date. * * @public */ type ValuePending = { data: T | null; isPending: boolean; }; /** * @public */ interface PreviewStoreState { values: { [TDocumentId in string]?: ValuePending }; subscriptions: { [TDocumentId in string]?: { [TSubscriptionId in string]?: true } }; } /** * @beta */ type GetPreviewStateOptions = DocumentHandle; /** * @beta */ declare function getPreviewState(instance: SanityInstance, options: GetPreviewStateOptions): StateSource>; /** * @beta */ declare function getPreviewState(instance: SanityInstance, options: GetPreviewStateOptions): StateSource>; /** * @beta */ type ResolvePreviewOptions = DocumentHandle; /** * @beta */ declare const resolvePreview: BoundStoreAction>>; /** @public */ declare const getProjectState: BoundStoreAction | undefined], _sanity_client12.SanityProject>, [options?: ProjectHandle | undefined], StateSource<_sanity_client12.SanityProject | undefined>>; /** @public */ declare const resolveProject: BoundStoreAction | undefined], _sanity_client12.SanityProject>, [options?: ProjectHandle | undefined], Promise<_sanity_client12.SanityProject>>; /** * @public * The result of a projection query */ interface ProjectionValuePending { data: TValue | null; isPending: boolean; } /** * @public * @deprecated * Template literals are a bit too limited, so this type is deprecated. * Use `string` instead. Projection strings are validated at runtime. */ type ValidProjection = string; interface ProjectionOptions extends DocumentHandle { projection: TProjection; } /** * @beta */ declare function getProjectionState(instance: SanityInstance, options: ProjectionOptions): StateSource> | undefined>; /** * @beta */ declare function getProjectionState(instance: SanityInstance, options: ProjectionOptions): StateSource | undefined>; /** * @beta */ declare function getProjectionState(instance: SanityInstance, options: ProjectionOptions): StateSource> | undefined>; /** @beta */ declare function resolveProjection(instance: SanityInstance, options: ProjectionOptions): Promise>>; /** @beta */ declare function resolveProjection(instance: SanityInstance, options: ProjectionOptions): Promise>; /** @public */ declare const getProjectsState: BoundStoreAction[]>, [options?: { organizationId?: string; includeMembers?: boolean; } | undefined], StateSource[] | undefined>>; /** @public */ declare const resolveProjects: BoundStoreAction[]>, [options?: { organizationId?: string; includeMembers?: boolean; } | undefined], Promise[]>>; /** * @beta */ interface QueryOptions extends Pick, DatasetHandle { query: TQuery; params?: Record; } /** * @beta */ interface ResolveQueryOptions extends QueryOptions { signal?: AbortSignal; } /** @beta */ declare const getQueryKey: (options: QueryOptions) => string; /** @beta */ 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(instance: SanityInstance, queryOptions: QueryOptions): StateSource | undefined>; /** @beta */ declare function getQueryState(instance: SanityInstance, queryOptions: QueryOptions): StateSource; /** @beta */ declare function getQueryState(instance: SanityInstance, queryOptions: QueryOptions): StateSource; /** * 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. * Unlike `getQueryState`, which registers subscribers to keep the query live and performs automatic cleanup, * `resolveQuery` does not track subscribers. 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 active subscribers. * * @beta */ declare function resolveQuery(instance: SanityInstance, queryOptions: ResolveQueryOptions): Promise>; /** @beta */ declare function resolveQuery(instance: SanityInstance, queryOptions: ResolveQueryOptions): Promise; /** * Represents a document in a Sanity dataset that represents release options. * @internal */ type ReleaseDocument = SanityDocument$2 & { name: string; publishAt?: string; state: 'active' | 'scheduled'; metadata: { title: string; releaseType: 'asap' | 'scheduled' | 'undecided'; intendedPublishAt?: string; description?: string; }; }; interface ReleasesStoreState { activeReleases?: ReleaseDocument[]; error?: unknown; } /** * Get the active releases from the store. * @internal */ declare const getActiveReleasesState: BoundStoreAction>; declare const _getPerspectiveStateSelector: StoreAction, unknown>; type OmitFirst = T extends [unknown, ...infer R] ? R : never; type SelectorParams = OmitFirst>; type BoundGetPerspectiveState = BoundStoreAction>; /** * 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; /** @internal */ declare const getUsersKey: (instance: SanityInstance, { resourceType, organizationId, batchSize, projectId, userId }?: GetUsersOptions) => string; /** @internal */ declare const parseUsersKey: (key: string) => { batchSize: number; resourceType?: "organization" | "project"; projectId?: string; organizationId?: string; userId?: string; }; /** * 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>; /** * 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>; /** * 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>; /** * @beta */ declare const getUserState: BoundStoreAction>; /** * @beta */ declare const resolveUser: BoundStoreAction>; interface StoreEntry { params: TParams; instance: SanityInstance; key: string; data?: TData; error?: unknown; subscriptions: string[]; lastFetchInitiatedAt?: string; } /** * Internal helper type * @public */ interface FetcherStoreState { stateByParams: { [TSerializedKey in string]?: StoreEntry }; error?: unknown; } /** * Internal helper type * @public */ interface FetcherStore { getState: BoundStoreAction, TParams, StateSource>; resolveState: BoundStoreAction, TParams, Promise>; } /** * Creates a GROQ search filter string (`[@] match text::query("...")`) * from a raw search query string. * * It applies wildcard ('*') logic to the last eligible token and escapes * double quotes within the search term. * * If the input query is empty or only whitespace, it returns an empty string. * * @param query - The raw input search string. * @returns The GROQ search filter string, or an empty string. * @internal */ declare function createGroqSearchFilter(query: string): string; /** * Filter criteria for intent matching. Can be combined to create more specific intents. * * @example * ```typescript * // matches only geopoints in the travel-project project, production dataset * const filter: IntentFilter = { * projectId: 'travel-project', * dataset: 'production', * types: ['geopoint'] * } * * // matches all documents in the travel-project project * const filter: IntentFilter = { * projectId: 'travel-project', * types: ['*'] * } * * // matches geopoints in the travel-project production dataset and map pins in all projects in the org * const filters: IntentFilter[] = [ * { * projectId: 'travel-project', * dataset: 'production', * types: ['geopoint'] * }, * { * types: ['map-pin'] * } * ] * ``` * @public */ interface IntentFilter { /** * Project ID to match against * @remarks When specified, the intent will only match for the specified project. */ projectId?: string; /** * Dataset to match against * @remarks When specified, the intent will only match for the specified dataset. Requires projectId to be specified. */ dataset?: string; /** * Document types that this intent can handle * @remarks This is required for all filters. Use ['*'] to match all document types. */ types: string[]; } /** * Intent definition structure for registering user intents * @public */ interface Intent { /** * Unique identifier for this intent * @remarks Should be unique across all registered intents in an org for proper matching */ id: string; /** * The action that this intent performs * @remarks Examples: "view", "edit", "create", "delete" */ action: 'view' | 'edit' | 'create' | 'delete'; /** * Human-readable title for this intent * @remarks Used for display purposes in UI or logs */ title: string; /** * Detailed description of what this intent does * @remarks Helps users understand the purpose and behavior of the intent */ description?: string; /** * Array of filter criteria for intent matching * @remarks At least one filter is required. Use `{types: ['*']}` to match everything */ filters: IntentFilter[]; } /** * Creates a properly typed intent definition for registration with the backend. * * This utility function provides TypeScript support and validation for intent declarations. * It is also used in the CLI if intents are declared as bare objects in an intents file. * * @param intent - The intent definition object * @returns The same intent object with proper typing * * @example * ```typescript * // Specific filter for a document type * const viewGeopointInMapApp = defineIntent({ * id: 'viewGeopointInMapApp', * action: 'view', * title: 'View a geopoint in the map app', * description: 'This lets you view a geopoint in the map app', * filters: [ * { * projectId: 'travel-project', * dataset: 'production', * types: ['geopoint'] * } * ] * }) * * export default viewGeopointInMapApp * ``` * * If your intent is asynchronous, resolve the promise before defining / returning the intent * ```typescript * async function createAsyncIntent() { * const currentProject = await asyncProjectFunction() * const currentDataset = await asyncDatasetFunction() * * return defineIntent({ * id: 'dynamicIntent', * action: 'view', * title: 'Dynamic Intent', * description: 'Intent with dynamically resolved values', * filters: [ * { * projectId: currentProject, // Resolved value * dataset: currentDataset, // Resolved value * types: ['document'] * } * ] * }) * } * * const intent = await createAsyncIntent() * export default intent * ``` * * @public */ declare function defineIntent(intent: Intent): Intent; /** * @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; /** * This version is provided by pkg-utils at build time * @internal */ declare const CORE_SDK_VERSION: {}; /** * @public */ type SanityProject = SanityProject$1; export { type ActionErrorEvent, type ActionsResult, type AgentGenerateOptions, type AgentGenerateResult, type AgentPatchOptions, type AgentPatchResult, type AgentPromptOptions, type AgentPromptResult, type AgentTransformOptions, type AgentTransformResult, type AgentTranslateOptions, type AgentTranslateResult, type ApiErrorBody, type ApplyDocumentActionsOptions, type AuthConfig, type AuthProvider, type AuthState, AuthStateType, type AuthStoreState, CORE_SDK_VERSION, type CanvasSource, type ClientOptions, type ClientStoreState as ClientState, type ComlinkControllerState, type ComlinkNodeState, type CreateDocumentAction, type CurrentUser, type DatasetHandle, type DatasetSource, type DeleteDocumentAction, type DiscardDocumentAction, type DisconnectEvent, type DocumentAction, type DocumentCreatedEvent, type DocumentDeletedEvent, type DocumentDiscardedEvent, type DocumentEditedEvent, type DocumentEvent, type DocumentHandle, type DocumentOptions, type DocumentPermissionsResult, type DocumentPublishedEvent, type DocumentSource, type DocumentTypeHandle, type DocumentUnpublishedEvent, type EditDocumentAction, type ErrorAuthState, type FavoriteStatusResponse, type FetcherStore, type FetcherStoreState, type FrameMessage, type GetPreviewStateOptions, type GetUserOptions, type GetUsersOptions, type InstanceContext, type Intent, type IntentFilter, type JsonMatch, type LogContext, type LogLevel, type LogNamespace, type LoggedInAuthState, type LoggedOutAuthState, type Logger, type LoggerConfig, type LoggingInAuthState, type MediaLibrarySource, type Membership, type NewTokenResponseMessage, type NodeState, type OrgVerificationResult, type PermissionDeniedReason, type PerspectiveHandle, type PresenceLocation, type PreviewStoreState, type PreviewValue, type ProjectHandle, type ProjectionValuePending, type PublishDocumentAction, type QueryOptions, type ReleaseDocument, type ReleasePerspective, type RequestNewTokenMessage, type ResolvePreviewOptions, type ResolveUserOptions, type ResolveUsersOptions, type Role, type RollCallEvent, type SanityConfig, type SanityDocument, type SanityInstance, SanityProject, type SanityUser, type SanityUserResponse, type Selector, type StateEvent, type StateSource, type StudioConfig, type TokenSource, type TransactionAcceptedEvent, type TransactionRevertedEvent, type TransportEvent, type UnpublishDocumentAction, type UserPresence, type UserProfile, type UsersGroupState, type UsersStoreState, type ValidProjection, type ValuePending, type WindowMessage, agentGenerate, agentPatch, agentPrompt, agentTransform, agentTranslate, applyDocumentActions, configureLogging, createDatasetHandle, createDocument, createDocumentHandle, createDocumentTypeHandle, createGroqSearchFilter, createProjectHandle, createSanityInstance, defineIntent, deleteDocument, destroyController, discardDocument, editDocument, getActiveReleasesState, getAuthState, getClient, getClientErrorApiBody, getClientErrorApiDescription, getClientErrorApiType, getClientState, getCorsErrorProjectId, getCurrentUserState, getDashboardOrganizationId, getDatasetsState, getDocumentState, getDocumentSyncStatus, getFavoritesState, getIndexForKey, getIsInDashboardState, getLoginUrlState, getNodeState, getOrCreateChannel, getOrCreateController, getOrCreateNode, getPathDepth, getPermissionsState, getPerspectiveState, getPresence, getPreviewState, getProjectState, getProjectionState, getProjectsState, getQueryKey, getQueryState, getTokenState, getUserState, getUsersKey, getUsersState, handleAuthCallback, isCanvasSource, isDatasetSource, isMediaLibrarySource, isProjectUserNotFoundClientError, isStudioConfig, joinPaths, jsonMatch, loadMoreUsers, logout, observeOrganizationVerificationState, parseQueryKey, parseUsersKey, publishDocument, releaseChannel, releaseNode, resolveDatasets, resolveDocument, resolveFavoritesState, resolvePermissions, resolvePreview, resolveProject, resolveProjection, resolveProjects, resolveQuery, resolveUser, resolveUsers, setAuthToken, slicePath, stringifyPath, subscribeDocumentEvents, unpublishDocument };