@sanity/sdk 2.5.0 → 2.6.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.
package/dist/index.d.ts CHANGED
@@ -101,6 +101,16 @@ interface PerspectiveHandle {
101
101
  */
102
102
  interface DatasetHandle<TDataset extends string = string, TProjectId extends string = string> extends ProjectHandle<TProjectId>, PerspectiveHandle {
103
103
  dataset?: TDataset;
104
+ /**
105
+ * @beta
106
+ * The name of the source to use for this operation.
107
+ */
108
+ sourceName?: string;
109
+ /**
110
+ * @beta
111
+ * Explicit source object to use for this operation.
112
+ */
113
+ source?: DocumentSource;
104
114
  }
105
115
  /**
106
116
  * Identifies a specific document type within a Sanity dataset and project.
@@ -144,40 +154,50 @@ interface SanityConfig extends DatasetHandle, PerspectiveHandle {
144
154
  studioMode?: {
145
155
  enabled: boolean;
146
156
  };
157
+ /**
158
+ * @beta
159
+ * A list of named sources to use for this instance.
160
+ */
161
+ sources?: Record<string, DocumentSource>;
147
162
  }
148
- declare const SOURCE_ID = "__sanity_internal_sourceId";
149
163
  /**
150
164
  * A document source can be used for querying.
165
+ * This will soon be the default way to identify where you are querying from.
151
166
  *
152
167
  * @beta
153
- * @see datasetSource Construct a document source for a given projectId and dataset.
154
- * @see mediaLibrarySource Construct a document source for a mediaLibraryId.
155
- * @see canvasSource Construct a document source for a canvasId.
156
- */
157
- type DocumentSource = {
158
- [SOURCE_ID]: ['media-library', string] | ['canvas', string] | {
159
- projectId: string;
160
- dataset: string;
161
- };
168
+ */
169
+ type DocumentSource = DatasetSource | MediaLibrarySource | CanvasSource;
170
+ /**
171
+ * @beta
172
+ */
173
+ type DatasetSource = {
174
+ projectId: string;
175
+ dataset: string;
162
176
  };
163
177
  /**
164
- * Returns a document source for a projectId and dataset.
165
- *
166
178
  * @beta
167
179
  */
168
- declare function datasetSource(projectId: string, dataset: string): DocumentSource;
180
+ type MediaLibrarySource = {
181
+ mediaLibraryId: string;
182
+ };
183
+ /**
184
+ * @beta
185
+ */
186
+ type CanvasSource = {
187
+ canvasId: string;
188
+ };
169
189
  /**
170
- * Returns a document source for a Media Library.
171
- *
172
190
  * @beta
173
191
  */
174
- declare function mediaLibrarySource(id: string): DocumentSource;
192
+ declare function isDatasetSource(source: DocumentSource): source is DatasetSource;
175
193
  /**
176
- * Returns a document source for a Canvas.
177
- *
178
194
  * @beta
179
195
  */
180
- declare function canvasSource(id: string): DocumentSource;
196
+ declare function isMediaLibrarySource(source: DocumentSource): source is MediaLibrarySource;
197
+ /**
198
+ * @beta
199
+ */
200
+ declare function isCanvasSource(source: DocumentSource): source is CanvasSource;
181
201
  /**
182
202
  * Represents a Sanity.io resource instance with its own configuration and lifecycle
183
203
  * @remarks Instances form a hierarchy through parent/child relationships
@@ -675,6 +695,277 @@ declare function createProjectHandle<TProjectId extends string = string>(handle:
675
695
  * @public
676
696
  */
677
697
  declare function createDatasetHandle<TDataset extends string = string, TProjectId extends string = string>(handle: DatasetHandle<TDataset, TProjectId>): DatasetHandle<TDataset, TProjectId>;
698
+ /**
699
+ * Logging infrastructure for the Sanity SDK
700
+ *
701
+ * Provides multi-level, namespace-based logging for both SDK users and maintainers.
702
+ * In production builds, all logging can be stripped via tree-shaking.
703
+ *
704
+ * @example SDK User
705
+ * ```ts
706
+ * import {configureLogging} from '@sanity/sdk'
707
+ *
708
+ * configureLogging({
709
+ * level: 'info',
710
+ * namespaces: ['auth', 'document']
711
+ * })
712
+ * ```
713
+ *
714
+ * @example SDK Maintainer
715
+ * ```ts
716
+ * configureLogging({
717
+ * level: 'trace',
718
+ * namespaces: ['*'],
719
+ * internal: true
720
+ * })
721
+ * ```
722
+ */
723
+ /**
724
+ * Log levels in order of verbosity (least to most)
725
+ * - error: Critical failures that prevent operation
726
+ * - warn: Issues that may cause problems but don't stop execution
727
+ * - info: High-level informational messages (SDK user level)
728
+ * - debug: Detailed debugging information (maintainer level)
729
+ * - trace: Very detailed tracing (maintainer level, includes RxJS streams)
730
+ * @public
731
+ */
732
+ type LogLevel = 'error' | 'warn' | 'info' | 'debug' | 'trace';
733
+ /**
734
+ * Log namespaces organize logs by functional domain
735
+ *
736
+ * @remarks
737
+ * This is an extensible string type. As logging is added to more modules,
738
+ * additional namespaces will be recognized. Currently implemented namespaces
739
+ * will be documented as they are added.
740
+ * @internal
741
+ */
742
+ type LogNamespace = string;
743
+ /**
744
+ * Configuration for the logging system
745
+ * @public
746
+ */
747
+ interface LoggerConfig {
748
+ /**
749
+ * Minimum log level to output
750
+ * @defaultValue 'warn'
751
+ */
752
+ level?: LogLevel;
753
+ /**
754
+ * Namespaces to enable. Use ['*'] for all namespaces
755
+ * @defaultValue []
756
+ * @remarks
757
+ * Available namespaces depend on which modules have logging integrated.
758
+ * Check the SDK documentation for the current list of instrumented modules.
759
+ * @example ['auth', 'document']
760
+ */
761
+ namespaces?: string[];
762
+ /**
763
+ * Enable internal/maintainer-level logging
764
+ * Shows RxJS streams, store internals, etc.
765
+ * @defaultValue false
766
+ */
767
+ internal?: boolean;
768
+ /**
769
+ * Custom log handler (for testing or custom output)
770
+ * @defaultValue console methods
771
+ */
772
+ handler?: LogHandler;
773
+ /**
774
+ * Enable timestamps in log output
775
+ * @defaultValue true
776
+ */
777
+ timestamps?: boolean;
778
+ /**
779
+ * Enable in production builds
780
+ * @defaultValue false
781
+ */
782
+ enableInProduction?: boolean;
783
+ }
784
+ /**
785
+ * Custom log handler interface
786
+ *
787
+ * @internal
788
+ */
789
+ interface LogHandler {
790
+ error: (message: string, context?: LogContext) => void;
791
+ warn: (message: string, context?: LogContext) => void;
792
+ info: (message: string, context?: LogContext) => void;
793
+ debug: (message: string, context?: LogContext) => void;
794
+ trace: (message: string, context?: LogContext) => void;
795
+ }
796
+ /**
797
+ * Context object attached to log messages
798
+ *
799
+ * This interface allows you to attach arbitrary contextual data to log messages.
800
+ * The index signature `[key: string]: unknown` enables you to add any custom
801
+ * properties relevant to your log entry (e.g., `userId`, `documentId`, `action`, etc.).
802
+ *
803
+ * **Sensitive data sanitization:**
804
+ * Top-level keys containing sensitive names (`token`, `password`, `secret`, `apiKey`,
805
+ * `authorization`) are automatically redacted to `[REDACTED]` in log output.
806
+ *
807
+ * @example
808
+ * ```ts
809
+ * logger.info('User logged in', {
810
+ * userId: '123', // Custom context
811
+ * action: 'login', // Custom context
812
+ * token: 'secret' // Will be redacted to [REDACTED]
813
+ * })
814
+ * ```
815
+ *
816
+ * @internal
817
+ */
818
+ interface LogContext {
819
+ /**
820
+ * Custom context properties that provide additional information about the log entry.
821
+ * Any key-value pairs can be added here (e.g., userId, documentId, requestId, etc.).
822
+ * Keys with sensitive names (token, password, secret, apiKey, authorization) are
823
+ * automatically sanitized.
824
+ */
825
+ [key: string]: unknown;
826
+ /** Error object if logging an error */
827
+ error?: Error | unknown;
828
+ /** Duration in milliseconds for timed operations */
829
+ duration?: number;
830
+ /** Stack trace for debugging */
831
+ stack?: string;
832
+ /** Instance context (automatically added when available) */
833
+ instanceContext?: InstanceContext;
834
+ }
835
+ /**
836
+ * Instance context information automatically added to logs
837
+ * @internal
838
+ */
839
+ interface InstanceContext {
840
+ /** Unique instance ID */
841
+ instanceId?: string;
842
+ /** Project ID */
843
+ projectId?: string;
844
+ /** Dataset name */
845
+ dataset?: string;
846
+ }
847
+ /**
848
+ * Logger instance for a specific namespace
849
+ * @internal
850
+ */
851
+ interface Logger {
852
+ readonly namespace: string;
853
+ error: (message: string, context?: LogContext) => void;
854
+ warn: (message: string, context?: LogContext) => void;
855
+ info: (message: string, context?: LogContext) => void;
856
+ debug: (message: string, context?: LogContext) => void;
857
+ trace: (message: string, context?: LogContext) => void;
858
+ /** Check if a log level is enabled (for performance-sensitive code) */
859
+ isLevelEnabled: (level: LogLevel) => boolean;
860
+ /** Create a child logger with extended context */
861
+ child: (context: LogContext) => Logger;
862
+ /** Get the instance context if available */
863
+ getInstanceContext: () => InstanceContext | undefined;
864
+ }
865
+ /**
866
+ * Configure logging for the Sanity SDK
867
+ *
868
+ * This function allows you to control what logs are output by the SDK,
869
+ * making it easier to debug issues in development or production.
870
+ *
871
+ * @remarks
872
+ * **Zero-Config via Environment Variable (Recommended):**
873
+ *
874
+ * The SDK automatically reads the `DEBUG` environment variable, making it
875
+ * easy to enable logging without code changes:
876
+ *
877
+ * ```bash
878
+ * # Enable all SDK logging at debug level
879
+ * DEBUG=sanity:* npm start
880
+ *
881
+ * # Enable specific namespaces
882
+ * DEBUG=sanity:auth,sanity:document npm start
883
+ *
884
+ * # Enable trace level for all namespaces
885
+ * DEBUG=sanity:trace:* npm start
886
+ *
887
+ * # Enable internal/maintainer logs
888
+ * DEBUG=sanity:*:internal npm start
889
+ * ```
890
+ *
891
+ * This matches the pattern used by Sanity CLI and Studio, making it familiar
892
+ * and easy for support teams to help troubleshoot issues.
893
+ *
894
+ * **Programmatic Configuration (Advanced):**
895
+ *
896
+ * For more control (custom handlers, dynamic configuration), call this function
897
+ * explicitly. Programmatic configuration overrides environment variables.
898
+ *
899
+ * **For Application Developers:**
900
+ * Use `info`, `warn`, or `error` levels to see high-level SDK activity
901
+ * without being overwhelmed by internal details.
902
+ *
903
+ * **For SDK Maintainers:**
904
+ * Use `debug` or `trace` levels with `internal: true` to see detailed
905
+ * information about store operations, RxJS streams, and state transitions.
906
+ *
907
+ * **Instance Context:**
908
+ * Logs automatically include instance information (projectId, dataset, instanceId)
909
+ * when available, making it easier to debug multi-instance scenarios:
910
+ * ```
911
+ * [INFO] [auth] [project:abc] [dataset:production] User logged in
912
+ * ```
913
+ *
914
+ * **Available Namespaces:**
915
+ * - `sdk` - SDK initialization, configuration, and lifecycle
916
+ * - `auth` - Authentication and authorization (when instrumented in the future)
917
+ * - And more as logging is added to modules
918
+ *
919
+ * @example Zero-config via environment variable (recommended for debugging)
920
+ * ```bash
921
+ * # Just set DEBUG and run your app - no code changes needed!
922
+ * DEBUG=sanity:* npm start
923
+ * ```
924
+ *
925
+ * @example Programmatic configuration (application developer)
926
+ * ```ts
927
+ * import {configureLogging} from '@sanity/sdk'
928
+ *
929
+ * // Log warnings and errors for auth and document operations
930
+ * configureLogging({
931
+ * level: 'warn',
932
+ * namespaces: ['auth', 'document']
933
+ * })
934
+ * ```
935
+ *
936
+ * @example Programmatic configuration (SDK maintainer)
937
+ * ```ts
938
+ * import {configureLogging} from '@sanity/sdk'
939
+ *
940
+ * // Enable all logs including internal traces
941
+ * configureLogging({
942
+ * level: 'trace',
943
+ * namespaces: ['*'],
944
+ * internal: true
945
+ * })
946
+ * ```
947
+ *
948
+ * @example Custom handler (for testing)
949
+ * ```ts
950
+ * import {configureLogging} from '@sanity/sdk'
951
+ *
952
+ * const logs: string[] = []
953
+ * configureLogging({
954
+ * level: 'info',
955
+ * namespaces: ['*'],
956
+ * handler: {
957
+ * error: (msg) => logs.push(msg),
958
+ * warn: (msg) => logs.push(msg),
959
+ * info: (msg) => logs.push(msg),
960
+ * debug: (msg) => logs.push(msg),
961
+ * trace: (msg) => logs.push(msg),
962
+ * }
963
+ * })
964
+ * ```
965
+ *
966
+ * @public
967
+ */
968
+ declare function configureLogging(config: LoggerConfig): void;
678
969
  /** @public */
679
970
  declare const getDatasetsState: BoundStoreAction<FetcherStoreState<[options?: ProjectHandle<string> | undefined], _sanity_client12.DatasetsResponse>, [options?: ProjectHandle<string> | undefined], StateSource<_sanity_client12.DatasetsResponse | undefined>>;
680
971
  /** @public */
@@ -1938,4 +2229,4 @@ declare const CORE_SDK_VERSION: {};
1938
2229
  * @public
1939
2230
  */
1940
2231
  type SanityProject = SanityProject$1;
1941
- export { type ActionErrorEvent, type ActionsResult, type AgentGenerateOptions, type AgentGenerateResult, type AgentPatchOptions, type AgentPatchResult, type AgentPromptOptions, type AgentPromptResult, type AgentTransformOptions, type AgentTransformResult, type AgentTranslateOptions, type AgentTranslateResult, type ApiErrorBody, type ApplyDocumentActionsOptions, type AuthConfig, type AuthProvider, type AuthState, AuthStateType, type AuthStoreState, CORE_SDK_VERSION, type ClientOptions, type ClientStoreState as ClientState, type ComlinkControllerState, type ComlinkNodeState, type CreateDocumentAction, type CurrentUser, type DatasetHandle, type DeleteDocumentAction, type DiscardDocumentAction, type DisconnectEvent, type DocumentAction, type DocumentCreatedEvent, type DocumentDeletedEvent, type DocumentDiscardedEvent, type DocumentEditedEvent, type DocumentEvent, type DocumentHandle, type DocumentOptions, type DocumentPermissionsResult, type DocumentPublishedEvent, type DocumentSource, type DocumentTypeHandle, type DocumentUnpublishedEvent, type EditDocumentAction, type ErrorAuthState, type FavoriteStatusResponse, type FetcherStore, type FetcherStoreState, type FrameMessage, type GetPreviewStateOptions, type GetUserOptions, type GetUsersOptions, type Intent, type IntentFilter, type JsonMatch, type LoggedInAuthState, type LoggedOutAuthState, type LoggingInAuthState, type Membership, type NewTokenResponseMessage, type NodeState, type OrgVerificationResult, type PermissionDeniedReason, type PerspectiveHandle, type PresenceLocation, type PreviewStoreState, type PreviewValue, type ProjectHandle, type ProjectionValuePending, type PublishDocumentAction, type QueryOptions, type ReleaseDocument, type ReleasePerspective, type RequestNewTokenMessage, type ResolvePreviewOptions, type ResolveUserOptions, type ResolveUsersOptions, type Role, type RollCallEvent, type SanityConfig, type SanityDocument, type SanityInstance, SanityProject, type SanityUser, type SanityUserResponse, type Selector, type StateEvent, type StateSource, type TransactionAcceptedEvent, type TransactionRevertedEvent, type TransportEvent, type UnpublishDocumentAction, type UserPresence, type UserProfile, type UsersGroupState, type UsersStoreState, type ValidProjection, type ValuePending, type WindowMessage, agentGenerate, agentPatch, agentPrompt, agentTransform, agentTranslate, applyDocumentActions, canvasSource, createDatasetHandle, createDocument, createDocumentHandle, createDocumentTypeHandle, createGroqSearchFilter, createProjectHandle, createSanityInstance, datasetSource, defineIntent, deleteDocument, destroyController, discardDocument, editDocument, getActiveReleasesState, getAuthState, getClient, getClientErrorApiBody, getClientErrorApiDescription, getClientErrorApiType, getClientState, getCorsErrorProjectId, getCurrentUserState, getDashboardOrganizationId, getDatasetsState, getDocumentState, getDocumentSyncStatus, getFavoritesState, getIndexForKey, getIsInDashboardState, getLoginUrlState, getNodeState, getOrCreateChannel, getOrCreateController, getOrCreateNode, getPathDepth, getPermissionsState, getPerspectiveState, getPresence, getPreviewState, getProjectState, getProjectionState, getProjectsState, getQueryKey, getQueryState, getTokenState, getUserState, getUsersKey, getUsersState, handleAuthCallback, isProjectUserNotFoundClientError, joinPaths, jsonMatch, loadMoreUsers, logout, mediaLibrarySource, observeOrganizationVerificationState, parseQueryKey, parseUsersKey, publishDocument, releaseChannel, releaseNode, resolveDatasets, resolveDocument, resolveFavoritesState, resolvePermissions, resolvePreview, resolveProject, resolveProjection, resolveProjects, resolveQuery, resolveUser, resolveUsers, setAuthToken, slicePath, stringifyPath, subscribeDocumentEvents, unpublishDocument };
2232
+ export { type ActionErrorEvent, type ActionsResult, type AgentGenerateOptions, type AgentGenerateResult, type AgentPatchOptions, type AgentPatchResult, type AgentPromptOptions, type AgentPromptResult, type AgentTransformOptions, type AgentTransformResult, type AgentTranslateOptions, type AgentTranslateResult, type ApiErrorBody, type ApplyDocumentActionsOptions, type AuthConfig, type AuthProvider, type AuthState, AuthStateType, type AuthStoreState, CORE_SDK_VERSION, type CanvasSource, type ClientOptions, type ClientStoreState as ClientState, type ComlinkControllerState, type ComlinkNodeState, type CreateDocumentAction, type CurrentUser, type DatasetHandle, type DatasetSource, type DeleteDocumentAction, type DiscardDocumentAction, type DisconnectEvent, type DocumentAction, type DocumentCreatedEvent, type DocumentDeletedEvent, type DocumentDiscardedEvent, type DocumentEditedEvent, type DocumentEvent, type DocumentHandle, type DocumentOptions, type DocumentPermissionsResult, type DocumentPublishedEvent, type DocumentSource, type DocumentTypeHandle, type DocumentUnpublishedEvent, type EditDocumentAction, type ErrorAuthState, type FavoriteStatusResponse, type FetcherStore, type FetcherStoreState, type FrameMessage, type GetPreviewStateOptions, type GetUserOptions, type GetUsersOptions, type InstanceContext, type Intent, type IntentFilter, type JsonMatch, type LogContext, type LogLevel, type LogNamespace, type LoggedInAuthState, type LoggedOutAuthState, type Logger, type LoggerConfig, type LoggingInAuthState, type MediaLibrarySource, type Membership, type NewTokenResponseMessage, type NodeState, type OrgVerificationResult, type PermissionDeniedReason, type PerspectiveHandle, type PresenceLocation, type PreviewStoreState, type PreviewValue, type ProjectHandle, type ProjectionValuePending, type PublishDocumentAction, type QueryOptions, type ReleaseDocument, type ReleasePerspective, type RequestNewTokenMessage, type ResolvePreviewOptions, type ResolveUserOptions, type ResolveUsersOptions, type Role, type RollCallEvent, type SanityConfig, type SanityDocument, type SanityInstance, SanityProject, type SanityUser, type SanityUserResponse, type Selector, type StateEvent, type StateSource, type TransactionAcceptedEvent, type TransactionRevertedEvent, type TransportEvent, type UnpublishDocumentAction, type UserPresence, type UserProfile, type UsersGroupState, type UsersStoreState, type ValidProjection, type ValuePending, type WindowMessage, agentGenerate, agentPatch, agentPrompt, agentTransform, agentTranslate, applyDocumentActions, configureLogging, createDatasetHandle, createDocument, createDocumentHandle, createDocumentTypeHandle, createGroqSearchFilter, createProjectHandle, createSanityInstance, defineIntent, deleteDocument, destroyController, discardDocument, editDocument, getActiveReleasesState, getAuthState, getClient, getClientErrorApiBody, getClientErrorApiDescription, getClientErrorApiType, getClientState, getCorsErrorProjectId, getCurrentUserState, getDashboardOrganizationId, getDatasetsState, getDocumentState, getDocumentSyncStatus, getFavoritesState, getIndexForKey, getIsInDashboardState, getLoginUrlState, getNodeState, getOrCreateChannel, getOrCreateController, getOrCreateNode, getPathDepth, getPermissionsState, getPerspectiveState, getPresence, getPreviewState, getProjectState, getProjectionState, getProjectsState, getQueryKey, getQueryState, getTokenState, getUserState, getUsersKey, getUsersState, handleAuthCallback, isCanvasSource, isDatasetSource, isMediaLibrarySource, isProjectUserNotFoundClientError, joinPaths, jsonMatch, loadMoreUsers, logout, observeOrganizationVerificationState, parseQueryKey, parseUsersKey, publishDocument, releaseChannel, releaseNode, resolveDatasets, resolveDocument, resolveFavoritesState, resolvePermissions, resolvePreview, resolveProject, resolveProjection, resolveProjects, resolveQuery, resolveUser, resolveUsers, setAuthToken, slicePath, stringifyPath, subscribeDocumentEvents, unpublishDocument };