@sanity/sdk 2.8.0 → 2.10.0

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