@sanity/sdk 2.8.0 → 2.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/dist/_chunks-dts/utils.d.ts +2396 -0
  2. package/dist/_chunks-es/_internal.js +129 -0
  3. package/dist/_chunks-es/_internal.js.map +1 -0
  4. package/dist/_chunks-es/createGroqSearchFilter.js +1460 -0
  5. package/dist/_chunks-es/createGroqSearchFilter.js.map +1 -0
  6. package/dist/_chunks-es/telemetryManager.js +87 -0
  7. package/dist/_chunks-es/telemetryManager.js.map +1 -0
  8. package/dist/_chunks-es/version.js +7 -0
  9. package/dist/_chunks-es/version.js.map +1 -0
  10. package/dist/_exports/_internal.d.ts +64 -0
  11. package/dist/_exports/_internal.js +20 -0
  12. package/dist/_exports/_internal.js.map +1 -0
  13. package/dist/index.d.ts +2 -2343
  14. package/dist/index.js +383 -1777
  15. package/dist/index.js.map +1 -1
  16. package/package.json +11 -4
  17. package/src/_exports/_internal.ts +14 -0
  18. package/src/_exports/index.ts +10 -1
  19. package/src/auth/authStore.test.ts +150 -1
  20. package/src/auth/authStore.ts +11 -11
  21. package/src/auth/dashboardAuth.ts +2 -2
  22. package/src/auth/handleAuthCallback.ts +9 -3
  23. package/src/auth/logout.test.ts +1 -1
  24. package/src/auth/logout.ts +1 -1
  25. package/src/auth/refreshStampedToken.test.ts +118 -1
  26. package/src/auth/refreshStampedToken.ts +3 -2
  27. package/src/auth/standaloneAuth.ts +9 -3
  28. package/src/auth/studioAuth.ts +34 -7
  29. package/src/auth/studioModeAuth.ts +2 -1
  30. package/src/auth/subscribeToStateAndFetchCurrentUser.test.ts +10 -2
  31. package/src/auth/subscribeToStateAndFetchCurrentUser.ts +5 -1
  32. package/src/auth/subscribeToStorageEventsAndSetToken.ts +2 -2
  33. package/src/auth/utils.ts +33 -0
  34. package/src/client/clientStore.test.ts +14 -0
  35. package/src/client/clientStore.ts +2 -1
  36. package/src/comlink/node/getNodeState.ts +2 -1
  37. package/src/config/sanityConfig.ts +6 -0
  38. package/src/document/actions.ts +18 -11
  39. package/src/document/applyDocumentActions.test.ts +7 -6
  40. package/src/document/applyDocumentActions.ts +10 -4
  41. package/src/document/documentStore.test.ts +536 -188
  42. package/src/document/documentStore.ts +142 -76
  43. package/src/document/events.ts +7 -2
  44. package/src/document/permissions.test.ts +18 -16
  45. package/src/document/permissions.ts +35 -11
  46. package/src/document/processActions.test.ts +359 -32
  47. package/src/document/processActions.ts +104 -76
  48. package/src/document/reducers.test.ts +117 -29
  49. package/src/document/reducers.ts +43 -36
  50. package/src/document/sharedListener.ts +16 -6
  51. package/src/document/util.ts +14 -0
  52. package/src/favorites/favorites.test.ts +9 -2
  53. package/src/presence/bifurTransport.ts +6 -1
  54. package/src/preview/getPreviewState.test.ts +115 -98
  55. package/src/preview/getPreviewState.ts +38 -60
  56. package/src/preview/previewProjectionUtils.test.ts +179 -0
  57. package/src/preview/previewProjectionUtils.ts +93 -0
  58. package/src/preview/resolvePreview.test.ts +42 -25
  59. package/src/preview/resolvePreview.ts +29 -10
  60. package/src/preview/{previewStore.ts → types.ts} +8 -17
  61. package/src/projection/getProjectionState.test.ts +16 -16
  62. package/src/projection/getProjectionState.ts +2 -1
  63. package/src/projection/projectionQuery.ts +2 -3
  64. package/src/projection/types.ts +1 -1
  65. package/src/query/queryStore.ts +2 -1
  66. package/src/releases/getPerspectiveState.ts +7 -6
  67. package/src/releases/releasesStore.test.ts +20 -5
  68. package/src/releases/releasesStore.ts +20 -8
  69. package/src/store/createStateSourceAction.test.ts +62 -0
  70. package/src/store/createStateSourceAction.ts +34 -39
  71. package/src/telemetry/__telemetry__/sdk.telemetry.ts +42 -0
  72. package/src/telemetry/devMode.test.ts +52 -0
  73. package/src/telemetry/devMode.ts +40 -0
  74. package/src/telemetry/initTelemetry.test.ts +225 -0
  75. package/src/telemetry/initTelemetry.ts +205 -0
  76. package/src/telemetry/telemetryManager.test.ts +263 -0
  77. package/src/telemetry/telemetryManager.ts +187 -0
  78. package/src/users/usersStore.test.ts +1 -0
  79. package/src/users/usersStore.ts +5 -1
  80. package/src/utils/createFetcherStore.test.ts +6 -4
  81. package/src/utils/createFetcherStore.ts +2 -1
  82. package/src/utils/getStagingApiHost.test.ts +21 -0
  83. package/src/utils/getStagingApiHost.ts +14 -0
  84. package/src/utils/ids.test.ts +1 -29
  85. package/src/utils/ids.ts +0 -10
  86. package/src/utils/setCleanupTimeout.ts +24 -0
  87. package/src/preview/previewQuery.test.ts +0 -236
  88. package/src/preview/previewQuery.ts +0 -153
  89. package/src/preview/previewStore.test.ts +0 -36
  90. package/src/preview/subscribeToStateAndFetchBatches.test.ts +0 -221
  91. package/src/preview/subscribeToStateAndFetchBatches.ts +0 -112
  92. package/src/preview/util.ts +0 -13
