@sanity/sdk 2.19.0 → 2.20.1

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 (62) hide show
  1. package/dist/_exports/_internal.d.ts +2 -2
  2. package/dist/_exports/_internal.js +196 -22
  3. package/dist/_exports/_internal.js.map +1 -1
  4. package/dist/authStore-CWTAuieY.js +1072 -0
  5. package/dist/authStore-CWTAuieY.js.map +1 -0
  6. package/dist/clientStore-CMzJ7XhZ.js +168 -0
  7. package/dist/clientStore-CMzJ7XhZ.js.map +1 -0
  8. package/dist/createGroqSearchFilter-B0NdA-EP.js +1222 -0
  9. package/dist/createGroqSearchFilter-B0NdA-EP.js.map +1 -0
  10. package/dist/getEnv-76AjZd_f.js +178 -0
  11. package/dist/getEnv-76AjZd_f.js.map +1 -0
  12. package/dist/index.d.ts +2 -2105
  13. package/dist/index.js +4140 -3870
  14. package/dist/index.js.map +1 -1
  15. package/dist/rolldown-runtime-vyAXikos.js +9 -0
  16. package/dist/telemetryManager-w-AMXtmz.js +127 -0
  17. package/dist/telemetryManager-w-AMXtmz.js.map +1 -0
  18. package/dist/utils-BMwA8Kg9.d.ts +3334 -0
  19. package/dist/utils-BMwA8Kg9.d.ts.map +1 -0
  20. package/dist/version-ByqNiWrK.js +9 -0
  21. package/dist/version-ByqNiWrK.js.map +1 -0
  22. package/package.json +12 -20
  23. package/src/_exports/_internal.ts +1 -0
  24. package/src/_exports/index.ts +30 -0
  25. package/src/comments/addonDatasetStore.test.ts +215 -0
  26. package/src/comments/addonDatasetStore.ts +249 -0
  27. package/src/comments/buildCommentThreads.test.ts +83 -0
  28. package/src/comments/buildCommentThreads.ts +54 -0
  29. package/src/comments/commentActions.test.ts +540 -0
  30. package/src/comments/commentActions.ts +555 -0
  31. package/src/comments/commentFieldPath.test.ts +40 -0
  32. package/src/comments/commentFieldPath.ts +44 -0
  33. package/src/comments/commentsConstants.ts +80 -0
  34. package/src/comments/commentsStore.test.ts +419 -0
  35. package/src/comments/commentsStore.ts +483 -0
  36. package/src/comments/normalizeComment.test.ts +116 -0
  37. package/src/comments/normalizeComment.ts +45 -0
  38. package/src/comments/observeComments.test.ts +193 -0
  39. package/src/comments/observeComments.ts +113 -0
  40. package/src/comments/reducers.test.ts +277 -0
  41. package/src/comments/reducers.ts +316 -0
  42. package/src/comments/types.ts +249 -0
  43. package/src/comments/weakenReferences.test.ts +47 -0
  44. package/src/comments/weakenReferences.ts +29 -0
  45. package/src/document/documentConstants.ts +8 -0
  46. package/src/document/documentStore.test.ts +98 -1
  47. package/src/document/documentStore.ts +36 -5
  48. package/src/document/patchOperations.test.ts +27 -0
  49. package/src/document/patchOperations.ts +10 -1
  50. package/src/document/permissions.test.ts +3 -1
  51. package/src/document/reducers.test.ts +133 -0
  52. package/src/document/reducers.ts +18 -3
  53. package/src/projection/projectionStore.test.ts +0 -8
  54. package/dist/_chunks-dts/createGroqSearchFilter.d.ts +0 -923
  55. package/dist/_chunks-dts/createGroqSearchFilter.d.ts.map +0 -1
  56. package/dist/_chunks-es/_internal.js +0 -134
  57. package/dist/_chunks-es/_internal.js.map +0 -1
  58. package/dist/_chunks-es/createGroqSearchFilter.js +0 -1590
  59. package/dist/_chunks-es/createGroqSearchFilter.js.map +0 -1
  60. package/dist/_chunks-es/telemetryManager.js +0 -93
  61. package/dist/_chunks-es/telemetryManager.js.map +0 -1
  62. package/dist/index.d.ts.map +0 -1