@@ -0,0 +1,2396 @@
1
+ import * as _sanity_client12 from "@sanity/client";
2
+ import { ClientConfig, ClientError, ClientPerspective, ListenEvent, MultipleMutationResult, ResponseQueryOptions, SanityClient, SanityDocument, SanityProject, StackablePerspective } from "@sanity/client";
3
+ import { CurrentUser, CurrentUser as CurrentUser$1, Mutation, PatchOperations, Role, SanityDocument as SanityDocument$1, SanityDocument as SanityDocument$3, SanityDocumentLike } from "@sanity/types";
4
+ import { Observable, Subject } from "rxjs";
5
+ import * as _sanity_comlink5 from "@sanity/comlink";
6
+ import { ChannelInput, ChannelInstance, Controller, Message, Node, NodeInput, Status } from "@sanity/comlink";
7
+ import { PatchMutation } from "@sanity/mutate/_unstable_store";
8
+ import { SanityDocument as SanityDocument$2, SanityProjectionResult, SanityQueryResult } from "groq";
9
+ import { ExprNode } from "groq-js";
10
+ import { CanvasResource, MediaResource, StudioResource } from "@sanity/message-protocol";
11
+ import { getIndexForKey, getPathDepth, joinPaths, jsonMatch, slicePath, stringifyPath } from "@sanity/json-match";
12
+ /**
13
+ * Configuration for an authentication provider
14
+ * @public
15
+ */
16
+ interface AuthProvider {
17
+ /**
18
+ * Unique identifier for the auth provider (e.g., 'google', 'github')
19
+ */
20
+ name: string;
21
+ /**
22
+ * Display name for the auth provider in the UI
23
+ */
24
+ title: string;
25
+ /**
26
+ * Complete authentication URL including callback and token parameters
27
+ */
28
+ url: string;
29
+ /**
30
+ * Optional URL for direct sign-up flow
31
+ */
32
+ signUpUrl?: string;
33
+ }
34
+ /**
35
+ * Configuration options for creating an auth store.
36
+ *
37
+ * @public
38
+ */
39
+ interface AuthConfig {
40
+ /**
41
+ * The initial location href to use when handling auth callbacks.
42
+ * Defaults to the current window location if available.
43
+ */
44
+ initialLocationHref?: string;
45
+ /**
46
+ * Factory function to create a SanityClient instance.
47
+ * Defaults to the standard Sanity client factory if not provided.
48
+ */
49
+ clientFactory?: (config: ClientConfig) => SanityClient;
50
+ /**
51
+ * Custom authentication providers to use instead of or in addition to the default ones.
52
+ * Can be an array of providers or a function that takes the default providers and returns
53
+ * a modified array or a Promise resolving to one.
54
+ */
55
+ providers?: AuthProvider[] | ((prev: AuthProvider[]) => AuthProvider[] | Promise<AuthProvider[]>);
56
+ /**
57
+ * The API hostname for requests. Usually leave this undefined, but it can be set
58
+ * if using a custom domain or CNAME for the API endpoint.
59
+ */
60
+ apiHost?: string;
61
+ /**
62
+ * Storage implementation to persist authentication state.
63
+ * Defaults to `localStorage` if available.
64
+ */
65
+ storageArea?: Storage;
66
+ /**
67
+ * A callback URL for your application.
68
+ * If none is provided, the auth API will redirect back to the current location (`location.href`).
69
+ * When handling callbacks, this URL's pathname is checked to ensure it matches the callback.
70
+ */
71
+ callbackUrl?: string;
72
+ /**
73
+ * A static authentication token to use instead of handling the OAuth flow.
74
+ * When provided, the auth store will remain in a logged-in state with this token,
75
+ * ignoring any storage or callback handling.
76
+ */
77
+ token?: string;
78
+ }
79
+ /**
80
+ * A minimal Observable-compatible interface for subscribing to token changes.
81
+ * Any object with a `subscribe` method that follows this contract will work,
82
+ * including RxJS Observables. This avoids coupling the SDK to a specific
83
+ * reactive library.
84
+ *
85
+ * @public
86
+ */
87
+ interface TokenSource {
88
+ /** Subscribe to token emissions. Emits `null` when logged out. */
89
+ subscribe(observer: {
90
+ next: (token: string | null) => void;
91
+ }): {
92
+ unsubscribe(): void;
93
+ };
94
+ }
95
+ /**
96
+ * Studio-specific configuration for the SDK.
97
+ * When present, the SDK operates in studio mode and derives auth from the
98
+ * provided token source instead of discovering tokens independently.
99
+ *
100
+ * @public
101
+ */
102
+ interface StudioConfig {
103
+ /**
104
+ * Whether the Studio has already determined the user is authenticated.
105
+ * When `true` and the token source emits `null`, the SDK infers
106
+ * cookie-based auth is in use rather than transitioning to logged-out.
107
+ */
108
+ authenticated?: boolean;
109
+ /** Reactive auth token source from the Studio's auth store. */
110
+ auth?: {
111
+ /**
112
+ * A reactive token source. The SDK subscribes and stays in sync — the
113
+ * Studio is the single authority for auth and handles token refresh.
114
+ *
115
+ * Optional because older Studios may not expose it. When absent, the
116
+ * SDK falls back to localStorage/cookie discovery.
117
+ */
118
+ token?: TokenSource;
119
+ };
120
+ }
121
+ /**
122
+ * Represents the minimal configuration required to identify a Sanity project.
123
+ * @public
124
+ */
125
+ interface ProjectHandle<TProjectId extends string = string> {
126
+ projectId?: TProjectId;
127
+ }
128
+ /**
129
+ * @public
130
+ */
131
+ type ReleasePerspective = {
132
+ releaseName: string;
133
+ excludedPerspectives?: StackablePerspective[];
134
+ };
135
+ /**
136
+ * @public
137
+ */
138
+ interface PerspectiveHandle {
139
+ perspective?: ClientPerspective | ReleasePerspective;
140
+ }
141
+ /**
142
+ * @public
143
+ */
144
+ interface DatasetHandle<TDataset extends string = string, TProjectId extends string = string> extends ProjectHandle<TProjectId>, PerspectiveHandle {
145
+ dataset?: TDataset;
146
+ /**
147
+ * @beta
148
+ * Explicit source object to use for this operation.
149
+ */
150
+ source?: DocumentSource;
151
+ }
152
+ /**
153
+ * Identifies a specific document type within a Sanity dataset and project.
154
+ * Includes `projectId`, `dataset`, and `documentType`.
155
+ * Optionally includes a `documentId` and `liveEdit` flag.
156
+ * @public
157
+ */
158
+ interface DocumentTypeHandle<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string> extends DatasetHandle<TDataset, TProjectId> {
159
+ documentId?: string;
160
+ documentType: TDocumentType;
161
+ /**
162
+ * Indicates whether this document uses liveEdit mode.
163
+ * When `true`, the document does not use the draft/published model and edits are applied directly to the document.
164
+ * @see https://www.sanity.io/docs/content-lake/drafts#ca0663a8f002
165
+ */
166
+ liveEdit?: boolean;
167
+ }
168
+ /**
169
+ * Uniquely identifies a specific document within a Sanity dataset and project.
170
+ * Includes `projectId`, `dataset`, `documentType`, and the required `documentId`.
171
+ * Commonly used by document-related hooks and components to reference a document without fetching its full content initially.
172
+ * @public
173
+ */
174
+ interface DocumentHandle<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string> extends DocumentTypeHandle<TDocumentType, TDataset, TProjectId> {
175
+ documentId: string;
176
+ }
177
+ /**
178
+ * Represents the complete configuration for a Sanity SDK instance
179
+ * @public
180
+ */
181
+ interface SanityConfig extends DatasetHandle, PerspectiveHandle {
182
+ /**
183
+ * Authentication configuration for the instance
184
+ * @remarks Merged with parent configurations when using createChild
185
+ */
186
+ auth?: AuthConfig;
187
+ /**
188
+ * Studio configuration provided by a Sanity Studio workspace.
189
+ * When present, the SDK operates in studio mode and derives auth from the
190
+ * workspace's reactive token source — no manual configuration needed.
191
+ *
192
+ * @remarks Typically set automatically by `SanityApp` when it detects an
193
+ * `SDKStudioContext` provider. Can also be set explicitly for programmatic use.
194
+ */
195
+ studio?: StudioConfig;
196
+ /**
197
+ * Studio mode configuration for use of the SDK in a Sanity Studio.
198
+ * @remarks Controls whether studio mode features are enabled.
199
+ * @deprecated Use `studio` instead, which provides richer integration
200
+ * with the Studio's workspace (auth token sync, etc.).
201
+ */
202
+ studioMode?: {
203
+ enabled: boolean;
204
+ };
205
+ /**
206
+ * @beta
207
+ * A list of named sources to use for this instance.
208
+ */
209
+ sources?: Record<string, DocumentSource>;
210
+ }
211
+ /**
212
+ * A document source can be used for querying.
213
+ * This will soon be the default way to identify where you are querying from.
214
+ *
215
+ * @beta
216
+ */
217
+ type DocumentSource = DatasetSource | MediaLibrarySource | CanvasSource;
218
+ /**
219
+ * @beta
220
+ */
221
+ type DatasetSource = {
222
+ projectId: string;
223
+ dataset: string;
224
+ };
225
+ /**
226
+ * @beta
227
+ */
228
+ type MediaLibrarySource = {
229
+ mediaLibraryId: string;
230
+ };
231
+ /**
232
+ * @beta
233
+ */
234
+ type CanvasSource = {
235
+ canvasId: string;
236
+ };
237
+ /**
238
+ * @beta
239
+ */
240
+ declare function isDatasetSource(source: DocumentSource): source is DatasetSource;
241
+ /**
242
+ * @beta
243
+ */
244
+ declare function isMediaLibrarySource(source: DocumentSource): source is MediaLibrarySource;
245
+ /**
246
+ * @beta
247
+ */
248
+ declare function isCanvasSource(source: DocumentSource): source is CanvasSource;
249
+ /**
250
+ * Returns `true` when the config indicates the SDK is running inside a Studio.
251
+ * Checks the new `studio` field first, then falls back to the deprecated
252
+ * `studioMode.enabled` for backwards compatibility.
253
+ *
254
+ * @internal
255
+ */
256
+ declare function isStudioConfig(config: SanityConfig): boolean;
257
+ /**
258
+ * Represents a Sanity.io resource instance with its own configuration and lifecycle
259
+ * @remarks Instances form a hierarchy through parent/child relationships
260
+ *
261
+ * @public
262
+ */
263
+ interface SanityInstance {
264
+ /**
265
+ * Unique identifier for this instance
266
+ * @remarks Generated using crypto.randomUUID()
267
+ */
268
+ readonly instanceId: string;
269
+ /**
270
+ * Resolved configuration for this instance
271
+ * @remarks Merges values from parent instances where appropriate
272
+ */
273
+ readonly config: SanityConfig;
274
+ /**
275
+ * Checks if the instance has been disposed
276
+ * @returns true if dispose() has been called
277
+ */
278
+ isDisposed(): boolean;
279
+ /**
280
+ * Disposes the instance and cleans up associated resources
281
+ * @remarks Triggers all registered onDispose callbacks
282
+ */
283
+ dispose(): void;
284
+ /**
285
+ * Registers a callback to be invoked when the instance is disposed
286
+ * @param cb - Callback to execute on disposal
287
+ * @returns Function to unsubscribe the callback
288
+ */
289
+ onDispose(cb: () => void): () => void;
290
+ /**
291
+ * Gets the parent instance in the hierarchy
292
+ * @returns Parent instance or undefined if this is the root
293
+ */
294
+ getParent(): SanityInstance | undefined;
295
+ /**
296
+ * Creates a child instance with merged configuration
297
+ * @param config - Configuration to merge with parent values
298
+ * @remarks Child instances inherit parent configuration but can override values
299
+ */
300
+ createChild(config: SanityConfig): SanityInstance;
301
+ /**
302
+ * Traverses the instance hierarchy to find the first instance whose configuration
303
+ * matches the given target config using a shallow comparison.
304
+ * @param targetConfig - A partial configuration object containing key-value pairs to match.
305
+ * @returns The first matching instance or undefined if no match is found.
306
+ */
307
+ match(targetConfig: Partial<SanityConfig>): SanityInstance | undefined;
308
+ }
309
+ /**
310
+ * Creates a new Sanity resource instance
311
+ * @param config - Configuration for the instance (optional)
312
+ * @returns A configured SanityInstance
313
+ * @remarks When creating child instances, configurations are merged with parent values
314
+ *
315
+ * @public
316
+ */
317
+ declare function createSanityInstance(config?: SanityConfig): SanityInstance;
318
+ /**
319
+ * Represents a reactive store state container with multiple access patterns
320
+ */
321
+ interface StoreState<TState> {
322
+ /**
323
+ * Gets the current state value
324
+ *
325
+ * @remarks
326
+ * This is a direct synchronous accessor that doesn't trigger subscriptions
327
+ */
328
+ get: () => TState;
329
+ /**
330
+ * Updates the store state
331
+ * @param name - Action name for devtools tracking
332
+ * @param updatedState - New state value or updater function
333
+ *
334
+ * @remarks
335
+ * When providing a partial object, previous top-level keys not included in
336
+ * the update will be preserved.
337
+ */
338
+ set: (name: string, updatedState: Partial<TState> | ((s: TState) => Partial<TState>)) => void;
339
+ /**
340
+ * Observable stream of state changes
341
+ * @remarks
342
+ * - Emits immediately with current state on subscription
343
+ * - Shares underlying subscription between observers
344
+ * - Only emits when state reference changes
345
+ * - Completes when store is disposed
346
+ */
347
+ observable: Observable<TState>;
348
+ }
349
+ /**
350
+ * Context object provided to store initialization functions
351
+ */
352
+ interface StoreContext<TState, TKey = unknown> {
353
+ /**
354
+ * Sanity instance associated with this store
355
+ *
356
+ * @remarks
357
+ * Provides access to the Sanity configuration and instance lifecycle methods
358
+ */
359
+ instance: SanityInstance;
360
+ /**
361
+ * Reactive store state management utilities
362
+ *
363
+ * @remarks
364
+ * Contains methods for getting/setting state and observing changes
365
+ */
366
+ state: StoreState<TState>;
367
+ /**
368
+ * The key used to instantiate the store.
369
+ */
370
+ key: TKey;
371
+ }
372
+ /** @alpha */
373
+ type AgentGenerateOptions = Parameters<SanityClient['observable']['agent']['action']['generate']>[0];
374
+ /** @alpha */
375
+ type AgentTransformOptions = Parameters<SanityClient['observable']['agent']['action']['transform']>[0];
376
+ /** @alpha */
377
+ type AgentTranslateOptions = Parameters<SanityClient['observable']['agent']['action']['translate']>[0];
378
+ /** @alpha */
379
+ type AgentPromptOptions = Parameters<SanityClient['agent']['action']['prompt']>[0];
380
+ /** @alpha */
381
+ type AgentPatchOptions = Parameters<SanityClient['agent']['action']['patch']>[0];
382
+ /** @alpha */
383
+ type AgentGenerateResult = Awaited<ReturnType<SanityClient['observable']['agent']['action']['generate']>>;
384
+ /** @alpha */
385
+ type AgentTransformResult = Awaited<ReturnType<SanityClient['observable']['agent']['action']['transform']>>;
386
+ /** @alpha */
387
+ type AgentTranslateResult = Awaited<ReturnType<SanityClient['observable']['agent']['action']['translate']>>;
388
+ /** @alpha */
389
+ type AgentPromptResult = Awaited<ReturnType<SanityClient['agent']['action']['prompt']>>;
390
+ /** @alpha */
391
+ type AgentPatchResult = Awaited<ReturnType<SanityClient['agent']['action']['patch']>>;
392
+ /**
393
+ * Generates a new document using the agent.
394
+ * @param instance - The Sanity instance.
395
+ * @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.
396
+ * @returns An Observable emitting the result of the agent generate action.
397
+ * @alpha
398
+ */
399
+ declare function agentGenerate(instance: SanityInstance, options: AgentGenerateOptions): AgentGenerateResult;
400
+ /**
401
+ * Transforms a document using the agent.
402
+ * @param instance - The Sanity instance.
403
+ * @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.
404
+ * @returns An Observable emitting the result of the agent transform action.
405
+ * @alpha
406
+ */
407
+ declare function agentTransform(instance: SanityInstance, options: AgentTransformOptions): AgentTransformResult;
408
+ /**
409
+ * Translates a document using the agent.
410
+ * @param instance - The Sanity instance.
411
+ * @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.
412
+ * @returns An Observable emitting the result of the agent translate action.
413
+ * @alpha
414
+ */
415
+ declare function agentTranslate(instance: SanityInstance, options: AgentTranslateOptions): AgentTranslateResult;
416
+ /**
417
+ * Prompts the agent using the same instruction template format as the other actions, but returns text or json instead of acting on a document.
418
+ * @param instance - The Sanity instance.
419
+ * @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.
420
+ * @returns An Observable emitting the result of the agent prompt action.
421
+ * @alpha
422
+ */
423
+ declare function agentPrompt(instance: SanityInstance, options: AgentPromptOptions): Observable<AgentPromptResult>;
424
+ /**
425
+ * Patches a document using the agent.
426
+ * @param instance - The Sanity instance.
427
+ * @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.
428
+ * @returns An Observable emitting the result of the agent patch action.
429
+ * @alpha
430
+ */
431
+ declare function agentPatch(instance: SanityInstance, options: AgentPatchOptions): Observable<AgentPatchResult>;
432
+ /**
433
+ * Represents the various states the authentication type can be in.
434
+ *
435
+ * @public
436
+ */
437
+ declare enum AuthStateType {
438
+ LOGGED_IN = "logged-in",
439
+ LOGGING_IN = "logging-in",
440
+ ERROR = "error",
441
+ LOGGED_OUT = "logged-out",
442
+ }
443
+ /**
444
+ * Error message returned by the organization verification
445
+ * @public
446
+ */
447
+ interface OrgVerificationResult {
448
+ error: string | null;
449
+ }
450
+ /**
451
+ * Creates an observable that emits the organization verification state for a given instance.
452
+ * It combines the dashboard organization ID (from auth context) with the
453
+ * project's actual organization ID (fetched via getProjectState) and compares them.
454
+ * @public
455
+ */
456
+ declare function observeOrganizationVerificationState(instance: SanityInstance, projectIds: string[]): Observable<OrgVerificationResult>;
457
+ /**
458
+ * Defines a store action that operates on a specific state type
459
+ */
460
+ type StoreAction<TState, TParams extends unknown[], TReturn, TKey = unknown> = (context: StoreContext<TState, TKey>, ...params: TParams) => TReturn;
461
+ /**
462
+ * Represents a store action that has been bound to a specific store instance
463
+ */
464
+ type BoundStoreAction<_TState, TParams extends unknown[], TReturn> = (instance: SanityInstance, ...params: TParams) => TReturn;
465
+ /**
466
+ * @public
467
+ */
468
+ declare const handleAuthCallback: BoundStoreAction<AuthStoreState, [locationHref?: string | undefined], Promise<string | false>>;
469
+ /**
470
+ * @public
471
+ */
472
+ declare const logout: BoundStoreAction<AuthStoreState, [], Promise<void>>;
473
+ type AllowedClientConfigKey = 'useCdn' | 'token' | 'perspective' | 'apiHost' | 'proxy' | 'withCredentials' | 'timeout' | 'maxRetries' | 'dataset' | 'projectId' | 'requestTagPrefix' | 'useProjectHostname';
474
+ /**
475
+ * States tracked by the client store
476
+ * @public
477
+ */
478
+ interface ClientStoreState {
479
+ token: string | null;
480
+ clients: { [TKey in string]?: SanityClient };
481
+ authMethod?: 'localstorage' | 'cookie';
482
+ }
483
+ /**
484
+ * Options used when retrieving a client instance from the client store.
485
+ *
486
+ * This interface extends the base {@link ClientConfig} and adds:
487
+ *
488
+ * - **apiVersion:** A required string indicating the API version for the client.
489
+ * - **scope:** An optional flag to choose between the project-specific client
490
+ * ('project') and the global client ('global'). When set to `'global'`, the
491
+ * global client is used.
492
+ *
493
+ * These options are utilized by `getClient` and `getClientState` to configure and
494
+ * return appropriate client instances that automatically handle authentication
495
+ * updates and configuration changes.
496
+ *
497
+ * @public
498
+ */
499
+ interface ClientOptions extends Pick<ClientConfig, AllowedClientConfigKey> {
500
+ /**
501
+ * An optional flag to choose between the default client (typically project-level)
502
+ * and the global client ('global'). When set to `'global'`, the global client
503
+ * is used.
504
+ */
505
+ 'scope'?: 'default' | 'global';
506
+ /**
507
+ * A required string indicating the API version for the client.
508
+ */
509
+ 'apiVersion': string;
510
+ /**
511
+ * @internal
512
+ */
513
+ '~experimental_resource'?: ClientConfig['~experimental_resource'];
514
+ /**
515
+ * @internal
516
+ */
517
+ 'source'?: DocumentSource;
518
+ }
519
+ /**
520
+ * Retrieves a Sanity client instance configured with the provided options.
521
+ *
522
+ * This function returns a client instance configured for the project or as a
523
+ * global client based on the options provided. It ensures efficient reuse of
524
+ * client instances by returning the same instance for the same options.
525
+ * For automatic handling of authentication token updates, consider using
526
+ * `getClientState`.
527
+ *
528
+ * @public
529
+ */
530
+ declare const getClient: BoundStoreAction<ClientStoreState, [options: ClientOptions], SanityClient>;
531
+ /**
532
+ * Returns a state source for the Sanity client instance.
533
+ *
534
+ * This function provides a subscribable state source that emits updated client
535
+ * instances whenever relevant configurations change (such as authentication tokens).
536
+ * Use this when you need to react to client configuration changes in your application.
537
+ *
538
+ * @public
539
+ */
540
+ declare const getClientState: BoundStoreAction<ClientStoreState, [options: ClientOptions], StateSource<SanityClient>>;
541
+ /**
542
+ * Message sent from a containing app to an iframe
543
+ * @public
544
+ */
545
+ type FrameMessage = Message;
546
+ /**
547
+ * Message sent from an iframe to a containing app
548
+ * @public
549
+ */
550
+ type WindowMessage = Message;
551
+ /**
552
+ * Message from SDK (iframe) to Parent (dashboard) to request a new token
553
+ * @internal
554
+ */
555
+ type RequestNewTokenMessage = {
556
+ type: 'dashboard/v1/auth/tokens/create';
557
+ payload?: undefined;
558
+ };
559
+ /**
560
+ * Message from Parent (dashboard) to SDK (iframe) with the new token
561
+ * @internal
562
+ */
563
+ type NewTokenResponseMessage = {
564
+ type: 'dashboard/v1/auth/tokens/create';
565
+ payload: {
566
+ token: string | null;
567
+ error?: string;
568
+ };
569
+ };
570
+ /**
571
+ * Individual channel with its relevant options
572
+ * @public
573
+ */
574
+ interface ChannelEntry {
575
+ channel: ChannelInstance<FrameMessage, WindowMessage>;
576
+ options: ChannelInput;
577
+ refCount: number;
578
+ }
579
+ /**
580
+ * Internal state tracking comlink connections
581
+ * @public
582
+ */
583
+ interface ComlinkControllerState {
584
+ controller: Controller | null;
585
+ controllerOrigin: string | null;
586
+ channels: Map<string, ChannelEntry>;
587
+ }
588
+ /**
589
+ * Calls the destroy method on the controller and resets the controller state.
590
+ * @public
591
+ */
592
+ declare const destroyController: BoundStoreAction<ComlinkControllerState, [], void>;
593
+ /**
594
+ * Retrieve or create a channel to be used for communication between
595
+ * an application and the controller.
596
+ * @public
597
+ */
598
+ declare const getOrCreateChannel: BoundStoreAction<ComlinkControllerState, [options: ChannelInput], ChannelInstance<_sanity_comlink5.Message, _sanity_comlink5.Message>>;
599
+ /**
600
+ * Initializes or fetches a controller to handle communication
601
+ * between an application and iframes.
602
+ * @public
603
+ */
604
+ declare const getOrCreateController: BoundStoreAction<ComlinkControllerState, [targetOrigin: string], Controller>;
605
+ /**
606
+ * Signals to the store that the consumer has stopped using the channel
607
+ * @public
608
+ */
609
+ declare const releaseChannel: BoundStoreAction<ComlinkControllerState, [name: string], void>;
610
+ /**
611
+ * Individual node with its relevant options
612
+ * @public
613
+ */
614
+ interface NodeEntry {
615
+ node: Node<WindowMessage, FrameMessage>;
616
+ options: NodeInput;
617
+ status: Status;
618
+ statusUnsub?: () => void;
619
+ }
620
+ /**
621
+ * Internal state tracking comlink connections
622
+ * @public
623
+ */
624
+ interface ComlinkNodeState {
625
+ nodes: Map<string, NodeEntry>;
626
+ subscriptions: Map<string, Set<symbol>>;
627
+ }
628
+ /**
629
+ * Signals to the store that the consumer has stopped using the node
630
+ * @public
631
+ */
632
+ declare const releaseNode: BoundStoreAction<ComlinkNodeState, [name: string], void>;
633
+ /**
634
+ * Retrieve or create a node to be used for communication between
635
+ * an application and the controller -- specifically, a node should
636
+ * be created within a frame / window to communicate with the controller.
637
+ * @public
638
+ */
639
+ declare const getOrCreateNode: BoundStoreAction<ComlinkNodeState, [options: NodeInput], Node<_sanity_comlink5.Message, _sanity_comlink5.Message>>;
640
+ /**
641
+ * @public
642
+ */
643
+ interface NodeState {
644
+ node: Node<WindowMessage, FrameMessage>;
645
+ status: Status | undefined;
646
+ }
647
+ /**
648
+ * Provides a subscribable state source for a node by name
649
+ * @param instance - The Sanity instance to get the node state for
650
+ * @param nodeInput - The configuration for the node to get the state for
651
+
652
+ * @returns A subscribable state source for the node
653
+ * @public
654
+ */
655
+ declare const getNodeState: BoundStoreAction<ComlinkNodeState, [NodeInput], StateSource<NodeState | undefined>>;
656
+ /**
657
+ * Creates or validates a `DocumentHandle` object.
658
+ * Ensures the provided object conforms to the `DocumentHandle` interface.
659
+ * @param handle - The object containing document identification properties.
660
+ * @returns The validated `DocumentHandle` object.
661
+ * @public
662
+ */
663
+ declare function createDocumentHandle<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string>(handle: DocumentHandle<TDocumentType, TDataset, TProjectId>): DocumentHandle<TDocumentType, TDataset, TProjectId>;
664
+ /**
665
+ * Creates or validates a `DocumentTypeHandle` object.
666
+ * Ensures the provided object conforms to the `DocumentTypeHandle` interface.
667
+ * @param handle - The object containing document type identification properties.
668
+ * @returns The validated `DocumentTypeHandle` object.
669
+ * @public
670
+ */
671
+ declare function createDocumentTypeHandle<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string>(handle: DocumentTypeHandle<TDocumentType, TDataset, TProjectId>): DocumentTypeHandle<TDocumentType, TDataset, TProjectId>;
672
+ /**
673
+ * Creates or validates a `ProjectHandle` object.
674
+ * Ensures the provided object conforms to the `ProjectHandle` interface.
675
+ * @param handle - The object containing project identification properties.
676
+ * @returns The validated `ProjectHandle` object.
677
+ * @public
678
+ */
679
+ declare function createProjectHandle<TProjectId extends string = string>(handle: ProjectHandle<TProjectId>): ProjectHandle<TProjectId>;
680
+ /**
681
+ * Creates or validates a `DatasetHandle` object.
682
+ * Ensures the provided object conforms to the `DatasetHandle` interface.
683
+ * @param handle - The object containing dataset identification properties.
684
+ * @returns The validated `DatasetHandle` object.
685
+ * @public
686
+ */
687
+ declare function createDatasetHandle<TDataset extends string = string, TProjectId extends string = string>(handle: DatasetHandle<TDataset, TProjectId>): DatasetHandle<TDataset, TProjectId>;
688
+ /**
689
+ * Logging infrastructure for the Sanity SDK
690
+ *
691
+ * Provides multi-level, namespace-based logging for both SDK users and maintainers.
692
+ * In production builds, all logging can be stripped via tree-shaking.
693
+ *
694
+ * @example SDK User
695
+ * ```ts
696
+ * import {configureLogging} from '@sanity/sdk'
697
+ *
698
+ * configureLogging({
699
+ * level: 'info',
700
+ * namespaces: ['auth', 'document']
701
+ * })
702
+ * ```
703
+ *
704
+ * @example SDK Maintainer
705
+ * ```ts
706
+ * configureLogging({
707
+ * level: 'trace',
708
+ * namespaces: ['*'],
709
+ * internal: true
710
+ * })
711
+ * ```
712
+ */
713
+ /**
714
+ * Log levels in order of verbosity (least to most)
715
+ * - error: Critical failures that prevent operation
716
+ * - warn: Issues that may cause problems but don't stop execution
717
+ * - info: High-level informational messages (SDK user level)
718
+ * - debug: Detailed debugging information (maintainer level)
719
+ * - trace: Very detailed tracing (maintainer level, includes RxJS streams)
720
+ * @public
721
+ */
722
+ type LogLevel = 'error' | 'warn' | 'info' | 'debug' | 'trace';
723
+ /**
724
+ * Log namespaces organize logs by functional domain
725
+ *
726
+ * @remarks
727
+ * This is an extensible string type. As logging is added to more modules,
728
+ * additional namespaces will be recognized. Currently implemented namespaces
729
+ * will be documented as they are added.
730
+ * @internal
731
+ */
732
+ type LogNamespace = string;
733
+ /**
734
+ * Configuration for the logging system
735
+ * @public
736
+ */
737
+ interface LoggerConfig {
738
+ /**
739
+ * Minimum log level to output
740
+ * @defaultValue 'warn'
741
+ */
742
+ level?: LogLevel;
743
+ /**
744
+ * Namespaces to enable. Use ['*'] for all namespaces
745
+ * @defaultValue []
746
+ * @remarks
747
+ * Available namespaces depend on which modules have logging integrated.
748
+ * Check the SDK documentation for the current list of instrumented modules.
749
+ * @example ['auth', 'document']
750
+ */
751
+ namespaces?: string[];
752
+ /**
753
+ * Enable internal/maintainer-level logging
754
+ * Shows RxJS streams, store internals, etc.
755
+ * @defaultValue false
756
+ */
757
+ internal?: boolean;
758
+ /**
759
+ * Custom log handler (for testing or custom output)
760
+ * @defaultValue console methods
761
+ */
762
+ handler?: LogHandler;
763
+ /**
764
+ * Enable timestamps in log output
765
+ * @defaultValue true
766
+ */
767
+ timestamps?: boolean;
768
+ /**
769
+ * Enable in production builds
770
+ * @defaultValue false
771
+ */
772
+ enableInProduction?: boolean;
773
+ }
774
+ /**
775
+ * Custom log handler interface
776
+ *
777
+ * @internal
778
+ */
779
+ interface LogHandler {
780
+ error: (message: string, context?: LogContext) => void;
781
+ warn: (message: string, context?: LogContext) => void;
782
+ info: (message: string, context?: LogContext) => void;
783
+ debug: (message: string, context?: LogContext) => void;
784
+ trace: (message: string, context?: LogContext) => void;
785
+ }
786
+ /**
787
+ * Context object attached to log messages
788
+ *
789
+ * This interface allows you to attach arbitrary contextual data to log messages.
790
+ * The index signature `[key: string]: unknown` enables you to add any custom
791
+ * properties relevant to your log entry (e.g., `userId`, `documentId`, `action`, etc.).
792
+ *
793
+ * **Sensitive data sanitization:**
794
+ * Top-level keys containing sensitive names (`token`, `password`, `secret`, `apiKey`,
795
+ * `authorization`) are automatically redacted to `[REDACTED]` in log output.
796
+ *
797
+ * @example
798
+ * ```ts
799
+ * logger.info('User logged in', {
800
+ * userId: '123', // Custom context
801
+ * action: 'login', // Custom context
802
+ * token: 'secret' // Will be redacted to [REDACTED]
803
+ * })
804
+ * ```
805
+ *
806
+ * @internal
807
+ */
808
+ interface LogContext {
809
+ /**
810
+ * Custom context properties that provide additional information about the log entry.
811
+ * Any key-value pairs can be added here (e.g., userId, documentId, requestId, etc.).
812
+ * Keys with sensitive names (token, password, secret, apiKey, authorization) are
813
+ * automatically sanitized.
814
+ */
815
+ [key: string]: unknown;
816
+ /** Error object if logging an error */
817
+ error?: Error | unknown;
818
+ /** Duration in milliseconds for timed operations */
819
+ duration?: number;
820
+ /** Stack trace for debugging */
821
+ stack?: string;
822
+ /** Instance context (automatically added when available) */
823
+ instanceContext?: InstanceContext;
824
+ }
825
+ /**
826
+ * Instance context information automatically added to logs
827
+ * @internal
828
+ */
829
+ interface InstanceContext {
830
+ /** Unique instance ID */
831
+ instanceId?: string;
832
+ /** Project ID */
833
+ projectId?: string;
834
+ /** Dataset name */
835
+ dataset?: string;
836
+ }
837
+ /**
838
+ * Logger instance for a specific namespace
839
+ * @internal
840
+ */
841
+ interface Logger {
842
+ readonly namespace: string;
843
+ error: (message: string, context?: LogContext) => void;
844
+ warn: (message: string, context?: LogContext) => void;
845
+ info: (message: string, context?: LogContext) => void;
846
+ debug: (message: string, context?: LogContext) => void;
847
+ trace: (message: string, context?: LogContext) => void;
848
+ /** Check if a log level is enabled (for performance-sensitive code) */
849
+ isLevelEnabled: (level: LogLevel) => boolean;
850
+ /** Create a child logger with extended context */
851
+ child: (context: LogContext) => Logger;
852
+ /** Get the instance context if available */
853
+ getInstanceContext: () => InstanceContext | undefined;
854
+ }
855
+ /**
856
+ * Configure logging for the Sanity SDK
857
+ *
858
+ * This function allows you to control what logs are output by the SDK,
859
+ * making it easier to debug issues in development or production.
860
+ *
861
+ * @remarks
862
+ * **Zero-Config via Environment Variable (Recommended):**
863
+ *
864
+ * The SDK automatically reads the `DEBUG` environment variable, making it
865
+ * easy to enable logging without code changes:
866
+ *
867
+ * ```bash
868
+ * # Enable all SDK logging at debug level
869
+ * DEBUG=sanity:* npm start
870
+ *
871
+ * # Enable specific namespaces
872
+ * DEBUG=sanity:auth,sanity:document npm start
873
+ *
874
+ * # Enable trace level for all namespaces
875
+ * DEBUG=sanity:trace:* npm start
876
+ *
877
+ * # Enable internal/maintainer logs
878
+ * DEBUG=sanity:*:internal npm start
879
+ * ```
880
+ *
881
+ * This matches the pattern used by Sanity CLI and Studio, making it familiar
882
+ * and easy for support teams to help troubleshoot issues.
883
+ *
884
+ * **Programmatic Configuration (Advanced):**
885
+ *
886
+ * For more control (custom handlers, dynamic configuration), call this function
887
+ * explicitly. Programmatic configuration overrides environment variables.
888
+ *
889
+ * **For Application Developers:**
890
+ * Use `info`, `warn`, or `error` levels to see high-level SDK activity
891
+ * without being overwhelmed by internal details.
892
+ *
893
+ * **For SDK Maintainers:**
894
+ * Use `debug` or `trace` levels with `internal: true` to see detailed
895
+ * information about store operations, RxJS streams, and state transitions.
896
+ *
897
+ * **Instance Context:**
898
+ * Logs automatically include instance information (projectId, dataset, instanceId)
899
+ * when available, making it easier to debug multi-instance scenarios:
900
+ * ```
901
+ * [INFO] [auth] [project:abc] [dataset:production] User logged in
902
+ * ```
903
+ *
904
+ * **Available Namespaces:**
905
+ * - `sdk` - SDK initialization, configuration, and lifecycle
906
+ * - `auth` - Authentication and authorization (when instrumented in the future)
907
+ * - And more as logging is added to modules
908
+ *
909
+ * @example Zero-config via environment variable (recommended for debugging)
910
+ * ```bash
911
+ * # Just set DEBUG and run your app - no code changes needed!
912
+ * DEBUG=sanity:* npm start
913
+ * ```
914
+ *
915
+ * @example Programmatic configuration (application developer)
916
+ * ```ts
917
+ * import {configureLogging} from '@sanity/sdk'
918
+ *
919
+ * // Log warnings and errors for auth and document operations
920
+ * configureLogging({
921
+ * level: 'warn',
922
+ * namespaces: ['auth', 'document']
923
+ * })
924
+ * ```
925
+ *
926
+ * @example Programmatic configuration (SDK maintainer)
927
+ * ```ts
928
+ * import {configureLogging} from '@sanity/sdk'
929
+ *
930
+ * // Enable all logs including internal traces
931
+ * configureLogging({
932
+ * level: 'trace',
933
+ * namespaces: ['*'],
934
+ * internal: true
935
+ * })
936
+ * ```
937
+ *
938
+ * @example Custom handler (for testing)
939
+ * ```ts
940
+ * import {configureLogging} from '@sanity/sdk'
941
+ *
942
+ * const logs: string[] = []
943
+ * configureLogging({
944
+ * level: 'info',
945
+ * namespaces: ['*'],
946
+ * handler: {
947
+ * error: (msg) => logs.push(msg),
948
+ * warn: (msg) => logs.push(msg),
949
+ * info: (msg) => logs.push(msg),
950
+ * debug: (msg) => logs.push(msg),
951
+ * trace: (msg) => logs.push(msg),
952
+ * }
953
+ * })
954
+ * ```
955
+ *
956
+ * @public
957
+ */
958
+ declare function configureLogging(config: LoggerConfig): void;
959
+ /** @public */
960
+ declare const getDatasetsState: BoundStoreAction<FetcherStoreState<[options?: ProjectHandle<string> | undefined], _sanity_client12.DatasetsResponse>, [options?: ProjectHandle<string> | undefined], StateSource<_sanity_client12.DatasetsResponse | undefined>>;
961
+ /** @public */
962
+ declare const resolveDatasets: BoundStoreAction<FetcherStoreState<[options?: ProjectHandle<string> | undefined], _sanity_client12.DatasetsResponse>, [options?: ProjectHandle<string> | undefined], Promise<_sanity_client12.DatasetsResponse>>;
963
+ /**
964
+ * Represents an action to create a new document.
965
+ * Specifies the document type and optionally a document ID (which will be treated as the published ID).
966
+ * @beta
967
+ */
968
+ interface CreateDocumentAction<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string> extends DocumentTypeHandle<TDocumentType, TDataset, TProjectId> {
969
+ type: 'document.create';
970
+ /**
971
+ * Optional initial field values for the document.
972
+ * These values will be set when the document is created.
973
+ * System fields (_id, _type, _rev, _createdAt, _updatedAt) are omitted as they are set automatically.
974
+ */
975
+ initialValue?: Partial<Omit<SanityDocument$2<TDocumentType, `${TProjectId}.${TDataset}`>, '_id' | '_type' | '_rev' | '_createdAt' | '_updatedAt'>>;
976
+ }
977
+ /**
978
+ * Represents an action to delete an existing document.
979
+ * Requires the full document handle including the document ID.
980
+ * @beta
981
+ */
982
+ interface DeleteDocumentAction<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string> extends DocumentHandle<TDocumentType, TDataset, TProjectId> {
983
+ type: 'document.delete';
984
+ }
985
+ /**
986
+ * Represents an action to edit an existing document using patches.
987
+ * Requires the full document handle and an array of patch operations.
988
+ * @beta
989
+ */
990
+ interface EditDocumentAction<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string> extends DocumentHandle<TDocumentType, TDataset, TProjectId> {
991
+ type: 'document.edit';
992
+ patches?: PatchOperations[];
993
+ }
994
+ /**
995
+ * Represents an action to publish the draft version of a document.
996
+ * Requires the full document handle.
997
+ * @beta
998
+ */
999
+ interface PublishDocumentAction<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string> extends DocumentHandle<TDocumentType, TDataset, TProjectId> {
1000
+ type: 'document.publish';
1001
+ }
1002
+ /**
1003
+ * Represents an action to unpublish a document, moving its published content to a draft.
1004
+ * Requires the full document handle.
1005
+ * @beta
1006
+ */
1007
+ interface UnpublishDocumentAction<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string> extends DocumentHandle<TDocumentType, TDataset, TProjectId> {
1008
+ type: 'document.unpublish';
1009
+ }
1010
+ /**
1011
+ * Represents an action to discard the draft changes of a document.
1012
+ * Requires the full document handle.
1013
+ * @beta
1014
+ */
1015
+ interface DiscardDocumentAction<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string> extends DocumentHandle<TDocumentType, TDataset, TProjectId> {
1016
+ type: 'document.discard';
1017
+ }
1018
+ /**
1019
+ * Union type representing all possible document actions within the SDK.
1020
+ * @beta
1021
+ */
1022
+ 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>;
1023
+ /**
1024
+ * Creates a `CreateDocumentAction` object.
1025
+ * @param doc - A handle identifying the document type, dataset, and project. An optional `documentId` can be provided.
1026
+ * @param initialValue - Optional initial field values for the document. (System fields are omitted as they are set automatically.)
1027
+ * @returns A `CreateDocumentAction` object ready for dispatch.
1028
+ * @beta
1029
+ */
1030
+ declare function createDocument<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string>(doc: DocumentTypeHandle<TDocumentType, TDataset, TProjectId>, initialValue?: Partial<Omit<SanityDocument$2<TDocumentType, `${TProjectId}.${TDataset}`>, '_id' | '_type' | '_rev' | '_createdAt' | '_updatedAt'>>): CreateDocumentAction<TDocumentType, TDataset, TProjectId>;
1031
+ /**
1032
+ * Creates a `DeleteDocumentAction` object.
1033
+ * @param doc - A handle uniquely identifying the document to be deleted.
1034
+ * @returns A `DeleteDocumentAction` object ready for dispatch.
1035
+ * @beta
1036
+ */
1037
+ declare function deleteDocument<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string>(doc: DocumentHandle<TDocumentType, TDataset, TProjectId>): DeleteDocumentAction<TDocumentType, TDataset, TProjectId>;
1038
+ /**
1039
+ * Creates an `EditDocumentAction` object with patches for modifying a document.
1040
+ * Accepts patches in either the standard `PatchOperations` format or as a `SanityMutatePatchMutation` from `@sanity/mutate`.
1041
+ *
1042
+ * @param doc - A handle uniquely identifying the document to be edited.
1043
+ * @param sanityMutatePatch - A patch mutation object from `@sanity/mutate`.
1044
+ * @returns An `EditDocumentAction` object ready for dispatch.
1045
+ * @beta
1046
+ */
1047
+ declare function editDocument<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string>(doc: DocumentHandle<TDocumentType, TDataset, TProjectId>, sanityMutatePatch: PatchMutation): EditDocumentAction<TDocumentType, TDataset, TProjectId>;
1048
+ /**
1049
+ * Creates an `EditDocumentAction` object with patches for modifying a document.
1050
+ *
1051
+ * @param doc - A handle uniquely identifying the document to be edited.
1052
+ * @param patches - A single patch operation or an array of patch operations.
1053
+ * @returns An `EditDocumentAction` object ready for dispatch.
1054
+ * @beta
1055
+ */
1056
+ declare function editDocument<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string>(doc: DocumentHandle<TDocumentType, TDataset, TProjectId>, patches?: PatchOperations | PatchOperations[]): EditDocumentAction<TDocumentType, TDataset, TProjectId>;
1057
+ /**
1058
+ * Creates a `PublishDocumentAction` object.
1059
+ * @param doc - A handle uniquely identifying the document to be published.
1060
+ * @returns A `PublishDocumentAction` object ready for dispatch.
1061
+ * @beta
1062
+ */
1063
+ declare function publishDocument<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string>(doc: DocumentHandle<TDocumentType, TDataset, TProjectId>): PublishDocumentAction<TDocumentType, TDataset, TProjectId>;
1064
+ /**
1065
+ * Creates an `UnpublishDocumentAction` object.
1066
+ * @param doc - A handle uniquely identifying the document to be unpublished.
1067
+ * @returns An `UnpublishDocumentAction` object ready for dispatch.
1068
+ * @beta
1069
+ */
1070
+ declare function unpublishDocument<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string>(doc: DocumentHandle<TDocumentType, TDataset, TProjectId>): UnpublishDocumentAction<TDocumentType, TDataset, TProjectId>;
1071
+ /**
1072
+ * Creates a `DiscardDocumentAction` object.
1073
+ * @param doc - A handle uniquely identifying the document whose draft changes are to be discarded.
1074
+ * @returns A `DiscardDocumentAction` object ready for dispatch.
1075
+ * @beta
1076
+ */
1077
+ declare function discardDocument<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string>(doc: DocumentHandle<TDocumentType, TDataset, TProjectId>): DiscardDocumentAction<TDocumentType, TDataset, TProjectId>;
1078
+ /**
1079
+ * Represents a reactive state source that provides synchronized access to store data
1080
+ *
1081
+ * @remarks
1082
+ * Designed to work with React's useSyncExternalStore hook. Provides three ways to access data:
1083
+ * 1. `getCurrent()` for synchronous current value access
1084
+ * 2. `subscribe()` for imperative change notifications
1085
+ * 3. `observable` for reactive stream access
1086
+ *
1087
+ * @public
1088
+ */
1089
+ interface StateSource<T> {
1090
+ /**
1091
+ * Subscribes to state changes with optional callback
1092
+ * @param onStoreChanged - Called whenever relevant state changes occur
1093
+ * @returns Unsubscribe function to clean up the subscription
1094
+ */
1095
+ subscribe: (onStoreChanged?: () => void) => () => void;
1096
+ /**
1097
+ * Gets the current derived state value
1098
+ *
1099
+ * @remarks
1100
+ * Safe to call without subscription. Will always return the latest value
1101
+ * based on the current store state and selector parameters.
1102
+ */
1103
+ getCurrent: () => T;
1104
+ /**
1105
+ * Observable stream of state values
1106
+ *
1107
+ * @remarks
1108
+ * Shares a single underlying subscription between all observers. Emits:
1109
+ * - Immediately with current value on subscription
1110
+ * - On every relevant state change
1111
+ * - Errors if selector throws
1112
+ */
1113
+ observable: Observable<T>;
1114
+ }
1115
+ /**
1116
+ * Context passed to selectors when deriving state
1117
+ *
1118
+ * @remarks
1119
+ * Provides access to both the current state value and the Sanity instance,
1120
+ * allowing selectors to use configuration values when computing derived state.
1121
+ * The context is memoized for each state object and instance combination
1122
+ * to optimize performance and prevent unnecessary recalculations.
1123
+ *
1124
+ * @example
1125
+ * ```ts
1126
+ * // Using both state and instance in a selector (psuedo example)
1127
+ * const getUserByProjectId = createStateSourceAction(
1128
+ * ({ state, instance }: SelectorContext<UsersState>, options?: ProjectHandle) => {
1129
+ * const allUsers = state.users
1130
+ * const projectId = options?.projectId ?? instance.config.projectId
1131
+ * return allUsers.filter(user => user.projectId === projectId)
1132
+ * }
1133
+ * )
1134
+ * ```
1135
+ */
1136
+ interface SelectorContext<TState> {
1137
+ /**
1138
+ * The current state object from the store
1139
+ */
1140
+ state: TState;
1141
+ /**
1142
+ * The Sanity instance associated with this state
1143
+ */
1144
+ instance: SanityInstance;
1145
+ }
1146
+ /**
1147
+ * Function type for selecting derived state from store state and parameters
1148
+ * @public
1149
+ */
1150
+ type Selector<TState, TParams extends unknown[], TReturn> = (context: SelectorContext<TState>, ...params: TParams) => TReturn;
1151
+ /**
1152
+ * Split the entire path string on dots "outside" of any brackets.
1153
+ *
1154
+ * For example:
1155
+ * ```
1156
+ * "friends[0].name"
1157
+ * ```
1158
+ *
1159
+ * becomes:
1160
+ *
1161
+ * ```
1162
+ * [...ParseSegment<"friends[0]">, ...ParseSegment<"name">]
1163
+ * ```
1164
+ *
1165
+ * (We use a simple recursion that splits on the first dot.)
1166
+ */
1167
+ type PathParts<TPath extends string> = TPath extends `${infer Head}.${infer Tail}` ? [Head, ...PathParts<Tail>] : TPath extends '' ? [] : [TPath];
1168
+ /**
1169
+ * Given a type T and an array of "access keys" Parts, recursively index into T.
1170
+ *
1171
+ * If a part is a key, it looks up that property.
1172
+ * If T is an array and the part is a number, it "indexes" into the element type.
1173
+ */
1174
+ 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,
1175
+ // Key/index doesn't exist
1176
+ TTail extends readonly (string | number)[] ? TTail : []> : never;
1177
+ /**
1178
+ * Given a document type TDocument and a JSON Match path string TPath,
1179
+ * compute the type found at that path.
1180
+ * @beta
1181
+ */
1182
+ type JsonMatch<TDocument, TPath extends string> = DeepGet<TDocument, PathParts<TPath>>;
1183
+ /**
1184
+ * Represents a set of document that will go into `applyMutations`. Before
1185
+ * applying a mutation, it's expected that all relevant documents that the
1186
+ * mutations affect are included, including those that do not exist yet.
1187
+ * Documents that don't exist have a `null` value.
1188
+ */
1189
+ type DocumentSet<TDocument extends SanityDocument$1 = SanityDocument$1> = { [TDocumentId in string]?: TDocument | null };
1190
+ type Grant = 'read' | 'update' | 'create' | 'history';
1191
+ /** @beta */
1192
+ interface PermissionDeniedReason {
1193
+ type: 'precondition' | 'access';
1194
+ message: string;
1195
+ documentId?: string;
1196
+ }
1197
+ /** @beta */
1198
+ type DocumentPermissionsResult = {
1199
+ allowed: false;
1200
+ message: string;
1201
+ reasons: PermissionDeniedReason[];
1202
+ } | {
1203
+ allowed: true;
1204
+ message?: undefined;
1205
+ reasons?: undefined;
1206
+ };
1207
+ interface SharedListener {
1208
+ events: Observable<ListenEvent<SanityDocument>>;
1209
+ dispose: () => void;
1210
+ }
1211
+ interface DocumentStoreState {
1212
+ documentStates: { [TDocumentId in string]?: DocumentState };
1213
+ queued: QueuedTransaction[];
1214
+ applied: AppliedTransaction[];
1215
+ outgoing?: OutgoingTransaction;
1216
+ grants?: Record<Grant, ExprNode>;
1217
+ error?: unknown;
1218
+ sharedListener: SharedListener;
1219
+ fetchDocument: (documentId: string) => Observable<SanityDocument$2 | null>;
1220
+ events: Subject<DocumentEvent>;
1221
+ }
1222
+ interface DocumentState {
1223
+ id: string;
1224
+ /**
1225
+ * the "remote" local copy that matches the server. represents the last known
1226
+ * server state. this gets updated every time we confirm remote patches
1227
+ */
1228
+ remote?: SanityDocument$2 | null;
1229
+ /**
1230
+ * the current ephemeral working copy that includes local optimistic changes
1231
+ * that have not yet been confirmed by the server
1232
+ */
1233
+ local?: SanityDocument$2 | null;
1234
+ /**
1235
+ * the revision that our remote document is at
1236
+ */
1237
+ remoteRev?: string | null;
1238
+ /**
1239
+ * Array of subscription IDs. This document state will be deleted if there are
1240
+ * no subscribers.
1241
+ */
1242
+ subscriptions: string[];
1243
+ /**
1244
+ * An object keyed by transaction ID of revisions sent out but that have not
1245
+ * yet been verified yet. When an applied transaction is transitioned to an
1246
+ * outgoing transaction, it also adds unverified revisions for each document
1247
+ * that is part of that outgoing transaction. Transactions are submitted to
1248
+ * the server with a locally generated transaction ID. This way we can observe
1249
+ * when our transaction comes back through the shared listener. Each listener
1250
+ * event that comes back contains a `previousRev`. If we see our own
1251
+ * transaction with a different `previousRev` than expected, we can rebase our
1252
+ * local transactions on top of this new remote.
1253
+ */
1254
+ unverifiedRevisions?: { [TTransactionId in string]?: UnverifiedDocumentRevision };
1255
+ }
1256
+ /**
1257
+ * @beta
1258
+ * Options for specifying a document and optionally a path within it.
1259
+ */
1260
+ interface DocumentOptions<TPath extends string | undefined = undefined, TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string> extends DocumentHandle<TDocumentType, TDataset, TProjectId> {
1261
+ path?: TPath;
1262
+ }
1263
+ /** @beta */
1264
+ declare function getDocumentState<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string>(instance: SanityInstance, options: DocumentOptions<undefined, TDocumentType, TDataset, TProjectId>): StateSource<SanityDocument$2<TDocumentType, `${TProjectId}.${TDataset}`> | undefined | null>;
1265
+ /** @beta */
1266
+ 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<SanityDocument$2<TDocumentType, `${TProjectId}.${TDataset}`>, TPath> | undefined>;
1267
+ /** @beta */
1268
+ declare function getDocumentState<TData>(instance: SanityInstance, options: DocumentOptions<string | undefined>): StateSource<TData | undefined | null>;
1269
+ /** @beta */
1270
+ declare function resolveDocument<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string>(instance: SanityInstance, docHandle: DocumentHandle<TDocumentType, TDataset, TProjectId>): Promise<SanityDocument$2<TDocumentType, `${TProjectId}.${TDataset}`> | null>;
1271
+ /** @beta */
1272
+ declare function resolveDocument<TData extends SanityDocument$2>(instance: SanityInstance, docHandle: DocumentHandle<string, string, string>): Promise<TData | null>;
1273
+ /** @beta */
1274
+ declare const getDocumentSyncStatus: BoundStoreAction<DocumentStoreState, [doc: DocumentHandle<string, string, string>], StateSource<boolean | undefined>>;
1275
+ type PermissionsStateOptions = {
1276
+ source?: DocumentSource;
1277
+ actions: DocumentAction[];
1278
+ };
1279
+ /** @beta */
1280
+ declare const getPermissionsState: BoundStoreAction<DocumentStoreState, [PermissionsStateOptions], StateSource<DocumentPermissionsResult>>;
1281
+ /** @beta */
1282
+ declare const resolvePermissions: BoundStoreAction<DocumentStoreState, [options: PermissionsStateOptions], Promise<DocumentPermissionsResult>>;
1283
+ /** @beta */
1284
+ declare const subscribeDocumentEvents: BoundStoreAction<DocumentStoreState, [options: {
1285
+ source?: DocumentSource;
1286
+ eventHandler: (e: DocumentEvent) => void;
1287
+ }], () => void>;
1288
+ type ActionMap = {
1289
+ create: 'sanity.action.document.version.create';
1290
+ discard: 'sanity.action.document.version.discard';
1291
+ unpublish: 'sanity.action.document.unpublish';
1292
+ delete: 'sanity.action.document.delete';
1293
+ edit: 'sanity.action.document.edit';
1294
+ publish: 'sanity.action.document.publish';
1295
+ };
1296
+ type OptimisticLock = {
1297
+ ifDraftRevisionId?: string;
1298
+ ifPublishedRevisionId?: string;
1299
+ };
1300
+ type HttpAction = {
1301
+ actionType: ActionMap['create'];
1302
+ publishedId: string;
1303
+ attributes: SanityDocumentLike;
1304
+ } | {
1305
+ actionType: ActionMap['discard'];
1306
+ versionId: string;
1307
+ purge?: boolean;
1308
+ } | {
1309
+ actionType: ActionMap['unpublish'];
1310
+ draftId: string;
1311
+ publishedId: string;
1312
+ } | {
1313
+ actionType: ActionMap['delete'];
1314
+ publishedId: string;
1315
+ includeDrafts?: string[];
1316
+ } | {
1317
+ actionType: ActionMap['edit'];
1318
+ draftId: string;
1319
+ publishedId: string;
1320
+ patch: PatchOperations;
1321
+ } | ({
1322
+ actionType: ActionMap['publish'];
1323
+ draftId: string;
1324
+ publishedId: string;
1325
+ } & OptimisticLock);
1326
+ /**
1327
+ * Represents a transaction that is queued to be applied but has not yet been
1328
+ * applied. A transaction will remain in a queued state until all required
1329
+ * documents for the transactions are available locally.
1330
+ */
1331
+ interface QueuedTransaction {
1332
+ /**
1333
+ * the ID of this transaction. this is generated client-side.
1334
+ */
1335
+ transactionId: string;
1336
+ /**
1337
+ * the high-level actions associated with this transaction. note that these
1338
+ * actions don't mention draft IDs and is meant to abstract away the draft
1339
+ * model from users.
1340
+ */
1341
+ actions: DocumentAction[];
1342
+ /**
1343
+ * An optional flag set to disable this transaction from being batched with
1344
+ * other transactions.
1345
+ */
1346
+ disableBatching?: boolean;
1347
+ }
1348
+ /**
1349
+ * Represents a transaction that has been applied locally but has not been
1350
+ * committed/transitioned-to-outgoing. These transactions are visible to the
1351
+ * user but may be rebased upon a new working document set. Applied transactions
1352
+ * also contain the resulting `outgoingActions` that will be submitted to
1353
+ * Content Lake. These `outgoingActions` depend on the state of the working
1354
+ * documents so they are recomputed on rebase and are only relevant to applied
1355
+ * actions (we cannot compute `outgoingActions` for queued transactions because
1356
+ * we haven't resolved the set of documents the actions are dependent on yet).
1357
+ *
1358
+ * In order to support better conflict resolution, the original `previous` set
1359
+ * is saved as the `base` set.
1360
+ */
1361
+ interface AppliedTransaction extends QueuedTransaction {
1362
+ /**
1363
+ * the resulting set of documents after the actions have been applied
1364
+ */
1365
+ working: DocumentSet;
1366
+ /**
1367
+ * the previous set of documents before the action was applied
1368
+ */
1369
+ previous: DocumentSet;
1370
+ /**
1371
+ * the original `previous` document set captured when this action was
1372
+ * originally applied. this is used as a reference point to do a 3-way merge
1373
+ * if this applied transaction ever needs to be reapplied on a different
1374
+ * set of documents.
1375
+ */
1376
+ base: DocumentSet;
1377
+ /**
1378
+ * the `_rev`s from `previous` document set
1379
+ */
1380
+ previousRevs: { [TDocumentId in string]?: string };
1381
+ /**
1382
+ * a timestamp for when this transaction was applied locally
1383
+ */
1384
+ timestamp: string;
1385
+ /**
1386
+ * the resulting HTTP actions derived from the state of the `working` document
1387
+ * set. these are sent to Content Lake as-is when this transaction is batched
1388
+ * and transitioned into an outgoing transaction.
1389
+ */
1390
+ outgoingActions: HttpAction[];
1391
+ /**
1392
+ * similar to `outgoingActions` but comprised of mutations instead of actions.
1393
+ * Useful for debugging, and is also used by liveEdit documents to send mutations,
1394
+ * since they can't use the Actions API which is pretty dependent on the draft model.
1395
+ */
1396
+ outgoingMutations: Mutation[];
1397
+ }
1398
+ /**
1399
+ * Represents a set of applied transactions batched into a single outgoing
1400
+ * transaction. An outgoing transaction is the result of batching many applied
1401
+ * actions. An outgoing transaction may be reverted locally if the server
1402
+ * does not accept it.
1403
+ */
1404
+ interface OutgoingTransaction extends AppliedTransaction {
1405
+ disableBatching: boolean;
1406
+ batchedTransactionIds: string[];
1407
+ }
1408
+ interface UnverifiedDocumentRevision {
1409
+ transactionId: string;
1410
+ documentId: string;
1411
+ previousRev: string | undefined;
1412
+ timestamp: string;
1413
+ }
1414
+ /** @beta Response body from submitting an outgoing transaction (actions or mutations API). */
1415
+ type DocumentTransactionSubmissionResult = Awaited<ReturnType<SanityClient['action']>> | MultipleMutationResult;
1416
+ /** @beta */
1417
+ type DocumentEvent = ActionErrorEvent | TransactionRevertedEvent | TransactionAcceptedEvent | DocumentRebaseErrorEvent | DocumentEditedEvent | DocumentCreatedEvent | DocumentDeletedEvent | DocumentPublishedEvent | DocumentUnpublishedEvent | DocumentDiscardedEvent;
1418
+ /**
1419
+ * @beta
1420
+ * Event emitted when a precondition to applying an action fails.
1421
+ * (For example: when trying to edit a document that no longer exists.)
1422
+ */
1423
+ interface ActionErrorEvent {
1424
+ type: 'error';
1425
+ documentId: string;
1426
+ transactionId: string;
1427
+ message: string;
1428
+ error: unknown;
1429
+ }
1430
+ /**
1431
+ * @beta
1432
+ * Event emitted when a transaction is accepted.
1433
+ */
1434
+ interface TransactionAcceptedEvent {
1435
+ type: 'accepted';
1436
+ outgoing: OutgoingTransaction;
1437
+ result: DocumentTransactionSubmissionResult;
1438
+ }
1439
+ /**
1440
+ * @beta
1441
+ * Event emitted when a transaction is reverted.
1442
+ */
1443
+ interface TransactionRevertedEvent {
1444
+ type: 'reverted';
1445
+ message: string;
1446
+ error: unknown;
1447
+ outgoing: OutgoingTransaction;
1448
+ }
1449
+ /**
1450
+ * @beta
1451
+ * Event emitted when an attempt to apply local changes to a modified remote document fails.
1452
+ */
1453
+ interface DocumentRebaseErrorEvent {
1454
+ type: 'rebase-error';
1455
+ documentId: string;
1456
+ transactionId: string;
1457
+ message: string;
1458
+ error: unknown;
1459
+ }
1460
+ /**
1461
+ * @beta
1462
+ * Event emitted when a document is edited.
1463
+ */
1464
+ interface DocumentEditedEvent {
1465
+ type: 'edited';
1466
+ documentId: string;
1467
+ outgoing: OutgoingTransaction;
1468
+ }
1469
+ /**
1470
+ * @beta
1471
+ * Event emitted when a document is created.
1472
+ */
1473
+ interface DocumentCreatedEvent {
1474
+ type: 'created';
1475
+ documentId: string;
1476
+ outgoing: OutgoingTransaction;
1477
+ }
1478
+ /**
1479
+ * @beta
1480
+ * Event emitted when a document is deleted.
1481
+ */
1482
+ interface DocumentDeletedEvent {
1483
+ type: 'deleted';
1484
+ documentId: string;
1485
+ outgoing: OutgoingTransaction;
1486
+ }
1487
+ /**
1488
+ * @beta
1489
+ * Event emitted when a document is published.
1490
+ */
1491
+ interface DocumentPublishedEvent {
1492
+ type: 'published';
1493
+ documentId: string;
1494
+ outgoing: OutgoingTransaction;
1495
+ }
1496
+ /**
1497
+ * @beta
1498
+ * Event emitted when a document is unpublished.
1499
+ */
1500
+ interface DocumentUnpublishedEvent {
1501
+ type: 'unpublished';
1502
+ documentId: string;
1503
+ outgoing: OutgoingTransaction;
1504
+ }
1505
+ /**
1506
+ * @beta
1507
+ * Event emitted when a document version is discarded.
1508
+ */
1509
+ interface DocumentDiscardedEvent {
1510
+ type: 'discarded';
1511
+ documentId: string;
1512
+ outgoing: OutgoingTransaction;
1513
+ }
1514
+ /** @beta */
1515
+ interface ActionsResult<TDocument extends SanityDocument$2 = SanityDocument$2> {
1516
+ transactionId: string;
1517
+ documents: DocumentSet<TDocument>;
1518
+ previous: DocumentSet<TDocument>;
1519
+ previousRevs: {
1520
+ [documentId: string]: string | undefined;
1521
+ };
1522
+ appeared: string[];
1523
+ updated: string[];
1524
+ disappeared: string[];
1525
+ submitted: () => Promise<DocumentTransactionSubmissionResult>;
1526
+ }
1527
+ /** @beta */
1528
+ interface ApplyDocumentActionsOptions {
1529
+ /**
1530
+ * List of actions to apply.
1531
+ */
1532
+ actions: DocumentAction[];
1533
+ /**
1534
+ * The source to which the documents being acted on belong.
1535
+ */
1536
+ source?: DocumentSource;
1537
+ /**
1538
+ * Optionally provide an ID to be used as this transaction ID
1539
+ */
1540
+ transactionId?: string;
1541
+ /**
1542
+ * Set this to true to prevent this action from being batched with others.
1543
+ */
1544
+ disableBatching?: boolean;
1545
+ }
1546
+ /** @beta */
1547
+ declare function applyDocumentActions<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string>(instance: SanityInstance, options: ApplyDocumentActionsOptions): Promise<ActionsResult<SanityDocument$2<TDocumentType, `${TProjectId}.${TDataset}`>>>;
1548
+ /** @beta */
1549
+ declare function applyDocumentActions(instance: SanityInstance, options: ApplyDocumentActionsOptions): Promise<ActionsResult>;
1550
+ /**
1551
+ * @public
1552
+ */
1553
+ interface FavoriteStatusResponse {
1554
+ isFavorited: boolean;
1555
+ }
1556
+ /**
1557
+ * @public
1558
+ */
1559
+ interface FavoriteDocumentContext extends DocumentHandle {
1560
+ resourceId: string;
1561
+ resourceType: StudioResource['type'] | MediaResource['type'] | CanvasResource['type'];
1562
+ schemaName?: string;
1563
+ }
1564
+ /**
1565
+ * Gets a StateSource for the favorite status of a document.
1566
+ * @param instance - The Sanity instance.
1567
+ * @param context - The document context including ID, type, and resource information.
1568
+ * @returns A StateSource emitting `{ isFavorited: boolean }`.
1569
+ * @public
1570
+ */
1571
+ declare const getFavoritesState: BoundStoreAction<FetcherStoreState<[FavoriteDocumentContext], FavoriteStatusResponse>, [FavoriteDocumentContext], StateSource<FavoriteStatusResponse | undefined>>;
1572
+ /**
1573
+ * Resolves the favorite status for a document.
1574
+ * @param instance - The Sanity instance.
1575
+ * @param context - The document context including ID, type, and resource information.
1576
+ * @returns A Promise resolving to `{ isFavorited: boolean }`.
1577
+ * @public
1578
+ */
1579
+ declare const resolveFavoritesState: BoundStoreAction<FetcherStoreState<[FavoriteDocumentContext], FavoriteStatusResponse>, [FavoriteDocumentContext], Promise<FavoriteStatusResponse>>;
1580
+ /**
1581
+ * @public
1582
+ */
1583
+ interface SanityUser {
1584
+ sanityUserId: string;
1585
+ profile: UserProfile;
1586
+ memberships: Membership[];
1587
+ }
1588
+ /**
1589
+ * @public
1590
+ */
1591
+ interface Membership {
1592
+ addedAt?: string;
1593
+ resourceType: string;
1594
+ resourceId: string;
1595
+ roleNames: Array<string>;
1596
+ lastSeenAt?: string | null;
1597
+ }
1598
+ /**
1599
+ * @public
1600
+ */
1601
+ interface UserProfile {
1602
+ id: string;
1603
+ displayName: string;
1604
+ email: string;
1605
+ familyName?: string;
1606
+ givenName?: string;
1607
+ middleName?: string | null;
1608
+ imageUrl?: string;
1609
+ provider: string;
1610
+ tosAcceptedAt?: string;
1611
+ createdAt: string;
1612
+ updatedAt?: string;
1613
+ isCurrentUser?: boolean;
1614
+ providerId?: string;
1615
+ }
1616
+ /**
1617
+ * @public
1618
+ */
1619
+ interface GetUsersOptions extends ProjectHandle {
1620
+ resourceType?: 'organization' | 'project';
1621
+ batchSize?: number;
1622
+ organizationId?: string;
1623
+ userId?: string;
1624
+ }
1625
+ /**
1626
+ * @public
1627
+ */
1628
+ interface UsersGroupState {
1629
+ subscriptions: string[];
1630
+ totalCount?: number;
1631
+ nextCursor?: string | null;
1632
+ lastLoadMoreRequest?: string;
1633
+ users?: SanityUser[];
1634
+ error?: unknown;
1635
+ }
1636
+ /**
1637
+ * @public
1638
+ */
1639
+ interface SanityUserResponse {
1640
+ data: SanityUser[];
1641
+ totalCount: number;
1642
+ nextCursor: string | null;
1643
+ }
1644
+ /**
1645
+ * @public
1646
+ */
1647
+ interface UsersStoreState {
1648
+ users: { [TUsersKey in string]?: UsersGroupState };
1649
+ error?: unknown;
1650
+ }
1651
+ /**
1652
+ * @public
1653
+ */
1654
+ interface ResolveUsersOptions extends GetUsersOptions {
1655
+ signal?: AbortSignal;
1656
+ }
1657
+ /**
1658
+ * @public
1659
+ */
1660
+ interface GetUserOptions extends ProjectHandle {
1661
+ userId: string;
1662
+ resourceType?: 'organization' | 'project';
1663
+ organizationId?: string;
1664
+ }
1665
+ /**
1666
+ * @public
1667
+ */
1668
+ interface ResolveUserOptions extends GetUserOptions {
1669
+ signal?: AbortSignal;
1670
+ }
1671
+ /** @public */
1672
+ interface PresenceLocation {
1673
+ type: 'document';
1674
+ documentId: string;
1675
+ path: string[];
1676
+ lastActiveAt: string;
1677
+ }
1678
+ /** @public */
1679
+ interface UserPresence {
1680
+ user: SanityUser;
1681
+ locations: PresenceLocation[];
1682
+ sessionId: string;
1683
+ }
1684
+ /** @public */
1685
+ type TransportEvent = RollCallEvent | StateEvent | DisconnectEvent;
1686
+ /** @public */
1687
+ interface RollCallEvent {
1688
+ type: 'rollCall';
1689
+ userId: string;
1690
+ sessionId: string;
1691
+ }
1692
+ /** @public */
1693
+ interface StateEvent {
1694
+ type: 'state';
1695
+ userId: string;
1696
+ sessionId: string;
1697
+ timestamp: string;
1698
+ locations: PresenceLocation[];
1699
+ }
1700
+ /** @public */
1701
+ interface DisconnectEvent {
1702
+ type: 'disconnect';
1703
+ userId: string;
1704
+ sessionId: string;
1705
+ timestamp: string;
1706
+ }
1707
+ type PresenceStoreState = {
1708
+ locations: Map<string, {
1709
+ userId: string;
1710
+ locations: PresenceLocation[];
1711
+ }>;
1712
+ users: Record<string, SanityUser | undefined>;
1713
+ };
1714
+ /** @public */
1715
+
1716
+ /** @public */
1717
+ declare const getPresence: BoundStoreAction<PresenceStoreState, [((object & {
1718
+ projectId?: string;
1719
+ dataset?: string;
1720
+ }) | undefined)?, ...unknown[]], StateSource<UserPresence[]>>;
1721
+ /**
1722
+ * @public
1723
+ * The result of a projection query
1724
+ */
1725
+ interface ProjectionValuePending<TValue extends object> {
1726
+ data: TValue | null;
1727
+ isPending: boolean;
1728
+ }
1729
+ /**
1730
+ * @public
1731
+ * @deprecated
1732
+ * Template literals are a bit too limited, so this type is deprecated.
1733
+ * Use `string` instead. Projection strings are validated at runtime.
1734
+ */
1735
+ type ValidProjection = string;
1736
+ interface DocumentStatus {
1737
+ lastEditedDraftAt?: string;
1738
+ lastEditedPublishedAt?: string;
1739
+ lastEditedVersionAt?: string;
1740
+ }
1741
+ /**
1742
+ *
1743
+ * @internal
1744
+ */
1745
+ interface PreviewQueryResult {
1746
+ _id: string;
1747
+ _type: string;
1748
+ _updatedAt: string;
1749
+ titleCandidates: Record<string, unknown>;
1750
+ subtitleCandidates: Record<string, unknown>;
1751
+ media?: PreviewMedia | null;
1752
+ _status?: DocumentStatus;
1753
+ }
1754
+ /**
1755
+ * Represents a media asset in a preview.
1756
+ *
1757
+ * @public
1758
+ */
1759
+ interface PreviewMedia {
1760
+ type: 'image-asset';
1761
+ _ref: string;
1762
+ url: string;
1763
+ }
1764
+ /**
1765
+ * Represents the set of values displayed as a preview for a given Sanity document.
1766
+ * This includes a primary title, a secondary subtitle, an optional piece of media associated
1767
+ * with the document, and the document's status.
1768
+ *
1769
+ * @public
1770
+ */
1771
+ interface PreviewValue {
1772
+ /**
1773
+ * The primary text displayed for the document preview.
1774
+ */
1775
+ title: string;
1776
+ /**
1777
+ * A secondary line of text providing additional context about the document.
1778
+ */
1779
+ subtitle?: string;
1780
+ /**
1781
+ * An optional piece of media representing the document within its preview.
1782
+ * Currently, only image assets are available.
1783
+ */
1784
+ media?: PreviewMedia | null;
1785
+ /**
1786
+ * The status of the document.
1787
+ */
1788
+ _status?: {
1789
+ /** The date of the last published edit */
1790
+ lastEditedPublishedAt?: string;
1791
+ /** The date of the last draft edit */
1792
+ lastEditedDraftAt?: string;
1793
+ };
1794
+ }
1795
+ /**
1796
+ * Represents the current state of a preview value along with a flag indicating whether
1797
+ * the preview data is still being fetched or is fully resolved.
1798
+ *
1799
+ * The tuple contains a preview value or null, and a boolean indicating if the data is
1800
+ * pending. A `true` value means a fetch is ongoing; `false` indicates that the
1801
+ * currently provided preview value is up-to-date.
1802
+ *
1803
+ * @public
1804
+ */
1805
+ type ValuePending<T> = {
1806
+ data: T | null;
1807
+ isPending: boolean;
1808
+ };
1809
+ /**
1810
+ * @public
1811
+ * @deprecated This interface is kept for backwards compatibility but is no longer used internally.
1812
+ * Preview state is now stored in the projection store.
1813
+ */
1814
+ interface PreviewStoreState {
1815
+ values: { [TDocumentId in string]?: ValuePending<PreviewValue> };
1816
+ subscriptions: { [TDocumentId in string]?: { [TSubscriptionId in string]?: true } };
1817
+ }
1818
+ /**
1819
+ * @beta
1820
+ * @deprecated This type is deprecated and will be removed in a future release.
1821
+ */
1822
+ type GetPreviewStateOptions = DocumentHandle;
1823
+ /**
1824
+ * @beta
1825
+ * @deprecated This function is deprecated and will be removed in a future release.
1826
+ */
1827
+ declare function getPreviewState<TResult extends object>(instance: SanityInstance, options: GetPreviewStateOptions): StateSource<ValuePending<TResult>>;
1828
+ /**
1829
+ * @beta
1830
+ * @deprecated This function is deprecated and will be removed in a future release.
1831
+ */
1832
+ declare function getPreviewState(instance: SanityInstance, options: GetPreviewStateOptions): StateSource<ValuePending<PreviewValue>>;
1833
+ /**
1834
+ * Generates a GROQ projection for preview data without requiring a schema.
1835
+ * Uses common field names to make educated guesses about which fields to use.
1836
+ *
1837
+ * @internal
1838
+ */
1839
+ declare const PREVIEW_PROJECTION: string;
1840
+ /**
1841
+ * Transforms a projection result (with titleCandidates, subtitleCandidates, media)
1842
+ * into a PreviewValue (with title, subtitle, media).
1843
+ *
1844
+ * @param projectionResult - The raw projection result from GROQ
1845
+ * @param instance - The Sanity instance to use for client configuration
1846
+ * @param source - Data source for the preview
1847
+ * @internal
1848
+ */
1849
+ declare function transformProjectionToPreview(instance: SanityInstance, projectionResult: PreviewQueryResult, source?: DocumentSource): PreviewValue;
1850
+ /**
1851
+ * @beta
1852
+ * @deprecated This type is deprecated and will be removed in a future release.
1853
+ */
1854
+ type ResolvePreviewOptions = DocumentHandle;
1855
+ /**
1856
+ * @beta
1857
+ * @deprecated This function is deprecated and will be removed in a future release.
1858
+ */
1859
+ declare function resolvePreview(instance: SanityInstance, options: ResolvePreviewOptions): Promise<ValuePending<PreviewValue>>;
1860
+ /** @public */
1861
+ declare const getProjectState: BoundStoreAction<FetcherStoreState<[options?: ProjectHandle<string> | undefined], _sanity_client12.SanityProject>, [options?: ProjectHandle<string> | undefined], StateSource<_sanity_client12.SanityProject | undefined>>;
1862
+ /** @public */
1863
+ declare const resolveProject: BoundStoreAction<FetcherStoreState<[options?: ProjectHandle<string> | undefined], _sanity_client12.SanityProject>, [options?: ProjectHandle<string> | undefined], Promise<_sanity_client12.SanityProject>>;
1864
+ interface ProjectionOptions<TProjection extends string = string, TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string> extends DocumentHandle<TDocumentType, TDataset, TProjectId> {
1865
+ projection: TProjection;
1866
+ }
1867
+ /**
1868
+ * @beta
1869
+ */
1870
+ 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<SanityProjectionResult<TProjection, TDocumentType, `${TProjectId}.${TDataset}`>> | undefined>;
1871
+ /**
1872
+ * @beta
1873
+ */
1874
+ declare function getProjectionState<TData extends object>(instance: SanityInstance, options: ProjectionOptions): StateSource<ProjectionValuePending<TData> | undefined>;
1875
+ /**
1876
+ * @beta
1877
+ */
1878
+ declare function getProjectionState(instance: SanityInstance, options: ProjectionOptions): StateSource<ProjectionValuePending<Record<string, unknown>> | undefined>;
1879
+ /** @beta */
1880
+ 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<SanityProjectionResult<TProjection, TDocumentType, `${TProjectId}.${TDataset}`>>>;
1881
+ /** @beta */
1882
+ declare function resolveProjection<TData extends object>(instance: SanityInstance, options: ProjectionOptions): Promise<ProjectionValuePending<TData>>;
1883
+ /** @public */
1884
+ declare const getProjectsState: BoundStoreAction<FetcherStoreState<[options?: {
1885
+ organizationId?: string;
1886
+ includeMembers?: boolean;
1887
+ } | undefined], Omit<_sanity_client12.SanityProject, "members">[]>, [options?: {
1888
+ organizationId?: string;
1889
+ includeMembers?: boolean;
1890
+ } | undefined], StateSource<Omit<_sanity_client12.SanityProject, "members">[] | undefined>>;
1891
+ /** @public */
1892
+ declare const resolveProjects: BoundStoreAction<FetcherStoreState<[options?: {
1893
+ organizationId?: string;
1894
+ includeMembers?: boolean;
1895
+ } | undefined], Omit<_sanity_client12.SanityProject, "members">[]>, [options?: {
1896
+ organizationId?: string;
1897
+ includeMembers?: boolean;
1898
+ } | undefined], Promise<Omit<_sanity_client12.SanityProject, "members">[]>>;
1899
+ /**
1900
+ * @beta
1901
+ */
1902
+ 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> {
1903
+ query: TQuery;
1904
+ params?: Record<string, unknown>;
1905
+ }
1906
+ /**
1907
+ * @beta
1908
+ */
1909
+ interface ResolveQueryOptions<TQuery extends string = string, TDataset extends string = string, TProjectId extends string = string> extends QueryOptions<TQuery, TDataset, TProjectId> {
1910
+ signal?: AbortSignal;
1911
+ }
1912
+ /** @beta */
1913
+ declare const getQueryKey: (options: QueryOptions) => string;
1914
+ /** @beta */
1915
+ declare const parseQueryKey: (key: string) => QueryOptions;
1916
+ /**
1917
+ * Returns the state source for a query.
1918
+ *
1919
+ * This function returns a state source that represents the current result of a GROQ query.
1920
+ * Subscribing to the state source will instruct the SDK to fetch the query (if not already fetched)
1921
+ * and will keep the query live using the Live content API (considering sync tags) to provide up-to-date results.
1922
+ * When the last subscriber is removed, the query state is automatically cleaned up from the store.
1923
+ *
1924
+ * Note: This functionality is for advanced users who want to build their own framework integrations.
1925
+ * Our SDK also provides a React integration (useQuery hook) for convenient usage.
1926
+ *
1927
+ * Note: Automatic cleanup can interfere with React Suspense because if a component suspends while being the only subscriber,
1928
+ * cleanup might occur unexpectedly. In such cases, consider using `resolveQuery` instead.
1929
+ *
1930
+ * @beta
1931
+ */
1932
+ declare function getQueryState<TQuery extends string = string, TDataset extends string = string, TProjectId extends string = string>(instance: SanityInstance, queryOptions: QueryOptions<TQuery, TDataset, TProjectId>): StateSource<SanityQueryResult<TQuery, `${TProjectId}.${TDataset}`> | undefined>;
1933
+ /** @beta */
1934
+ declare function getQueryState<TData>(instance: SanityInstance, queryOptions: QueryOptions): StateSource<TData | undefined>;
1935
+ /** @beta */
1936
+ declare function getQueryState(instance: SanityInstance, queryOptions: QueryOptions): StateSource<unknown>;
1937
+ /**
1938
+ * Resolves the result of a query without registering a lasting subscriber.
1939
+ *
1940
+ * This function fetches the result of a GROQ query and returns a promise that resolves with the query result.
1941
+ * Unlike `getQueryState`, which registers subscribers to keep the query live and performs automatic cleanup,
1942
+ * `resolveQuery` does not track subscribers. This makes it ideal for use with React Suspense, where the returned
1943
+ * promise is thrown to delay rendering until the query result becomes available.
1944
+ * Once the promise resolves, it is expected that a real subscriber will be added via `getQueryState` to manage ongoing updates.
1945
+ *
1946
+ * Additionally, an optional AbortSignal can be provided to cancel the query and immediately clear the associated state
1947
+ * if there are no active subscribers.
1948
+ *
1949
+ * @beta
1950
+ */
1951
+ declare function resolveQuery<TQuery extends string = string, TDataset extends string = string, TProjectId extends string = string>(instance: SanityInstance, queryOptions: ResolveQueryOptions<TQuery, TDataset, TProjectId>): Promise<SanityQueryResult<TQuery, `${TProjectId}.${TDataset}`>>;
1952
+ /** @beta */
1953
+ declare function resolveQuery<TData>(instance: SanityInstance, queryOptions: ResolveQueryOptions): Promise<TData>;
1954
+ /**
1955
+ * Represents a document in a Sanity dataset that represents release options.
1956
+ * @internal
1957
+ */
1958
+ type ReleaseDocument = SanityDocument$1 & {
1959
+ name: string;
1960
+ publishAt?: string;
1961
+ state: 'active' | 'scheduled';
1962
+ metadata: {
1963
+ title: string;
1964
+ releaseType: 'asap' | 'scheduled' | 'undecided';
1965
+ intendedPublishAt?: string;
1966
+ description?: string;
1967
+ };
1968
+ };
1969
+ interface ReleasesStoreState {
1970
+ activeReleases?: ReleaseDocument[];
1971
+ error?: unknown;
1972
+ }
1973
+ /**
1974
+ * Get the active releases from the store.
1975
+ * @internal
1976
+ */
1977
+ declare const getActiveReleasesState: (instance: SanityInstance, options?: {
1978
+ source?: DocumentSource;
1979
+ }) => StateSource<ReleaseDocument[] | undefined>;
1980
+ declare const _getPerspectiveStateSelector: StoreAction<ReleasesStoreState, [_?: (PerspectiveHandle & {
1981
+ projectId?: string;
1982
+ dataset?: string;
1983
+ source?: DocumentSource;
1984
+ }) | undefined], StateSource<string[] | "previewDrafts" | "published" | "drafts" | "raw" | undefined>, unknown>;
1985
+ type OmitFirst<T extends unknown[]> = T extends [unknown, ...infer R] ? R : never;
1986
+ type SelectorParams = OmitFirst<Parameters<typeof _getPerspectiveStateSelector>>;
1987
+ type BoundGetPerspectiveState = BoundStoreAction<ReleasesStoreState, SelectorParams, ReturnType<typeof _getPerspectiveStateSelector>>;
1988
+ /**
1989
+ * Provides a subscribable state source for a "perspective" for the Sanity client,
1990
+ * which is used to fetch documents as though certain Content Releases are active.
1991
+ *
1992
+ * @param instance - The Sanity instance to get the perspective for
1993
+ * @param options - The options for the perspective -- usually a release name
1994
+ *
1995
+ * @returns A subscribable perspective value, usually a list of applicable release names,
1996
+ * or a single release name / default perspective (such as 'drafts').
1997
+ *
1998
+ * @public
1999
+ */
2000
+ declare const getPerspectiveState: BoundGetPerspectiveState;
2001
+ /** @internal */
2002
+ declare const getUsersKey: (instance: SanityInstance, {
2003
+ resourceType,
2004
+ organizationId,
2005
+ batchSize,
2006
+ projectId,
2007
+ userId
2008
+ }?: GetUsersOptions) => string;
2009
+ /** @internal */
2010
+ declare const parseUsersKey: (key: string) => {
2011
+ batchSize: number;
2012
+ resourceType?: "organization" | "project";
2013
+ projectId?: string;
2014
+ organizationId?: string;
2015
+ userId?: string;
2016
+ };
2017
+ /**
2018
+ * Returns the state source for users associated with a specific resource.
2019
+ *
2020
+ * This function returns a state source that represents the current list of users for a given
2021
+ * resource. Subscribing to the state source will instruct the SDK to fetch the users (if not
2022
+ * already fetched) and will load more from this state source as well. When the last subscriber is
2023
+ * removed, the users state is automatically cleaned up from the store after a delay.
2024
+ *
2025
+ * Note: This functionality is for advanced users who want to build their own framework
2026
+ * integrations. Our SDK also provides a React integration for convenient usage.
2027
+ *
2028
+ * @beta
2029
+ */
2030
+ declare const getUsersState: BoundStoreAction<UsersStoreState, [options?: GetUsersOptions | undefined], StateSource<{
2031
+ data: SanityUser[];
2032
+ totalCount: number;
2033
+ hasMore: boolean;
2034
+ } | undefined>>;
2035
+ /**
2036
+ * Resolves the users for a specific resource without registering a lasting subscriber.
2037
+ *
2038
+ * This function fetches the users for a given resource and returns a promise that resolves with
2039
+ * the users result. Unlike `getUsersState`, which registers subscribers to keep the data live and
2040
+ * performs automatic cleanup, `resolveUsers` does not track subscribers. This makes it ideal for
2041
+ * use with React Suspense, where the returned promise is thrown to delay rendering until the users
2042
+ * result becomes available. Once the promise resolves, it is expected that a real subscriber will
2043
+ * be added via `getUsersState` to manage ongoing updates.
2044
+ *
2045
+ * Additionally, an optional AbortSignal can be provided to cancel the request and immediately
2046
+ * clear the associated state if there are no active subscribers.
2047
+ *
2048
+ * @beta
2049
+ */
2050
+ declare const resolveUsers: BoundStoreAction<UsersStoreState, [ResolveUsersOptions], Promise<{
2051
+ data: SanityUser[];
2052
+ totalCount: number;
2053
+ hasMore: boolean;
2054
+ }>>;
2055
+ /**
2056
+ * Loads more users for a specific resource.
2057
+ *
2058
+ * This function triggers a request to fetch the next page of users for a given resource. It
2059
+ * requires that users have already been loaded for the resource (via `resolveUsers` or
2060
+ * `getUsersState`), and that there are more users available to load (as indicated by the `hasMore`
2061
+ * property).
2062
+ *
2063
+ * The function returns a promise that resolves when the next page of users has been loaded.
2064
+ *
2065
+ * @beta
2066
+ */
2067
+ declare const loadMoreUsers: BoundStoreAction<UsersStoreState, [options?: GetUsersOptions | undefined], Promise<{
2068
+ data: SanityUser[];
2069
+ totalCount: number;
2070
+ hasMore: boolean;
2071
+ }>>;
2072
+ /**
2073
+ * @beta
2074
+ */
2075
+ declare const getUserState: BoundStoreAction<UsersStoreState, [GetUserOptions], Observable<SanityUser | undefined>>;
2076
+ /**
2077
+ * @beta
2078
+ */
2079
+ declare const resolveUser: BoundStoreAction<UsersStoreState, [ResolveUserOptions], Promise<SanityUser>>;
2080
+ interface StoreEntry<TParams extends unknown[], TData> {
2081
+ params: TParams;
2082
+ instance: SanityInstance;
2083
+ key: string;
2084
+ data?: TData;
2085
+ error?: unknown;
2086
+ subscriptions: string[];
2087
+ lastFetchInitiatedAt?: string;
2088
+ }
2089
+ /**
2090
+ * Internal helper type
2091
+ * @public
2092
+ */
2093
+ interface FetcherStoreState<TParams extends unknown[], TData> {
2094
+ stateByParams: { [TSerializedKey in string]?: StoreEntry<TParams, TData> };
2095
+ error?: unknown;
2096
+ }
2097
+ /**
2098
+ * Internal helper type
2099
+ * @public
2100
+ */
2101
+ interface FetcherStore<TParams extends unknown[], TData> {
2102
+ getState: BoundStoreAction<FetcherStoreState<TParams, TData>, TParams, StateSource<TData | undefined>>;
2103
+ resolveState: BoundStoreAction<FetcherStoreState<TParams, TData>, TParams, Promise<TData>>;
2104
+ }
2105
+ /**
2106
+ * Creates a GROQ search filter string (`[@] match text::query("...")`)
2107
+ * from a raw search query string.
2108
+ *
2109
+ * It applies wildcard ('*') logic to the last eligible token and escapes
2110
+ * double quotes within the search term.
2111
+ *
2112
+ * If the input query is empty or only whitespace, it returns an empty string.
2113
+ *
2114
+ * @param query - The raw input search string.
2115
+ * @returns The GROQ search filter string, or an empty string.
2116
+ * @internal
2117
+ */
2118
+ declare function createGroqSearchFilter(query: string): string;
2119
+ /**
2120
+ * Filter criteria for intent matching. Can be combined to create more specific intents.
2121
+ *
2122
+ * @example
2123
+ * ```typescript
2124
+ * // matches only geopoints in the travel-project project, production dataset
2125
+ * const filter: IntentFilter = {
2126
+ * projectId: 'travel-project',
2127
+ * dataset: 'production',
2128
+ * types: ['geopoint']
2129
+ * }
2130
+ *
2131
+ * // matches all documents in the travel-project project
2132
+ * const filter: IntentFilter = {
2133
+ * projectId: 'travel-project',
2134
+ * types: ['*']
2135
+ * }
2136
+ *
2137
+ * // matches geopoints in the travel-project production dataset and map pins in all projects in the org
2138
+ * const filters: IntentFilter[] = [
2139
+ * {
2140
+ * projectId: 'travel-project',
2141
+ * dataset: 'production',
2142
+ * types: ['geopoint']
2143
+ * },
2144
+ * {
2145
+ * types: ['map-pin']
2146
+ * }
2147
+ * ]
2148
+ * ```
2149
+ * @public
2150
+ */
2151
+ interface IntentFilter {
2152
+ /**
2153
+ * Project ID to match against
2154
+ * @remarks When specified, the intent will only match for the specified project.
2155
+ */
2156
+ projectId?: string;
2157
+ /**
2158
+ * Dataset to match against
2159
+ * @remarks When specified, the intent will only match for the specified dataset. Requires projectId to be specified.
2160
+ */
2161
+ dataset?: string;
2162
+ /**
2163
+ * Document types that this intent can handle
2164
+ * @remarks This is required for all filters. Use ['*'] to match all document types.
2165
+ */
2166
+ types: string[];
2167
+ }
2168
+ /**
2169
+ * Intent definition structure for registering user intents
2170
+ * @public
2171
+ */
2172
+ interface Intent {
2173
+ /**
2174
+ * Unique identifier for this intent
2175
+ * @remarks Should be unique across all registered intents in an org for proper matching
2176
+ */
2177
+ id: string;
2178
+ /**
2179
+ * The action that this intent performs
2180
+ * @remarks Examples: "view", "edit", "create", "delete"
2181
+ */
2182
+ action: 'view' | 'edit' | 'create' | 'delete';
2183
+ /**
2184
+ * Human-readable title for this intent
2185
+ * @remarks Used for display purposes in UI or logs
2186
+ */
2187
+ title: string;
2188
+ /**
2189
+ * Detailed description of what this intent does
2190
+ * @remarks Helps users understand the purpose and behavior of the intent
2191
+ */
2192
+ description?: string;
2193
+ /**
2194
+ * Array of filter criteria for intent matching
2195
+ * @remarks At least one filter is required. Use `{types: ['*']}` to match everything
2196
+ */
2197
+ filters: IntentFilter[];
2198
+ }
2199
+ /**
2200
+ * Creates a properly typed intent definition for registration with the backend.
2201
+ *
2202
+ * This utility function provides TypeScript support and validation for intent declarations.
2203
+ * It is also used in the CLI if intents are declared as bare objects in an intents file.
2204
+ *
2205
+ * @param intent - The intent definition object
2206
+ * @returns The same intent object with proper typing
2207
+ *
2208
+ * @example
2209
+ * ```typescript
2210
+ * // Specific filter for a document type
2211
+ * const viewGeopointInMapApp = defineIntent({
2212
+ * id: 'viewGeopointInMapApp',
2213
+ * action: 'view',
2214
+ * title: 'View a geopoint in the map app',
2215
+ * description: 'This lets you view a geopoint in the map app',
2216
+ * filters: [
2217
+ * {
2218
+ * projectId: 'travel-project',
2219
+ * dataset: 'production',
2220
+ * types: ['geopoint']
2221
+ * }
2222
+ * ]
2223
+ * })
2224
+ *
2225
+ * export default viewGeopointInMapApp
2226
+ * ```
2227
+ *
2228
+ * If your intent is asynchronous, resolve the promise before defining / returning the intent
2229
+ * ```typescript
2230
+ * async function createAsyncIntent() {
2231
+ * const currentProject = await asyncProjectFunction()
2232
+ * const currentDataset = await asyncDatasetFunction()
2233
+ *
2234
+ * return defineIntent({
2235
+ * id: 'dynamicIntent',
2236
+ * action: 'view',
2237
+ * title: 'Dynamic Intent',
2238
+ * description: 'Intent with dynamically resolved values',
2239
+ * filters: [
2240
+ * {
2241
+ * projectId: currentProject, // Resolved value
2242
+ * dataset: currentDataset, // Resolved value
2243
+ * types: ['document']
2244
+ * }
2245
+ * ]
2246
+ * })
2247
+ * }
2248
+ *
2249
+ * const intent = await createAsyncIntent()
2250
+ * export default intent
2251
+ * ```
2252
+ *
2253
+ * @public
2254
+ */
2255
+ declare function defineIntent(intent: Intent): Intent;
2256
+ /**
2257
+ * @public
2258
+ * Extracts the project ID from a CorsOriginError message.
2259
+ * @param error - The error to extract the project ID from.
2260
+ * @returns The project ID or null if the error is not a CorsOriginError.
2261
+ */
2262
+ declare function getCorsErrorProjectId(error: Error): string | null;
2263
+ /**
2264
+ * This version is provided by pkg-utils at build time
2265
+ * @internal
2266
+ */
2267
+ declare const CORE_SDK_VERSION: {};
2268
+ /**
2269
+ * @public
2270
+ */
2271
+ type SanityProject$1 = SanityProject;
2272
+ /**
2273
+ * Represents the various states the authentication can be in.
2274
+ *
2275
+ * @public
2276
+ */
2277
+ type AuthState = LoggedInAuthState | LoggedOutAuthState | LoggingInAuthState | ErrorAuthState;
2278
+ /**
2279
+ * Logged-in state from the auth state.
2280
+ * @public
2281
+ */
2282
+ type LoggedInAuthState = {
2283
+ type: AuthStateType.LOGGED_IN;
2284
+ token: string;
2285
+ currentUser: CurrentUser | null;
2286
+ lastTokenRefresh?: number;
2287
+ };
2288
+ /**
2289
+ * Logged-out state from the auth state.
2290
+ * @public
2291
+ */
2292
+ type LoggedOutAuthState = {
2293
+ type: AuthStateType.LOGGED_OUT;
2294
+ isDestroyingSession: boolean;
2295
+ };
2296
+ /**
2297
+ * Logging-in state from the auth state.
2298
+ * @public
2299
+ */
2300
+ type LoggingInAuthState = {
2301
+ type: AuthStateType.LOGGING_IN;
2302
+ isExchangingToken: boolean;
2303
+ };
2304
+ /**
2305
+ * Error state from the auth state.
2306
+ * @public
2307
+ */
2308
+ type ErrorAuthState = {
2309
+ type: AuthStateType.ERROR;
2310
+ error: unknown;
2311
+ };
2312
+ /**
2313
+ * Represents the various states the authentication can be in.
2314
+ *
2315
+ * @public
2316
+ */
2317
+ interface DashboardContext {
2318
+ mode?: string;
2319
+ env?: string;
2320
+ orgId?: string;
2321
+ }
2322
+ /**
2323
+ * The method of authentication used.
2324
+ * @internal
2325
+ */
2326
+ type AuthMethodOptions = 'localstorage' | 'cookie' | undefined;
2327
+ /**
2328
+ * @public
2329
+ */
2330
+ interface AuthStoreState {
2331
+ authState: AuthState;
2332
+ providers?: AuthProvider[];
2333
+ options: {
2334
+ initialLocationHref: string;
2335
+ clientFactory: (config: ClientConfig) => SanityClient;
2336
+ customProviders: AuthConfig['providers'];
2337
+ storageKey: string;
2338
+ storageArea: Storage | undefined;
2339
+ apiHost: string | undefined;
2340
+ loginUrl: string;
2341
+ callbackUrl: string | undefined;
2342
+ providedToken: string | undefined;
2343
+ authMethod: AuthMethodOptions;
2344
+ };
2345
+ dashboardContext?: DashboardContext;
2346
+ }
2347
+ /**
2348
+ * @public
2349
+ */
2350
+ declare const getCurrentUserState: BoundStoreAction<AuthStoreState, [], StateSource<CurrentUser | null>>;
2351
+ /**
2352
+ * @public
2353
+ */
2354
+ declare const getTokenState: BoundStoreAction<AuthStoreState, [], StateSource<string | null>>;
2355
+ /**
2356
+ * @public
2357
+ */
2358
+ declare const getLoginUrlState: BoundStoreAction<AuthStoreState, [], StateSource<string>>;
2359
+ /**
2360
+ * @public
2361
+ */
2362
+ declare const getAuthState: BoundStoreAction<AuthStoreState, [], StateSource<AuthState>>;
2363
+ /**
2364
+ * @public
2365
+ */
2366
+ declare const getDashboardOrganizationId: BoundStoreAction<AuthStoreState, [], StateSource<string | undefined>>;
2367
+ /**
2368
+ * Returns a state source indicating if the SDK is running within a dashboard context.
2369
+ * @public
2370
+ */
2371
+ declare const getIsInDashboardState: BoundStoreAction<AuthStoreState, [], StateSource<boolean>>;
2372
+ /**
2373
+ * Action to explicitly set the authentication token.
2374
+ * Used internally by the Comlink token refresh.
2375
+ * @internal
2376
+ */
2377
+ declare const setAuthToken: BoundStoreAction<AuthStoreState, [token: string | null], void>;
2378
+ /** @internal */
2379
+ type ApiErrorBody = {
2380
+ error?: {
2381
+ type?: string;
2382
+ description?: string;
2383
+ };
2384
+ type?: string;
2385
+ description?: string;
2386
+ message?: string;
2387
+ };
2388
+ /** @internal Extracts the structured API error body from a ClientError, if present. */
2389
+ declare function getClientErrorApiBody(error: ClientError): ApiErrorBody | undefined;
2390
+ /** @internal Returns the error type string from an API error body, if available. */
2391
+ declare function getClientErrorApiType(error: ClientError): string | undefined;
2392
+ /** @internal Returns the error description string from an API error body, if available. */
2393
+ declare function getClientErrorApiDescription(error: ClientError): string | undefined;
2394
+ /** @internal True if the error represents a projectUserNotFoundError. */
2395
+ declare function isProjectUserNotFoundClientError(error: ClientError): boolean;
2396
+ export { resolveProjects as $, logout as $n, getDocumentSyncStatus as $t, getCorsErrorProjectId as A, LoggerConfig as An, ProjectHandle as Ar, SanityUserResponse as At, resolveUser as B, ComlinkControllerState as Bn, ActionErrorEvent as Bt, getIndexForKey as C, resolveDatasets as Cn, DatasetHandle as Cr, UserPresence as Ct, slicePath as D, LogLevel as Dn, DocumentTypeHandle as Dr, ResolveUserOptions as Dt, jsonMatch as E, LogContext as En, DocumentSource as Er, Membership as Et, FetcherStore as F, NodeState as Fn, isCanvasSource as Fr, getFavoritesState as Ft, ReleaseDocument as G, FrameMessage as Gn, DocumentEvent as Gt, getUsersKey as H, getOrCreateChannel as Hn, DocumentDeletedEvent as Ht, FetcherStoreState as I, getNodeState as In, isDatasetSource as Ir, resolveFavoritesState as It, getQueryKey as J, WindowMessage as Jn, DocumentUnpublishedEvent as Jt, getActiveReleasesState as K, NewTokenResponseMessage as Kn, DocumentPublishedEvent as Kt, getUserState as L, ComlinkNodeState as Ln, isMediaLibrarySource as Lr, ActionsResult as Lt, IntentFilter as M, createDocumentHandle as Mn, SanityConfig as Mr, UsersGroupState as Mt, defineIntent as N, createDocumentTypeHandle as Nn, StudioConfig as Nr, UsersStoreState as Nt, stringifyPath as O, LogNamespace as On, MediaLibrarySource as Or, ResolveUsersOptions as Ot, createGroqSearchFilter as P, createProjectHandle as Pn, TokenSource as Pr, FavoriteStatusResponse as Pt, getProjectsState as Q, getClientState as Qn, getDocumentState as Qt, getUsersState as R, getOrCreateNode as Rn, AuthConfig as Rr, ApplyDocumentActionsOptions as Rt, SanityProject$1 as S, getDatasetsState as Sn, CanvasSource as Sr, TransportEvent as St, joinPaths as T, InstanceContext as Tn, DocumentHandle as Tr, GetUsersOptions as Tt, parseUsersKey as U, getOrCreateController as Un, DocumentDiscardedEvent as Ut, resolveUsers as V, destroyController as Vn, DocumentCreatedEvent as Vt, getPerspectiveState as W, releaseChannel as Wn, DocumentEditedEvent as Wt, parseQueryKey as X, ClientStoreState as Xn, TransactionRevertedEvent as Xt, getQueryState as Y, ClientOptions as Yn, TransactionAcceptedEvent as Yt, resolveQuery as Z, getClient as Zn, DocumentOptions as Zt, getTokenState as _, deleteDocument as _n, agentTransform as _r, getPresence as _t, isProjectUserNotFoundClientError as a, PermissionDeniedReason as an, AgentGenerateResult as ar, resolvePreview as at, Role as b, publishDocument as bn, createSanityInstance as br, RollCallEvent as bt, ErrorAuthState as c, StateSource as cn, AgentPromptOptions as cr, GetPreviewStateOptions as ct, LoggingInAuthState as d, DiscardDocumentAction as dn, AgentTransformResult as dr, PreviewQueryResult as dt, getPermissionsState as en, handleAuthCallback as er, resolveProjection as et, getAuthState as f, DocumentAction as fn, AgentTranslateOptions as fr, PreviewStoreState as ft, getLoginUrlState as g, createDocument as gn, agentPrompt as gr, ValidProjection as gt, getIsInDashboardState as h, UnpublishDocumentAction as hn, agentPatch as hr, ProjectionValuePending as ht, getClientErrorApiType as i, DocumentPermissionsResult as in, AgentGenerateOptions as ir, ResolvePreviewOptions as it, Intent as j, createDatasetHandle as jn, ReleasePerspective as jr, UserProfile as jt, CORE_SDK_VERSION as k, Logger as kn, PerspectiveHandle as kr, SanityUser as kt, LoggedInAuthState as l, CreateDocumentAction as ln, AgentPromptResult as lr, getPreviewState as lt, getDashboardOrganizationId as m, PublishDocumentAction as mn, agentGenerate as mr, ValuePending as mt, getClientErrorApiBody as n, resolvePermissions as nn, OrgVerificationResult as nr, getProjectState as nt, AuthState as o, JsonMatch as on, AgentPatchOptions as or, transformProjectionToPreview as ot, getCurrentUserState as p, EditDocumentAction as pn, AgentTranslateResult as pr, PreviewValue as pt, QueryOptions as q, RequestNewTokenMessage as qn, DocumentTransactionSubmissionResult as qt, getClientErrorApiDescription as r, subscribeDocumentEvents as rn, AuthStateType as rr, resolveProject as rt, AuthStoreState as s, Selector as sn, AgentPatchResult as sr, PREVIEW_PROJECTION as st, ApiErrorBody as t, resolveDocument as tn, observeOrganizationVerificationState as tr, getProjectionState as tt, LoggedOutAuthState as u, DeleteDocumentAction as un, AgentTransformOptions as ur, PreviewMedia as ut, setAuthToken as v, discardDocument as vn, agentTranslate as vr, DisconnectEvent as vt, getPathDepth as w, configureLogging as wn, DatasetSource as wr, GetUserOptions as wt, SanityDocument$3 as x, unpublishDocument as xn, isStudioConfig as xr, StateEvent as xt, CurrentUser$1 as y, editDocument as yn, SanityInstance as yr, PresenceLocation as yt, loadMoreUsers as z, releaseNode as zn, AuthProvider as zr, applyDocumentActions as zt };