@@ -0,0 +1,3334 @@
1
+ import { ClientConfig, ClientError, ClientPerspective, ListenEvent, MultipleMutationResult, ReleaseDocument, ReleaseDocument as ReleaseDocument$1, ResponseQueryOptions, SanityClient, SanityDocument, SanityProject, StackablePerspective } from "@sanity/client";
2
+ import { Observable, Subject } from "rxjs";
3
+ import { CurrentUser, CurrentUser as CurrentUser$1, Mutation, PatchOperations, Path, PortableTextBlock, Role, SanityDocument as SanityDocument$1, SanityDocument as SanityDocument$3, SanityDocumentLike } from "@sanity/types";
4
+ import "zustand/middleware";
5
+ import { ChannelInput, ChannelInstance, Controller, Message, Node, NodeInput, Status } from "@sanity/comlink";
6
+ import { getIndexForKey as getIndexForKey$1, getPathDepth, joinPaths, jsonMatch as jsonMatch$1, slicePath as slicePath$1, stringifyPath as stringifyPath$1 } from "@sanity/json-match";
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
+ /**
12
+ * Configuration for an authentication provider
13
+ * @public
14
+ */
15
+ interface AuthProvider {
16
+ /**
17
+ * Unique identifier for the auth provider (e.g., 'google', 'github')
18
+ */
19
+ name: string;
20
+ /**
21
+ * Display name for the auth provider in the UI
22
+ */
23
+ title: string;
24
+ /**
25
+ * Complete authentication URL including callback and token parameters
26
+ */
27
+ url: string;
28
+ /**
29
+ * Optional URL for direct sign-up flow
30
+ */
31
+ signUpUrl?: string;
32
+ }
33
+ /**
34
+ * Configuration options for creating an auth store.
35
+ *
36
+ * @public
37
+ */
38
+ interface AuthConfig {
39
+ /**
40
+ * The initial location href to use when handling auth callbacks.
41
+ * Defaults to the current window location if available.
42
+ */
43
+ initialLocationHref?: string;
44
+ /**
45
+ * Factory function to create a SanityClient instance.
46
+ * Defaults to the standard Sanity client factory if not provided.
47
+ */
48
+ clientFactory?: (config: ClientConfig) => SanityClient;
49
+ /**
50
+ * Custom authentication providers to use instead of or in addition to the default ones.
51
+ * Can be an array of providers or a function that takes the default providers and returns
52
+ * a modified array or a Promise resolving to one.
53
+ */
54
+ providers?: AuthProvider[] | ((prev: AuthProvider[]) => AuthProvider[] | Promise<AuthProvider[]>);
55
+ /**
56
+ * The API hostname for requests. Usually leave this undefined, but it can be set
57
+ * if using a custom domain or CNAME for the API endpoint.
58
+ */
59
+ apiHost?: string;
60
+ /**
61
+ * Storage implementation to persist authentication state.
62
+ * Defaults to `localStorage` if available.
63
+ */
64
+ storageArea?: Storage;
65
+ /**
66
+ * A callback URL for your application.
67
+ * If none is provided, the auth API will redirect back to the current location (`location.href`).
68
+ * When handling callbacks, this URL's pathname is checked to ensure it matches the callback.
69
+ */
70
+ callbackUrl?: string;
71
+ /**
72
+ * A static authentication token to use instead of handling the OAuth flow.
73
+ * When provided, the auth store will remain in a logged-in state with this token,
74
+ * ignoring any storage or callback handling.
75
+ */
76
+ token?: string;
77
+ }
78
+ /**
79
+ * A minimal Observable-compatible interface for subscribing to token changes.
80
+ * Any object with a `subscribe` method that follows this contract will work,
81
+ * including RxJS Observables. This avoids coupling the SDK to a specific
82
+ * reactive library.
83
+ *
84
+ * @public
85
+ */
86
+ interface TokenSource {
87
+ /** Subscribe to token emissions. Emits `null` when logged out. */
88
+ subscribe(observer: {
89
+ next: (token: string | null) => void;
90
+ }): {
91
+ unsubscribe(): void;
92
+ };
93
+ }
94
+ /**
95
+ * Studio-specific configuration for the SDK.
96
+ * When present, the SDK operates in studio mode and derives auth from the
97
+ * provided token source instead of discovering tokens independently.
98
+ *
99
+ * @public
100
+ */
101
+ interface StudioConfig {
102
+ /**
103
+ * Whether the Studio has already determined the user is authenticated.
104
+ * When `true` and the token source emits `null`, the SDK infers
105
+ * cookie-based auth is in use rather than transitioning to logged-out.
106
+ */
107
+ authenticated?: boolean;
108
+ /** Reactive auth token source from the Studio's auth store. */
109
+ auth?: {
110
+ /**
111
+ * A reactive token source. The SDK subscribes and stays in sync — the
112
+ * Studio is the single authority for auth and handles token refresh.
113
+ *
114
+ * Optional because older Studios may not expose it. When absent, the
115
+ * SDK falls back to localStorage/cookie discovery.
116
+ */
117
+ token?: TokenSource;
118
+ };
119
+ }
120
+ /**
121
+ * Represents the minimal configuration required to identify a Sanity project.
122
+ * @public
123
+ */
124
+ interface ProjectHandle<TProjectId extends string = string> {
125
+ projectId?: TProjectId;
126
+ }
127
+ /**
128
+ * @public
129
+ */
130
+ type ReleasePerspective = {
131
+ releaseName: string;
132
+ excludedPerspectives?: StackablePerspective[];
133
+ };
134
+ /**
135
+ * @public
136
+ */
137
+ interface PerspectiveHandle {
138
+ perspective?: ClientPerspective | ReleasePerspective;
139
+ }
140
+ /**
141
+ * @public
142
+ */
143
+ interface DatasetHandle<TDataset extends string = string, TProjectId extends string = string> extends ProjectHandle<TProjectId>, PerspectiveHandle {
144
+ dataset?: TDataset;
145
+ /**
146
+ * @beta
147
+ * Explicit resource object to use for this operation.
148
+ */
149
+ resource?: DocumentResource;
150
+ /**
151
+ * @deprecated Use `resource` instead.
152
+ * @beta
153
+ */
154
+ source?: DocumentResource;
155
+ }
156
+ /**
157
+ * Identifies a specific document type within a Sanity dataset and project.
158
+ * Includes `projectId`, `dataset`, and `documentType`.
159
+ * Optionally includes a `documentId` and `liveEdit` flag.
160
+ * @public
161
+ */
162
+ interface DocumentTypeHandle<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string> extends DatasetHandle<TDataset, TProjectId> {
163
+ documentId?: string;
164
+ documentType: TDocumentType;
165
+ /**
166
+ * Indicates whether this document uses liveEdit mode.
167
+ * When `true`, the document does not use the draft/published model and edits are applied directly to the document.
168
+ * @see https://www.sanity.io/docs/content-lake/drafts#ca0663a8f002
169
+ */
170
+ liveEdit?: boolean;
171
+ }
172
+ /**
173
+ * Uniquely identifies a specific document within a Sanity dataset and project.
174
+ * Includes `projectId`, `dataset`, `documentType`, and the required `documentId`.
175
+ * Commonly used by document-related hooks and components to reference a document without fetching its full content initially.
176
+ * @public
177
+ */
178
+ interface DocumentHandle<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string> extends DocumentTypeHandle<TDocumentType, TDataset, TProjectId> {
179
+ documentId: string;
180
+ }
181
+ /**
182
+ * Identifies a release within a Sanity dataset and project. `releaseId` is the
183
+ * `name` parameter on the release document (e.g. `{name: 'r41035a4'}`).
184
+ * The underlying release document ID is `_.releases.<releaseId>`.
185
+ * It's also the `id` parameter sent to the Actions API.
186
+ * (This type doesn't need to have ProjectId / Dataset generics since it's always the same shape)
187
+ * @beta
188
+ */
189
+ interface ReleaseHandle extends DatasetHandle {
190
+ releaseId: string;
191
+ }
192
+ /**
193
+ * Represents the complete configuration for a Sanity SDK instance
194
+ * @public
195
+ */
196
+ interface SanityConfig extends DatasetHandle, PerspectiveHandle {
197
+ /**
198
+ * Authentication configuration for the instance
199
+ */
200
+ auth?: AuthConfig;
201
+ /**
202
+ * Studio configuration provided by a Sanity Studio workspace.
203
+ * When present, the SDK operates in studio mode and derives auth from the
204
+ * workspace's reactive token source — no manual configuration needed.
205
+ *
206
+ * @remarks Typically set automatically by `SanityApp` when it detects an
207
+ * `SDKStudioContext` provider. Can also be set explicitly for programmatic use.
208
+ */
209
+ studio?: StudioConfig;
210
+ /**
211
+ * Studio mode configuration for use of the SDK in a Sanity Studio.
212
+ * @remarks Controls whether studio mode features are enabled.
213
+ * @deprecated Use `studio` instead, which provides richer integration
214
+ * with the Studio's workspace (auth token sync, etc.).
215
+ */
216
+ studioMode?: {
217
+ enabled: boolean;
218
+ };
219
+ /**
220
+ * @beta
221
+ * A list of named resources to use for this instance.
222
+ */
223
+ resources?: Record<string, DocumentResource>;
224
+ /**
225
+ * @deprecated Use `resources` instead.
226
+ * @beta
227
+ */
228
+ sources?: Record<string, DocumentResource>;
229
+ }
230
+ /**
231
+ * A document resource can be used for querying.
232
+ * This will soon be the default way to identify where you are querying from.
233
+ *
234
+ * @beta
235
+ */
236
+ type DocumentResource = DatasetResource | MediaLibraryResource | CanvasResource$1;
237
+ /**
238
+ * @beta
239
+ */
240
+ type DatasetResource = {
241
+ projectId: string;
242
+ dataset: string;
243
+ };
244
+ /**
245
+ * @beta
246
+ */
247
+ type MediaLibraryResource = {
248
+ mediaLibraryId: string;
249
+ };
250
+ /**
251
+ * @beta
252
+ */
253
+ type CanvasResource$1 = {
254
+ canvasId: string;
255
+ };
256
+ /**
257
+ * @beta
258
+ */
259
+ declare function isDatasetResource(resource: DocumentResource): resource is DatasetResource;
260
+ /**
261
+ * @beta
262
+ */
263
+ declare function isMediaLibraryResource(resource: DocumentResource): resource is MediaLibraryResource;
264
+ /**
265
+ * @beta
266
+ */
267
+ declare function isCanvasResource(resource: DocumentResource): resource is CanvasResource$1;
268
+ /**
269
+ * @deprecated Use `DocumentResource` instead.
270
+ * @beta
271
+ */
272
+ type DocumentSource = DocumentResource;
273
+ /**
274
+ * @deprecated Use `DatasetResource` instead.
275
+ * @beta
276
+ */
277
+ type DatasetSource = DatasetResource;
278
+ /**
279
+ * @deprecated Use `MediaLibraryResource` instead.
280
+ * @beta
281
+ */
282
+ type MediaLibrarySource = MediaLibraryResource;
283
+ /**
284
+ * @deprecated Use `CanvasResource` instead.
285
+ * @beta
286
+ */
287
+ type CanvasSource = CanvasResource$1;
288
+ /**
289
+ * @deprecated Use `isDatasetResource` instead.
290
+ * @beta
291
+ */
292
+ declare function isDatasetSource(source: DocumentSource): source is DatasetSource;
293
+ /**
294
+ * @deprecated Use `isMediaLibraryResource` instead.
295
+ * @beta
296
+ */
297
+ declare function isMediaLibrarySource(source: DocumentSource): source is MediaLibrarySource;
298
+ /**
299
+ * @deprecated Use `isCanvasResource` instead.
300
+ * @beta
301
+ */
302
+ declare function isCanvasSource(source: DocumentSource): source is CanvasSource;
303
+ /**
304
+ * Returns `true` when the config indicates the SDK is running inside a Studio.
305
+ * Checks the new `studio` field first, then falls back to the deprecated
306
+ * `studioMode.enabled` for backwards compatibility.
307
+ *
308
+ * @internal
309
+ */
310
+ declare function isStudioConfig(config: SanityConfig): boolean;
311
+ /**
312
+ * Represents a Sanity.io resource instance with its own configuration and lifecycle
313
+ *
314
+ * @public
315
+ */
316
+ interface SanityInstance {
317
+ /**
318
+ * Unique identifier for this instance
319
+ * @remarks Generated using crypto.randomUUID()
320
+ */
321
+ readonly instanceId: string;
322
+ /**
323
+ * Resolved configuration for this instance
324
+ */
325
+ readonly config: SanityConfig;
326
+ /**
327
+ * Checks if the instance has been disposed
328
+ * @returns true if dispose() has been called
329
+ */
330
+ isDisposed(): boolean;
331
+ /**
332
+ * Disposes the instance and cleans up associated resources
333
+ * @remarks Triggers all registered onDispose callbacks
334
+ */
335
+ dispose(): void;
336
+ /**
337
+ * Registers a callback to be invoked when the instance is disposed
338
+ * @param cb - Callback to execute on disposal
339
+ * @returns Function to unsubscribe the callback
340
+ */
341
+ onDispose(cb: () => void): () => void;
342
+ /**
343
+ * Gets the parent instance in the hierarchy
344
+ * @returns Parent instance or undefined if this is the root
345
+ * @deprecated The parent/child instance hierarchy is deprecated. Use a single SanityInstance instead.
346
+ */
347
+ getParent(): SanityInstance | undefined;
348
+ /**
349
+ * Creates a child instance with merged configuration
350
+ * @param config - Configuration to merge with parent values
351
+ * @deprecated The parent/child instance hierarchy is deprecated. Use a single SanityInstance instead.
352
+ */
353
+ createChild(config: SanityConfig): SanityInstance;
354
+ /**
355
+ * Traverses the instance hierarchy to find the first instance whose configuration
356
+ * matches the given target config using a shallow comparison.
357
+ * @param targetConfig - A partial configuration object containing key-value pairs to match.
358
+ * @returns The first matching instance or undefined if no match is found.
359
+ * @deprecated The parent/child instance hierarchy is deprecated. Use a single SanityInstance instead.
360
+ */
361
+ match(targetConfig: Partial<SanityConfig>): SanityInstance | undefined;
362
+ }
363
+ /**
364
+ * Creates a new Sanity resource instance
365
+ * @param config - Configuration for the instance (optional)
366
+ * @returns A configured SanityInstance
367
+ * @remarks When creating child instances, configurations are merged with parent values
368
+ *
369
+ * @public
370
+ */
371
+ declare function createSanityInstance(config?: SanityConfig): SanityInstance;
372
+ /**
373
+ * Represents a reactive store state container with multiple access patterns
374
+ */
375
+ interface StoreState<TState> {
376
+ /**
377
+ * Gets the current state value
378
+ *
379
+ * @remarks
380
+ * This is a direct synchronous accessor that doesn't trigger subscriptions
381
+ */
382
+ get: () => TState;
383
+ /**
384
+ * Updates the store state
385
+ * @param name - Action name for devtools tracking
386
+ * @param updatedState - New state value or updater function
387
+ *
388
+ * @remarks
389
+ * When providing a partial object, previous top-level keys not included in
390
+ * the update will be preserved.
391
+ */
392
+ set: (name: string, updatedState: Partial<TState> | ((s: TState) => Partial<TState>)) => void;
393
+ /**
394
+ * Observable stream of state changes
395
+ * @remarks
396
+ * - Emits immediately with current state on subscription
397
+ * - Shares underlying subscription between observers
398
+ * - Only emits when state reference changes
399
+ * - Completes when store is disposed
400
+ */
401
+ observable: Observable<TState>;
402
+ }
403
+ /**
404
+ * Context object provided to store initialization functions
405
+ */
406
+ interface StoreContext<TState, TKey = unknown> {
407
+ /**
408
+ * Sanity instance associated with this store
409
+ *
410
+ * @remarks
411
+ * Provides access to the Sanity configuration and instance lifecycle methods
412
+ */
413
+ instance: SanityInstance;
414
+ /**
415
+ * Reactive store state management utilities
416
+ *
417
+ * @remarks
418
+ * Contains methods for getting/setting state and observing changes
419
+ */
420
+ state: StoreState<TState>;
421
+ /**
422
+ * The key used to instantiate the store.
423
+ */
424
+ key: TKey;
425
+ }
426
+ /** @alpha */
427
+ type AgentGenerateOptions = Parameters<SanityClient['observable']['agent']['action']['generate']>[0];
428
+ /** @alpha */
429
+ type AgentTransformOptions = Parameters<SanityClient['observable']['agent']['action']['transform']>[0];
430
+ /** @alpha */
431
+ type AgentTranslateOptions = Parameters<SanityClient['observable']['agent']['action']['translate']>[0];
432
+ /** @alpha */
433
+ type AgentPromptOptions = Parameters<SanityClient['agent']['action']['prompt']>[0];
434
+ /** @alpha */
435
+ type AgentPatchOptions = Parameters<SanityClient['agent']['action']['patch']>[0];
436
+ /** @alpha */
437
+ type AgentGenerateResult = Awaited<ReturnType<SanityClient['observable']['agent']['action']['generate']>>;
438
+ /** @alpha */
439
+ type AgentTransformResult = Awaited<ReturnType<SanityClient['observable']['agent']['action']['transform']>>;
440
+ /** @alpha */
441
+ type AgentTranslateResult = Awaited<ReturnType<SanityClient['observable']['agent']['action']['translate']>>;
442
+ /** @alpha */
443
+ type AgentPromptResult = Awaited<ReturnType<SanityClient['agent']['action']['prompt']>>;
444
+ /** @alpha */
445
+ type AgentPatchResult = Awaited<ReturnType<SanityClient['agent']['action']['patch']>>;
446
+ /**
447
+ * Generates a new document using the agent.
448
+ * @param instance - The Sanity instance.
449
+ * @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.
450
+ * @returns An Observable emitting the result of the agent generate action.
451
+ * @alpha
452
+ */
453
+ declare function agentGenerate(instance: SanityInstance, options: AgentGenerateOptions, resource?: DocumentResource): AgentGenerateResult;
454
+ /**
455
+ * Transforms a document using the agent.
456
+ * @param instance - The Sanity instance.
457
+ * @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.
458
+ * @returns An Observable emitting the result of the agent transform action.
459
+ * @alpha
460
+ */
461
+ declare function agentTransform(instance: SanityInstance, options: AgentTransformOptions, resource?: DocumentResource): AgentTransformResult;
462
+ /**
463
+ * Translates a document using the agent.
464
+ * @param instance - The Sanity instance.
465
+ * @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.
466
+ * @returns An Observable emitting the result of the agent translate action.
467
+ * @alpha
468
+ */
469
+ declare function agentTranslate(instance: SanityInstance, options: AgentTranslateOptions, resource?: DocumentResource): AgentTranslateResult;
470
+ /**
471
+ * Prompts the agent using the same instruction template format as the other actions, but returns text or json instead of acting on a document.
472
+ * @param instance - The Sanity instance.
473
+ * @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.
474
+ * @returns An Observable emitting the result of the agent prompt action.
475
+ * @alpha
476
+ */
477
+ declare function agentPrompt(instance: SanityInstance, options: AgentPromptOptions, resource?: DocumentResource): Observable<AgentPromptResult>;
478
+ /**
479
+ * Patches a document using the agent.
480
+ * @param instance - The Sanity instance.
481
+ * @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.
482
+ * @returns An Observable emitting the result of the agent patch action.
483
+ * @alpha
484
+ */
485
+ declare function agentPatch(instance: SanityInstance, options: AgentPatchOptions, resource?: DocumentResource): Observable<AgentPatchResult>;
486
+ /**
487
+ * Represents the various states the authentication type can be in.
488
+ *
489
+ * @public
490
+ */
491
+ declare enum AuthStateType {
492
+ LOGGED_IN = "logged-in",
493
+ LOGGING_IN = "logging-in",
494
+ ERROR = "error",
495
+ LOGGED_OUT = "logged-out"
496
+ }
497
+ /**
498
+ * Error message returned by the organization verification
499
+ * @public
500
+ */
501
+ interface OrgVerificationResult {
502
+ error: string | null;
503
+ }
504
+ /**
505
+ * Creates an observable that emits the organization verification state for a given instance.
506
+ * It combines the dashboard organization ID (from auth context) with the
507
+ * project's actual organization ID (fetched via getProjectState) and compares them.
508
+ * @public
509
+ */
510
+ declare function observeOrganizationVerificationState(instance: SanityInstance, projectIds: string[]): Observable<OrgVerificationResult>;
511
+ /**
512
+ * Defines a store action that operates on a specific state type
513
+ */
514
+ type StoreAction<TState, TParams extends unknown[], TReturn, TKey = unknown> = (context: StoreContext<TState, TKey>, ...params: TParams) => TReturn;
515
+ /**
516
+ * Represents a store action that has been bound to a specific store instance
517
+ */
518
+ type BoundStoreAction<_TState, TParams extends unknown[], TReturn> = (instance: SanityInstance, ...params: TParams) => TReturn;
519
+ /**
520
+ * @public
521
+ */
522
+ declare const handleAuthCallback: BoundStoreAction<AuthStoreState, [locationHref?: string | undefined], Promise<string | false>>;
523
+ /**
524
+ * @public
525
+ */
526
+ declare const logout: BoundStoreAction<AuthStoreState, [], Promise<void>>;
527
+ type AllowedClientConfigKey = 'useCdn' | 'token' | 'perspective' | 'apiHost' | 'proxy' | 'withCredentials' | 'timeout' | 'maxRetries' | 'dataset' | 'projectId' | 'requestTagPrefix' | 'useProjectHostname';
528
+ /**
529
+ * States tracked by the client store
530
+ * @public
531
+ */
532
+ interface ClientStoreState {
533
+ token: string | null;
534
+ clients: { [TKey in string]?: SanityClient; };
535
+ authMethod?: 'localstorage' | 'cookie';
536
+ }
537
+ /**
538
+ * Options used when retrieving a client instance from the client store.
539
+ *
540
+ * This interface extends the base {@link ClientConfig} and adds:
541
+ *
542
+ * - **apiVersion:** A required string indicating the API version for the client.
543
+ * - **scope:** An optional flag to choose between the project-specific client
544
+ * ('project') and the global client ('global'). When set to `'global'`, the
545
+ * global client is used.
546
+ *
547
+ * These options are utilized by `getClient` and `getClientState` to configure and
548
+ * return appropriate client instances that automatically handle authentication
549
+ * updates and configuration changes.
550
+ *
551
+ * @public
552
+ */
553
+ interface ClientOptions extends Pick<ClientConfig, AllowedClientConfigKey> {
554
+ /**
555
+ * An optional flag to choose between the default client (typically project-level)
556
+ * and the global client ('global'). When set to `'global'`, the global client
557
+ * is used.
558
+ */
559
+ scope?: 'default' | 'global';
560
+ /**
561
+ * A required string indicating the API version for the client.
562
+ */
563
+ apiVersion: string;
564
+ /**
565
+ * @internal
566
+ * The SDK resource to use for the client -- this will get transformed into a ClientConfig resource.
567
+ */
568
+ resource?: DocumentResource;
569
+ }
570
+ /**
571
+ * Retrieves a Sanity client instance configured with the provided options.
572
+ *
573
+ * This function returns a client instance configured for the project or as a
574
+ * global client based on the options provided. It ensures efficient reuse of
575
+ * client instances by returning the same instance for the same options.
576
+ * For automatic handling of authentication token updates, consider using
577
+ * `getClientState`.
578
+ *
579
+ * @public
580
+ */
581
+ declare const getClient: BoundStoreAction<ClientStoreState, [options: ClientOptions], SanityClient>;
582
+ /**
583
+ * Returns a state source for the Sanity client instance.
584
+ *
585
+ * This function provides a subscribable state source that emits updated client
586
+ * instances whenever relevant configurations change (such as authentication tokens).
587
+ * Use this when you need to react to client configuration changes in your application.
588
+ *
589
+ * @public
590
+ */
591
+ declare const getClientState: BoundStoreAction<ClientStoreState, [options: ClientOptions], StateSource<SanityClient>>;
592
+ /**
593
+ * Message sent from a containing app to an iframe
594
+ * @public
595
+ */
596
+ type FrameMessage = Message;
597
+ /**
598
+ * Message sent from an iframe to a containing app
599
+ * @public
600
+ */
601
+ type WindowMessage = Message;
602
+ /**
603
+ * Message from SDK (iframe) to Parent (dashboard) to request a new token
604
+ * @internal
605
+ */
606
+ type RequestNewTokenMessage = {
607
+ type: 'dashboard/v1/auth/tokens/create';
608
+ payload?: undefined;
609
+ };
610
+ /**
611
+ * Message from Parent (dashboard) to SDK (iframe) with the new token
612
+ * @internal
613
+ */
614
+ type NewTokenResponseMessage = {
615
+ type: 'dashboard/v1/auth/tokens/create';
616
+ payload: {
617
+ token: string | null;
618
+ error?: string;
619
+ };
620
+ };
621
+ /**
622
+ * Individual channel with its relevant options
623
+ * @public
624
+ */
625
+ interface ChannelEntry {
626
+ channel: ChannelInstance<FrameMessage, WindowMessage>;
627
+ options: ChannelInput;
628
+ refCount: number;
629
+ }
630
+ /**
631
+ * Internal state tracking comlink connections
632
+ * @public
633
+ */
634
+ interface ComlinkControllerState {
635
+ controller: Controller | null;
636
+ controllerOrigin: string | null;
637
+ channels: Map<string, ChannelEntry>;
638
+ }
639
+ /**
640
+ * Calls the destroy method on the controller and resets the controller state.
641
+ * @public
642
+ */
643
+ declare const destroyController: BoundStoreAction<ComlinkControllerState, [], void>;
644
+ /**
645
+ * Retrieve or create a channel to be used for communication between
646
+ * an application and the controller.
647
+ * @public
648
+ */
649
+ declare const getOrCreateChannel: BoundStoreAction<ComlinkControllerState, [options: ChannelInput], ChannelInstance<import("@sanity/comlink").Message, import("@sanity/comlink").Message>>;
650
+ /**
651
+ * Initializes or fetches a controller to handle communication
652
+ * between an application and iframes.
653
+ * @public
654
+ */
655
+ declare const getOrCreateController: BoundStoreAction<ComlinkControllerState, [targetOrigin: string], Controller>;
656
+ /**
657
+ * Signals to the store that the consumer has stopped using the channel
658
+ * @public
659
+ */
660
+ declare const releaseChannel: BoundStoreAction<ComlinkControllerState, [name: string], void>;
661
+ /**
662
+ * Individual node with its relevant options
663
+ * @public
664
+ */
665
+ interface NodeEntry {
666
+ node: Node<WindowMessage, FrameMessage>;
667
+ options: NodeInput;
668
+ status: Status;
669
+ statusUnsub?: () => void;
670
+ }
671
+ /**
672
+ * Internal state tracking comlink connections
673
+ * @public
674
+ */
675
+ interface ComlinkNodeState {
676
+ nodes: Map<string, NodeEntry>;
677
+ subscriptions: Map<string, Set<symbol>>;
678
+ }
679
+ /**
680
+ * Signals to the store that the consumer has stopped using the node
681
+ * @public
682
+ */
683
+ declare const releaseNode: BoundStoreAction<ComlinkNodeState, [name: string], void>;
684
+ /**
685
+ * Retrieve or create a node to be used for communication between
686
+ * an application and the controller -- specifically, a node should
687
+ * be created within a frame / window to communicate with the controller.
688
+ * @public
689
+ */
690
+ declare const getOrCreateNode: BoundStoreAction<ComlinkNodeState, [options: NodeInput], Node<import("@sanity/comlink").Message, import("@sanity/comlink").Message>>;
691
+ /**
692
+ * @public
693
+ */
694
+ interface NodeState {
695
+ node: Node<WindowMessage, FrameMessage>;
696
+ status: Status | undefined;
697
+ }
698
+ /**
699
+ * Provides a subscribable state source for a node by name
700
+ * @param instance - The Sanity instance to get the node state for
701
+ * @param nodeInput - The configuration for the node to get the state for
702
+ * @returns A subscribable state source for the node
703
+ * @public
704
+ */
705
+ declare const getNodeState: BoundStoreAction<ComlinkNodeState, [NodeInput], StateSource<NodeState | undefined>>;
706
+ /**
707
+ * Whether a thread is still being discussed or has been closed out.
708
+ * @beta
709
+ */
710
+ type CommentStatus = 'open' | 'resolved';
711
+ /**
712
+ * The body of a comment, as Portable Text.
713
+ *
714
+ * Mentions appear here as inline objects of type `mention` carrying a `userId`.
715
+ * The SDK stores and returns them untouched, so a mention written in the Studio
716
+ * survives a round trip, but there is no API for composing one yet.
717
+ * @beta
718
+ */
719
+ type CommentMessage = PortableTextBlock[] | null;
720
+ /**
721
+ * One block touched by a text selection, and that block's text with the
722
+ * selection boundaries marked.
723
+ *
724
+ * `text` is the block's *entire* plain text with two private-use sentinel
725
+ * characters (U+F000 and U+F001) inserted where the selection starts and ends.
726
+ * Storing marked-up text rather than character offsets is what lets a highlight
727
+ * survive edits elsewhere in the same block.
728
+ * @beta
729
+ */
730
+ interface CommentTextSelectionItem {
731
+ _key: string;
732
+ text: string;
733
+ }
734
+ /**
735
+ * A comment anchored to a run of text inside a Portable Text field.
736
+ *
737
+ * The SDK passes this through untouched. Resolving it back to a position in a
738
+ * live editor needs the editor's current value, so that lives in
739
+ * `@portabletext/plugin-sdk-value` rather than here.
740
+ * @beta
741
+ */
742
+ interface CommentTextSelection {
743
+ type: 'text';
744
+ value: CommentTextSelectionItem[];
745
+ }
746
+ /**
747
+ * An emoji reaction on a comment.
748
+ *
749
+ * Read only for now: a reaction added in the Studio shows up here, but there is
750
+ * no action for adding or removing one.
751
+ * @beta
752
+ */
753
+ interface CommentReaction {
754
+ shortName: string;
755
+ userId: string;
756
+ addedAt: string;
757
+ }
758
+ /**
759
+ * Why a comment is not yet on the server.
760
+ *
761
+ * Local only, never written. Present on a comment whose create request failed,
762
+ * so an app can offer a retry.
763
+ * @beta
764
+ */
765
+ type CommentLocalState = {
766
+ type: 'createError';
767
+ error: Error;
768
+ } | {
769
+ type: 'createRetrying';
770
+ };
771
+ /**
772
+ * A single comment.
773
+ *
774
+ * Deliberately not the stored document. Comments are moving from per-dataset
775
+ * addon datasets to an organization-level store, and the two disagree on the
776
+ * document type, on how the commented document is referenced, and on where the
777
+ * author is recorded. Everything here reads the same on both sides, so an app
778
+ * written against this survives the move.
779
+ *
780
+ * Threads are flat: every comment in a thread shares a `threadId`, the thread's
781
+ * first comment has no `parentCommentId`, and replies carry that first comment's
782
+ * `id`. Use {@link CommentThread} to work with them grouped.
783
+ *
784
+ * @beta
785
+ */
786
+ interface Comment {
787
+ id: string;
788
+ createdAt: string;
789
+ /**
790
+ * Who wrote it.
791
+ *
792
+ * Absent when the server carries the author instead of the document. The
793
+ * Studio's comments dataset stores it on the document, so it is present on
794
+ * everything written today, but an agent-authored comment records
795
+ * attribution elsewhere. Render a fallback rather than assuming a user id.
796
+ */
797
+ authorId?: string;
798
+ message: CommentMessage;
799
+ threadId: string;
800
+ /** Absent on the comment that starts a thread. */
801
+ parentCommentId?: string;
802
+ status: CommentStatus;
803
+ /** Set once the message has been rewritten. */
804
+ lastEditedAt?: string;
805
+ /** The document the thread hangs on, always the published id. */
806
+ documentId: string;
807
+ documentType: string;
808
+ /** The field the thread hangs off, for example `title`. */
809
+ fieldPath: string;
810
+ /** Set when the comment is anchored to a run of text in a Portable Text field. */
811
+ selection?: CommentTextSelection;
812
+ /** A copy of the content the comment was written about. */
813
+ contentSnapshot?: unknown;
814
+ reactions: CommentReaction[];
815
+ /** Local only. Present while a create is failing or being retried. */
816
+ state?: CommentLocalState;
817
+ }
818
+ /**
819
+ * A thread: one comment plus its replies.
820
+ *
821
+ * Unlike the Studio, the SDK returns every thread it finds. The Studio hides
822
+ * threads whose field is gone from the schema or hidden by a conditional, which
823
+ * it can do because it has the schema. Check `fieldPath` yourself if your app
824
+ * needs the same behaviour.
825
+ * @beta
826
+ */
827
+ interface CommentThread {
828
+ threadId: string;
829
+ /** The field the thread hangs off, taken from its first comment. */
830
+ fieldPath: string;
831
+ parentComment: Comment;
832
+ /** Oldest first. */
833
+ replies: Comment[];
834
+ /** The parent plus its replies. */
835
+ commentsCount: number;
836
+ /** Taken from the parent comment; replies follow it. */
837
+ status: CommentStatus;
838
+ /** `createdAt` of the most recent comment in the thread. */
839
+ lastActivityAt: string;
840
+ }
841
+ /** @beta */
842
+ interface CreateCommentOptions extends DocumentHandle {
843
+ message: CommentMessage;
844
+ /**
845
+ * Which field the thread hangs off, for example `title` or
846
+ * `body[_key=="intro"].content`.
847
+ *
848
+ * Required, and it has to resolve to a real path. There is no such thing as a
849
+ * comment on a document as a whole: the Studio only ever creates field
850
+ * comments, and its comment inspector throws on an empty path rather than
851
+ * ignoring it, so a pathless comment takes the inspector down for everyone
852
+ * looking at that document.
853
+ */
854
+ fieldPath: string | Path;
855
+ /**
856
+ * Anchors the comment to a run of text inside a Portable Text field. Building
857
+ * one needs a live editor, so this comes from
858
+ * `@portabletext/plugin-sdk-value` rather than being constructed by hand.
859
+ */
860
+ selection?: CommentTextSelection;
861
+ /** Reuse the id of a failed comment to retry it. Defaults to a new id. */
862
+ commentId?: string;
863
+ /** Defaults to a new id, which starts a new thread. */
864
+ threadId?: string;
865
+ /** @defaultValue `'open'` */
866
+ status?: CommentStatus;
867
+ /**
868
+ * The `_rev` of the document when the comment was written.
869
+ *
870
+ * Not filled in automatically: the SDK's local document revision is replaced
871
+ * by a transaction id while an edit is in flight, so it can name a revision
872
+ * that never reached the server. Nothing in the Studio reads this today.
873
+ */
874
+ documentRevisionId?: string;
875
+ /**
876
+ * Ambient information stored alongside the comment, merged over the defaults.
877
+ *
878
+ * The Studio writes `tool`, `payload`, `intent`, and `notification` here for
879
+ * its notification backend. The SDK has no source for any of them, so
880
+ * mentions in comments created this way do not send email unless you supply
881
+ * `notification` yourself. Deliberately loose: the organization-level store
882
+ * treats this as free-form, so no shape is worth promising.
883
+ */
884
+ context?: Record<string, unknown>;
885
+ /** A copy of the content being discussed. References in it are weakened. */
886
+ contentSnapshot?: unknown;
887
+ }
888
+ /** @beta */
889
+ interface ReplyToCommentOptions extends DocumentHandle {
890
+ /** The comment being replied to. Replies to a reply join the same thread. */
891
+ parentCommentId: string;
892
+ message: CommentMessage;
893
+ commentId?: string;
894
+ /** Only needed when the parent is not loaded, such as following a deep link. */
895
+ threadId?: string;
896
+ /** Only needed when the parent is not loaded. */
897
+ fieldPath?: string | Path;
898
+ /** Required when the parent is not loaded. */
899
+ status?: CommentStatus;
900
+ }
901
+ /** @beta */
902
+ interface UpdateCommentOptions extends DatasetHandle {
903
+ commentId: string;
904
+ message: CommentMessage;
905
+ }
906
+ /** @beta */
907
+ interface SetCommentStatusOptions extends DatasetHandle {
908
+ /** The thread's first comment. Replies follow their parent. */
909
+ commentId: string;
910
+ status: CommentStatus;
911
+ }
912
+ /** @beta */
913
+ interface RemoveCommentOptions extends DatasetHandle {
914
+ commentId: string;
915
+ }
916
+ /**
917
+ * Starts a thread on a document, or on one of its fields.
918
+ *
919
+ * Creates the project's comments dataset if this is the first comment anywhere
920
+ * in it. The comment appears locally before the server confirms it; if the
921
+ * write fails it stays, carrying `_state.createError`, and retrying with the
922
+ * same `commentId` replaces it.
923
+ *
924
+ * @beta
925
+ */
926
+ declare const createComment: (instance: SanityInstance, options: CreateCommentOptions) => Promise<Comment>;
927
+ /**
928
+ * Adds a reply to an existing thread.
929
+ *
930
+ * The thread and field are taken from the parent comment, so a reply always
931
+ * matches the same list as the comment it answers. Supply them only when the
932
+ * parent is not loaded.
933
+ *
934
+ * @beta
935
+ */
936
+ declare const replyToComment: (instance: SanityInstance, options: ReplyToCommentOptions) => Promise<Comment>;
937
+ /**
938
+ * Rewrites a comment's message and stamps `lastEditedAt`.
939
+ * @beta
940
+ */
941
+ declare const updateComment: (instance: SanityInstance, options: UpdateCommentOptions) => Promise<void>;
942
+ /**
943
+ * Resolves or reopens a thread.
944
+ *
945
+ * Pass the thread's first comment: replies follow it, patched server-side in
946
+ * one query so a reply created by someone else at the same moment is caught
947
+ * too.
948
+ *
949
+ * @beta
950
+ */
951
+ declare const setCommentStatus: (instance: SanityInstance, options: SetCommentStatusOptions) => Promise<void>;
952
+ /**
953
+ * Deletes a comment, and its replies when it starts a thread.
954
+ * @beta
955
+ */
956
+ declare const removeComment: (instance: SanityInstance, options: RemoveCommentOptions) => Promise<void>;
957
+ /**
958
+ * Represents a reactive state source that provides synchronized access to store data
959
+ *
960
+ * @remarks
961
+ * Designed to work with React's useSyncExternalStore hook. Provides three ways to access data:
962
+ * 1. `getCurrent()` for synchronous current value access
963
+ * 2. `subscribe()` for imperative change notifications
964
+ * 3. `observable` for reactive stream access
965
+ *
966
+ * @public
967
+ */
968
+ interface StateSource<T> {
969
+ /**
970
+ * Subscribes to state changes with optional callback
971
+ * @param onStoreChanged - Called whenever relevant state changes occur
972
+ * @returns Unsubscribe function to clean up the subscription
973
+ */
974
+ subscribe: (onStoreChanged?: () => void) => () => void;
975
+ /**
976
+ * Gets the current derived state value
977
+ *
978
+ * @remarks
979
+ * Safe to call without subscription. Will always return the latest value
980
+ * based on the current store state and selector parameters.
981
+ */
982
+ getCurrent: () => T;
983
+ /**
984
+ * Observable stream of state values
985
+ *
986
+ * @remarks
987
+ * Shares a single underlying subscription between all observers. Emits:
988
+ * - Immediately with current value on subscription
989
+ * - On every relevant state change
990
+ * - Errors if selector throws
991
+ */
992
+ observable: Observable<T>;
993
+ }
994
+ /**
995
+ * Context passed to selectors when deriving state
996
+ *
997
+ * @remarks
998
+ * Provides access to both the current state value and the Sanity instance,
999
+ * allowing selectors to use configuration values when computing derived state.
1000
+ * The context is memoized for each state object and instance combination
1001
+ * to optimize performance and prevent unnecessary recalculations.
1002
+ *
1003
+ * @example
1004
+ * ```ts
1005
+ * // Using both state and instance in a selector (psuedo example)
1006
+ * const getUserByProjectId = createStateSourceAction(
1007
+ * ({ state, instance }: SelectorContext<UsersState>, options?: ProjectHandle) => {
1008
+ * const allUsers = state.users
1009
+ * const projectId = options?.projectId ?? instance.config.projectId
1010
+ * return allUsers.filter(user => user.projectId === projectId)
1011
+ * }
1012
+ * )
1013
+ * ```
1014
+ */
1015
+ interface SelectorContext<TState> {
1016
+ /**
1017
+ * The current state object from the store
1018
+ */
1019
+ state: TState;
1020
+ /**
1021
+ * The Sanity instance associated with this state
1022
+ */
1023
+ instance: SanityInstance;
1024
+ }
1025
+ /**
1026
+ * Function type for selecting derived state from store state and parameters
1027
+ * @public
1028
+ */
1029
+ type Selector<TState, TParams extends unknown[], TReturn> = (context: SelectorContext<TState>, ...params: TParams) => TReturn;
1030
+ /**
1031
+ * Which comments to read.
1032
+ * @beta
1033
+ */
1034
+ interface CommentsOptions extends DocumentHandle {
1035
+ /**
1036
+ * Narrow to one field. Omit to get every comment on the document.
1037
+ */
1038
+ fieldPath?: string | Path;
1039
+ /** Narrow to open or resolved threads. Omit for both. */
1040
+ status?: CommentStatus;
1041
+ }
1042
+ /** @beta */
1043
+ interface ResolveCommentsOptions extends CommentsOptions {
1044
+ signal?: AbortSignal;
1045
+ }
1046
+ /**
1047
+ * A stable string standing for one set of read options.
1048
+ *
1049
+ * Only React needs this: it holds one state source steady across renders and
1050
+ * defers swapping to a new one while the previous list is still on screen.
1051
+ * `fieldPath` is normalised on the way in, so a path array and the equivalent
1052
+ * string address the same list.
1053
+ *
1054
+ * @internal
1055
+ */
1056
+ declare function getCommentsOptionsKey(options: CommentsOptions): string;
1057
+ /** @internal */
1058
+ declare function parseCommentsOptionsKey(key: string): CommentsOptions;
1059
+ /**
1060
+ * Every comment on a document, newest first.
1061
+ *
1062
+ * `undefined` until the first snapshot arrives. Replies are included; use
1063
+ * {@link getCommentThreadsState} to read them grouped.
1064
+ *
1065
+ * @beta
1066
+ */
1067
+ declare const getCommentsState: (instance: SanityInstance, options: CommentsOptions) => StateSource<Comment[] | undefined>;
1068
+ /**
1069
+ * Threads on a document, newest thread first, each with its replies oldest first.
1070
+ *
1071
+ * A thread's `status` and `fieldPath` come from its first comment, so filtering
1072
+ * by either selects whole threads rather than individual replies.
1073
+ *
1074
+ * @beta
1075
+ */
1076
+ declare const getCommentThreadsState: (instance: SanityInstance, options: CommentsOptions) => StateSource<CommentThread[] | undefined>;
1077
+ /**
1078
+ * Waits for a document's comments to load.
1079
+ *
1080
+ * Holds a subscriber only while resolving, so a component that suspends on this
1081
+ * and then errors before mounting does not strand the list. Throw the promise
1082
+ * for Suspense, then read through {@link getCommentsState}.
1083
+ *
1084
+ * @beta
1085
+ */
1086
+ declare const resolveComments: (instance: SanityInstance, options: ResolveCommentsOptions) => Promise<Comment[]>;
1087
+ /**
1088
+ * Waits for a document's comments to load, grouped into threads.
1089
+ * @beta
1090
+ */
1091
+ declare const resolveCommentThreads: (instance: SanityInstance, options: ResolveCommentsOptions) => Promise<CommentThread[]>;
1092
+ /**
1093
+ * Creates or validates a `DocumentHandle` object.
1094
+ * Ensures the provided object conforms to the `DocumentHandle` interface.
1095
+ * @param handle - The object containing document identification properties.
1096
+ * @returns The validated `DocumentHandle` object.
1097
+ * @public
1098
+ */
1099
+ declare function createDocumentHandle<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string>(handle: DocumentHandle<TDocumentType, TDataset, TProjectId>): DocumentHandle<TDocumentType, TDataset, TProjectId>;
1100
+ /**
1101
+ * Creates or validates a `DocumentTypeHandle` object.
1102
+ * Ensures the provided object conforms to the `DocumentTypeHandle` interface.
1103
+ * @param handle - The object containing document type identification properties.
1104
+ * @returns The validated `DocumentTypeHandle` object.
1105
+ * @public
1106
+ */
1107
+ declare function createDocumentTypeHandle<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string>(handle: DocumentTypeHandle<TDocumentType, TDataset, TProjectId>): DocumentTypeHandle<TDocumentType, TDataset, TProjectId>;
1108
+ /**
1109
+ * Creates or validates a `ProjectHandle` object.
1110
+ * Ensures the provided object conforms to the `ProjectHandle` interface.
1111
+ * @param handle - The object containing project identification properties.
1112
+ * @returns The validated `ProjectHandle` object.
1113
+ * @public
1114
+ */
1115
+ declare function createProjectHandle<TProjectId extends string = string>(handle: ProjectHandle<TProjectId>): ProjectHandle<TProjectId>;
1116
+ /**
1117
+ * Creates or validates a `DatasetHandle` object.
1118
+ * Ensures the provided object conforms to the `DatasetHandle` interface.
1119
+ * @param handle - The object containing dataset identification properties.
1120
+ * @returns The validated `DatasetHandle` object.
1121
+ * @public
1122
+ */
1123
+ declare function createDatasetHandle<TDataset extends string = string, TProjectId extends string = string>(handle: DatasetHandle<TDataset, TProjectId>): DatasetHandle<TDataset, TProjectId>;
1124
+ /**
1125
+ * Logging infrastructure for the Sanity SDK
1126
+ *
1127
+ * Provides multi-level, namespace-based logging for both SDK users and maintainers.
1128
+ * In production builds, all logging can be stripped via tree-shaking.
1129
+ *
1130
+ * @example SDK User
1131
+ * ```ts
1132
+ * import {configureLogging} from '@sanity/sdk'
1133
+ *
1134
+ * configureLogging({
1135
+ * level: 'info',
1136
+ * namespaces: ['auth', 'document']
1137
+ * })
1138
+ * ```
1139
+ *
1140
+ * @example SDK Maintainer
1141
+ * ```ts
1142
+ * configureLogging({
1143
+ * level: 'trace',
1144
+ * namespaces: ['*'],
1145
+ * internal: true
1146
+ * })
1147
+ * ```
1148
+ */
1149
+ /**
1150
+ * Log levels in order of verbosity (least to most)
1151
+ * - error: Critical failures that prevent operation
1152
+ * - warn: Issues that may cause problems but don't stop execution
1153
+ * - info: High-level informational messages (SDK user level)
1154
+ * - debug: Detailed debugging information (maintainer level)
1155
+ * - trace: Very detailed tracing (maintainer level, includes RxJS streams)
1156
+ * @public
1157
+ */
1158
+ type LogLevel = 'error' | 'warn' | 'info' | 'debug' | 'trace';
1159
+ /**
1160
+ * Log namespaces organize logs by functional domain
1161
+ *
1162
+ * @remarks
1163
+ * This is an extensible string type. As logging is added to more modules,
1164
+ * additional namespaces will be recognized. Currently implemented namespaces
1165
+ * will be documented as they are added.
1166
+ * @internal
1167
+ */
1168
+ type LogNamespace = string;
1169
+ /**
1170
+ * Configuration for the logging system
1171
+ * @public
1172
+ */
1173
+ interface LoggerConfig {
1174
+ /**
1175
+ * Minimum log level to output
1176
+ * @defaultValue 'warn'
1177
+ */
1178
+ level?: LogLevel;
1179
+ /**
1180
+ * Namespaces to enable. Use ['*'] for all namespaces
1181
+ * @defaultValue []
1182
+ * @remarks
1183
+ * Available namespaces depend on which modules have logging integrated.
1184
+ * Check the SDK documentation for the current list of instrumented modules.
1185
+ * @example ['auth', 'document']
1186
+ */
1187
+ namespaces?: string[];
1188
+ /**
1189
+ * Enable internal/maintainer-level logging
1190
+ * Shows RxJS streams, store internals, etc.
1191
+ * @defaultValue false
1192
+ */
1193
+ internal?: boolean;
1194
+ /**
1195
+ * Custom log handler (for testing or custom output)
1196
+ * @defaultValue console methods
1197
+ */
1198
+ handler?: LogHandler;
1199
+ /**
1200
+ * Enable timestamps in log output
1201
+ * @defaultValue true
1202
+ */
1203
+ timestamps?: boolean;
1204
+ /**
1205
+ * Enable in production builds
1206
+ * @defaultValue false
1207
+ */
1208
+ enableInProduction?: boolean;
1209
+ }
1210
+ /**
1211
+ * Custom log handler interface
1212
+ *
1213
+ * @internal
1214
+ */
1215
+ interface LogHandler {
1216
+ error: (message: string, context?: LogContext) => void;
1217
+ warn: (message: string, context?: LogContext) => void;
1218
+ info: (message: string, context?: LogContext) => void;
1219
+ debug: (message: string, context?: LogContext) => void;
1220
+ trace: (message: string, context?: LogContext) => void;
1221
+ }
1222
+ /**
1223
+ * Context object attached to log messages
1224
+ *
1225
+ * This interface allows you to attach arbitrary contextual data to log messages.
1226
+ * The index signature `[key: string]: unknown` enables you to add any custom
1227
+ * properties relevant to your log entry (e.g., `userId`, `documentId`, `action`, etc.).
1228
+ *
1229
+ * **Sensitive data sanitization:**
1230
+ * Top-level keys containing sensitive names (`token`, `password`, `secret`, `apiKey`,
1231
+ * `authorization`) are automatically redacted to `[REDACTED]` in log output.
1232
+ *
1233
+ * @example
1234
+ * ```ts
1235
+ * logger.info('User logged in', {
1236
+ * userId: '123', // Custom context
1237
+ * action: 'login', // Custom context
1238
+ * token: 'secret' // Will be redacted to [REDACTED]
1239
+ * })
1240
+ * ```
1241
+ *
1242
+ * @internal
1243
+ */
1244
+ interface LogContext {
1245
+ /**
1246
+ * Custom context properties that provide additional information about the log entry.
1247
+ * Any key-value pairs can be added here (e.g., userId, documentId, requestId, etc.).
1248
+ * Keys with sensitive names (token, password, secret, apiKey, authorization) are
1249
+ * automatically sanitized.
1250
+ */
1251
+ [key: string]: unknown;
1252
+ /** Error object if logging an error */
1253
+ error?: Error | unknown;
1254
+ /** Duration in milliseconds for timed operations */
1255
+ duration?: number;
1256
+ /** Stack trace for debugging */
1257
+ stack?: string;
1258
+ /** Instance context (automatically added when available) */
1259
+ instanceContext?: InstanceContext;
1260
+ }
1261
+ /**
1262
+ * Instance context information automatically added to logs
1263
+ * @internal
1264
+ */
1265
+ interface InstanceContext {
1266
+ /** Unique instance ID */
1267
+ instanceId?: string;
1268
+ /** Project ID */
1269
+ projectId?: string;
1270
+ /** Dataset name */
1271
+ dataset?: string;
1272
+ }
1273
+ /**
1274
+ * Logger instance for a specific namespace
1275
+ * @internal
1276
+ */
1277
+ interface Logger {
1278
+ readonly namespace: string;
1279
+ error: (message: string, context?: LogContext) => void;
1280
+ warn: (message: string, context?: LogContext) => void;
1281
+ info: (message: string, context?: LogContext) => void;
1282
+ debug: (message: string, context?: LogContext) => void;
1283
+ trace: (message: string, context?: LogContext) => void;
1284
+ /** Check if a log level is enabled (for performance-sensitive code) */
1285
+ isLevelEnabled: (level: LogLevel) => boolean;
1286
+ /** Create a child logger with extended context */
1287
+ child: (context: LogContext) => Logger;
1288
+ /** Get the instance context if available */
1289
+ getInstanceContext: () => InstanceContext | undefined;
1290
+ }
1291
+ /**
1292
+ * Configure logging for the Sanity SDK
1293
+ *
1294
+ * This function allows you to control what logs are output by the SDK,
1295
+ * making it easier to debug issues in development or production.
1296
+ *
1297
+ * @remarks
1298
+ * **Zero-Config via Environment Variable (Recommended):**
1299
+ *
1300
+ * The SDK automatically reads the `DEBUG` environment variable, making it
1301
+ * easy to enable logging without code changes:
1302
+ *
1303
+ * ```bash
1304
+ * # Enable all SDK logging at debug level
1305
+ * DEBUG=sanity:* npm start
1306
+ *
1307
+ * # Enable specific namespaces
1308
+ * DEBUG=sanity:auth,sanity:document npm start
1309
+ *
1310
+ * # Enable trace level for all namespaces
1311
+ * DEBUG=sanity:trace:* npm start
1312
+ *
1313
+ * # Enable internal/maintainer logs
1314
+ * DEBUG=sanity:*:internal npm start
1315
+ * ```
1316
+ *
1317
+ * This matches the pattern used by Sanity CLI and Studio, making it familiar
1318
+ * and easy for support teams to help troubleshoot issues.
1319
+ *
1320
+ * **Programmatic Configuration (Advanced):**
1321
+ *
1322
+ * For more control (custom handlers, dynamic configuration), call this function
1323
+ * explicitly. Programmatic configuration overrides environment variables.
1324
+ *
1325
+ * **For Application Developers:**
1326
+ * Use `info`, `warn`, or `error` levels to see high-level SDK activity
1327
+ * without being overwhelmed by internal details.
1328
+ *
1329
+ * **For SDK Maintainers:**
1330
+ * Use `debug` or `trace` levels with `internal: true` to see detailed
1331
+ * information about store operations, RxJS streams, and state transitions.
1332
+ *
1333
+ * **Instance Context:**
1334
+ * Logs automatically include instance information (projectId, dataset, instanceId)
1335
+ * when available, making it easier to debug multi-instance scenarios:
1336
+ * ```
1337
+ * [INFO] [auth] [project:abc] [dataset:production] User logged in
1338
+ * ```
1339
+ *
1340
+ * **Available Namespaces:**
1341
+ * - `sdk` - SDK initialization, configuration, and lifecycle
1342
+ * - `auth` - Authentication and authorization (when instrumented in the future)
1343
+ * - And more as logging is added to modules
1344
+ *
1345
+ * @example Zero-config via environment variable (recommended for debugging)
1346
+ * ```bash
1347
+ * # Just set DEBUG and run your app - no code changes needed!
1348
+ * DEBUG=sanity:* npm start
1349
+ * ```
1350
+ *
1351
+ * @example Programmatic configuration (application developer)
1352
+ * ```ts
1353
+ * import {configureLogging} from '@sanity/sdk'
1354
+ *
1355
+ * // Log warnings and errors for auth and document operations
1356
+ * configureLogging({
1357
+ * level: 'warn',
1358
+ * namespaces: ['auth', 'document']
1359
+ * })
1360
+ * ```
1361
+ *
1362
+ * @example Programmatic configuration (SDK maintainer)
1363
+ * ```ts
1364
+ * import {configureLogging} from '@sanity/sdk'
1365
+ *
1366
+ * // Enable all logs including internal traces
1367
+ * configureLogging({
1368
+ * level: 'trace',
1369
+ * namespaces: ['*'],
1370
+ * internal: true
1371
+ * })
1372
+ * ```
1373
+ *
1374
+ * @example Custom handler (for testing)
1375
+ * ```ts
1376
+ * import {configureLogging} from '@sanity/sdk'
1377
+ *
1378
+ * const logs: string[] = []
1379
+ * configureLogging({
1380
+ * level: 'info',
1381
+ * namespaces: ['*'],
1382
+ * handler: {
1383
+ * error: (msg) => logs.push(msg),
1384
+ * warn: (msg) => logs.push(msg),
1385
+ * info: (msg) => logs.push(msg),
1386
+ * debug: (msg) => logs.push(msg),
1387
+ * trace: (msg) => logs.push(msg),
1388
+ * }
1389
+ * })
1390
+ * ```
1391
+ *
1392
+ * @public
1393
+ */
1394
+ declare function configureLogging(config: LoggerConfig): void;
1395
+ /** @public */
1396
+ declare const getDatasetsState: BoundStoreAction<FetcherStoreState<[options?: ProjectHandle<string> | undefined], import("@sanity/client").DatasetsResponse>, [options?: ProjectHandle<string> | undefined], StateSource<import("@sanity/client").DatasetsResponse | undefined>>;
1397
+ /** @public */
1398
+ declare const resolveDatasets: BoundStoreAction<FetcherStoreState<[options?: ProjectHandle<string> | undefined], import("@sanity/client").DatasetsResponse>, [options?: ProjectHandle<string> | undefined], Promise<import("@sanity/client").DatasetsResponse>>;
1399
+ /**
1400
+ * Represents an action to create a new document.
1401
+ * Specifies the document type and optionally a document ID (which will be treated as the published ID).
1402
+ * @beta
1403
+ */
1404
+ interface CreateDocumentAction<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string> extends DocumentTypeHandle<TDocumentType, TDataset, TProjectId> {
1405
+ type: 'document.create';
1406
+ /**
1407
+ * Optional initial field values for the document.
1408
+ * These values will be set when the document is created.
1409
+ * System fields (_id, _type, _rev, _createdAt, _updatedAt) are omitted as they are set automatically.
1410
+ */
1411
+ initialValue?: Partial<Omit<SanityDocument$2<TDocumentType, `${TProjectId}.${TDataset}`>, '_id' | '_type' | '_rev' | '_createdAt' | '_updatedAt'>>;
1412
+ }
1413
+ /**
1414
+ * Represents an action to delete an existing document.
1415
+ * Requires the full document handle including the document ID.
1416
+ * @beta
1417
+ */
1418
+ interface DeleteDocumentAction<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string> extends DocumentHandle<TDocumentType, TDataset, TProjectId> {
1419
+ type: 'document.delete';
1420
+ }
1421
+ /**
1422
+ * Represents an action to edit an existing document using patches.
1423
+ * Requires the full document handle and an array of patch operations.
1424
+ * @beta
1425
+ */
1426
+ interface EditDocumentAction<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string> extends DocumentHandle<TDocumentType, TDataset, TProjectId> {
1427
+ type: 'document.edit';
1428
+ patches?: PatchOperations[];
1429
+ /**
1430
+ * When `true`, the given `patches` are forwarded verbatim to the server and
1431
+ * applied as-is locally, instead of being re-derived by diffing document
1432
+ * snapshots. This preserves the operational intent of the patches (e.g.
1433
+ * keyed array inserts/unsets), which lets concurrent edits from other
1434
+ * clients interleave coherently instead of being overwritten by
1435
+ * position-based patches computed from a stale snapshot.
1436
+ *
1437
+ * Use this when the patches were produced by an editor that tracks its own
1438
+ * operations (e.g. a collaborative text editor). During a rebase onto a
1439
+ * changed remote document, preserved patches are re-applied operationally;
1440
+ * if a patch can no longer apply, the transaction is skipped and reported
1441
+ * as a `rebase-error` document event.
1442
+ */
1443
+ preserveOperations?: boolean;
1444
+ }
1445
+ /**
1446
+ * Represents an action to publish the draft version of a document.
1447
+ * Requires the full document handle.
1448
+ * @beta
1449
+ */
1450
+ interface PublishDocumentAction<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string> extends DocumentHandle<TDocumentType, TDataset, TProjectId> {
1451
+ type: 'document.publish';
1452
+ }
1453
+ /**
1454
+ * Represents an action to unpublish a document, moving its published content to a draft.
1455
+ * Requires the full document handle.
1456
+ * @beta
1457
+ */
1458
+ interface UnpublishDocumentAction<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string> extends DocumentHandle<TDocumentType, TDataset, TProjectId> {
1459
+ type: 'document.unpublish';
1460
+ }
1461
+ /**
1462
+ * Represents an action to discard the draft changes of a document.
1463
+ * Requires the full document handle.
1464
+ * @beta
1465
+ */
1466
+ interface DiscardDocumentAction<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string> extends DocumentHandle<TDocumentType, TDataset, TProjectId> {
1467
+ type: 'document.discard';
1468
+ }
1469
+ /**
1470
+ * Union type representing all possible document actions within the SDK.
1471
+ * @beta
1472
+ */
1473
+ 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>;
1474
+ /**
1475
+ * Union of every action accepted by `applyDocumentActions` — both document-
1476
+ * level actions and release-lifecycle actions.
1477
+ * @beta
1478
+ */
1479
+ type Action<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string> = DocumentAction<TDocumentType, TDataset, TProjectId> | ReleaseAction;
1480
+ /**
1481
+ * Creates a `CreateDocumentAction` object.
1482
+ * @param doc - A handle identifying the document type, dataset, and project. An optional `documentId` can be provided.
1483
+ * @param initialValue - Optional initial field values for the document. (System fields are omitted as they are set automatically.)
1484
+ * @returns A `CreateDocumentAction` object ready for dispatch.
1485
+ * @beta
1486
+ */
1487
+ 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>;
1488
+ /**
1489
+ * Creates a `DeleteDocumentAction` object.
1490
+ * @param doc - A handle uniquely identifying the document to be deleted.
1491
+ * @returns A `DeleteDocumentAction` object ready for dispatch.
1492
+ * @beta
1493
+ */
1494
+ declare function deleteDocument<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string>(doc: DocumentHandle<TDocumentType, TDataset, TProjectId>): DeleteDocumentAction<TDocumentType, TDataset, TProjectId>;
1495
+ /**
1496
+ * Options for creating an `EditDocumentAction`.
1497
+ * @beta
1498
+ */
1499
+ interface EditDocumentOptions {
1500
+ /**
1501
+ * Forward the given patches verbatim instead of re-deriving them by
1502
+ * diffing document snapshots. See {@link EditDocumentAction.preserveOperations}.
1503
+ */
1504
+ preserveOperations?: boolean;
1505
+ }
1506
+ /**
1507
+ * Creates an `EditDocumentAction` object with patches for modifying a document.
1508
+ * Accepts patches in either the standard `PatchOperations` format or as a `SanityMutatePatchMutation` from `@sanity/mutate`.
1509
+ *
1510
+ * @param doc - A handle uniquely identifying the document to be edited.
1511
+ * @param sanityMutatePatch - A patch mutation object from `@sanity/mutate`.
1512
+ * @param options - Options controlling how the patches are processed.
1513
+ * @returns An `EditDocumentAction` object ready for dispatch.
1514
+ * @beta
1515
+ */
1516
+ declare function editDocument<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string>(doc: DocumentHandle<TDocumentType, TDataset, TProjectId>, sanityMutatePatch: PatchMutation, options?: EditDocumentOptions): EditDocumentAction<TDocumentType, TDataset, TProjectId>;
1517
+ /**
1518
+ * Creates an `EditDocumentAction` object with patches for modifying a document.
1519
+ *
1520
+ * @param doc - A handle uniquely identifying the document to be edited.
1521
+ * @param patches - A single patch operation or an array of patch operations.
1522
+ * @param options - Options controlling how the patches are processed.
1523
+ * @returns An `EditDocumentAction` object ready for dispatch.
1524
+ * @beta
1525
+ */
1526
+ declare function editDocument<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string>(doc: DocumentHandle<TDocumentType, TDataset, TProjectId>, patches?: PatchOperations | PatchOperations[], options?: EditDocumentOptions): EditDocumentAction<TDocumentType, TDataset, TProjectId>;
1527
+ /**
1528
+ * Creates a `PublishDocumentAction` object.
1529
+ * @param doc - A handle uniquely identifying the document to be published.
1530
+ * @returns A `PublishDocumentAction` object ready for dispatch.
1531
+ * @beta
1532
+ */
1533
+ declare function publishDocument<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string>(doc: DocumentHandle<TDocumentType, TDataset, TProjectId>): PublishDocumentAction<TDocumentType, TDataset, TProjectId>;
1534
+ /**
1535
+ * Creates an `UnpublishDocumentAction` object.
1536
+ * @param doc - A handle uniquely identifying the document to be unpublished.
1537
+ * @returns An `UnpublishDocumentAction` object ready for dispatch.
1538
+ * @beta
1539
+ */
1540
+ declare function unpublishDocument<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string>(doc: DocumentHandle<TDocumentType, TDataset, TProjectId>): UnpublishDocumentAction<TDocumentType, TDataset, TProjectId>;
1541
+ /**
1542
+ * Creates a `DiscardDocumentAction` object.
1543
+ * @param doc - A handle uniquely identifying the document whose draft changes are to be discarded.
1544
+ * @returns A `DiscardDocumentAction` object ready for dispatch.
1545
+ * @beta
1546
+ */
1547
+ declare function discardDocument<TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string>(doc: DocumentHandle<TDocumentType, TDataset, TProjectId>): DiscardDocumentAction<TDocumentType, TDataset, TProjectId>;
1548
+ /**
1549
+ * Creates a new release. The `releaseId` must be unique within the current
1550
+ * retention period.
1551
+ * @beta
1552
+ */
1553
+ interface CreateReleaseAction extends ReleaseHandle {
1554
+ type: 'release.create';
1555
+ metadata: ReleaseDocument['metadata'];
1556
+ }
1557
+ /**
1558
+ * Patches the metadata of an existing release.
1559
+ * @beta
1560
+ */
1561
+ interface EditReleaseAction extends ReleaseHandle {
1562
+ type: 'release.edit';
1563
+ patch: PatchOperations;
1564
+ }
1565
+ /**
1566
+ * Publishes all version documents in a release.
1567
+ * @beta
1568
+ */
1569
+ interface PublishReleaseAction extends ReleaseHandle {
1570
+ type: 'release.publish';
1571
+ }
1572
+ /**
1573
+ * Schedules a release to be published at the given UTC time. Locks the
1574
+ * version documents server-side until the release is unscheduled or published.
1575
+ * @beta
1576
+ */
1577
+ interface ScheduleReleaseAction extends ReleaseHandle {
1578
+ type: 'release.schedule';
1579
+ publishAt: string;
1580
+ }
1581
+ /**
1582
+ * Unschedules a release that was previously scheduled, returning it to the
1583
+ * active editable state.
1584
+ * @beta
1585
+ */
1586
+ interface UnscheduleReleaseAction extends ReleaseHandle {
1587
+ type: 'release.unschedule';
1588
+ }
1589
+ /**
1590
+ * Archives an active release. Version documents within the release are
1591
+ * removed and no longer queryable, though still recoverable through history
1592
+ * during the retention period.
1593
+ * @beta
1594
+ */
1595
+ interface ArchiveReleaseAction extends ReleaseHandle {
1596
+ type: 'release.archive';
1597
+ }
1598
+ /**
1599
+ * Restores an archived release. Only possible during the retention period.
1600
+ * @beta
1601
+ */
1602
+ interface UnarchiveReleaseAction extends ReleaseHandle {
1603
+ type: 'release.unarchive';
1604
+ }
1605
+ /**
1606
+ * Permanently deletes an archived or published release. To remove an active
1607
+ * release, use the archive action first.
1608
+ * @beta
1609
+ */
1610
+ interface DeleteReleaseAction extends ReleaseHandle {
1611
+ type: 'release.delete';
1612
+ }
1613
+ /**
1614
+ * Union of all release actions that can be dispatched alongside document
1615
+ * actions through `applyDocumentActions`.
1616
+ * @beta
1617
+ */
1618
+ type ReleaseAction = CreateReleaseAction | EditReleaseAction | PublishReleaseAction | ScheduleReleaseAction | UnscheduleReleaseAction | ArchiveReleaseAction | UnarchiveReleaseAction | DeleteReleaseAction;
1619
+ /** @beta */
1620
+ declare function createRelease(handle: ReleaseHandle, metadata?: ReleaseDocument['metadata']): CreateReleaseAction;
1621
+ /** @beta */
1622
+ declare function editRelease(handle: ReleaseHandle, patch: PatchOperations): EditReleaseAction;
1623
+ /** @beta */
1624
+ declare function publishRelease(handle: ReleaseHandle): PublishReleaseAction;
1625
+ /** @beta */
1626
+ declare function scheduleRelease(handle: ReleaseHandle, publishAt: string): ScheduleReleaseAction;
1627
+ /** @beta */
1628
+ declare function unscheduleRelease(handle: ReleaseHandle): UnscheduleReleaseAction;
1629
+ /** @beta */
1630
+ declare function archiveRelease(handle: ReleaseHandle): ArchiveReleaseAction;
1631
+ /** @beta */
1632
+ declare function unarchiveRelease(handle: ReleaseHandle): UnarchiveReleaseAction;
1633
+ /** @beta */
1634
+ declare function deleteRelease(handle: ReleaseHandle): DeleteReleaseAction;
1635
+ /**
1636
+ * Split the entire path string on dots "outside" of any brackets.
1637
+ *
1638
+ * For example:
1639
+ * ```
1640
+ * "friends[0].name"
1641
+ * ```
1642
+ *
1643
+ * becomes:
1644
+ *
1645
+ * ```
1646
+ * [...ParseSegment<"friends[0]">, ...ParseSegment<"name">]
1647
+ * ```
1648
+ *
1649
+ * (We use a simple recursion that splits on the first dot.)
1650
+ */
1651
+ type PathParts<TPath extends string> = TPath extends `${infer Head}.${infer Tail}` ? [Head, ...PathParts<Tail>] : TPath extends '' ? [] : [TPath];
1652
+ /**
1653
+ * Given a type T and an array of "access keys" Parts, recursively index into T.
1654
+ *
1655
+ * If a part is a key, it looks up that property.
1656
+ * If T is an array and the part is a number, it "indexes" into the element type.
1657
+ */
1658
+ type DeepGet<TValue, TPath extends readonly (string | number)[]> = TPath extends [] ? TValue : TPath extends readonly [infer THead, ...infer TTail] ? DeepGet<TValue extends undefined | null ? undefined : THead extends keyof TValue ? TValue[THead] : THead extends number ? TValue extends readonly (infer TElement)[] ? TElement | undefined : undefined : undefined // Key/index doesn't exist
1659
+ , TTail extends readonly (string | number)[] ? TTail : []> : never;
1660
+ /**
1661
+ * Given a document type TDocument and a JSON Match path string TPath,
1662
+ * compute the type found at that path.
1663
+ * @beta
1664
+ */
1665
+ type JsonMatch<TDocument, TPath extends string> = DeepGet<TDocument, PathParts<TPath>>;
1666
+ /**
1667
+ * Represents a set of document that will go into `applyMutations`. Before
1668
+ * applying a mutation, it's expected that all relevant documents that the
1669
+ * mutations affect are included, including those that do not exist yet.
1670
+ * Documents that don't exist have a `null` value.
1671
+ */
1672
+ type DocumentSet<TDocument extends SanityDocument$1 = SanityDocument$1> = { [TDocumentId in string]?: TDocument | null; };
1673
+ type Grant = 'read' | 'update' | 'create' | 'history';
1674
+ /** @beta */
1675
+ interface PermissionDeniedReason {
1676
+ type: 'precondition' | 'access';
1677
+ message: string;
1678
+ documentId?: string;
1679
+ }
1680
+ /** @beta */
1681
+ type DocumentPermissionsResult = {
1682
+ allowed: false;
1683
+ message: string;
1684
+ reasons: PermissionDeniedReason[];
1685
+ } | {
1686
+ allowed: true;
1687
+ message?: undefined;
1688
+ reasons?: undefined;
1689
+ };
1690
+ interface SharedListener {
1691
+ events: Observable<ListenEvent<SanityDocument>>;
1692
+ dispose: () => void;
1693
+ }
1694
+ interface DocumentStoreState {
1695
+ documentStates: { [TDocumentId in string]?: DocumentState; };
1696
+ queued: QueuedTransaction[];
1697
+ applied: AppliedTransaction[];
1698
+ outgoing?: OutgoingTransaction;
1699
+ grants?: Record<Grant, ExprNode>;
1700
+ /**
1701
+ * The current user's identity (their user ID).
1702
+ */
1703
+ identity?: string;
1704
+ error?: unknown;
1705
+ sharedListener: SharedListener;
1706
+ fetchDocument: (documentId: string) => Observable<SanityDocument$2 | null>;
1707
+ events: Subject<DocumentEvent>;
1708
+ }
1709
+ interface DocumentState {
1710
+ id: string;
1711
+ /**
1712
+ * the "remote" local copy that matches the server. represents the last known
1713
+ * server state. this gets updated every time we confirm remote patches
1714
+ */
1715
+ remote?: SanityDocument$2 | null;
1716
+ /**
1717
+ * the current ephemeral working copy that includes local optimistic changes
1718
+ * that have not yet been confirmed by the server
1719
+ */
1720
+ local?: SanityDocument$2 | null;
1721
+ /**
1722
+ * the revision that our remote document is at
1723
+ */
1724
+ remoteRev?: string | null;
1725
+ /**
1726
+ * Array of subscription IDs. This document state will be deleted if there are
1727
+ * no subscribers.
1728
+ */
1729
+ subscriptions: string[];
1730
+ /**
1731
+ * An object keyed by transaction ID of revisions sent out but that have not
1732
+ * yet been verified yet. When an applied transaction is transitioned to an
1733
+ * outgoing transaction, it also adds unverified revisions for each document
1734
+ * that is part of that outgoing transaction. Transactions are submitted to
1735
+ * the server with a locally generated transaction ID. This way we can observe
1736
+ * when our transaction comes back through the shared listener. Each listener
1737
+ * event that comes back contains a `previousRev`. If we see our own
1738
+ * transaction with a different `previousRev` than expected, we can rebase our
1739
+ * local transactions on top of this new remote.
1740
+ */
1741
+ unverifiedRevisions?: { [TTransactionId in string]?: UnverifiedDocumentRevision; };
1742
+ /**
1743
+ * transaction IDs recently submitted by this client for this document,
1744
+ * newest last. used to label `remote-patches` events with the correct
1745
+ * `origin` even after the corresponding `unverifiedRevisions` entry has
1746
+ * been pruned (e.g. by a sync event that raced the listener echo). capped
1747
+ * to the most recent entries.
1748
+ */
1749
+ recentOwnTransactionIds?: string[];
1750
+ }
1751
+ /**
1752
+ * @beta
1753
+ * Options for specifying a document and optionally a path within it.
1754
+ */
1755
+ interface DocumentOptions<TPath extends string | undefined = undefined, TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string> extends DocumentHandle<TDocumentType, TDataset, TProjectId> {
1756
+ path?: TPath;
1757
+ }
1758
+ /** @beta */
1759
+ 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>;
1760
+ /** @beta */
1761
+ 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>;
1762
+ /** @beta */
1763
+ declare function getDocumentState<TData>(instance: SanityInstance, options: DocumentOptions<string | undefined>): StateSource<TData | undefined | null>;
1764
+ /** @beta */
1765
+ 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>;
1766
+ /** @beta */
1767
+ declare function resolveDocument<TData extends SanityDocument$2>(instance: SanityInstance, docHandle: DocumentHandle<string, string, string>): Promise<TData | null>;
1768
+ /** @beta */
1769
+ declare const getDocumentSyncStatus: BoundStoreAction<DocumentStoreState, [doc: DocumentHandle<string, string, string>], StateSource<boolean | undefined>>;
1770
+ type PermissionsStateOptions = {
1771
+ resource?: DocumentResource;
1772
+ actions: DocumentAction[];
1773
+ };
1774
+ /** @beta */
1775
+ declare const getPermissionsState: BoundStoreAction<DocumentStoreState, [PermissionsStateOptions], StateSource<DocumentPermissionsResult>>;
1776
+ /** @beta */
1777
+ declare const resolvePermissions: BoundStoreAction<DocumentStoreState, [options: PermissionsStateOptions], Promise<DocumentPermissionsResult>>;
1778
+ /** @beta */
1779
+ declare const subscribeDocumentEvents: BoundStoreAction<DocumentStoreState, [options: {
1780
+ resource?: DocumentResource;
1781
+ eventHandler: (e: DocumentEvent) => void;
1782
+ }], () => void>;
1783
+ type ActionMap = {
1784
+ create: 'sanity.action.document.version.create';
1785
+ discard: 'sanity.action.document.version.discard';
1786
+ unpublish: 'sanity.action.document.unpublish';
1787
+ delete: 'sanity.action.document.delete';
1788
+ edit: 'sanity.action.document.edit';
1789
+ publish: 'sanity.action.document.publish';
1790
+ releaseCreate: 'sanity.action.release.create';
1791
+ releaseEdit: 'sanity.action.release.edit';
1792
+ releasePublish: 'sanity.action.release.publish';
1793
+ releaseSchedule: 'sanity.action.release.schedule';
1794
+ releaseUnschedule: 'sanity.action.release.unschedule';
1795
+ releaseArchive: 'sanity.action.release.archive';
1796
+ releaseUnarchive: 'sanity.action.release.unarchive';
1797
+ releaseDelete: 'sanity.action.release.delete';
1798
+ };
1799
+ type OptimisticLock = {
1800
+ ifDraftRevisionId?: string;
1801
+ ifPublishedRevisionId?: string;
1802
+ };
1803
+ interface ReleaseMetadataPayload {
1804
+ title?: string;
1805
+ description?: string;
1806
+ intendedPublishAt?: string;
1807
+ releaseType?: 'asap' | 'scheduled' | 'undecided';
1808
+ cardinality?: 'one' | 'many';
1809
+ }
1810
+ type HttpAction = {
1811
+ actionType: ActionMap['create'];
1812
+ publishedId: string;
1813
+ attributes: SanityDocumentLike;
1814
+ } | {
1815
+ actionType: ActionMap['discard'];
1816
+ versionId: string;
1817
+ purge?: boolean;
1818
+ } | {
1819
+ actionType: ActionMap['unpublish'];
1820
+ draftId: string;
1821
+ publishedId: string;
1822
+ } | {
1823
+ actionType: ActionMap['delete'];
1824
+ publishedId: string;
1825
+ includeDrafts?: string[];
1826
+ } | {
1827
+ actionType: ActionMap['edit'];
1828
+ draftId: string;
1829
+ publishedId: string;
1830
+ patch: PatchOperations;
1831
+ } | ({
1832
+ actionType: ActionMap['publish'];
1833
+ draftId: string;
1834
+ publishedId: string;
1835
+ } & OptimisticLock) | {
1836
+ actionType: ActionMap['releaseCreate'];
1837
+ releaseId: string;
1838
+ metadata?: ReleaseMetadataPayload;
1839
+ } | {
1840
+ actionType: ActionMap['releaseEdit'];
1841
+ releaseId: string;
1842
+ patch: PatchOperations;
1843
+ } | {
1844
+ actionType: ActionMap['releasePublish'];
1845
+ releaseId: string;
1846
+ } | {
1847
+ actionType: ActionMap['releaseSchedule'];
1848
+ releaseId: string;
1849
+ publishAt: string;
1850
+ } | {
1851
+ actionType: ActionMap['releaseUnschedule'];
1852
+ releaseId: string;
1853
+ } | {
1854
+ actionType: ActionMap['releaseArchive'];
1855
+ releaseId: string;
1856
+ } | {
1857
+ actionType: ActionMap['releaseUnarchive'];
1858
+ releaseId: string;
1859
+ } | {
1860
+ actionType: ActionMap['releaseDelete'];
1861
+ releaseId: string;
1862
+ };
1863
+ /**
1864
+ * Represents a transaction that is queued to be applied but has not yet been
1865
+ * applied. A transaction will remain in a queued state until all required
1866
+ * documents for the transactions are available locally.
1867
+ */
1868
+ interface QueuedTransaction {
1869
+ /**
1870
+ * the ID of this transaction. this is generated client-side.
1871
+ */
1872
+ transactionId: string;
1873
+ /**
1874
+ * the high-level actions associated with this transaction. note that these
1875
+ * actions don't mention draft IDs and is meant to abstract away the draft
1876
+ * model from users.
1877
+ */
1878
+ actions: Action[];
1879
+ /**
1880
+ * An optional flag set to disable this transaction from being batched with
1881
+ * other transactions.
1882
+ */
1883
+ disableBatching?: boolean;
1884
+ }
1885
+ /**
1886
+ * Represents a transaction that has been applied locally but has not been
1887
+ * committed/transitioned-to-outgoing. These transactions are visible to the
1888
+ * user but may be rebased upon a new working document set. Applied transactions
1889
+ * also contain the resulting `outgoingActions` that will be submitted to
1890
+ * Content Lake. These `outgoingActions` depend on the state of the working
1891
+ * documents so they are recomputed on rebase and are only relevant to applied
1892
+ * actions (we cannot compute `outgoingActions` for queued transactions because
1893
+ * we haven't resolved the set of documents the actions are dependent on yet).
1894
+ *
1895
+ * In order to support better conflict resolution, the original `previous` set
1896
+ * is saved as the `base` set.
1897
+ */
1898
+ interface AppliedTransaction extends QueuedTransaction {
1899
+ /**
1900
+ * the resulting set of documents after the actions have been applied
1901
+ */
1902
+ working: DocumentSet;
1903
+ /**
1904
+ * the previous set of documents before the action was applied
1905
+ */
1906
+ previous: DocumentSet;
1907
+ /**
1908
+ * the original `previous` document set captured when this action was
1909
+ * originally applied. this is used as a reference point to do a 3-way merge
1910
+ * if this applied transaction ever needs to be reapplied on a different
1911
+ * set of documents.
1912
+ */
1913
+ base: DocumentSet;
1914
+ /**
1915
+ * the `_rev`s from `previous` document set
1916
+ */
1917
+ previousRevs: { [TDocumentId in string]?: string; };
1918
+ /**
1919
+ * a timestamp for when this transaction was applied locally
1920
+ */
1921
+ timestamp: string;
1922
+ /**
1923
+ * the resulting HTTP actions derived from the state of the `working` document
1924
+ * set. these are sent to Content Lake as-is when this transaction is batched
1925
+ * and transitioned into an outgoing transaction.
1926
+ */
1927
+ outgoingActions: HttpAction[];
1928
+ /**
1929
+ * similar to `outgoingActions` but comprised of mutations instead of actions.
1930
+ * Useful for debugging, and is also used by liveEdit documents to send mutations,
1931
+ * since they can't use the Actions API which is pretty dependent on the draft model.
1932
+ */
1933
+ outgoingMutations: Mutation[];
1934
+ }
1935
+ /**
1936
+ * Represents a set of applied transactions batched into a single outgoing
1937
+ * transaction. An outgoing transaction is the result of batching many applied
1938
+ * actions. An outgoing transaction may be reverted locally if the server
1939
+ * does not accept it.
1940
+ */
1941
+ interface OutgoingTransaction extends AppliedTransaction {
1942
+ disableBatching: boolean;
1943
+ batchedTransactionIds: string[];
1944
+ }
1945
+ interface UnverifiedDocumentRevision {
1946
+ transactionId: string;
1947
+ documentId: string;
1948
+ previousRev: string | undefined;
1949
+ timestamp: string;
1950
+ }
1951
+ /** @beta Response body from submitting an outgoing transaction (actions or mutations API). */
1952
+ type DocumentTransactionSubmissionResult = Awaited<ReturnType<SanityClient['action']>> | MultipleMutationResult;
1953
+ /** @beta */
1954
+ type DocumentEvent = ActionErrorEvent | TransactionRevertedEvent | TransactionAcceptedEvent | DocumentRebaseErrorEvent | DocumentEditedEvent | DocumentCreatedEvent | DocumentDeletedEvent | DocumentPublishedEvent | DocumentUnpublishedEvent | DocumentDiscardedEvent | DocumentRemotePatchesEvent;
1955
+ /**
1956
+ * @beta
1957
+ * Event emitted when a precondition to applying an action fails.
1958
+ * (For example: when trying to edit a document that no longer exists.)
1959
+ */
1960
+ interface ActionErrorEvent {
1961
+ type: 'error';
1962
+ documentId: string;
1963
+ transactionId: string;
1964
+ message: string;
1965
+ error: unknown;
1966
+ }
1967
+ /**
1968
+ * @beta
1969
+ * Event emitted when a transaction is accepted.
1970
+ */
1971
+ interface TransactionAcceptedEvent {
1972
+ type: 'accepted';
1973
+ outgoing: OutgoingTransaction;
1974
+ result: DocumentTransactionSubmissionResult;
1975
+ }
1976
+ /**
1977
+ * @beta
1978
+ * Event emitted when a transaction is reverted.
1979
+ */
1980
+ interface TransactionRevertedEvent {
1981
+ type: 'reverted';
1982
+ message: string;
1983
+ error: unknown;
1984
+ outgoing: OutgoingTransaction;
1985
+ }
1986
+ /**
1987
+ * @beta
1988
+ * Event emitted when an attempt to apply local changes to a modified remote document fails.
1989
+ */
1990
+ interface DocumentRebaseErrorEvent {
1991
+ type: 'rebase-error';
1992
+ documentId: string;
1993
+ transactionId: string;
1994
+ message: string;
1995
+ error: unknown;
1996
+ }
1997
+ /**
1998
+ * @beta
1999
+ * Event emitted when a document is edited.
2000
+ */
2001
+ interface DocumentEditedEvent {
2002
+ type: 'edited';
2003
+ documentId: string;
2004
+ outgoing: OutgoingTransaction;
2005
+ }
2006
+ /**
2007
+ * @beta
2008
+ * Event emitted when a document is created.
2009
+ */
2010
+ interface DocumentCreatedEvent {
2011
+ type: 'created';
2012
+ documentId: string;
2013
+ outgoing: OutgoingTransaction;
2014
+ }
2015
+ /**
2016
+ * @beta
2017
+ * Event emitted when a document is deleted.
2018
+ */
2019
+ interface DocumentDeletedEvent {
2020
+ type: 'deleted';
2021
+ documentId: string;
2022
+ outgoing: OutgoingTransaction;
2023
+ }
2024
+ /**
2025
+ * @beta
2026
+ * Event emitted when a document is published.
2027
+ */
2028
+ interface DocumentPublishedEvent {
2029
+ type: 'published';
2030
+ documentId: string;
2031
+ outgoing: OutgoingTransaction;
2032
+ }
2033
+ /**
2034
+ * @beta
2035
+ * Event emitted when a document is unpublished.
2036
+ */
2037
+ interface DocumentUnpublishedEvent {
2038
+ type: 'unpublished';
2039
+ documentId: string;
2040
+ outgoing: OutgoingTransaction;
2041
+ }
2042
+ /**
2043
+ * @beta
2044
+ * Event emitted when a document version is discarded.
2045
+ */
2046
+ interface DocumentDiscardedEvent {
2047
+ type: 'discarded';
2048
+ documentId: string;
2049
+ outgoing: OutgoingTransaction;
2050
+ }
2051
+ /**
2052
+ * @beta
2053
+ * Event emitted when patches for a document are observed through the listener.
2054
+ *
2055
+ * Unlike the whole-document snapshots the store keeps, these are the raw patch
2056
+ * operations from the transaction that produced the change, preserving the
2057
+ * operational intent of the edit (e.g. keyed array inserts/unsets). Consumers
2058
+ * that maintain their own local state, like collaborative text editors, can
2059
+ * apply these directly instead of diffing document snapshots.
2060
+ *
2061
+ * `origin` is `'local'` when the transaction was submitted by this document
2062
+ * store instance (an own edit observed back through the listener) and
2063
+ * `'remote'` when it came from another client.
2064
+ */
2065
+ interface DocumentRemotePatchesEvent {
2066
+ type: 'remote-patches';
2067
+ /** The ID of the document version the patches apply to (e.g. a draft ID). */
2068
+ documentId: string;
2069
+ /** The transaction ID that carried these patches. */
2070
+ transactionId: string;
2071
+ /** The revision the document was at before this transaction. */
2072
+ previousRev?: string;
2073
+ /** The timestamp of the transaction. */
2074
+ timestamp: string;
2075
+ /** The patch operations, rooted at the document. */
2076
+ patches: PatchOperations[];
2077
+ /** Whether the transaction originated from this client or another one. */
2078
+ origin: 'local' | 'remote';
2079
+ }
2080
+ /** @beta */
2081
+ interface ActionsResult<TDocument extends SanityDocument$2 = SanityDocument$2> {
2082
+ transactionId: string;
2083
+ documents: DocumentSet<TDocument>;
2084
+ previous: DocumentSet<TDocument>;
2085
+ previousRevs: {
2086
+ [documentId: string]: string | undefined;
2087
+ };
2088
+ appeared: string[];
2089
+ updated: string[];
2090
+ disappeared: string[];
2091
+ submitted: () => Promise<DocumentTransactionSubmissionResult>;
2092
+ }
2093
+ /** @beta */
2094
+ interface ApplyDocumentActionsOptions {
2095
+ /**
2096
+ * List of actions to apply. Accepts both document actions and release
2097
+ * lifecycle actions because they share the same transaction pipeline.
2098
+ */
2099
+ actions: Action[];
2100
+ /**
2101
+ * The resource to which the documents being acted on belong.
2102
+ */
2103
+ resource?: DocumentResource;
2104
+ /**
2105
+ * Optionally provide an ID to be used as this transaction ID
2106
+ */
2107
+ transactionId?: string;
2108
+ /**
2109
+ * Set this to true to prevent this action from being batched with others.
2110
+ */
2111
+ disableBatching?: boolean;
2112
+ }
2113
+ /** @beta */
2114
+ 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}`>>>;
2115
+ /** @beta */
2116
+ declare function applyDocumentActions(instance: SanityInstance, options: ApplyDocumentActionsOptions): Promise<ActionsResult>;
2117
+ /**
2118
+ * Returns the full release document ID for the given release name.
2119
+ * e.g. `getReleaseDocumentId('my-release') === '_.releases.my-release'`
2120
+ * @beta
2121
+ */
2122
+ declare function getReleaseDocumentId(releaseId: string): string;
2123
+ /**
2124
+ * @public
2125
+ */
2126
+ interface FavoriteStatusResponse {
2127
+ isFavorited: boolean;
2128
+ }
2129
+ /**
2130
+ * @public
2131
+ */
2132
+ interface FavoriteDocumentContext extends DocumentHandle {
2133
+ resourceId: string;
2134
+ resourceType: StudioResource['type'] | MediaResource['type'] | CanvasResource['type'];
2135
+ schemaName?: string;
2136
+ }
2137
+ /**
2138
+ * Gets a StateSource for the favorite status of a document.
2139
+ * @param instance - The Sanity instance.
2140
+ * @param context - The document context including ID, type, and resource information.
2141
+ * @returns A StateSource emitting `{ isFavorited: boolean }`.
2142
+ * @public
2143
+ */
2144
+ declare const getFavoritesState: BoundStoreAction<FetcherStoreState<[FavoriteDocumentContext], FavoriteStatusResponse>, [FavoriteDocumentContext], StateSource<FavoriteStatusResponse | undefined>>;
2145
+ /**
2146
+ * Resolves the favorite status for a document.
2147
+ * @param instance - The Sanity instance.
2148
+ * @param context - The document context including ID, type, and resource information.
2149
+ * @returns A Promise resolving to `{ isFavorited: boolean }`.
2150
+ * @public
2151
+ */
2152
+ declare const resolveFavoritesState: BoundStoreAction<FetcherStoreState<[FavoriteDocumentContext], FavoriteStatusResponse>, [FavoriteDocumentContext], Promise<FavoriteStatusResponse>>;
2153
+ /** @public */
2154
+ interface OrganizationMember {
2155
+ sanityUserId: string;
2156
+ isCurrentUser: boolean;
2157
+ user: {
2158
+ id: string;
2159
+ displayName: string;
2160
+ familyName: string;
2161
+ givenName: string;
2162
+ middleName: string | null;
2163
+ imageUrl: string | null;
2164
+ email: string;
2165
+ loginProvider: string;
2166
+ };
2167
+ roles: Array<{
2168
+ name: string;
2169
+ title: string;
2170
+ description?: string;
2171
+ }>;
2172
+ }
2173
+ /**
2174
+ * The base fields returned from `/organizations/<id>` for every organization.
2175
+ * @public
2176
+ */
2177
+ interface OrganizationBase {
2178
+ id: string;
2179
+ name: string;
2180
+ slug: string | null;
2181
+ createdAt: string;
2182
+ createdByUserId: string;
2183
+ updatedAt: string;
2184
+ deletedAt: string | null;
2185
+ dashboardStatus: 'enabled' | 'disabled';
2186
+ aiFeaturesStatus: 'enabled' | 'disabled';
2187
+ mediaLibraryStatus: 'enabled' | 'disabled';
2188
+ requestAccessStatus: 'allowed' | 'disabled';
2189
+ telemetryConsentStatus: 'allowed' | 'msa_denied' | 'customer_denied';
2190
+ oauthAppsStatus: 'allowed' | 'blocked';
2191
+ defaultRoleName: string;
2192
+ domains: string[] | null;
2193
+ }
2194
+ /** @public */
2195
+ interface OrganizationOptions<IncludeMembers extends boolean = false, IncludeFeatures extends boolean = false> {
2196
+ includeMembers?: IncludeMembers;
2197
+ includeFeatures?: IncludeFeatures;
2198
+ organizationId: string;
2199
+ }
2200
+ /**
2201
+ * An `Organization` with `members` and/or `features` conditionally included
2202
+ * based on the query options used to fetch it.
2203
+ * @public
2204
+ */
2205
+ type Organization<IncludeMembers extends boolean = false, IncludeFeatures extends boolean = false> = OrganizationBase & (boolean extends IncludeMembers ? {
2206
+ members?: OrganizationMember[];
2207
+ } : IncludeMembers extends true ? {
2208
+ members: OrganizationMember[];
2209
+ } : unknown) & (boolean extends IncludeFeatures ? {
2210
+ features?: string[];
2211
+ } : IncludeFeatures extends true ? {
2212
+ features: string[];
2213
+ } : unknown);
2214
+ /**
2215
+ * Public signature for the organization state source. The conditional generics
2216
+ * cannot flow through `BoundStoreAction`, so we declare the signature here
2217
+ * and assign the (already-correct) runtime function to it.
2218
+ */
2219
+ type GetOrganizationState = <IncludeMembers extends boolean = false, IncludeFeatures extends boolean = false>(instance: SanityInstance, options: OrganizationOptions<IncludeMembers, IncludeFeatures>) => StateSource<Organization<IncludeMembers, IncludeFeatures> | undefined>;
2220
+ type ResolveOrganization = <IncludeMembers extends boolean = false, IncludeFeatures extends boolean = false>(instance: SanityInstance, options: OrganizationOptions<IncludeMembers, IncludeFeatures>) => Promise<Organization<IncludeMembers, IncludeFeatures>>;
2221
+ /** @public */
2222
+ declare const getOrganizationState: GetOrganizationState;
2223
+ /** @public */
2224
+ declare const resolveOrganization: ResolveOrganization;
2225
+ /**
2226
+ * The list shape returned from `/organizations`, with `members` and/or
2227
+ * `features` conditionally included based on the query options used.
2228
+ * @public
2229
+ */
2230
+ type Organizations<IncludeMembers extends boolean = false, IncludeFeatures extends boolean = false> = (Pick<OrganizationBase, 'id' | 'name' | 'slug' | 'createdAt' | 'updatedAt' | 'defaultRoleName' | 'dashboardStatus' | 'aiFeaturesStatus'> & (boolean extends IncludeMembers ? {
2231
+ members?: OrganizationMember[];
2232
+ } : IncludeMembers extends true ? {
2233
+ members: OrganizationMember[];
2234
+ } : unknown) & (boolean extends IncludeFeatures ? {
2235
+ features?: string[];
2236
+ } : IncludeFeatures extends true ? {
2237
+ features: string[];
2238
+ } : unknown))[];
2239
+ /** @public */
2240
+ interface OrganizationsOptions<IncludeMembers extends boolean = false, IncludeFeatures extends boolean = false> extends Omit<OrganizationOptions<IncludeMembers, IncludeFeatures>, 'organizationId'> {
2241
+ /**
2242
+ * When `true`, includes organisations the user has access to via
2243
+ * project-level grants, not just direct organisation memberships.
2244
+ */
2245
+ includeImplicitMemberships?: boolean;
2246
+ }
2247
+ /**
2248
+ * Public signature for the organization state source. The conditional generics
2249
+ * cannot flow through `BoundStoreAction`, so we declare the signature here
2250
+ * and assign the (already-correct) runtime function to it.
2251
+ */
2252
+ type GetOrganizationsState = <IncludeMembers extends boolean = false, IncludeFeatures extends boolean = false>(instance: SanityInstance, options?: OrganizationsOptions<IncludeMembers, IncludeFeatures>) => StateSource<Organizations<IncludeMembers, IncludeFeatures> | undefined>;
2253
+ type ResolveOrganizations = <IncludeMembers extends boolean = false, IncludeFeatures extends boolean = false>(instance: SanityInstance, options?: OrganizationsOptions<IncludeMembers, IncludeFeatures>) => Promise<Organizations<IncludeMembers, IncludeFeatures>>;
2254
+ /** @public */
2255
+ declare const getOrganizationsState: GetOrganizationsState;
2256
+ /** @public */
2257
+ declare const resolveOrganizations: ResolveOrganizations;
2258
+ /**
2259
+ * @public
2260
+ */
2261
+ interface SanityUser {
2262
+ sanityUserId: string;
2263
+ profile: UserProfile;
2264
+ memberships: Membership[];
2265
+ }
2266
+ /**
2267
+ * @public
2268
+ */
2269
+ interface Membership {
2270
+ addedAt?: string;
2271
+ resourceType: string;
2272
+ resourceId: string;
2273
+ roleNames: Array<string>;
2274
+ lastSeenAt?: string | null;
2275
+ }
2276
+ /**
2277
+ * @public
2278
+ */
2279
+ interface UserProfile {
2280
+ id: string;
2281
+ displayName: string;
2282
+ email: string;
2283
+ familyName?: string;
2284
+ givenName?: string;
2285
+ middleName?: string | null;
2286
+ imageUrl?: string;
2287
+ provider: string;
2288
+ tosAcceptedAt?: string;
2289
+ createdAt: string;
2290
+ updatedAt?: string;
2291
+ isCurrentUser?: boolean;
2292
+ providerId?: string;
2293
+ }
2294
+ /**
2295
+ * @public
2296
+ */
2297
+ interface GetUsersOptions extends ProjectHandle {
2298
+ resourceType?: 'organization' | 'project';
2299
+ batchSize?: number;
2300
+ organizationId?: string;
2301
+ userId?: string;
2302
+ }
2303
+ /**
2304
+ * @public
2305
+ */
2306
+ interface UsersGroupState {
2307
+ subscriptions: string[];
2308
+ totalCount?: number;
2309
+ nextCursor?: string | null;
2310
+ lastLoadMoreRequest?: string;
2311
+ users?: SanityUser[];
2312
+ error?: unknown;
2313
+ }
2314
+ /**
2315
+ * @public
2316
+ */
2317
+ interface SanityUserResponse {
2318
+ data: SanityUser[];
2319
+ totalCount: number;
2320
+ nextCursor: string | null;
2321
+ }
2322
+ /**
2323
+ * @public
2324
+ */
2325
+ interface UsersStoreState {
2326
+ users: { [TUsersKey in string]?: UsersGroupState; };
2327
+ error?: unknown;
2328
+ }
2329
+ /**
2330
+ * @public
2331
+ */
2332
+ interface ResolveUsersOptions extends GetUsersOptions {
2333
+ signal?: AbortSignal;
2334
+ }
2335
+ /**
2336
+ * @public
2337
+ */
2338
+ interface GetUserOptions extends ProjectHandle {
2339
+ userId: string;
2340
+ resourceType?: 'organization' | 'project';
2341
+ organizationId?: string;
2342
+ }
2343
+ /**
2344
+ * @public
2345
+ */
2346
+ interface ResolveUserOptions extends GetUserOptions {
2347
+ signal?: AbortSignal;
2348
+ }
2349
+ /**
2350
+ * One end of a text selection: a Portable Text path plus a character offset
2351
+ * within the span it addresses.
2352
+ * @public
2353
+ */
2354
+ interface PresenceSelectionPoint {
2355
+ path: Path;
2356
+ offset: number;
2357
+ }
2358
+ /**
2359
+ * A Portable Text caret or selected range, as exchanged with the Studio.
2360
+ *
2361
+ * Structurally identical to `EditorSelection` from `@portabletext/editor`, and
2362
+ * declared separately so that `@sanity/sdk` stays free of React dependencies. A
2363
+ * value from the editor can be passed straight through, and vice versa.
2364
+ *
2365
+ * `offset` is a character offset within the span that `path` addresses.
2366
+ * @public
2367
+ */
2368
+ type PresenceSelection = {
2369
+ anchor: PresenceSelectionPoint;
2370
+ focus: PresenceSelectionPoint;
2371
+ backward?: boolean;
2372
+ } | null;
2373
+ /**
2374
+ * Somewhere a participant is, as it arrives over the wire.
2375
+ *
2376
+ * Prefer {@link DocumentPresence} from `getDocumentPresence`, which is scoped to one
2377
+ * document, flattened for rendering, and types `path` accurately.
2378
+ * @public
2379
+ */
2380
+ interface PresenceLocation {
2381
+ type: 'document';
2382
+ /**
2383
+ * The specific document the participant is in, so a draft, published, or version
2384
+ * id rather than a bare document id.
2385
+ */
2386
+ documentId: string;
2387
+ /**
2388
+ * The focused field path, empty when they are in the document but not a field.
2389
+ *
2390
+ * Declared as `string[]`, but segments can also be numbers or `{_key: string}`
2391
+ * objects when the focus is inside an array or a Portable Text field, because
2392
+ * that is what other clients send. Guard for those rather than assuming strings.
2393
+ * Widening the declared type is a breaking change, so it waits for the next major;
2394
+ * {@link DocumentPresence.path} is typed correctly today.
2395
+ */
2396
+ path: string[];
2397
+ /**
2398
+ * When the participant said they were last active, on *their* clock.
2399
+ *
2400
+ * Fine for display, unreliable for deciding whether someone is still here: it is
2401
+ * subject to clock skew between machines. Presence already drops participants that
2402
+ * stop announcing, so a session appearing here is one the SDK still considers
2403
+ * live.
2404
+ */
2405
+ lastActiveAt: string;
2406
+ /** A Portable Text caret, when the focused field is a Portable Text field. */
2407
+ selection?: PresenceSelection;
2408
+ }
2409
+ /**
2410
+ * Which specific document a presence id resolves to.
2411
+ *
2412
+ * Presence compares exact document ids, so a client in a draft and a client in the
2413
+ * published document are in different places even for the same `documentId`. Pass
2414
+ * the perspective you are editing under and the SDK resolves it; the React hooks
2415
+ * take it from `ResourceProvider` when you do not pass one.
2416
+ * @public
2417
+ */
2418
+ interface PresencePerspectiveOptions extends PerspectiveHandle {
2419
+ /** Live-edit documents have no draft, so presence resolves to the published id. */
2420
+ liveEdit?: boolean;
2421
+ }
2422
+ /**
2423
+ * What an app reports about where the current user is.
2424
+ *
2425
+ * Omit `path` for document-level presence, or pass one for field-level presence.
2426
+ * @public
2427
+ */
2428
+ interface ReportPresenceOptions extends PresencePerspectiveOptions {
2429
+ /**
2430
+ * The document the user is in.
2431
+ *
2432
+ * Pass the plain document id; the perspective decides which specific document that
2433
+ * resolves to. An already-specific id is accepted and re-resolved, so passing
2434
+ * `drafts.abc` while the perspective is `published` reports the published document.
2435
+ */
2436
+ documentId: string;
2437
+ /**
2438
+ * The focused field path. Supports keyed and numeric segments, so array items
2439
+ * and Portable Text spans can be addressed.
2440
+ */
2441
+ path?: Path;
2442
+ /** A Portable Text caret, when the focused field is a Portable Text field. */
2443
+ selection?: PresenceSelection;
2444
+ }
2445
+ /**
2446
+ * One participant's session and everywhere it currently is.
2447
+ *
2448
+ * Keyed by session, not by user: the same person in two tabs is two entries with
2449
+ * the same `user`.
2450
+ * @public
2451
+ */
2452
+ interface UserPresence {
2453
+ user: SanityUser;
2454
+ locations: PresenceLocation[];
2455
+ /** Identifies one tab. Stable while that tab is open, and not reused. */
2456
+ sessionId: string;
2457
+ }
2458
+ /**
2459
+ * One participant at one location within a single document, flattened so it can
2460
+ * be rendered directly against a field.
2461
+ *
2462
+ * Unlike {@link PresenceLocation.path}, `path` here is typed as a full `Path`, so
2463
+ * keyed and numeric segments are described rather than cast away.
2464
+ * @beta
2465
+ */
2466
+ interface DocumentPresence {
2467
+ user: SanityUser;
2468
+ /** Identifies one tab, so the same person in two tabs appears twice. */
2469
+ sessionId: string;
2470
+ /**
2471
+ * The specific document id this participant is in: a draft, published, or
2472
+ * version id, depending on which perspective they are editing.
2473
+ */
2474
+ documentId: string;
2475
+ /** The focused field path. Empty when they are in the document but no field. */
2476
+ path: Path;
2477
+ /**
2478
+ * When they said they were last active, on *their* clock. Fine for display,
2479
+ * unreliable for liveness. See {@link PresenceLocation.lastActiveAt}.
2480
+ */
2481
+ lastActiveAt: string;
2482
+ /** The Portable Text caret, when they are focused in a Portable Text field. */
2483
+ selection?: PresenceSelection;
2484
+ }
2485
+ /** @beta */
2486
+ interface DocumentPresenceOptions extends PresencePerspectiveOptions {
2487
+ /**
2488
+ * The document to look at. Resolved through the perspective exactly as
2489
+ * {@link ReportPresenceOptions.documentId} is, so reads match writes.
2490
+ */
2491
+ documentId: string;
2492
+ /**
2493
+ * Narrows to participants at or below this field path. Omit it for everyone in
2494
+ * the document.
2495
+ */
2496
+ path?: Path;
2497
+ /**
2498
+ * By default a draft, its published version, and any release versions are
2499
+ * treated as the same document, which is what document lists want. Set this to
2500
+ * compare ids exactly, which is what field-level indicators want so that a
2501
+ * draft and a release version do not bleed into each other.
2502
+ */
2503
+ excludeVersions?: boolean;
2504
+ }
2505
+ /** @public */
2506
+ type TransportEvent = RollCallEvent | StateEvent | DisconnectEvent;
2507
+ /** @public */
2508
+ interface RollCallEvent {
2509
+ type: 'rollCall';
2510
+ userId: string;
2511
+ sessionId: string;
2512
+ }
2513
+ /** @public */
2514
+ interface StateEvent {
2515
+ type: 'state';
2516
+ userId: string;
2517
+ sessionId: string;
2518
+ timestamp: string;
2519
+ locations: PresenceLocation[];
2520
+ }
2521
+ /** @public */
2522
+ interface DisconnectEvent {
2523
+ type: 'disconnect';
2524
+ userId: string;
2525
+ sessionId: string;
2526
+ timestamp: string;
2527
+ }
2528
+ /** @beta */
2529
+ declare function getPresence(instance: SanityInstance, params?: {
2530
+ resource?: DocumentResource;
2531
+ }): StateSource<UserPresence[]>;
2532
+ /**
2533
+ * Presence within a single document, flattened to one entry per participant per
2534
+ * location so it can be rendered directly against a field.
2535
+ *
2536
+ * Reading presence never announces anything. Use `reportPresence` to make the
2537
+ * current user visible to others.
2538
+ *
2539
+ * @param instance - the Sanity instance
2540
+ * @param params - the document to look at, its perspective, an optional `path` to
2541
+ * narrow to a field subtree, and `excludeVersions` to compare document ids exactly
2542
+ *
2543
+ * @beta
2544
+ */
2545
+ declare function getDocumentPresence(instance: SanityInstance, params: {
2546
+ resource?: DocumentResource;
2547
+ } & DocumentPresenceOptions): StateSource<DocumentPresence[]>;
2548
+ /**
2549
+ * Announces where the current user is, so other clients in the same project and
2550
+ * dataset can show them. Reading presence never announces anything, so this is
2551
+ * the only way an app becomes visible to others.
2552
+ *
2553
+ * Call it again whenever the user moves. Announcements are collapsed over a short
2554
+ * window and then repeated every 30 seconds while idle, which is what tells peers
2555
+ * the session is still alive.
2556
+ *
2557
+ * Which specific document each location resolves to depends on its perspective, and
2558
+ * that matters for interoperability: other clients, the Studio included, compare
2559
+ * exact document ids for field-level presence. Pass the perspective you are editing
2560
+ * under rather than building a draft or version id yourself.
2561
+ *
2562
+ * @param instance - the Sanity instance
2563
+ * @param params - the resource to announce on, plus the locations to report.
2564
+ * Pass one location with a `documentId` for document-level presence, add a
2565
+ * `path` for field-level presence, and pass an empty array to appear present
2566
+ * without being in any document.
2567
+ *
2568
+ * @beta
2569
+ */
2570
+ declare function reportPresence(instance: SanityInstance, params: {
2571
+ resource?: DocumentResource;
2572
+ locations: ReportPresenceOptions[];
2573
+ }): void;
2574
+ /**
2575
+ * @public
2576
+ * The result of a projection query
2577
+ */
2578
+ interface ProjectionValuePending<TValue extends object> {
2579
+ data: TValue | null;
2580
+ isPending: boolean;
2581
+ }
2582
+ /**
2583
+ * @public
2584
+ * @deprecated
2585
+ * Template literals are a bit too limited, so this type is deprecated.
2586
+ * Use `string` instead. Projection strings are validated at runtime.
2587
+ */
2588
+ type ValidProjection = string;
2589
+ interface DocumentStatus {
2590
+ lastEditedDraftAt?: string;
2591
+ lastEditedPublishedAt?: string;
2592
+ lastEditedVersionAt?: string;
2593
+ }
2594
+ /**
2595
+ *
2596
+ * @internal
2597
+ */
2598
+ interface PreviewQueryResult {
2599
+ _id: string;
2600
+ _type: string;
2601
+ _updatedAt: string;
2602
+ titleCandidates: Record<string, unknown>;
2603
+ subtitleCandidates: Record<string, unknown>;
2604
+ media?: PreviewMedia | null;
2605
+ _status?: DocumentStatus;
2606
+ }
2607
+ /**
2608
+ * Represents a media asset in a preview.
2609
+ *
2610
+ * @public
2611
+ */
2612
+ interface PreviewMedia {
2613
+ type: 'image-asset';
2614
+ _ref: string;
2615
+ url: string;
2616
+ }
2617
+ /**
2618
+ * Represents the set of values displayed as a preview for a given Sanity document.
2619
+ * This includes a primary title, a secondary subtitle, an optional piece of media associated
2620
+ * with the document, and the document's status.
2621
+ *
2622
+ * @public
2623
+ */
2624
+ interface PreviewValue {
2625
+ /**
2626
+ * The primary text displayed for the document preview.
2627
+ */
2628
+ title: string;
2629
+ /**
2630
+ * A secondary line of text providing additional context about the document.
2631
+ */
2632
+ subtitle?: string;
2633
+ /**
2634
+ * An optional piece of media representing the document within its preview.
2635
+ * Currently, only image assets are available.
2636
+ */
2637
+ media?: PreviewMedia | null;
2638
+ /**
2639
+ * The status of the document.
2640
+ */
2641
+ _status?: {
2642
+ /** The date of the last published edit */
2643
+ lastEditedPublishedAt?: string;
2644
+ /** The date of the last draft edit */
2645
+ lastEditedDraftAt?: string;
2646
+ };
2647
+ }
2648
+ /**
2649
+ * Represents the current state of a preview value along with a flag indicating whether
2650
+ * the preview data is still being fetched or is fully resolved.
2651
+ *
2652
+ * The tuple contains a preview value or null, and a boolean indicating if the data is
2653
+ * pending. A `true` value means a fetch is ongoing; `false` indicates that the
2654
+ * currently provided preview value is up-to-date.
2655
+ *
2656
+ * @public
2657
+ */
2658
+ type ValuePending<T> = {
2659
+ data: T | null;
2660
+ isPending: boolean;
2661
+ };
2662
+ /**
2663
+ * @public
2664
+ * @deprecated This interface is kept for backwards compatibility but is no longer used internally.
2665
+ * Preview state is now stored in the projection store.
2666
+ */
2667
+ interface PreviewStoreState {
2668
+ values: { [TDocumentId in string]?: ValuePending<PreviewValue>; };
2669
+ subscriptions: { [TDocumentId in string]?: { [TSubscriptionId in string]?: true; }; };
2670
+ }
2671
+ /**
2672
+ * @beta
2673
+ * @deprecated This type is deprecated and will be removed in a future release.
2674
+ */
2675
+ type GetPreviewStateOptions = DocumentHandle;
2676
+ /**
2677
+ * @beta
2678
+ * @deprecated This function is deprecated and will be removed in a future release.
2679
+ */
2680
+ declare function getPreviewState<TResult extends object>(instance: SanityInstance, options: GetPreviewStateOptions): StateSource<ValuePending<TResult>>;
2681
+ /**
2682
+ * @beta
2683
+ * @deprecated This function is deprecated and will be removed in a future release.
2684
+ */
2685
+ declare function getPreviewState(instance: SanityInstance, options: GetPreviewStateOptions): StateSource<ValuePending<PreviewValue>>;
2686
+ /**
2687
+ * Generates a GROQ projection for preview data without requiring a schema.
2688
+ * Uses common field names to make educated guesses about which fields to use.
2689
+ *
2690
+ * @internal
2691
+ */
2692
+ declare const PREVIEW_PROJECTION: string;
2693
+ /**
2694
+ * Transforms a projection result (with titleCandidates, subtitleCandidates, media)
2695
+ * into a PreviewValue (with title, subtitle, media).
2696
+ *
2697
+ * @param projectionResult - The raw projection result from GROQ
2698
+ * @param instance - The Sanity instance to use for client configuration
2699
+ * @param resource - Data resource for the preview
2700
+ * @internal
2701
+ */
2702
+ declare function transformProjectionToPreview(instance: SanityInstance, projectionResult: PreviewQueryResult, resource?: DocumentResource): PreviewValue;
2703
+ /**
2704
+ * @beta
2705
+ * @deprecated This type is deprecated and will be removed in a future release.
2706
+ */
2707
+ type ResolvePreviewOptions = DocumentHandle;
2708
+ /**
2709
+ * @beta
2710
+ * @deprecated This function is deprecated and will be removed in a future release.
2711
+ */
2712
+ declare function resolvePreview(instance: SanityInstance, options: ResolvePreviewOptions): Promise<ValuePending<PreviewValue>>;
2713
+ /** @public */
2714
+ interface ProjectMemberRole {
2715
+ name: string;
2716
+ title: string;
2717
+ description: string;
2718
+ }
2719
+ /** @public */
2720
+ interface ProjectMember {
2721
+ id: string;
2722
+ createdAt: string;
2723
+ updatedAt: string;
2724
+ isCurrentUser: boolean;
2725
+ isRobot: boolean;
2726
+ roles: ProjectMemberRole[];
2727
+ }
2728
+ /** @public */
2729
+ interface ProjectMetadata {
2730
+ color?: string;
2731
+ externalStudioHost?: string;
2732
+ initialTemplate?: string;
2733
+ cliInitializedAt?: string;
2734
+ integration: 'manage' | 'cli';
2735
+ }
2736
+ /**
2737
+ * The base fields returned from `/projects` for every project.
2738
+ * @public
2739
+ */
2740
+ interface ProjectBase {
2741
+ id: string;
2742
+ displayName: string;
2743
+ studioHost: string | null;
2744
+ organizationId: string;
2745
+ metadata: ProjectMetadata;
2746
+ isBlocked: boolean;
2747
+ isDisabled: boolean;
2748
+ isDisabledByUser: boolean;
2749
+ activityFeedEnabled: boolean;
2750
+ createdAt: string;
2751
+ updatedAt: string;
2752
+ }
2753
+ /**
2754
+ * A `Project` with `members` and/or `features` conditionally included
2755
+ * based on the query options used to fetch it.
2756
+ * @public
2757
+ */
2758
+ type Project<IncludeMembers extends boolean = true, IncludeFeatures extends boolean = true> = ProjectBase & (boolean extends IncludeMembers ? {
2759
+ members?: ProjectMember[];
2760
+ } : IncludeMembers extends true ? {
2761
+ members: ProjectMember[];
2762
+ } : unknown) & (boolean extends IncludeFeatures ? {
2763
+ features?: string[];
2764
+ } : IncludeFeatures extends true ? {
2765
+ features: string[];
2766
+ } : unknown);
2767
+ /** @public */
2768
+ interface ProjectOptions<IncludeMembers extends boolean = true, IncludeFeatures extends boolean = true> extends ProjectHandle {
2769
+ includeMembers?: IncludeMembers;
2770
+ includeFeatures?: IncludeFeatures;
2771
+ }
2772
+ /**
2773
+ * Public signature for the project state source. The conditional generics
2774
+ * cannot flow through `BoundStoreAction`, so we declare the signature here
2775
+ * and assign the (already-correct) runtime function to it.
2776
+ */
2777
+ type GetProjectState = <IncludeMembers extends boolean = true, IncludeFeatures extends boolean = true>(instance: SanityInstance, options?: ProjectOptions<IncludeMembers, IncludeFeatures>) => StateSource<Project<IncludeMembers, IncludeFeatures> | undefined>;
2778
+ type ResolveProject = <IncludeMembers extends boolean = true, IncludeFeatures extends boolean = true>(instance: SanityInstance, options?: ProjectOptions<IncludeMembers, IncludeFeatures>) => Promise<Project<IncludeMembers, IncludeFeatures>>;
2779
+ /** @public */
2780
+ declare const getProjectState: GetProjectState;
2781
+ /** @public */
2782
+ declare const resolveProject: ResolveProject;
2783
+ interface ProjectionOptions<TProjection extends string = string, TDocumentType extends string = string, TDataset extends string = string, TProjectId extends string = string> extends DocumentHandle<TDocumentType, TDataset, TProjectId> {
2784
+ projection: TProjection;
2785
+ }
2786
+ /**
2787
+ * @beta
2788
+ */
2789
+ 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>;
2790
+ /**
2791
+ * @beta
2792
+ */
2793
+ declare function getProjectionState<TData extends object>(instance: SanityInstance, options: ProjectionOptions): StateSource<ProjectionValuePending<TData> | undefined>;
2794
+ /**
2795
+ * @beta
2796
+ */
2797
+ declare function getProjectionState(instance: SanityInstance, options: ProjectionOptions): StateSource<ProjectionValuePending<Record<string, unknown>> | undefined>;
2798
+ /** @beta */
2799
+ 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}`>>>;
2800
+ /** @beta */
2801
+ declare function resolveProjection<TData extends object>(instance: SanityInstance, options: ProjectionOptions): Promise<ProjectionValuePending<TData>>;
2802
+ /** @public */
2803
+ interface ProjectsOptions<IncludeMembers extends boolean = false, IncludeFeatures extends boolean = true> {
2804
+ organizationId?: string;
2805
+ includeMembers?: IncludeMembers;
2806
+ includeFeatures?: IncludeFeatures;
2807
+ onlyExplicitMembership?: boolean;
2808
+ }
2809
+ /**
2810
+ * Public signature for the projects state source. The conditional generics
2811
+ * cannot flow through `BoundStoreAction`, so we declare the signature here
2812
+ * and assign the (already-correct) runtime function to it.
2813
+ */
2814
+ type GetProjectsState = <IncludeMembers extends boolean = false, IncludeFeatures extends boolean = true>(instance: SanityInstance, options?: ProjectsOptions<IncludeMembers, IncludeFeatures>) => StateSource<Project<IncludeMembers, IncludeFeatures>[] | undefined>;
2815
+ type ResolveProjects = <IncludeMembers extends boolean = false, IncludeFeatures extends boolean = true>(instance: SanityInstance, options?: ProjectsOptions<IncludeMembers, IncludeFeatures>) => Promise<Project<IncludeMembers, IncludeFeatures>[]>;
2816
+ /** @public */
2817
+ declare const getProjectsState: GetProjectsState;
2818
+ /** @public */
2819
+ declare const resolveProjects: ResolveProjects;
2820
+ /**
2821
+ * @beta
2822
+ */
2823
+ 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> {
2824
+ query: TQuery;
2825
+ params?: Record<string, unknown>;
2826
+ }
2827
+ /**
2828
+ * @beta
2829
+ */
2830
+ interface ResolveQueryOptions<TQuery extends string = string, TDataset extends string = string, TProjectId extends string = string> extends QueryOptions<TQuery, TDataset, TProjectId> {
2831
+ signal?: AbortSignal;
2832
+ }
2833
+ /** @beta */
2834
+ declare const getQueryKey: (options: QueryOptions) => string;
2835
+ /** @beta */
2836
+ declare const parseQueryKey: (key: string) => QueryOptions;
2837
+ /**
2838
+ * Returns the state source for a query.
2839
+ *
2840
+ * This function returns a state source that represents the current result of a GROQ query.
2841
+ * Subscribing to the state source will instruct the SDK to fetch the query (if not already fetched)
2842
+ * and will keep the query live using the Live content API (considering sync tags) to provide up-to-date results.
2843
+ * When the last subscriber is removed, the query state is automatically cleaned up from the store.
2844
+ *
2845
+ * Note: This functionality is for advanced users who want to build their own framework integrations.
2846
+ * Our SDK also provides a React integration (useQuery hook) for convenient usage.
2847
+ *
2848
+ * Note: Automatic cleanup can interfere with React Suspense because if a component suspends while being the only subscriber,
2849
+ * cleanup might occur unexpectedly. In such cases, consider using `resolveQuery` instead.
2850
+ *
2851
+ * @beta
2852
+ */
2853
+ 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>;
2854
+ /** @beta */
2855
+ declare function getQueryState<TData>(instance: SanityInstance, queryOptions: QueryOptions): StateSource<TData | undefined>;
2856
+ /** @beta */
2857
+ declare function getQueryState(instance: SanityInstance, queryOptions: QueryOptions): StateSource<unknown>;
2858
+ /**
2859
+ * Resolves the result of a query without registering a lasting subscriber.
2860
+ *
2861
+ * This function fetches the result of a GROQ query and returns a promise that resolves with the query result.
2862
+ * It registers a temporary subscriber for the lifetime of the resolution (released shortly after the promise
2863
+ * settles), so the query state participates in normal cleanup even when no lasting subscriber ever attaches —
2864
+ * e.g. when a suspended component errors before committing. This makes it ideal for use with React Suspense,
2865
+ * where the returned promise is thrown to delay rendering until the query result becomes available.
2866
+ * Once the promise resolves, it is expected that a real subscriber will be added via `getQueryState` to manage ongoing updates.
2867
+ *
2868
+ * Additionally, an optional AbortSignal can be provided to cancel the query and immediately clear the associated state
2869
+ * if there are no other active subscribers.
2870
+ *
2871
+ * @beta
2872
+ */
2873
+ 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}`>>;
2874
+ /** @beta */
2875
+ declare function resolveQuery<TData>(instance: SanityInstance, queryOptions: ResolveQueryOptions): Promise<TData>;
2876
+ /**
2877
+ * Lifecycle states a release document can be in. Mirrors the server's
2878
+ * `ReleaseState`.
2879
+ * @beta
2880
+ */
2881
+ type ReleaseState = 'active' | 'archiving' | 'unarchiving' | 'archived' | 'published' | 'publishing' | 'scheduled' | 'scheduling';
2882
+ interface ReleasesStoreState {
2883
+ activeReleases?: ReleaseDocument[];
2884
+ allReleases?: ReleaseDocument[];
2885
+ error?: unknown;
2886
+ }
2887
+ /**
2888
+ * Get the active releases from the store.
2889
+ * @internal
2890
+ */
2891
+ declare const getActiveReleasesState: (instance: SanityInstance, options?: {
2892
+ resource?: DocumentResource;
2893
+ }) => StateSource<ReleaseDocument[] | undefined>;
2894
+ /**
2895
+ * Get every release in the store, including archived and published.
2896
+ * @internal
2897
+ */
2898
+ declare const getAllReleasesState: (instance: SanityInstance, options?: {
2899
+ resource?: DocumentResource;
2900
+ }) => StateSource<ReleaseDocument[] | undefined>;
2901
+ declare const _getPerspectiveStateSelector: StoreAction<ReleasesStoreState, [_?: (PerspectiveHandle & {
2902
+ projectId?: string;
2903
+ dataset?: string;
2904
+ resource?: DocumentResource;
2905
+ }) | undefined], StateSource<string[] | "previewDrafts" | "published" | "drafts" | "raw" | undefined>, unknown>;
2906
+ type OmitFirst<T extends unknown[]> = T extends [unknown, ...infer R] ? R : never;
2907
+ type SelectorParams = OmitFirst<Parameters<typeof _getPerspectiveStateSelector>>;
2908
+ type BoundGetPerspectiveState = BoundStoreAction<ReleasesStoreState, SelectorParams, ReturnType<typeof _getPerspectiveStateSelector>>;
2909
+ /**
2910
+ * Provides a subscribable state source for a "perspective" for the Sanity client,
2911
+ * which is used to fetch documents as though certain Content Releases are active.
2912
+ *
2913
+ * @param instance - The Sanity instance to get the perspective for
2914
+ * @param options - The options for the perspective -- usually a release name
2915
+ *
2916
+ * @returns A subscribable perspective value, usually a list of applicable release names,
2917
+ * or a single release name / default perspective (such as 'drafts').
2918
+ *
2919
+ * @public
2920
+ */
2921
+ declare const getPerspectiveState: BoundGetPerspectiveState;
2922
+ /** @internal */
2923
+ declare const getUsersKey: (instance: SanityInstance, { resourceType, organizationId, batchSize, projectId, userId }?: GetUsersOptions) => string;
2924
+ /** @internal */
2925
+ declare const parseUsersKey: (key: string) => {
2926
+ batchSize: number;
2927
+ resourceType?: "organization" | "project";
2928
+ projectId?: string;
2929
+ organizationId?: string;
2930
+ userId?: string;
2931
+ };
2932
+ /**
2933
+ * Returns the state source for users associated with a specific resource.
2934
+ *
2935
+ * This function returns a state source that represents the current list of users for a given
2936
+ * resource. Subscribing to the state source will instruct the SDK to fetch the users (if not
2937
+ * already fetched) and will load more from this state source as well. When the last subscriber is
2938
+ * removed, the users state is automatically cleaned up from the store after a delay.
2939
+ *
2940
+ * Note: This functionality is for advanced users who want to build their own framework
2941
+ * integrations. Our SDK also provides a React integration for convenient usage.
2942
+ *
2943
+ * @beta
2944
+ */
2945
+ declare const getUsersState: BoundStoreAction<UsersStoreState, [options?: GetUsersOptions | undefined], StateSource<{
2946
+ data: SanityUser[];
2947
+ totalCount: number;
2948
+ hasMore: boolean;
2949
+ } | undefined>>;
2950
+ /**
2951
+ * Resolves the users for a specific resource without registering a lasting subscriber.
2952
+ *
2953
+ * This function fetches the users for a given resource and returns a promise that resolves with
2954
+ * the users result. Unlike `getUsersState`, which registers subscribers to keep the data live and
2955
+ * performs automatic cleanup, `resolveUsers` does not track subscribers. This makes it ideal for
2956
+ * use with React Suspense, where the returned promise is thrown to delay rendering until the users
2957
+ * result becomes available. Once the promise resolves, it is expected that a real subscriber will
2958
+ * be added via `getUsersState` to manage ongoing updates.
2959
+ *
2960
+ * Additionally, an optional AbortSignal can be provided to cancel the request and immediately
2961
+ * clear the associated state if there are no active subscribers.
2962
+ *
2963
+ * @beta
2964
+ */
2965
+ declare const resolveUsers: BoundStoreAction<UsersStoreState, [ResolveUsersOptions], Promise<{
2966
+ data: SanityUser[];
2967
+ totalCount: number;
2968
+ hasMore: boolean;
2969
+ }>>;
2970
+ /**
2971
+ * Loads more users for a specific resource.
2972
+ *
2973
+ * This function triggers a request to fetch the next page of users for a given resource. It
2974
+ * requires that users have already been loaded for the resource (via `resolveUsers` or
2975
+ * `getUsersState`), and that there are more users available to load (as indicated by the `hasMore`
2976
+ * property).
2977
+ *
2978
+ * The function returns a promise that resolves when the next page of users has been loaded.
2979
+ *
2980
+ * @beta
2981
+ */
2982
+ declare const loadMoreUsers: BoundStoreAction<UsersStoreState, [options?: GetUsersOptions | undefined], Promise<{
2983
+ data: SanityUser[];
2984
+ totalCount: number;
2985
+ hasMore: boolean;
2986
+ }>>;
2987
+ /**
2988
+ * @beta
2989
+ */
2990
+ declare const getUserState: BoundStoreAction<UsersStoreState, [GetUserOptions], Observable<SanityUser | undefined>>;
2991
+ /**
2992
+ * @beta
2993
+ */
2994
+ declare const resolveUser: BoundStoreAction<UsersStoreState, [ResolveUserOptions], Promise<SanityUser>>;
2995
+ interface StoreEntry<TParams extends unknown[], TData> {
2996
+ params: TParams;
2997
+ instance: SanityInstance;
2998
+ key: string;
2999
+ data?: TData;
3000
+ error?: unknown;
3001
+ subscriptions: string[];
3002
+ lastFetchInitiatedAt?: string;
3003
+ }
3004
+ /**
3005
+ * Internal helper type
3006
+ * @public
3007
+ */
3008
+ interface FetcherStoreState<TParams extends unknown[], TData> {
3009
+ stateByParams: { [TSerializedKey in string]?: StoreEntry<TParams, TData>; };
3010
+ error?: unknown;
3011
+ }
3012
+ /**
3013
+ * Internal helper type
3014
+ * @public
3015
+ */
3016
+ interface FetcherStore<TParams extends unknown[], TData> {
3017
+ getState: BoundStoreAction<FetcherStoreState<TParams, TData>, TParams, StateSource<TData | undefined>>;
3018
+ resolveState: BoundStoreAction<FetcherStoreState<TParams, TData>, TParams, Promise<TData>>;
3019
+ }
3020
+ /**
3021
+ * Creates a GROQ search filter string (`[@] match text::query("...")`)
3022
+ * from a raw search query string.
3023
+ *
3024
+ * It applies wildcard ('*') logic to the last eligible token and escapes
3025
+ * double quotes within the search term.
3026
+ *
3027
+ * If the input query is empty or only whitespace, it returns an empty string.
3028
+ *
3029
+ * @param query - The raw input search string.
3030
+ * @returns The GROQ search filter string, or an empty string.
3031
+ * @internal
3032
+ */
3033
+ declare function createGroqSearchFilter(query: string): string;
3034
+ /**
3035
+ * Filter criteria for intent matching. Can be combined to create more specific intents.
3036
+ *
3037
+ * @example
3038
+ * ```typescript
3039
+ * // matches only geopoints in the travel-project project, production dataset
3040
+ * const filter: IntentFilter = {
3041
+ * projectId: 'travel-project',
3042
+ * dataset: 'production',
3043
+ * types: ['geopoint']
3044
+ * }
3045
+ *
3046
+ * // matches all documents in the travel-project project
3047
+ * const filter: IntentFilter = {
3048
+ * projectId: 'travel-project',
3049
+ * types: ['*']
3050
+ * }
3051
+ *
3052
+ * // matches geopoints in the travel-project production dataset and map pins in all projects in the org
3053
+ * const filters: IntentFilter[] = [
3054
+ * {
3055
+ * projectId: 'travel-project',
3056
+ * dataset: 'production',
3057
+ * types: ['geopoint']
3058
+ * },
3059
+ * {
3060
+ * types: ['map-pin']
3061
+ * }
3062
+ * ]
3063
+ * ```
3064
+ * @public
3065
+ */
3066
+ interface IntentFilter {
3067
+ /**
3068
+ * Project ID to match against
3069
+ * @remarks When specified, the intent will only match for the specified project.
3070
+ */
3071
+ projectId?: string;
3072
+ /**
3073
+ * Dataset to match against
3074
+ * @remarks When specified, the intent will only match for the specified dataset. Requires projectId to be specified.
3075
+ */
3076
+ dataset?: string;
3077
+ /**
3078
+ * Document types that this intent can handle
3079
+ * @remarks This is required for all filters. Use ['*'] to match all document types.
3080
+ */
3081
+ types: string[];
3082
+ }
3083
+ /**
3084
+ * Intent definition structure for registering user intents
3085
+ * @public
3086
+ */
3087
+ interface Intent {
3088
+ /**
3089
+ * Unique identifier for this intent
3090
+ * @remarks Should be unique across all registered intents in an org for proper matching
3091
+ */
3092
+ id: string;
3093
+ /**
3094
+ * The action that this intent performs
3095
+ * @remarks Examples: "view", "edit", "create", "delete"
3096
+ */
3097
+ action: 'view' | 'edit' | 'create' | 'delete';
3098
+ /**
3099
+ * Human-readable title for this intent
3100
+ * @remarks Used for display purposes in UI or logs
3101
+ */
3102
+ title: string;
3103
+ /**
3104
+ * Detailed description of what this intent does
3105
+ * @remarks Helps users understand the purpose and behavior of the intent
3106
+ */
3107
+ description?: string;
3108
+ /**
3109
+ * Array of filter criteria for intent matching
3110
+ * @remarks At least one filter is required. Use `{types: ['*']}` to match everything
3111
+ */
3112
+ filters: IntentFilter[];
3113
+ }
3114
+ /**
3115
+ * Creates a properly typed intent definition for registration with the backend.
3116
+ *
3117
+ * This utility function provides TypeScript support and validation for intent declarations.
3118
+ * It is also used in the CLI if intents are declared as bare objects in an intents file.
3119
+ *
3120
+ * @param intent - The intent definition object
3121
+ * @returns The same intent object with proper typing
3122
+ *
3123
+ * @example
3124
+ * ```typescript
3125
+ * // Specific filter for a document type
3126
+ * const viewGeopointInMapApp = defineIntent({
3127
+ * id: 'viewGeopointInMapApp',
3128
+ * action: 'view',
3129
+ * title: 'View a geopoint in the map app',
3130
+ * description: 'This lets you view a geopoint in the map app',
3131
+ * filters: [
3132
+ * {
3133
+ * projectId: 'travel-project',
3134
+ * dataset: 'production',
3135
+ * types: ['geopoint']
3136
+ * }
3137
+ * ]
3138
+ * })
3139
+ *
3140
+ * export default viewGeopointInMapApp
3141
+ * ```
3142
+ *
3143
+ * If your intent is asynchronous, resolve the promise before defining / returning the intent
3144
+ * ```typescript
3145
+ * async function createAsyncIntent() {
3146
+ * const currentProject = await asyncProjectFunction()
3147
+ * const currentDataset = await asyncDatasetFunction()
3148
+ *
3149
+ * return defineIntent({
3150
+ * id: 'dynamicIntent',
3151
+ * action: 'view',
3152
+ * title: 'Dynamic Intent',
3153
+ * description: 'Intent with dynamically resolved values',
3154
+ * filters: [
3155
+ * {
3156
+ * projectId: currentProject, // Resolved value
3157
+ * dataset: currentDataset, // Resolved value
3158
+ * types: ['document']
3159
+ * }
3160
+ * ]
3161
+ * })
3162
+ * }
3163
+ *
3164
+ * const intent = await createAsyncIntent()
3165
+ * export default intent
3166
+ * ```
3167
+ *
3168
+ * @public
3169
+ */
3170
+ declare function defineIntent(intent: Intent): Intent;
3171
+ /**
3172
+ * @public
3173
+ * Extracts the project ID from a CorsOriginError message.
3174
+ * @param error - The error to extract the project ID from.
3175
+ * @returns The project ID or null if the error is not a CorsOriginError.
3176
+ */
3177
+ declare function getCorsErrorProjectId(error: Error): string | null;
3178
+ /**
3179
+ * Returns true when the given error looks like a dynamic-import or
3180
+ * code-split chunk-loading failure.
3181
+ *
3182
+ * These errors typically surface when a user has a tab open against a
3183
+ * previously-deployed version of an app and the JavaScript or CSS chunk
3184
+ * filenames have since changed: a fresh deployment removes the hashed assets
3185
+ * the open tab still references. Detecting them lets the SDK trigger an
3186
+ * automatic reload so the user gets the new build without manual intervention.
3187
+ *
3188
+ * Recognized shapes (webpack ChunkLoadError, Vite "Failed to fetch
3189
+ * dynamically imported module", Firefox "error loading dynamically imported
3190
+ * module", Safari "Importing a module script failed", and Vite "Unable to
3191
+ * preload CSS").
3192
+ *
3193
+ * @param error - The value to inspect. Anything that is not an Error
3194
+ * instance returns false.
3195
+ * @returns True if the error matches a known import/chunk-load failure.
3196
+ *
3197
+ * @public
3198
+ */
3199
+ declare function isImportError(error: unknown): boolean;
3200
+ /**
3201
+ * This version is provided by pkg-utils at build time
3202
+ * @internal
3203
+ */
3204
+ declare const CORE_SDK_VERSION: {};
3205
+ /**
3206
+ * @public
3207
+ */
3208
+ type SanityProject$1 = SanityProject;
3209
+ /**
3210
+ * Represents the various states the authentication can be in.
3211
+ *
3212
+ * @public
3213
+ */
3214
+ type AuthState = LoggedInAuthState | LoggedOutAuthState | LoggingInAuthState | ErrorAuthState;
3215
+ /**
3216
+ * Logged-in state from the auth state.
3217
+ * @public
3218
+ */
3219
+ type LoggedInAuthState = {
3220
+ type: AuthStateType.LOGGED_IN;
3221
+ token: string;
3222
+ currentUser: CurrentUser | null;
3223
+ lastTokenRefresh?: number;
3224
+ };
3225
+ /**
3226
+ * Logged-out state from the auth state.
3227
+ * @public
3228
+ */
3229
+ type LoggedOutAuthState = {
3230
+ type: AuthStateType.LOGGED_OUT;
3231
+ isDestroyingSession: boolean;
3232
+ };
3233
+ /**
3234
+ * Logging-in state from the auth state.
3235
+ * @public
3236
+ */
3237
+ type LoggingInAuthState = {
3238
+ type: AuthStateType.LOGGING_IN;
3239
+ isExchangingToken: boolean;
3240
+ };
3241
+ /**
3242
+ * Error state from the auth state.
3243
+ * @public
3244
+ */
3245
+ type ErrorAuthState = {
3246
+ type: AuthStateType.ERROR;
3247
+ error: unknown;
3248
+ };
3249
+ /**
3250
+ * Represents the various states the authentication can be in.
3251
+ *
3252
+ * @public
3253
+ */
3254
+ interface DashboardContext {
3255
+ mode?: string;
3256
+ env?: string;
3257
+ orgId?: string;
3258
+ }
3259
+ /**
3260
+ * The method of authentication used.
3261
+ * @internal
3262
+ */
3263
+ type AuthMethodOptions = 'localstorage' | 'cookie' | undefined;
3264
+ /**
3265
+ * @public
3266
+ */
3267
+ interface AuthStoreState {
3268
+ authState: AuthState;
3269
+ providers?: AuthProvider[];
3270
+ options: {
3271
+ initialLocationHref: string;
3272
+ clientFactory: (config: ClientConfig) => SanityClient;
3273
+ customProviders: AuthConfig['providers'];
3274
+ storageKey: string;
3275
+ storageArea: Storage | undefined;
3276
+ apiHost: string | undefined;
3277
+ loginUrl: string;
3278
+ callbackUrl: string | undefined;
3279
+ providedToken: string | undefined;
3280
+ authMethod: AuthMethodOptions;
3281
+ };
3282
+ dashboardContext?: DashboardContext;
3283
+ }
3284
+ /**
3285
+ * @public
3286
+ */
3287
+ declare const getCurrentUserState: BoundStoreAction<AuthStoreState, [], StateSource<CurrentUser | null>>;
3288
+ /**
3289
+ * @public
3290
+ */
3291
+ declare const getTokenState: BoundStoreAction<AuthStoreState, [], StateSource<string | null>>;
3292
+ /**
3293
+ * @public
3294
+ */
3295
+ declare const getLoginUrlState: BoundStoreAction<AuthStoreState, [], StateSource<string>>;
3296
+ /**
3297
+ * @public
3298
+ */
3299
+ declare const getAuthState: BoundStoreAction<AuthStoreState, [], StateSource<AuthState>>;
3300
+ /**
3301
+ * @public
3302
+ */
3303
+ declare const getDashboardOrganizationId: BoundStoreAction<AuthStoreState, [], StateSource<string | undefined>>;
3304
+ /**
3305
+ * Returns a state source indicating if the SDK is running within a dashboard context.
3306
+ * @public
3307
+ */
3308
+ declare const getIsInDashboardState: BoundStoreAction<AuthStoreState, [], StateSource<boolean>>;
3309
+ /**
3310
+ * Action to explicitly set the authentication token.
3311
+ * Used internally by the Comlink token refresh.
3312
+ * @internal
3313
+ */
3314
+ declare const setAuthToken: BoundStoreAction<AuthStoreState, [token: string | null], void>;
3315
+ /** @internal */
3316
+ type ApiErrorBody = {
3317
+ error?: {
3318
+ type?: string;
3319
+ description?: string;
3320
+ };
3321
+ type?: string;
3322
+ description?: string;
3323
+ message?: string;
3324
+ };
3325
+ /** @internal Extracts the structured API error body from a ClientError, if present. */
3326
+ declare function getClientErrorApiBody(error: ClientError): ApiErrorBody | undefined;
3327
+ /** @internal Returns the error type string from an API error body, if available. */
3328
+ declare function getClientErrorApiType(error: ClientError): string | undefined;
3329
+ /** @internal Returns the error description string from an API error body, if available. */
3330
+ declare function getClientErrorApiDescription(error: ClientError): string | undefined;
3331
+ /** @internal True if the error represents a projectUserNotFoundError. */
3332
+ declare function isProjectUserNotFoundClientError(error: ClientError): boolean;
3333
+ export { parseQueryKey as $, MediaLibrarySource as $i, UnpublishDocumentAction as $n, CommentTextSelection as $r, OrganizationsOptions as $t, CORE_SDK_VERSION as A, AgentPromptResult as Ai, getPermissionsState as An, getCommentThreadsState as Ar, DisconnectEvent as At, getUsersState as B, SanityInstance as Bi, CreateReleaseAction as Bn, ReplyToCommentOptions as Br, TransportEvent as Bt, SanityProject$1 as C, OrgVerificationResult as Ci, DocumentTransactionSubmissionResult as Cn, LoggerConfig as Cr, PreviewValue as Ct, jsonMatch$1 as D, AgentPatchOptions as Di, DocumentOptions as Dn, createProjectHandle as Dr, getDocumentPresence as Dt, joinPaths as E, AgentGenerateResult as Ei, TransactionRevertedEvent as En, createDocumentTypeHandle as Er, ValidProjection as Et, defineIntent as F, agentGenerate as Fi, PermissionDeniedReason as Fn, resolveComments as Fr, PresenceSelection as Ft, parseUsersKey as G, DatasetHandle as Gi, EditDocumentAction as Gn, replyToComment as Gr, ResolveUserOptions as Gt, resolveUser as H, isStudioConfig as Hi, DeleteReleaseAction as Hn, UpdateCommentOptions as Hr, GetUserOptions as Ht, createGroqSearchFilter as I, agentPatch as Ii, JsonMatch as In, Selector as Ir, PresenceSelectionPoint as It, getActiveReleasesState as J, DocumentHandle as Ji, PublishDocumentAction as Jn, Comment as Jr, SanityUserResponse as Jt, getPerspectiveState as K, DatasetResource as Ki, EditDocumentOptions as Kn, setCommentStatus as Kr, ResolveUsersOptions as Kt, FetcherStore as L, agentPrompt as Li, Action as Ln, StateSource as Lr, ReportPresenceOptions as Lt, getCorsErrorProjectId as M, AgentTransformResult as Mi, resolvePermissions as Mn, getCommentsState as Mr, DocumentPresenceOptions as Mt, Intent as N, AgentTranslateOptions as Ni, subscribeDocumentEvents as Nn, parseCommentsOptionsKey as Nr, PresenceLocation as Nt, slicePath$1 as O, AgentPatchResult as Oi, getDocumentState as On, CommentsOptions as Or, getPresence as Ot, IntentFilter as P, AgentTranslateResult as Pi, DocumentPermissionsResult as Pn, resolveCommentThreads as Pr, PresencePerspectiveOptions as Pt, getQueryState as Q, MediaLibraryResource as Qi, UnarchiveReleaseAction as Qn, CommentStatus as Qr, Organizations as Qt, FetcherStoreState as R, agentTransform as Ri, ArchiveReleaseAction as Rn, CreateCommentOptions as Rr, RollCallEvent as Rt, SanityDocument$3 as S, observeOrganizationVerificationState as Si, DocumentRemotePatchesEvent as Sn, Logger as Sr, PreviewStoreState as St, getPathDepth as T, AgentGenerateOptions as Ti, TransactionAcceptedEvent as Tn, createDocumentHandle as Tr, ProjectionValuePending as Tt, resolveUsers as U, CanvasResource$1 as Ui, DiscardDocumentAction as Un, createComment as Ur, GetUsersOptions as Ut, loadMoreUsers as V, createSanityInstance as Vi, DeleteDocumentAction as Vn, SetCommentStatusOptions as Vr, UserPresence as Vt, getUsersKey as W, CanvasSource as Wi, DocumentAction as Wn, removeComment as Wr, Membership as Wt, QueryOptions as X, DocumentSource as Xi, ReleaseAction as Xn, CommentMessage as Xr, UsersGroupState as Xt, getAllReleasesState as Y, DocumentResource as Yi, PublishReleaseAction as Yn, CommentLocalState as Yr, UserProfile as Yt, getQueryKey as Z, DocumentTypeHandle as Zi, ScheduleReleaseAction as Zn, CommentReaction as Zr, UsersStoreState as Zt, getTokenState as _, ClientStoreState as _i, DocumentDeletedEvent as _n, configureLogging as _r, PREVIEW_PROJECTION as _t, isProjectUserNotFoundClientError as a, StudioConfig as aa, getOrCreateNode as ai, OrganizationOptions as an, deleteRelease as ar, getProjectionState as at, ReleaseDocument$1 as b, logout as bi, DocumentEvent as bn, LogLevel as br, PreviewMedia as bt, ErrorAuthState as c, isCanvasSource as ca, destroyController as ci, FavoriteStatusResponse as cn, editRelease as cr, ProjectMember as ct, LoggingInAuthState as d, isMediaLibraryResource as da, releaseChannel as di, getReleaseDocumentId as dn, scheduleRelease as dr, ProjectOptions as dt, PerspectiveHandle as ea, CommentTextSelectionItem as ei, getOrganizationsState as en, UnscheduleReleaseAction as er, resolveQuery as et, getAuthState as f, isMediaLibrarySource as fa, FrameMessage as fi, ActionsResult as fn, unarchiveRelease as fr, getProjectState as ft, getLoginUrlState as g, ClientOptions as gi, DocumentCreatedEvent as gn, resolveDatasets as gr, transformProjectionToPreview as gt, getIsInDashboardState as h, WindowMessage as hi, ActionErrorEvent as hn, getDatasetsState as hr, resolvePreview as ht, getClientErrorApiType as i, SanityConfig as ia, ComlinkNodeState as ii, OrganizationMember as in, deleteDocument as ir, resolveProjection as it, isImportError as j, AgentTransformOptions as ji, resolveDocument as jn, getCommentsOptionsKey as jr, DocumentPresence as jt, stringifyPath$1 as k, AgentPromptOptions as ki, getDocumentSyncStatus as kn, ResolveCommentsOptions as kr, reportPresence as kt, LoggedInAuthState as l, isDatasetResource as la, getOrCreateChannel as li, getFavoritesState as ln, publishDocument as lr, ProjectMemberRole as lt, getDashboardOrganizationId as m, AuthProvider as ma, RequestNewTokenMessage as mi, applyDocumentActions as mn, unscheduleRelease as mr, ResolvePreviewOptions as mt, getClientErrorApiBody as n, ReleaseHandle as na, NodeState as ni, Organization as nn, createDocument as nr, getProjectsState as nt, AuthState as o, TokenSource as oa, releaseNode as oi, getOrganizationState as on, discardDocument as or, Project as ot, getCurrentUserState as p, AuthConfig as pa, NewTokenResponseMessage as pi, ApplyDocumentActionsOptions as pn, unpublishDocument as pr, resolveProject as pt, ReleaseState as q, DatasetSource as qi, EditReleaseAction as qn, updateComment as qr, SanityUser as qt, getClientErrorApiDescription as r, ReleasePerspective as ra, getNodeState as ri, OrganizationBase as rn, createRelease as rr, resolveProjects as rt, AuthStoreState as s, isCanvasResource as sa, ComlinkControllerState as si, resolveOrganization as sn, editDocument as sr, ProjectBase as st, ApiErrorBody as t, ProjectHandle as ta, CommentThread as ti, resolveOrganizations as tn, archiveRelease as tr, ProjectsOptions as tt, LoggedOutAuthState as u, isDatasetSource as ua, getOrCreateController as ui, resolveFavoritesState as un, publishRelease as ur, ProjectMetadata as ut, setAuthToken as v, getClient as vi, DocumentDiscardedEvent as vn, InstanceContext as vr, GetPreviewStateOptions as vt, getIndexForKey$1 as w, AuthStateType as wi, DocumentUnpublishedEvent as wn, createDatasetHandle as wr, ValuePending as wt, Role as x, handleAuthCallback as xi, DocumentPublishedEvent as xn, LogNamespace as xr, PreviewQueryResult as xt, CurrentUser$1 as y, getClientState as yi, DocumentEditedEvent as yn, LogContext as yr, getPreviewState as yt, getUserState as z, agentTranslate as zi, CreateDocumentAction as zn, RemoveCommentOptions as zr, StateEvent as zt };
3334
+ //# sourceMappingURL=utils-BMwA8Kg9.d.ts.map