@sanity/sdk-react 3.4.0 → 3.5.0-next.20260922190712

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.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["ClientError","SDK_CHANNEL_NAME","SDK_NODE_NAME","AuthStateType","getIsInDashboardState","setAuthToken","isStudioConfig","FrameMessage","NewTokenResponseMessage","RequestNewTokenMessage","WindowMessage","React","PropsWithChildren","useCallback","useEffect","useMemo","useRef","useAuthState","useWindowConnection","useSanityInstance","SdkParentComlinkMessage","SdkChildComlinkMessage","DEFAULT_RESPONSE_TIMEOUT","DashboardTokenRefresh","t0","$","_c","children","instance","isTokenRefreshInProgress","timeoutRef","processed401ErrorRef","authState","t1","Symbol","for","current","clearTimeout","clearRefreshTimeout","t2","name","connectTo","windowConnection","t3","setTimeout","res","fetch","token","errorContainer","document","getElementById","hasUnauthorizedError","Array","from","getElementsByTagName","some","_temp","remove","requestNewToken","t4","t5","t6","error","type","has401Error","ERROR","statusCode","isLoggedOut","LOGGED_OUT","undefined","t7","div","textContent","includes","ComlinkTokenRefreshProvider","FC","isInDashboard","getCurrent","isStudio","config","getLoginUrlState","useMemo","useSyncExternalStore","useSanityInstance","useLoginUrl","$","_c","instance","t0","subscribe","getCurrent","observeOrganizationVerificationState","OrgVerificationResult","useEffect","useState","useSanityInstance","useVerifyOrgProjects","t0","projectIds","$","_c","disabled","undefined","instance","error","setError","isInactive","length","prevInactive","setPrevInactive","t1","t2","verificationObservable$","subscription","subscribe","result","unsubscribe","CHUNK_RELOAD_STORAGE_KEY","readChunkReloadFlag","window","sessionStorage","getItem","setChunkReloadFlag","setItem","clearChunkReloadFlag","removeItem","FONT_SANS_SERIF","FONT_MONOSPACE","styles","Record","React","CSSProperties","container","padding","fontFamily","display","flexDirection","gap","fontSize","heading","margin","fontWeight","paragraph","link","appearance","background","border","font","textDecoration","cursor","code","styles","ErrorProps","heading","description","code","cta","text","href","onClick","Error","t0","$","_c","t1","t2","paragraph","__html","t3","t4","link","t5","container","useEffect","FallbackProps","clearChunkReloadFlag","readChunkReloadFlag","setChunkReloadFlag","Error","reload","window","location","ChunkLoadError","_props","$","_c","t0","Symbol","for","alreadyAttempted","t1","t2","t3","text","onClick","_temp","useMemo","FallbackProps","getErrorMessage","Error","CorsErrorComponentProps","projectId","CorsErrorComponent","t0","$","_c","error","origin","window","location","t1","url","URL","searchParams","set","toString","corsUrl","t2","description","code","cta","text","href","isInIframe","window","self","top","isLocalUrl","Window","url","location","href","startsWith","AuthError","Error","constructor","error","message","cause","ConfigurationError","Error","constructor","error","message","cause","SanityInstance","useCallback","useSanityInstance","createCallbackHook","callback","instance","params","TParams","TReturn","useHook","$","_c","t0","t1","handleAuthCallback","createCallbackHook","useHandleAuthCallback","useEffect","useHandleAuthCallback","LoginCallback","$","_c","handleAuthCallback","t0","t1","url","URL","location","href","toString","then","_temp","replacementLocation","history","replaceState","logout","createCallbackHook","useLogOut","SDK_CHANNEL_NAME","SDK_NODE_NAME","useEffect","useWindowConnection","DashboardAccessRequestProps","projectId","DashboardAccessRequest","t0","$","_c","t1","Symbol","for","name","connectTo","fetch","t2","t3","resourceType","resourceId","ClientError","AuthStateType","getIsInDashboardState","getClientErrorApiBody","getClientErrorApiDescription","isProjectUserNotFoundClientError","Suspense","useCallback","useEffect","useMemo","useRef","FallbackProps","useAuthState","useLogOut","useSanityInstance","Error","AuthError","ConfigurationError","DashboardAccessRequest","LoginErrorProps","LoginError","t0","$","_c","error","resetErrorBoundary","logout","authState","instance","config","t1","projectId","clientError","cause","t2","getCurrent","isInDashboard","t3","statusCode","isProjectUserNotFound","dashboardAccessProjectId","t4","handleRetry","message","retry","t5","description","errorMessage","startsWith","endsWith","type","ERROR","authErrorMessage","showRetryCta","hasAutoLoggedOutRef","t6","t7","current","t8","t9","t10","text","onClick","undefined","t11","t12","CorsOriginError","AuthStateType","getCorsErrorProjectId","isImportError","isDashboardEnvironment","isStudioConfig","useEffect","useMemo","ErrorBoundary","FallbackProps","ComlinkTokenRefreshProvider","DashboardTokenRefreshProvider","useAuthState","useLoginUrl","useVerifyOrgProjects","useSanityInstance","ChunkLoadError","CorsErrorComponent","isInIframe","AuthError","ConfigurationError","LoginCallback","LoginError","LoginErrorProps","document","querySelector","parsedUrl","URL","window","location","href","mode","URLSearchParams","hash","slice","get","script","createElement","src","type","async","head","appendChild","AuthBoundaryProps","LoginComponent","React","ComponentType","header","ReactNode","footer","CallbackComponent","LoginErrorComponent","projectIds","children","verifyOrganization","AuthBoundary","t0","$","_c","props","t1","undefined","authState","sessionResetKey","LOGGED_IN","token","t2","LoginComponentWithLayoutProps","fallbackProps","error","FallbackComponent","t3","t4","t5","AuthSwitchProps","AuthSwitch","instance","config","isStudio","disableVerifyOrg","orgError","isLoggedOut","LOGGED_OUT","isDestroyingSession","loginUrl","message","ERROR","LOGGING_IN","t6","Error","TokenSource","createContext","StudioWorkspaceHandle","projectId","dataset","authenticated","auth","token","SDKStudioContext","displayName","DEFAULT_RESOURCE_NAME","CanvasResource","getClientState","MediaLibraryResource","SanityInstance","firstValueFrom","API_VERSION","OrgResourcesApiItem","id","OrgResourcesApiResponse","data","OrgResources","mediaLibrary","canvas","getFirstResourceId","result","PromiseSettledResult","status","undefined","value","resolveOrgResources","instance","organizationId","Promise","client","apiVersion","scope","observable","mediaLibrariesResult","canvasesResult","allSettled","request","url","query","tag","mediaLibraryId","canvasId","DocumentResource","createContext","ResourcesContext","Record","DocumentResource","SanityInstance","ReactElement","ReactNode","use","useMemo","useSanityInstance","useOrganizationId","resolveOrgResources","ResourcesContext","DEFAULT_MEDIA_LIBRARY_RESOURCE_NAME","DEFAULT_CANVAS_RESOURCE_NAME","OrgResource","OrgResourcePromises","Map","PromiseLike","inferredResourceCache","WeakMap","getOrgResourcePromises","instance","organizationId","promises","get","basePromise","then","result","error","console","warn","mediaLibrary","undefined","canvas","r","set","InferredResourcesProvider","t0","$","_c","orgId","explicitResources","children","ml","inferred","t1","resources","t2","OrganizationResourcesProvider","inferMediaLibraryAndCanvas","t3","DocumentResource","createContext","ResourceContext","undefined","PerspectiveHandle","createContext","PerspectiveContext","undefined","createContext","ProjectContext","undefined","SanityInstance","Suspense","SanityInstanceContext","SanityInstanceProviderProps","instance","fallback","React","ReactNode","children","SanityInstanceProvider","t0","$","_c","t1","t2","createSanityInstance","DatasetResource","DocumentResource","isDatasetResource","SanityConfig","SanityInstance","initTelemetry","useContext","useEffect","useMemo","useRef","useState","ResourceContext","PerspectiveContext","ProjectContext","SanityInstanceContext","SanityInstanceProvider","DEFAULT_FALLBACK","ResourceProviderProps","resource","fallback","React","ReactNode","children","ResourceProvider","t0","$","_c","config","parentPerspective","parentResource","parentInstance","parentProjectId","projectId","dataset","perspective","t1","instance","t2","bb0","t3","undefined","configResource","bb1","effectiveResource","t4","bb2","effectiveProjectId","t5","t6","disposal","t7","t8","current","clearTimeout","timeoutId","setTimeout","isDisposed","dispose","t9","t10","t11","t12","t13","t14","DocumentResource","isDatasetResource","isImportError","SanityConfig","ReactElement","ReactNode","useEffect","useMemo","ErrorBoundary","FallbackProps","DEFAULT_RESOURCE_NAME","OrganizationResourcesProvider","ResourceProvider","AuthBoundary","AuthBoundaryProps","ChunkLoadError","clearChunkReloadFlag","SDKProviderProps","children","config","fallback","resources","Record","inferMediaLibraryAndCanvas","ResetChunkReloadFlagOnMount","$","_c","t0","Symbol","for","_temp","SDKProvider","props","defaultConfig","Array","isArray","defaultProjectId","projectId","defaultDataset","dataset","t1","bb0","t2","explicit","Object","hasOwn","t3","t4","resourcesValue","values","filter","map","_temp2","Set","_temp3","_temp4","from","projectIds","t5","t6","t7","ChunkAwareFallback","id","configObj","resource","fallbackProps","error","DocumentResource","SanityConfig","isStudioConfig","ReactElement","useContext","useEffect","useMemo","SDKStudioContext","StudioWorkspaceHandle","SDKProvider","isInIframe","isLocalUrl","SanityAppProps","config","resources","Record","children","React","ReactNode","fallback","inferMediaLibraryAndCanvas","REDIRECT_URL","deriveConfigFromWorkspace","workspace","projectId","dataset","studio","authenticated","auth","token","undefined","SanityApp","t0","$","_c","configProp","props","studioWorkspace","t1","bb0","t2","Symbol","for","resolvedConfig","t3","timeout","primaryConfig","Array","isArray","shouldRedirectWithoutConfig","window","setTimeout","_temp","clearTimeout","t4","console","warn","location","replace","SanityConfig","StrictMode","createRoot","SanityApp","RenderSanitySDKAppOptions","reactStrictMode","NamedSources","key","renderSanityApp","rootElement","HTMLElement","namedSources","options","children","React","ReactNode","Error","root","config","Object","values","render","unmount","Fetcher","FetcherSnapshot","isDeepEqual","useRef","useSyncExternalStore","useSanityInstance","FetcherHookResult","data","TData","isFetching","error","refetch","Promise","createFetcherHook","fetcher","TParams","params","useFetcherHook","instance","source","getState","getCurrent","status","resolveState","previous","snapshot","subscribe","next","prev","current","AccessResourceType","checkPermissions","createFetcherHook","FetcherHookResult","useCheckPermissions","resourceType","resourceId","permissions","Permission","Record","DocumentResource","PerspectiveHandle","useContext","useMemo","ResourceContext","PerspectiveContext","ResourcesContext","SanityInstanceContext","NormalizedResourceFields","WithResourceNameSupport","resource","T","resourceName","normalizeResourceOptions","projectId","dataset","perspective","options","resources","Record","contextResource","contextPerspective","Omit","rest","Error","JSON","stringify","resolvedResource","Object","hasOwn","resolvedPerspective","undefined","useEffectiveContextResource","$","_c","instance","t0","config","configResource","t1","bb0","t2","useNormalizedResourceOptions","effectiveContextResource","agentGenerate","AgentGenerateOptions","agentPatch","AgentPatchOptions","AgentPatchResult","agentPrompt","AgentPromptOptions","AgentPromptResult","agentTransform","AgentTransformOptions","agentTranslate","AgentTranslateOptions","useCallback","firstValueFrom","ResourceHandle","useSanityInstance","useNormalizedResourceOptions","Subscription","unsubscribe","Observer","next","value","T","error","err","complete","Subscribable","subscribe","observer","useAgentGenerate","resourceHandle","$","_c","instance","t0","resource","t1","options","useAgentTransform","useAgentTranslate","useAgentPrompt","useAgentPatch","Application","application","ApplicationInclude","createFetcherHook","FetcherHookResult","useApplication","applicationId","options","include","Include","ApplicationInclude","applications","ApplicationsOptions","ApplicationsResponse","createFetcherHook","FetcherHookResult","useApplications","options","Include","SanityInstance","MutationResult","useCallback","useRef","useState","useSanityInstance","MutationHookResult","mutate","input","TInput","Promise","TResult","isPending","error","data","reset","MutationState","status","createMutationHook","mutation","instance","idle","undefined","useMutationHook","state","setState","callId","id","current","prev","then","deleteApplication","createMutationHook","useDeleteApplication","updateApplication","createMutationHook","useUpdateApplication","getTokenState","createStateSourceHook","useAuthToken","CurrentUser","getCurrentUserState","createStateSourceHook","UseCurrentUser","useCurrentUser","ClientOptions","getClientState","SanityInstance","createStateSourceHook","useClient","getState","instance","options","Error","getConfig","ChannelInstance","Controller","Status","FrameMessage","getOrCreateChannel","getOrCreateController","releaseChannel","WindowMessage","useCallback","useEffect","useRef","useSanityInstance","FrameMessageHandler","event","TWindowMessage","Promise","UseFrameConnectionOptions","name","connectTo","targetOrigin","onMessage","data","Extract","type","K","heartbeat","onStatus","status","FrameConnection","connect","frameWindow","Window","sendMessage","TFrameMessage","params","T","useFrameConnection","options","$","_c","instance","controllerRef","channelRef","t0","t1","controller","channel","current","messageUnsubscribers","Object","entries","forEach","t2","handler","unsubscribe","on","push","_temp","Symbol","for","removeTarget","addTarget","t3","type_0","post","t4","unsub","SanityInstance","trackHookMounted","useRef","useSanityInstance","useTrackHookUsage","hookName","instance","tracked","current","trackHookUsage","Comment","createComment","CreateCommentOptions","DocumentResource","PerspectiveHandle","removeComment","RemoveCommentOptions","replyToComment","ReplyToCommentOptions","setCommentStatus","SetCommentStatusOptions","updateComment","UpdateCommentOptions","useContext","useMemo","PerspectiveContext","ResourcesContext","useSanityInstance","normalizeResourceOptions","useEffectiveContextResource","WithResourceNameSupport","trackHookUsage","CommentActions","options","Promise","Resolvable","resource","resourceName","projectId","dataset","perspective","useCommentActions","$","_c","instance","resources","contextResource","contextPerspective","t0","resolve","t1","options_0","options_1","options_2","options_3","options_4","CommentsOptions","SanityInstance","StateSource","getCommentsOptionsKey","parseCommentsOptionsKey","useEffect","useMemo","useRef","useState","useSyncExternalStore","useTransition","useSanityInstance","useNormalizedResourceOptions","WithResourceNameSupport","trackHookUsage","CommentListSource","getState","instance","options","T","resolve","signal","AbortSignal","Promise","useCommentList","hookName","value","isPending","normalized","startTransition","key","deferredKey","setDeferredKey","abortRef","AbortController","current","aborted","abort","deferred","getCurrent","subscribe","undefined","currentSignal","Comment","CommentsOptions","getCommentsState","resolveComments","useMemo","WithResourceNameSupport","CommentListSource","useCommentList","UseCommentsResult","comments","isPending","SOURCE","getState","resolve","useComments","options","$","_c","value","t0","CommentsOptions","CommentThread","getCommentThreadsState","resolveCommentThreads","useMemo","WithResourceNameSupport","CommentListSource","useCommentList","UseCommentThreadsResult","threads","isPending","SOURCE","getState","resolve","useCommentThreads","options","$","_c","value","t0","DocumentResource","useEffectiveContextResource","useResource","CanvasResource","MediaResource","StudioResource","DocumentHandle","FavoriteDocumentContext","useMemo","useSanityInstance","UseFavoriteProps","resourceId","resourceType","schemaName","useFavoriteContext","t0","$","_c","documentId","documentType","projectId","paramProjectId","dataset","paramDataset","paramResourceId","config","Error","t1","favorites","createFetcherHook","useFavoriteContext","UseFavoriteProps","useFavoriteStatus","useFavorite","props","context","data","isFavorited","CanvasResource","Events","MediaResource","SDK_CHANNEL_NAME","SDK_NODE_NAME","StudioResource","DocumentHandle","isDashboardEnvironment","FrameMessage","useCallback","useWindowConnection","useEmit","useTopic","DocumentInteractionHistory","recordEvent","eventType","UseRecordDocumentHistoryEventProps","resourceType","resourceId","schemaName","useRecordDocumentHistoryEvent","props","useBusRecordDocumentHistoryEvent","useComlinkRecordDocumentHistoryEvent","t0","$","_c","documentId","documentType","t1","Symbol","for","name","connectTo","sendMessage","Error","t2","message","type","data","document","id","resource","t3","error","console","emitActivity","capabilities","history","kind","FavoriteStatusResponse","setFavorite","useCallback","createMutationHook","useFavoriteContext","UseFavoriteProps","useSetFavorite","UpdateFavorite","favorite","Promise","unfavorite","isPending","error","reset","useUpdateFavorite","props","$","_c","context","mutate","t0","isFavorited","t1","t2","DocumentResource","isDatasetResource","useContext","ProjectContext","useNormalizedResourceOptions","useResolvedProjectId","options","$","_c","t0","resource","contextProjectId","t1","projectId","undefined","DatasetsResponse","datasets","ProjectHandle","createFetcherHook","FetcherHookResult","useResolvedProjectId","useDatasetsBase","useDatasets","options","$","_c","projectId","t0","Action","ActionsResult","applyDocumentActions","isDeepEqual","useContext","ResourceHandle","ResourcesContext","useSanityInstance","normalizeResourceOptions","useEffectiveContextResource","useApplyActions","$","_c","instance","resources","effectiveContextResource","t0","actionOrActions","options","actions","Array","isArray","optionsResource","resource","undefined","normalizedActions","map","action","action_0","actionResource","Error","JSON","stringify","effectiveResource","ActionsResult","DocumentAction","ResolveDocument","ResourceHandle","useApplyActions","useEditDocument","UseApplyDocumentActions","action","TDocumentType","TDataset","TProjectId","options","Promise","useApplyDocumentActions","ReturnType","createDocument","ResolveDocument","randomUuid","DocumentHandle","DocumentTypeHandle","useSanityInstance","trackHookUsage","useApplyDocumentActions","IgnoredKey","CreateDocumentOverrides","documentId","useCreateDocument","options","TDocumentType","TDataset","TProjectId","initialValue","Partial","Omit","overrides","Promise","Record","TData","$","_c","instance","apply","t0","handle","DocumentOptions","getDocumentState","JsonMatch","ResolveDocument","resolveDocument","identity","DocumentHandle","createStateSourceHook","useNormalizedResourceOptions","useTrackHookUsage","useDocumentProjection","useQuery","useDocumentValue","getState","instance","options","shouldSuspend","path","_path","getCurrent","undefined","suspender","getConfig","wrapHookWithData","useValue","params","TParams","TReturn","useHook","data","UseDocumentOptions","TDocumentType","TDataset","TProjectId","TPath","UseDocument","TData","useDocument","normalizedOptions","DocumentEvent","subscribeDocumentEvents","useCallback","useEffect","useInsertionEffect","useRef","ResourceHandle","useSanityInstance","useNormalizedResourceOptions","useTrackHookUsage","UseDocumentEventOptions","TDataset","TProjectId","onEvent","documentEvent","useDocumentEvent","options","$","_c","normalizedOptions","datasetHandle","ref","t0","current","t1","Symbol","for","stableHandler","instance","t2","t3","resource","eventHandler","DocumentAction","DocumentPermissionsResult","getPermissionsState","isDeepEqual","useCallback","useContext","useMemo","useSyncExternalStore","filter","firstValueFrom","ResourcesContext","useSanityInstance","normalizeResourceOptions","useEffectiveContextResource","WithResourceNameSupport","trackHookUsage","noopSubscribe","returnUndefined","undefined","useDocumentPermissions","actionOrActions","$","_c","instance","effectiveContextResource","resources","t0","bb0","normalized","Array","isArray","map","action","resource","action_0","actions","error","Error","JSON","stringify","t1","normalizedActions","actionResource","validationError","effectiveResource","permissionsOptions","t2","stateSource","isDocumentReady","getCurrent","result","subscribe","observable","pipe","_temp","permissions","DocumentHandle","DocumentOptions","getDocumentSyncStatus","resolveDocument","SanityInstance","StateSource","identity","createStateSourceHook","useNormalizedResourceOptions","UseDocumentSyncStatus","doc","useDocumentSyncStatusValue","getState","instance","shouldSuspend","getCurrent","undefined","suspender","getConfig","useDocumentSyncStatus","options","normalizedOptions","ActionsResult","DocumentOptions","editDocument","getDocumentState","JsonMatch","ResolveDocument","resolveDocument","useCallback","useSanityInstance","useNormalizedResourceOptions","trackHookUsage","useApplyDocumentActions","ignoredKeys","Updater","TValue","currentValue","useEditDocument","options","TDocumentType","TDataset","TProjectId","nextValue","Promise","TPath","TData","t0","$","_c","doc","path","instance","normalizedDoc","apply","isDocumentReady","getCurrent","undefined","t1","updater","currentPath","stateWithOptions","prev","set","fullDocState","current","nextValue_0","Error","allKeys","Object","keys","editActions","filter","_temp","key_0","key","Record","map","key_1","unset","includes","getQueryState","QueryOptions","resolveQuery","ResolveQueryResult","getQueryKey","parseQueryKey","useEffect","useMemo","useRef","useState","useSyncExternalStore","useTransition","useSanityInstance","useNormalizedResourceOptions","WithResourceNameSupport","trackHookUsage","UseQueryOptions","TQuery","TDataset","TProjectId","useQuery","options","data","isPending","TData","instance","normalized","startTransition","queryKey","deferredQueryKey","setDeferredQueryKey","ref","AbortController","current","signal","aborted","abort","getCurrent","subscribe","deferred","undefined","currentSignal","DocumentHandle","isDatasetResource","QueryOptions","createGroqSearchFilter","pickProperties","SortOrderingItem","useCallback","useMemo","useState","ResourceHandle","useNormalizedResourceOptions","useTrackHookUsage","useQuery","DEFAULT_BATCH_SIZE","DocumentsOptions","TDataset","TProjectId","Pick","documentType","TDocumentType","filter","batchSize","orderings","search","DocumentsResponse","data","hasMore","count","isPending","loadMore","useDocuments","t0","$","_c","params","rawOptions","t1","undefined","options","limit","setLimit","t2","Array","isArray","t3","_temp","documentTypes","t4","JSON","stringify","types","key","prevKey","setPrevKey","conditions","length","trimmedSearch","trim","searchFilter","push","filterClause","join","t5","map","_temp3","orderClause","dataQuery","countQuery","t6","t7","resource","t8","t9","t10","__handle","__types","t11","query","t12","t13","prev","Math","min","t14","ordering","field","direction","toLowerCase","_temp2","Boolean","str","i","Installation","installation","InstallationInclude","createFetcherHook","FetcherHookResult","useInstallation","installationId","options","include","Include","InstallationInclude","installations","InstallationsOptions","InstallationsResponse","createFetcherHook","FetcherHookResult","useInstallations","options","Include","Organization","organization","OrganizationOptions","createFetcherHook","FetcherHookResult","useOrganization","options","IncludeMembers","IncludeFeatures","Organizations","organizations","OrganizationsOptions","createFetcherHook","FetcherHookResult","useOrganizations","options","IncludeMembers","IncludeFeatures","DocumentHandle","isDatasetResource","QueryOptions","createGroqSearchFilter","pickProperties","SortOrderingItem","useCallback","useMemo","useState","useNormalizedResourceOptions","WithResourceNameSupport","useTrackHookUsage","useQuery","PaginatedDocumentsOptions","Omit","TDocumentType","TDataset","TProjectId","documentType","filter","pageSize","orderings","search","PaginatedDocumentsResponse","data","isPending","currentPage","totalPages","startIndex","endIndex","count","firstPage","hasFirstPage","previousPage","hasPreviousPage","nextPage","hasNextPage","lastPage","hasLastPage","goToPage","pageNumber","usePaginatedDocuments","params","rawOptions","options","pageIndex","setPageIndex","key","JSON","stringify","prevKey","setPrevKey","documentTypes","Array","isArray","i","filterClause","conditions","trimmedSearch","trim","searchFilter","push","length","join","orderClause","map","ordering","field","direction","toLowerCase","str","Boolean","dataQuery","countQuery","query","__types","__handle","resource","Math","ceil","prev","max","min","getPresence","isMediaLibraryResource","UserPresence","useCallback","useMemo","useSyncExternalStore","ResourceHandle","useSanityInstance","useNormalizedResourceOptions","trackHookUsage","usePresence","t0","$","_c","t1","undefined","options","normalizedOptions","resource","Error","sanityInstance","t2","source","t3","callback","subscribe","t4","t5","getCurrent","locations","t6","t7","DocumentPresence","getDocumentPresence","isMediaLibraryResource","Path","useCallback","useMemo","useSyncExternalStore","DocumentHandle","useSanityInstance","useNormalizedResourceOptions","trackHookUsage","UsePresenceForDocumentOptions","path","excludeVersions","usePresenceForDocument","options","$","_c","handle","normalizedOptions","resource","Error","sanityInstance","perspective","documentId","liveEdit","t0","JSON","stringify","pathKey","t1","parse","undefined","source","t2","callback","subscribe","t3","t4","getCurrent","presence","t5","t6","isMediaLibraryResource","PresenceSelection","reportPresence","ReportPresenceOptions","Path","useEffect","useMemo","useRef","DocumentHandle","useSanityInstance","useNormalizedResourceOptions","trackHookUsage","FOCUS_THROTTLE_MS","SELECTION_THROTTLE_MS","UseReportPresenceOptions","path","selection","throttleMs","useReportPresence","options","$","_c","handle","normalizedOptions","resource","Error","sanityInstance","perspective","documentId","liveEdit","interval","t0","JSON","stringify","locationKey","t1","parse","id","parsedPath","parsedSelection","parsedPerspective","parsedLiveEdit","t2","t3","t4","length","t5","t6","location","lastSentAt","pending","undefined","t7","t8","send","current","Date","now","locations","elapsed","clearTimeout","setTimeout","t10","t9","getProjectionState","resolveProjection","ResolveProjectionResult","useCallback","useMemo","useSyncExternalStore","distinctUntilChanged","EMPTY","Observable","startWith","switchMap","DocumentHandle","useSanityInstance","useNormalizedResourceOptions","trackHookUsage","useDocumentProjectionOptions","TDocumentType","TDataset","TProjectId","projection","TProjection","params","Record","ref","React","RefObject","useDocumentProjectionResults","data","TData","isPending","useDocumentProjection","options","t0","$","_c","docHandle","instance","t1","trim","normalizedProjection","normalizedDocHandle","t2","stateSource","getCurrent","t3","onStoreChanged","subscription","observer","IntersectionObserver","HTMLElement","next","intersectionObserver","t4","entry","isIntersecting","rootMargin","threshold","current","observe","disconnect","pipe","isVisible","obs","subscribe","unsubscribe","PreviewQueryResult","PreviewValue","PREVIEW_PROJECTION","transformProjectionToPreview","useMemo","DocumentHandle","useSanityInstance","useNormalizedResourceOptions","trackHookUsage","useDocumentProjection","useDocumentPreviewOptions","ref","React","RefObject","useDocumentPreviewResults","data","isPending","useDocumentPreview","t0","$","_c","docHandle","instance","normalizedDocHandle","t1","projection","projectionResult","t2","resource","previewValue","t3","Project","project","ProjectOptions","createFetcherHook","FetcherHookResult","useResolvedProjectId","useProjectBase","useProject","options","projectId","IncludeMembers","IncludeFeatures","Project","projects","ProjectsOptions","createFetcherHook","FetcherHookResult","useProjects","options","IncludeMembers","IncludeFeatures","DatasetHandle","DocumentResource","getActiveReleasesState","ReleaseDocument","SanityInstance","StateSource","filter","firstValueFrom","createStateSourceHook","useNormalizedResourceOptions","WithResourceNameSupport","UseActiveReleasesValue","options","resource","useActiveReleasesValue","getState","instance","shouldSuspend","getCurrent","undefined","suspender","observable","pipe","Boolean","useActiveReleases","$","_c","t0","normalizedOptions","DatasetHandle","DocumentResource","getAllReleasesState","ReleaseDocument","SanityInstance","StateSource","filter","firstValueFrom","createStateSourceHook","useNormalizedResourceOptions","WithResourceNameSupport","UseAllReleasesValue","options","resource","useAllReleasesValue","getState","instance","shouldSuspend","getCurrent","undefined","suspender","observable","pipe","Boolean","useAllReleases","$","_c","t0","normalizedOptions","ActionsResult","ReleaseAction","ResourceHandle","useApplyActions","UseApplyReleaseActions","action","options","Promise","useApplyReleaseActions","ReturnType","DocumentResource","getPerspectiveState","SanityInstance","StateSource","filter","firstValueFrom","ResourceHandle","createStateSourceHook","useNormalizedResourceOptions","UsePerspectiveValue","perspectiveHandle","resource","usePerspectiveValue","getState","instance","shouldSuspend","options","getCurrent","undefined","suspender","_options","observable","pipe","Boolean","usePerspective","$","_c","t0","normalizedOptions","GetUserOptions","getUsersState","resolveUsers","SanityUser","getUsersKey","parseUsersKey","useEffect","useMemo","useState","useSyncExternalStore","useTransition","useSanityInstance","trackHookUsage","UserResult","data","isPending","useUser","options","$","_c","instance","startTransition","t0","key","deferredKey","setDeferredKey","t1","deferred","t2","Symbol","for","AbortController","ref","setRef","t3","t4","signal","aborted","abort","t5","t6","getCurrent","subscribe","undefined","result","t7","GetUsersOptions","getUsersState","loadMoreUsers","resolveUsers","SanityUser","getUsersKey","parseUsersKey","useCallback","useEffect","useMemo","useState","useSyncExternalStore","useTransition","useSanityInstance","useResolvedProjectId","trackHookUsage","UsersResult","data","hasMore","isPending","loadMore","withResolvedProjectId","options","projectId","isOrgScoped","resourceType","organizationId","useUsers","$","_c","instance","startTransition","resolvedProjectId","t0","effectiveOptions","t1","key","deferredKey","setDeferredKey","t2","deferred","t3","Symbol","for","AbortController","ref","setRef","t4","t5","signal","aborted","abort","t6","getCurrent","subscribe","undefined","t7","t8","WindowWithEnv","Window","globalThis","ENV","Record","KnownEnvVar","getEnv","key","import","meta","env","process","window","undefined","version","getEnv","REACT_SDK_VERSION"],"sources":["../src/context/ComlinkTokenRefresh.tsx","../src/hooks/auth/useLoginUrl.tsx","../src/hooks/auth/useVerifyOrgProjects.tsx","../src/components/errors/chunkReloadStorage.ts","../src/components/errors/Error.styles.ts","../src/components/errors/Error.tsx","../src/components/errors/ChunkLoadError.tsx","../src/components/errors/CorsErrorComponent.tsx","../src/components/utils.ts","../src/components/auth/AuthError.ts","../src/components/auth/ConfigurationError.ts","../src/hooks/helpers/createCallbackHook.tsx","../src/hooks/auth/useHandleAuthCallback.tsx","../src/components/auth/LoginCallback.tsx","../src/hooks/auth/useLogOut.tsx","../src/components/auth/DashboardAccessRequest.tsx","../src/components/auth/LoginError.tsx","../src/components/auth/AuthBoundary.tsx","../src/context/SDKStudioContext.ts","../src/constants.ts","../src/utils/resolveOrgResources.ts","../src/context/ResourcesContext.tsx","../src/context/OrganizationResourcesProvider.tsx","../src/context/DefaultResourceContext.ts","../src/context/PerspectiveContext.ts","../src/context/ProjectContext.ts","../src/context/SanityInstanceProvider.tsx","../src/context/ResourceProvider.tsx","../src/components/SDKProvider.tsx","../src/components/SanityApp.tsx","../src/context/renderSanityApp.tsx","../src/hooks/helpers/createFetcherHook.ts","../src/hooks/access/useCheckPermissions.ts","../src/hooks/helpers/useNormalizedResourceOptions.ts","../src/hooks/agent/agentActions.ts","../src/hooks/applications/useApplication.ts","../src/hooks/applications/useApplications.ts","../src/hooks/helpers/createMutationHook.tsx","../src/hooks/applications/useDeleteApplication.ts","../src/hooks/applications/useUpdateApplication.ts","../src/hooks/auth/useAuthToken.tsx","../src/hooks/auth/useCurrentUser.tsx","../src/hooks/client/useClient.ts","../src/hooks/comlink/useFrameConnection.ts","../src/hooks/helpers/useTrackHookUsage.ts","../src/hooks/comments/useCommentActions.ts","../src/hooks/comments/useCommentList.ts","../src/hooks/comments/useComments.ts","../src/hooks/comments/useCommentThreads.ts","../src/hooks/context/useResource.ts","../src/hooks/dashboard/useFavoriteContext.ts","../src/hooks/dashboard/useFavorite.ts","../src/hooks/dashboard/useRecordDocumentHistoryEvent.ts","../src/hooks/dashboard/useUpdateFavorite.ts","../src/hooks/helpers/useResolvedProjectId.ts","../src/hooks/datasets/useDatasets.ts","../src/hooks/helpers/useApplyActions.ts","../src/hooks/document/useApplyDocumentActions.ts","../src/hooks/document/useCreateDocument.ts","../src/hooks/document/useDocument.ts","../src/hooks/document/useDocumentEvent.ts","../src/hooks/document/useDocumentPermissions.ts","../src/hooks/document/useDocumentSyncStatus.ts","../src/hooks/document/useEditDocument.ts","../src/hooks/query/useQuery.ts","../src/hooks/documents/useDocuments.ts","../src/hooks/installations/useInstallation.ts","../src/hooks/installations/useInstallations.ts","../src/hooks/organizations/useOrganization.ts","../src/hooks/organizations/useOrganizations.ts","../src/hooks/paginatedDocuments/usePaginatedDocuments.ts","../src/hooks/presence/usePresence.ts","../src/hooks/presence/usePresenceForDocument.ts","../src/hooks/presence/useReportPresence.ts","../src/hooks/projection/useDocumentProjection.ts","../src/hooks/preview/useDocumentPreview.tsx","../src/hooks/projects/useProject.ts","../src/hooks/projects/useProjects.ts","../src/hooks/releases/useActiveReleases.ts","../src/hooks/releases/useAllReleases.ts","../src/hooks/releases/useApplyReleaseActions.ts","../src/hooks/releases/usePerspective.ts","../src/hooks/users/useUser.ts","../src/hooks/users/useUsers.ts","../package.json","../src/utils/getEnv.ts","../src/version.ts"],"sourcesContent":["import {type ClientError} from '@sanity/client'\nimport {SDK_CHANNEL_NAME, SDK_NODE_NAME} from '@sanity/message-protocol'\nimport {AuthStateType, getIsInDashboardState, setAuthToken} from '@sanity/sdk'\nimport {isStudioConfig} from '@sanity/sdk/_internal'\nimport {\n type FrameMessage,\n type NewTokenResponseMessage,\n type RequestNewTokenMessage,\n type WindowMessage,\n} from '@sanity/sdk/comlink'\nimport React, {type PropsWithChildren, useCallback, useEffect, useMemo, useRef} from 'react'\n\nimport {useAuthState} from '../hooks/auth/useAuthState'\nimport {useWindowConnection} from '../hooks/comlink/useWindowConnection'\nimport {useSanityInstance} from '../hooks/context/useSanityInstance'\n\n// Define specific message types extending the base types for clarity\ntype SdkParentComlinkMessage = NewTokenResponseMessage | WindowMessage // Messages received by SDK\ntype SdkChildComlinkMessage = RequestNewTokenMessage | FrameMessage // Messages sent by SDK\n\nconst DEFAULT_RESPONSE_TIMEOUT = 10000 // 10 seconds\n\n/**\n * Component that handles token refresh in dashboard mode\n */\nfunction DashboardTokenRefresh({children}: PropsWithChildren) {\n const instance = useSanityInstance()\n const isTokenRefreshInProgress = useRef(false)\n const timeoutRef = useRef<NodeJS.Timeout | null>(null)\n const processed401ErrorRef = useRef<unknown | null>(null)\n const authState = useAuthState()\n\n const clearRefreshTimeout = useCallback(() => {\n if (timeoutRef.current) {\n clearTimeout(timeoutRef.current)\n timeoutRef.current = null\n }\n }, [])\n\n const windowConnection = useWindowConnection<SdkParentComlinkMessage, SdkChildComlinkMessage>({\n name: SDK_NODE_NAME,\n connectTo: SDK_CHANNEL_NAME,\n })\n\n const requestNewToken = useCallback(async () => {\n if (isTokenRefreshInProgress.current) {\n return\n }\n\n isTokenRefreshInProgress.current = true\n clearRefreshTimeout()\n\n timeoutRef.current = setTimeout(() => {\n if (isTokenRefreshInProgress.current) {\n isTokenRefreshInProgress.current = false\n }\n timeoutRef.current = null\n }, DEFAULT_RESPONSE_TIMEOUT)\n\n try {\n const res = await windowConnection.fetch<{token: string | null; error?: string}>(\n 'dashboard/v1/auth/tokens/create',\n )\n clearRefreshTimeout()\n\n if (res.token) {\n setAuthToken(instance, res.token)\n\n // Remove the unauthorized error from the error container\n const errorContainer = document.getElementById('__sanityError')\n if (errorContainer) {\n const hasUnauthorizedError = Array.from(errorContainer.getElementsByTagName('div')).some(\n (div) =>\n div.textContent?.includes(\n 'Uncaught error: Unauthorized - A valid session is required for this endpoint',\n ),\n )\n\n if (hasUnauthorizedError) {\n errorContainer.remove()\n }\n }\n }\n isTokenRefreshInProgress.current = false\n } catch {\n isTokenRefreshInProgress.current = false\n clearRefreshTimeout()\n }\n }, [windowConnection, clearRefreshTimeout, instance])\n\n useEffect(() => {\n return () => {\n clearRefreshTimeout()\n }\n }, [clearRefreshTimeout])\n\n useEffect(() => {\n const has401Error =\n authState.type === AuthStateType.ERROR &&\n authState.error &&\n (authState.error as ClientError)?.statusCode === 401 &&\n !isTokenRefreshInProgress.current &&\n processed401ErrorRef.current !== authState.error\n\n const isLoggedOut =\n authState.type === AuthStateType.LOGGED_OUT && !isTokenRefreshInProgress.current\n\n if (has401Error || isLoggedOut) {\n processed401ErrorRef.current =\n authState.type === AuthStateType.ERROR ? authState.error : undefined\n requestNewToken()\n } else if (\n authState.type !== AuthStateType.ERROR ||\n processed401ErrorRef.current !==\n (authState.type === AuthStateType.ERROR ? authState.error : undefined)\n ) {\n processed401ErrorRef.current = null\n }\n }, [authState, requestNewToken])\n\n return children\n}\n\n/**\n * This provider is used to provide the Comlink token refresh feature.\n * It is used to automatically request a new token on 401 error if enabled.\n * @public\n */\nexport const ComlinkTokenRefreshProvider: React.FC<PropsWithChildren> = ({children}) => {\n const instance = useSanityInstance()\n const isInDashboard = useMemo(() => getIsInDashboardState(instance).getCurrent(), [instance])\n const isStudio = isStudioConfig(instance.config)\n\n if (isInDashboard && !isStudio) {\n return <DashboardTokenRefresh>{children}</DashboardTokenRefresh>\n }\n\n // If we're not in the dashboard, we don't need to do anything\n return children\n}\n","import {getLoginUrlState} from '@sanity/sdk'\nimport {useMemo, useSyncExternalStore} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n * @internal\n */\nexport function useLoginUrl(): string {\n const instance = useSanityInstance()\n const {subscribe, getCurrent} = useMemo(() => getLoginUrlState(instance), [instance])\n\n return useSyncExternalStore(subscribe, getCurrent as () => string)\n}\n","import {observeOrganizationVerificationState, type OrgVerificationResult} from '@sanity/sdk'\nimport {useEffect, useState} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n * Hook that verifies the current projects belongs to the organization ID specified in the dashboard context.\n *\n * @public\n * @param disabled - When true, disables verification and skips project verification API calls\n * @returns Error message if the project doesn't match the organization ID, or null if all match or verification isn't needed\n * @category Projects\n * @example\n * ```tsx\n * function OrgVerifier() {\n * const error = useVerifyOrgProjects()\n *\n * if (error) {\n * return <div className=\"error\">{error}</div>\n * }\n *\n * return <div>Organization projects verified!</div>\n * }\n * ```\n */\nexport function useVerifyOrgProjects(disabled = false, projectIds?: string[]): string | null {\n const instance = useSanityInstance()\n const [error, setError] = useState<string | null>(null)\n\n const isInactive = disabled || !projectIds || projectIds.length === 0\n\n // Reset stale errors when verification turns off so the next activation\n // doesn't briefly leak the previous result.\n const [prevInactive, setPrevInactive] = useState(isInactive)\n if (prevInactive !== isInactive) {\n setPrevInactive(isInactive)\n if (isInactive) setError(null)\n }\n\n useEffect(() => {\n if (isInactive) return\n\n const verificationObservable$ = observeOrganizationVerificationState(instance, projectIds!)\n\n const subscription = verificationObservable$.subscribe((result: OrgVerificationResult) => {\n setError(result.error)\n })\n\n return () => {\n subscription.unsubscribe()\n }\n }, [instance, isInactive, projectIds])\n\n return error\n}\n","/**\n * Session-storage key tracking whether the SDK has already attempted an\n * automatic reload in response to a chunk-load error during this session.\n *\n * @internal\n */\nexport const CHUNK_RELOAD_STORAGE_KEY = '__sanity_sdk_chunk_reload_attempted'\n\n/**\n * Returns true when this session has already triggered an automatic reload.\n * Returns false if session storage is unreadable.\n *\n * @internal\n */\nexport function readChunkReloadFlag(): boolean {\n try {\n if (typeof window === 'undefined' || typeof window.sessionStorage === 'undefined') {\n return false\n }\n return window.sessionStorage.getItem(CHUNK_RELOAD_STORAGE_KEY) !== null\n } catch {\n return false\n }\n}\n\n/**\n * Marks the session as having attempted an automatic reload, so the next\n * chunk-load error renders the manual reload UI instead of looping.\n *\n * @internal\n */\nexport function setChunkReloadFlag(): void {\n try {\n if (typeof window === 'undefined' || typeof window.sessionStorage === 'undefined') return\n window.sessionStorage.setItem(CHUNK_RELOAD_STORAGE_KEY, '1')\n } catch {\n // Storage may be unavailable (private mode quotas, disabled cookies).\n // Falling through means the user sees the manual-reload UI instead of an\n // automatic reload, which is the correct degradation.\n }\n}\n\n/**\n * Clears the chunk-reload flag. Called from SDKProvider once the SDK\n * mounts successfully past the error boundary so a future incident in the\n * same session can trigger another automatic reload.\n *\n * @internal\n */\nexport function clearChunkReloadFlag(): void {\n try {\n if (typeof window === 'undefined' || typeof window.sessionStorage === 'undefined') return\n window.sessionStorage.removeItem(CHUNK_RELOAD_STORAGE_KEY)\n } catch {\n // No-op: see setChunkReloadFlag.\n }\n}\n","const FONT_SANS_SERIF = `-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Helvetica, Arial, system-ui, sans-serif`\nconst FONT_MONOSPACE = `-apple-system-ui-monospace, 'SF Mono', Menlo, Monaco, Consolas, monospace`\n\nconst styles: Record<string, React.CSSProperties> = {\n container: {\n padding: '28px',\n fontFamily: FONT_SANS_SERIF,\n display: 'flex',\n flexDirection: 'column',\n gap: '21px',\n fontSize: '14px',\n },\n heading: {\n margin: 0,\n fontSize: '28px',\n fontWeight: 700,\n },\n paragraph: {\n margin: 0,\n },\n link: {\n appearance: 'none',\n background: 'transparent',\n border: 0,\n padding: 0,\n font: 'inherit',\n textDecoration: 'underline',\n cursor: 'pointer',\n },\n code: {\n fontFamily: FONT_MONOSPACE,\n },\n}\n\nexport default styles\n","import styles from './Error.styles'\n\ntype ErrorProps = {\n heading: string\n description?: string\n code?: string\n cta?: {\n text: string\n href?: string\n onClick?: () => void\n }\n}\n\nexport function Error({heading, description, code, cta}: ErrorProps): React.ReactNode {\n return (\n <div style={styles['container']}>\n <h1 style={styles['heading']}>{heading}</h1>\n\n {description && (\n <p style={styles['paragraph']} dangerouslySetInnerHTML={{__html: description}} />\n )}\n\n {code && <code style={styles['code']}>{code}</code>}\n\n {cta && (cta.href || cta.onClick) && (\n <p style={styles['paragraph']}>\n {cta.href ? (\n <a style={styles['link']} href={cta.href} target=\"_blank\" rel=\"noopener noreferrer\">\n {cta.text}\n </a>\n ) : (\n <button style={styles['link']} onClick={cta.onClick}>\n {cta.text}\n </button>\n )}\n </p>\n )}\n </div>\n )\n}\n","import {useEffect} from 'react'\nimport {type FallbackProps} from 'react-error-boundary'\n\nimport {clearChunkReloadFlag, readChunkReloadFlag, setChunkReloadFlag} from './chunkReloadStorage'\nimport {Error} from './Error'\n\nfunction reload(): void {\n try {\n window.location.reload()\n } catch {\n // No-op: nothing useful we can do if reload itself throws.\n }\n}\n\n/**\n * Default fallback rendered when a dynamic-import or chunk-load error\n * bubbles up to the SDK's top-level error boundary.\n *\n * On the first occurrence in a session we set a flag and trigger\n * window.location.reload(), since chunk-load errors almost always indicate a\n * stale tab that simply needs a fresh index.html. If the flag is already set\n * we render a manual reload UI instead, which prevents an infinite reload\n * loop in the rare case the error is genuinely unrecoverable (network\n * outage, CSP, etc.).\n *\n * @internal\n */\nexport function ChunkLoadError(_props: FallbackProps): React.ReactNode {\n const alreadyAttempted = readChunkReloadFlag()\n\n useEffect(() => {\n if (alreadyAttempted) return\n setChunkReloadFlag()\n reload()\n }, [alreadyAttempted])\n\n if (!alreadyAttempted) {\n // Render nothing during the brief window before the page reloads so the\n // user does not see a flash of error UI.\n return null\n }\n\n return (\n <Error\n heading=\"A new version is available\"\n description=\"The page tried to load an asset that no longer exists. Reload to continue with the latest version.\"\n cta={{\n text: 'Reload page',\n onClick: () => {\n clearChunkReloadFlag()\n reload()\n },\n }}\n />\n )\n}\n","import {useMemo} from 'react'\nimport {type FallbackProps, getErrorMessage} from 'react-error-boundary'\n\nimport {Error} from './Error'\n\ntype CorsErrorComponentProps = FallbackProps & {\n projectId: string | null\n}\n\nexport function CorsErrorComponent({projectId, error}: CorsErrorComponentProps): React.ReactNode {\n const origin = window.location.origin\n const corsUrl = useMemo(() => {\n const url = new URL(`https://sanity.io/manage/project/${projectId}/api`)\n url.searchParams.set('cors', 'add')\n url.searchParams.set('origin', origin)\n url.searchParams.set('credentials', 'include')\n return url.toString()\n }, [origin, projectId])\n return (\n <Error\n heading=\"Before you continue…\"\n {...(projectId\n ? {\n description:\n 'To access your content, you need to <strong>add the following URL as a CORS origin</strong> to your Sanity project.',\n code: origin,\n cta: {\n text: 'Manage CORS configuration',\n href: corsUrl,\n },\n }\n : {\n description: getErrorMessage(error),\n })}\n />\n )\n}\n","export function isInIframe(): boolean {\n return typeof window !== 'undefined' && window.self !== window.top\n}\n\n/**\n * @internal\n *\n * Checks if the current URL is a local URL.\n *\n * @param window - The window object\n * @returns True if the current URL is a local URL, false otherwise\n */\nexport function isLocalUrl(window: Window): boolean {\n const url = typeof window !== 'undefined' ? window.location.href : ''\n\n return (\n url.startsWith('http://localhost') ||\n url.startsWith('https://localhost') ||\n url.startsWith('http://127.0.0.1') ||\n url.startsWith('https://127.0.0.1')\n )\n}\n","/**\n * Error class for authentication-related errors. Wraps errors thrown during the\n * authentication flow.\n *\n * @remarks\n * This class provides a consistent error type for authentication failures while\n * preserving the original error as the cause. If the original error has a\n * message property, it will be used as the error message.\n *\n * @alpha\n */\nexport class AuthError extends Error {\n constructor(error: unknown) {\n if (\n typeof error === 'object' &&\n !!error &&\n 'message' in error &&\n typeof error.message === 'string'\n ) {\n super(error.message)\n } else {\n super()\n }\n\n this.cause = error\n }\n}\n","/**\n * Error class for configuration-related errors. Wraps errors thrown during the\n * configuration flow.\n *\n * @alpha\n */\nexport class ConfigurationError extends Error {\n constructor(error: unknown) {\n if (\n typeof error === 'object' &&\n !!error &&\n 'message' in error &&\n typeof error.message === 'string'\n ) {\n super(error.message)\n } else {\n super()\n }\n\n this.cause = error\n }\n}\n","import {type SanityInstance} from '@sanity/sdk'\nimport {useCallback} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\nexport function createCallbackHook<TParams extends unknown[], TReturn>(\n callback: (instance: SanityInstance, ...params: TParams) => TReturn,\n): () => (...params: TParams) => TReturn {\n function useHook() {\n const instance = useSanityInstance()\n return useCallback((...params: TParams) => callback(instance, ...params), [instance])\n }\n\n return useHook\n}\n","import {handleAuthCallback} from '@sanity/sdk'\n\nimport {createCallbackHook} from '../helpers/createCallbackHook'\n\n/**\n * @internal\n * A React hook that returns a function for handling authentication callbacks.\n *\n * @remarks\n * This hook provides access to the authentication store's callback handler,\n * which processes auth redirects by extracting the session ID and fetching the\n * authentication token. If fetching the long-lived token is successful,\n * `handleAuthCallback` will return a Promise that resolves a new location that\n * removes the short-lived token from the URL. Use this in combination with\n * `history.replaceState` or your own router's `replace` function to update the\n * current location without triggering a reload.\n *\n * @example\n * ```tsx\n * function AuthCallback() {\n * const handleAuthCallback = useHandleAuthCallback()\n * const router = useRouter() // Example router\n *\n * useEffect(() => {\n * async function processCallback() {\n * // Handle the callback and get the cleaned URL\n * const newUrl = await handleAuthCallback(window.location.href)\n *\n * if (newUrl) {\n * // Replace URL without triggering navigation\n * router.replace(newUrl, {shallow: true})\n * }\n * }\n *\n * processCallback().catch(console.error)\n * }, [handleAuthCallback, router])\n *\n * return <div>Completing login...</div>\n * }\n * ```\n *\n * @returns A callback handler function that processes OAuth redirects\n * @public\n */\nexport const useHandleAuthCallback = createCallbackHook(handleAuthCallback)\n","import {useEffect} from 'react'\n\nimport {useHandleAuthCallback} from '../../hooks/auth/useHandleAuthCallback'\n\n/**\n * Component shown during auth callback processing that handles login completion.\n * Automatically processes the auth callback when mounted and updates the URL\n * to remove callback parameters without triggering a page reload.\n *\n * @alpha\n */\nexport function LoginCallback(): React.ReactNode {\n const handleAuthCallback = useHandleAuthCallback()\n\n useEffect(() => {\n const url = new URL(location.href)\n handleAuthCallback(url.toString()).then((replacementLocation) => {\n if (replacementLocation) {\n // history API with `replaceState` is used to prevent a reload but still\n // remove the short-lived token from the URL\n history.replaceState(null, '', replacementLocation)\n }\n })\n }, [handleAuthCallback])\n\n return null\n}\n","import {logout} from '@sanity/sdk'\n\nimport {createCallbackHook} from '../helpers/createCallbackHook'\n\n/**\n * Hook to log out of the current session\n * @internal\n * @returns A function to log out of the current session\n */\nexport const useLogOut = createCallbackHook(logout)\n","import {SDK_CHANNEL_NAME, SDK_NODE_NAME} from '@sanity/message-protocol'\nimport {useEffect} from 'react'\n\nimport {useWindowConnection} from '../../hooks/comlink/useWindowConnection'\n\ninterface DashboardAccessRequestProps {\n projectId: string\n}\n\n/**\n * Sends a `dashboard/v1/auth/access/request` message to the dashboard via\n * comlink so the user can request access to a project they don't belong to.\n *\n * This is intentionally isolated in its own component because\n * `useWindowConnection` suspends until a comlink node is available, which\n * never happens outside the dashboard. Callers must gate rendering on\n * `getIsInDashboardState(...).getCurrent()` and wrap this in a\n * {@link https://react.dev/reference/react/Suspense | Suspense} boundary\n * so the suspension stays local instead of bubbling up to the app shell.\n *\n * @internal\n */\nexport function DashboardAccessRequest({projectId}: DashboardAccessRequestProps): null {\n const {fetch} = useWindowConnection({\n name: SDK_NODE_NAME,\n connectTo: SDK_CHANNEL_NAME,\n })\n\n useEffect(() => {\n fetch('dashboard/v1/auth/access/request', {\n resourceType: 'project',\n resourceId: projectId,\n })\n }, [fetch, projectId])\n\n return null\n}\n","import {ClientError} from '@sanity/client'\nimport {AuthStateType, getIsInDashboardState} from '@sanity/sdk'\nimport {\n getClientErrorApiBody,\n getClientErrorApiDescription,\n isProjectUserNotFoundClientError,\n} from '@sanity/sdk/_internal'\nimport {Suspense, useCallback, useEffect, useMemo, useRef} from 'react'\nimport {type FallbackProps} from 'react-error-boundary'\n\nimport {useAuthState} from '../../hooks/auth/useAuthState'\nimport {useLogOut} from '../../hooks/auth/useLogOut'\nimport {useSanityInstance} from '../../hooks/context/useSanityInstance'\nimport {Error} from '../errors/Error'\nimport {AuthError} from './AuthError'\nimport {ConfigurationError} from './ConfigurationError'\nimport {DashboardAccessRequest} from './DashboardAccessRequest'\n/**\n * @alpha\n */\nexport type LoginErrorProps = FallbackProps\n\n/**\n * Displays authentication error details and provides retry functionality.\n * Only handles {@link AuthError} instances - rethrows other error types.\n *\n * @alpha\n */\nexport function LoginError({error, resetErrorBoundary}: LoginErrorProps): React.ReactNode {\n if (\n !(\n error instanceof AuthError ||\n error instanceof ConfigurationError ||\n error instanceof ClientError\n )\n )\n throw error\n\n const logout = useLogOut()\n const authState = useAuthState()\n const instance = useSanityInstance()\n const {\n config: {projectId},\n } = instance\n\n // Errors surfaced through `AuthBoundary` arrive wrapped in `AuthError`, with\n // the original `ClientError` tucked under `.cause`. Unwrapping it here lets\n // the 401/404 branches below respond to the real status code instead of\n // silently skipping because `error instanceof ClientError` is false.\n const clientError: ClientError | null =\n error instanceof ClientError\n ? error\n : error instanceof AuthError && error.cause instanceof ClientError\n ? error.cause\n : null\n\n const isInDashboard = getIsInDashboardState(instance).getCurrent()\n\n const isProjectUserNotFound =\n !!clientError && clientError.statusCode === 401 && isProjectUserNotFoundClientError(clientError)\n\n // The dashboard access request flow relies on a comlink connection to the\n // parent window. In standalone apps that connection never materializes, so\n // we must skip it entirely to avoid suspending forever on the parent's\n // Suspense boundary. Resolving to the projectId (or null) here lets the JSX\n // render the child with a single non-null guard.\n const dashboardAccessProjectId =\n isProjectUserNotFound && projectId && isInDashboard ? projectId : null\n\n const handleRetry = useCallback(async () => {\n await logout()\n resetErrorBoundary()\n }, [logout, resetErrorBoundary])\n\n // Display state is fully derived from the inputs above, so we don't need\n // to mirror it through useState/useEffect.\n const {authErrorMessage, showRetryCta} = useMemo(() => {\n let message = 'Please try again or contact support if the problem persists.'\n let retry = true\n\n if (clientError) {\n if (clientError.statusCode === 401) {\n if (isProjectUserNotFound) {\n const description = getClientErrorApiDescription(clientError)\n if (description) message = description\n retry = false\n } else if (!isInDashboard) {\n message = 'Signing you out and returning to login...'\n retry = true\n }\n // Dashboard non-projectUserNotFound 401: leave the current UI in place\n // and let ComlinkTokenRefreshProvider request a fresh token from the\n // parent window. The Retry button remains as a manual fallback.\n } else if (clientError.statusCode === 404) {\n const errorMessage = getClientErrorApiBody(clientError)?.message || ''\n message =\n errorMessage.startsWith('Session with sid') && errorMessage.endsWith('not found')\n ? 'The session ID is invalid or expired.'\n : 'The login link is invalid or expired. Please try again.'\n retry = true\n }\n }\n if (authState.type !== AuthStateType.ERROR && error instanceof ConfigurationError) {\n message = error.message\n retry = true\n }\n return {authErrorMessage: message, showRetryCta: retry}\n }, [authState, clientError, error, isInDashboard, isProjectUserNotFound])\n\n // Guards against re-entering the standalone auto-logout branch below. Once\n // `logout()` flips the auth store to LOGGED_OUT, `useAuthState` emits a new\n // `authState` reference and re-runs this effect; without the ref we'd call\n // `handleRetry` again on every emission and React eventually aborts with\n // \"Maximum update depth exceeded\", leaving a blank page.\n const hasAutoLoggedOutRef = useRef(false)\n\n // Standalone apps: the token is bad and there's no parent window to mint a\n // new one, so log the user out and let `AuthBoundary`'s LOGGED_OUT effect\n // redirect to the Sanity login URL.\n useEffect(() => {\n if (\n clientError &&\n clientError.statusCode === 401 &&\n !isProjectUserNotFound &&\n !isInDashboard &&\n !hasAutoLoggedOutRef.current\n ) {\n hasAutoLoggedOutRef.current = true\n handleRetry()\n }\n }, [clientError, handleRetry, isInDashboard, isProjectUserNotFound])\n\n return (\n <>\n {dashboardAccessProjectId && (\n <Suspense fallback={null}>\n <DashboardAccessRequest projectId={dashboardAccessProjectId} />\n </Suspense>\n )}\n <Error\n heading={\n error instanceof ConfigurationError ? 'Configuration Error' : 'Authentication Error'\n }\n description={authErrorMessage}\n cta={\n showRetryCta\n ? {\n text: 'Retry',\n onClick: handleRetry,\n }\n : undefined\n }\n />\n </>\n )\n}\n","import {CorsOriginError} from '@sanity/client'\nimport {AuthStateType, getCorsErrorProjectId, isImportError} from '@sanity/sdk'\nimport {isDashboardEnvironment, isStudioConfig} from '@sanity/sdk/_internal'\nimport {useEffect, useMemo} from 'react'\nimport {ErrorBoundary, type FallbackProps} from 'react-error-boundary'\n\nimport {ComlinkTokenRefreshProvider} from '../../context/ComlinkTokenRefresh'\nimport {DashboardTokenRefreshProvider} from '../../context/DashboardTokenRefresh'\nimport {useAuthState} from '../../hooks/auth/useAuthState'\nimport {useLoginUrl} from '../../hooks/auth/useLoginUrl'\nimport {useVerifyOrgProjects} from '../../hooks/auth/useVerifyOrgProjects'\nimport {useSanityInstance} from '../../hooks/context/useSanityInstance'\nimport {ChunkLoadError} from '../errors/ChunkLoadError'\nimport {CorsErrorComponent} from '../errors/CorsErrorComponent'\nimport {isInIframe} from '../utils'\nimport {AuthError} from './AuthError'\nimport {ConfigurationError} from './ConfigurationError'\nimport {LoginCallback} from './LoginCallback'\nimport {LoginError, type LoginErrorProps} from './LoginError'\n\n// Only import bridge if we're in an iframe. This assumes that the app is\n// running within SanityOS if it is in an iframe and that the bridge hasn't already been loaded\nif (isInIframe() && !document.querySelector('[data-sanity-core]')) {\n const parsedUrl = new URL(window.location.href)\n const mode = new URLSearchParams(parsedUrl.hash.slice(1)).get('mode')\n const script = document.createElement('script')\n script.src =\n mode === 'core-ui--staging'\n ? 'https://core.sanity-cdn.work/bridge.js'\n : 'https://core.sanity-cdn.com/bridge.js'\n script.type = 'module'\n script.async = true\n document.head.appendChild(script)\n}\n\n/**\n * @internal\n */\nexport interface AuthBoundaryProps {\n /**\n * Custom component to render the login screen.\n * Receives all props. Defaults to {@link Login}.\n */\n LoginComponent?: React.ComponentType<{\n header?: React.ReactNode\n footer?: React.ReactNode\n }>\n\n /**\n * Custom component to render during OAuth callback processing.\n * Receives all props. Defaults to {@link LoginCallback}.\n */\n CallbackComponent?: React.ComponentType<{\n header?: React.ReactNode\n footer?: React.ReactNode\n }>\n\n /**\n * Custom component to render when authentication errors occur.\n * Receives error boundary props and layout props. Defaults to\n * {@link LoginError}\n */\n LoginErrorComponent?: React.ComponentType<LoginErrorProps>\n\n /** Header content to display */\n header?: React.ReactNode\n\n /**\n * The project IDs to use for organization verification.\n */\n projectIds?: string[]\n\n /** Footer content to display */\n footer?: React.ReactNode\n\n /** Protected content to render when authenticated */\n children?: React.ReactNode\n\n /**\n * Whether to verify that the project belongs to the organization specified in the dashboard context.\n * By default, organization verification is enabled when running in a dashboard context.\n *\n * WARNING: Disabling organization verification is NOT RECOMMENDED and may cause your application\n * to break in the future. This should never be disabled in production environments.\n */\n verifyOrganization?: boolean\n}\n\n/**\n * A component that handles authentication flow and error boundaries for a\n * protected section of the application.\n *\n * @remarks\n * This component manages different authentication states and renders the\n * appropriate components based on that state.\n *\n * @example\n * ```tsx\n * function App() {\n * return (\n * <AuthBoundary header={<MyLogo />}>\n * <ProtectedContent />\n * </AuthBoundary>\n * )\n * }\n * ```\n *\n * @internal\n */\nexport function AuthBoundary({\n LoginErrorComponent = LoginError,\n ...props\n}: AuthBoundaryProps): React.ReactNode {\n /**\n * When the session is re-established (e.g. ComlinkTokenRefresh silently mints a\n * fresh token via setAuthToken), the auth store returns to LOGGED_IN but the\n * ErrorBoundary stays latched on its fallback until reset. Keying it on the\n * recovered session lets it clear automatically\n */\n const authState = useAuthState()\n const sessionResetKey =\n authState.type === AuthStateType.LOGGED_IN ? authState.token : authState.type\n\n const FallbackComponent = useMemo(() => {\n return function LoginComponentWithLayoutProps(fallbackProps: FallbackProps) {\n // Chunk-load errors from any lazy-loaded code beneath this boundary\n // (typically the consumer's app) get the chunk-aware fallback instead\n // of being misreported as auth errors.\n if (isImportError(fallbackProps.error)) {\n return <ChunkLoadError {...fallbackProps} />\n }\n if (fallbackProps.error instanceof CorsOriginError) {\n return (\n <CorsErrorComponent\n {...fallbackProps}\n projectId={getCorsErrorProjectId(fallbackProps.error)}\n />\n )\n }\n return <LoginErrorComponent {...fallbackProps} />\n }\n }, [LoginErrorComponent])\n\n return (\n <ComlinkTokenRefreshProvider>\n <DashboardTokenRefreshProvider>\n <ErrorBoundary FallbackComponent={FallbackComponent} resetKeys={[sessionResetKey]}>\n <AuthSwitch {...props} />\n </ErrorBoundary>\n </DashboardTokenRefreshProvider>\n </ComlinkTokenRefreshProvider>\n )\n}\n\ninterface AuthSwitchProps {\n LoginComponent?: React.ComponentType<{\n header?: React.ReactNode\n footer?: React.ReactNode\n }>\n CallbackComponent?: React.ComponentType<{\n header?: React.ReactNode\n footer?: React.ReactNode\n }>\n header?: React.ReactNode\n footer?: React.ReactNode\n children?: React.ReactNode\n verifyOrganization?: boolean\n projectIds?: string[]\n}\n\nfunction AuthSwitch({\n CallbackComponent = LoginCallback,\n children,\n verifyOrganization = true,\n projectIds,\n ...props\n}: AuthSwitchProps) {\n const authState = useAuthState()\n const instance = useSanityInstance()\n const isStudio = isStudioConfig(instance.config)\n const disableVerifyOrg =\n !verifyOrganization || isStudio || authState.type !== AuthStateType.LOGGED_IN\n const orgError = useVerifyOrgProjects(disableVerifyOrg, projectIds)\n\n const isLoggedOut = authState.type === AuthStateType.LOGGED_OUT && !authState.isDestroyingSession\n const loginUrl = useLoginUrl()\n\n useEffect(() => {\n if (isLoggedOut && !isInIframe() && !isStudio && !isDashboardEnvironment()) {\n // We don't want to redirect to login if we're in the Dashboard, in studio\n // mode, or in the workbench (the OS owns the session and mints the token)\n window.location.href = loginUrl\n }\n }, [isLoggedOut, loginUrl, isStudio])\n\n // Only check the error if verification is enabled\n if (verifyOrganization && orgError) {\n throw new ConfigurationError({message: orgError})\n }\n\n switch (authState.type) {\n case AuthStateType.ERROR: {\n throw new AuthError(authState.error)\n }\n case AuthStateType.LOGGING_IN: {\n return <CallbackComponent {...props} />\n }\n case AuthStateType.LOGGED_IN: {\n return children\n }\n case AuthStateType.LOGGED_OUT: {\n return null\n }\n default: {\n // @ts-expect-error - This state should never happen\n throw new Error(`Invalid auth state: ${authState.type}`)\n }\n }\n}\n","import {type TokenSource} from '@sanity/sdk'\nimport {createContext} from 'react'\n\n/**\n * Minimal duck-typed interface representing a Sanity Studio workspace.\n * The Studio's `Workspace` type satisfies this naturally — no import\n * dependency on the `sanity` package is required.\n *\n * @public\n */\nexport interface StudioWorkspaceHandle {\n /** The Sanity project ID for this workspace. */\n projectId: string\n /** The dataset name for this workspace. */\n dataset: string\n /**\n * Whether the Studio has determined the user is authenticated.\n * When `true` and the token source emits `null`, the SDK infers\n * cookie-based auth is in use and skips the logged-out state.\n */\n authenticated?: boolean\n /** Authentication state for this workspace. */\n auth: {\n /**\n * Reactive token source from the Studio's auth store.\n * When present, the SDK subscribes for ongoing token sync — the Studio\n * is the single authority for auth and handles token refresh.\n *\n * Optional because Studios before Aug 2022 may not expose it. When\n * absent, the SDK falls back to localStorage/cookie discovery.\n */\n token?: TokenSource\n }\n}\n\n/**\n * React context that allows the SDK to auto-detect when it is running\n * inside a Sanity Studio. The Studio provides a workspace handle via this\n * context, and `SanityApp` reads it to derive `projectId`, `dataset`, and\n * a reactive auth token — eliminating the need for manual configuration.\n *\n * @remarks\n * This context is defined in `@sanity/sdk-react` and provided by the Studio.\n * The Studio imports it from this package and wraps its component tree:\n *\n * ```tsx\n * import {SDKStudioContext} from '@sanity/sdk-react'\n *\n * function StudioRoot({children}) {\n * const workspace = useWorkspace()\n * return (\n * <SDKStudioContext.Provider value={workspace}>\n * {children}\n * </SDKStudioContext.Provider>\n * )\n * }\n * ```\n *\n * When `SanityApp` is rendered inside this provider, it auto-configures\n * without any `config` prop:\n *\n * ```tsx\n * <SanityApp fallback={<Loading />}>\n * <MyComponent />\n * </SanityApp>\n * ```\n *\n * @public\n */\nexport const SDKStudioContext = createContext<StudioWorkspaceHandle | null>(null)\nSDKStudioContext.displayName = 'SDKStudioContext'\n","/**\n * The name of the resource automatically registered from a single-config `<SanityApp>`.\n * Hooks that receive no resource information fall back to this named resource.\n */\nexport const DEFAULT_RESOURCE_NAME = 'default'\n","import {\n type CanvasResource,\n getClientState,\n type MediaLibraryResource,\n type SanityInstance,\n} from '@sanity/sdk'\nimport {firstValueFrom} from 'rxjs'\n\nconst API_VERSION = 'v2026-07-09'\n\ninterface OrgResourcesApiItem {\n id: string\n}\n\ninterface OrgResourcesApiResponse {\n data: OrgResourcesApiItem[]\n}\n\ninterface OrgResources {\n mediaLibrary?: MediaLibraryResource\n canvas?: CanvasResource\n}\n\n/**\n * Gets the id of the first resource from a settled request result. The request\n * is already scoped to a single organization, so the first item is the one we want.\n */\nfunction getFirstResourceId(\n result: PromiseSettledResult<OrgResourcesApiResponse>,\n): string | undefined {\n if (result.status !== 'fulfilled') return undefined\n return result.value.data?.[0]?.id\n}\n\n/**\n * Fetches the media library and canvas resources for the given organization.\n * Both requests are scoped to `organizationId` so each response contains only\n * that org's resources. Each resource is fetched independently — a failure for\n * one does not prevent the other from resolving.\n */\nexport async function resolveOrgResources(\n instance: SanityInstance,\n organizationId: string,\n): Promise<OrgResources> {\n const client = await firstValueFrom(\n getClientState(instance, {apiVersion: API_VERSION, scope: 'global'}).observable,\n )\n\n const [mediaLibrariesResult, canvasesResult] = await Promise.allSettled([\n client.request<OrgResourcesApiResponse>({\n url: `/media-libraries`,\n query: {organizationId},\n tag: 'org-resources.media-libraries',\n }),\n client.request<OrgResourcesApiResponse>({\n url: `/canvases`,\n query: {organizationId},\n tag: 'org-resources.canvases',\n }),\n ])\n\n const mediaLibraryId = getFirstResourceId(mediaLibrariesResult)\n const canvasId = getFirstResourceId(canvasesResult)\n\n return {\n mediaLibrary: mediaLibraryId ? {mediaLibraryId} : undefined,\n canvas: canvasId ? {canvasId} : undefined,\n }\n}\n","import {type DocumentResource} from '@sanity/sdk'\nimport {createContext} from 'react'\n\n/** Context for resources.\n * @beta\n */\nexport const ResourcesContext = createContext<Record<string, DocumentResource>>({})\n","import {type DocumentResource, type SanityInstance} from '@sanity/sdk'\nimport {type ReactElement, type ReactNode, use, useMemo} from 'react'\n\nimport {useSanityInstance} from '../hooks/context/useSanityInstance'\nimport {useOrganizationId} from '../hooks/dashboard/useOrganizationId'\nimport {resolveOrgResources} from '../utils/resolveOrgResources'\nimport {ResourcesContext} from './ResourcesContext'\n\nconst DEFAULT_MEDIA_LIBRARY_RESOURCE_NAME = 'media-library'\nconst DEFAULT_CANVAS_RESOURCE_NAME = 'canvas'\n\ntype OrgResource = typeof DEFAULT_MEDIA_LIBRARY_RESOURCE_NAME | typeof DEFAULT_CANVAS_RESOURCE_NAME\ntype OrgResourcePromises = Map<OrgResource, PromiseLike<DocumentResource | undefined>>\n\n// Module-level cache keyed by SanityInstance so Promise references are stable\n// across Suspense unmount/remount cycles. React's use() tracks promises by\n// identity, so stable references prevent unnecessary re-suspensions.\n// WeakMap entries are GC'd when the instance is disposed.\n// There is only ever one org at a time, so the instance alone is a sufficient\n// key — organizationId only scopes the fetch, it doesn't need to key the cache.\nconst inferredResourceCache = new WeakMap<SanityInstance, OrgResourcePromises>()\n\nfunction getOrgResourcePromises(\n instance: SanityInstance,\n organizationId: string,\n): OrgResourcePromises {\n let promises = inferredResourceCache.get(instance)\n if (!promises) {\n const basePromise = resolveOrgResources(instance, organizationId).then(\n (result) => result,\n (error) => {\n // eslint-disable-next-line no-console\n console.warn('[sanity/sdk] Failed to infer org resources:', error)\n return {mediaLibrary: undefined, canvas: undefined}\n },\n )\n promises = new Map([\n [DEFAULT_MEDIA_LIBRARY_RESOURCE_NAME, basePromise.then((r) => r.mediaLibrary)],\n [DEFAULT_CANVAS_RESOURCE_NAME, basePromise.then((r) => r.canvas)],\n ])\n inferredResourceCache.set(instance, promises)\n }\n\n return promises\n}\n\n/**\n * Inner component that suspends via use() until both inference promises settle.\n * Requires a Suspense boundary from the caller (usually a top ResourceProvider).\n */\nfunction InferredResourcesProvider({\n instance,\n orgId,\n explicitResources,\n children,\n}: {\n instance: SanityInstance\n orgId: string\n explicitResources: Record<string, DocumentResource>\n children: ReactNode\n}): ReactElement {\n const promises = getOrgResourcePromises(instance, orgId)\n const ml = use(promises.get(DEFAULT_MEDIA_LIBRARY_RESOURCE_NAME)!)\n const canvas = use(promises.get(DEFAULT_CANVAS_RESOURCE_NAME)!)\n\n const resources = useMemo(() => {\n const inferred: Record<string, DocumentResource> = {}\n if (ml !== undefined) inferred[DEFAULT_MEDIA_LIBRARY_RESOURCE_NAME] = ml\n if (canvas !== undefined) inferred[DEFAULT_CANVAS_RESOURCE_NAME] = canvas\n return {...inferred, ...explicitResources}\n }, [ml, canvas, explicitResources])\n\n return <ResourcesContext.Provider value={resources}>{children}</ResourcesContext.Provider>\n}\n\n/**\n * When `inferMediaLibraryAndCanvas` is set, this component suspends until\n * inference resolves. The nearest Suspense boundary (e.g. from ResourceProvider)\n * shows its fallback during that window.\n\n * If a user explicitly names a 'media-library' or 'canvas' resource,\n * this component will use that resource instead of inferring it.\n */\nexport function OrganizationResourcesProvider({\n resources: explicitResources = {},\n inferMediaLibraryAndCanvas,\n children,\n}: {\n resources?: Record<string, DocumentResource>\n inferMediaLibraryAndCanvas?: boolean\n children: ReactNode\n}): ReactElement {\n const instance = useSanityInstance()\n const orgId = useOrganizationId()\n\n if (!inferMediaLibraryAndCanvas || !orgId) {\n return (\n <ResourcesContext.Provider value={explicitResources}>{children}</ResourcesContext.Provider>\n )\n }\n\n return (\n <InferredResourcesProvider\n instance={instance}\n orgId={orgId}\n explicitResources={explicitResources}\n >\n {children}\n </InferredResourcesProvider>\n )\n}\n","import {type DocumentResource} from '@sanity/sdk'\nimport {createContext} from 'react'\n\n/**\n * Provides the active DocumentResource for a subtree.\n * Set by ResourceProvider; read by useNormalizedResourceOptions as a fallback\n * when hooks receive no explicit resource or resourceName.\n * @internal\n */\nexport const ResourceContext = createContext<DocumentResource | undefined>(undefined)\n","import {type PerspectiveHandle} from '@sanity/sdk'\nimport {createContext} from 'react'\n\n/**\n * Provides the active perspective for a subtree.\n * Set by ResourceProvider; injected by useNormalizedResourceOptions when\n * the hook's options don't include an explicit perspective.\n * @internal\n */\nexport const PerspectiveContext = createContext<PerspectiveHandle['perspective'] | undefined>(\n undefined,\n)\n","import {createContext} from 'react'\n\n/**\n * Carries a `projectId` for a subtree even when a complete\n * `DatasetResource` can't be formed — e.g. a `<ResourceProvider projectId=\"…\">`\n * with no `dataset` and no parent resource to inherit one from.\n *\n * Project-scoped hooks (`useProject`, `useDatasets`, `useUsers`) read this as a\n * fallback so they can still resolve a project in that case (the only hooks that would work with a config like this.)\n *\n * @remarks Temporary bridge for the dataset-less project scope.\n * Remove in the next major version; those hooks should just always use a projectId or default to a resource available.\n * @internal\n */\nexport const ProjectContext = createContext<string | undefined>(undefined)\n","import {type SanityInstance} from '@sanity/sdk'\nimport {Suspense} from 'react'\n\nimport {SanityInstanceContext} from './SanityInstanceContext'\n\n/**\n * Props for the SanityInstanceProvider component\n * @public\n */\nexport interface SanityInstanceProviderProps {\n /**\n * A pre-created SanityInstance to provide to child components.\n * The caller owns the instance lifecycle — SanityInstanceProvider\n * will not dispose it on unmount.\n */\n instance: SanityInstance\n /**\n * React node to show while content is loading.\n * Used as the fallback for the internal Suspense boundary.\n */\n fallback: React.ReactNode\n children: React.ReactNode\n}\n\n/**\n * Provides an externally-created Sanity instance to child components through React Context.\n *\n * @internal\n *\n * @remarks\n * Unlike {@link ResourceProvider}, this component does not create or dispose a SanityInstance.\n * The caller is responsible for creating the instance via `createSanityInstance` and disposing\n * it when appropriate. This is useful when a non-React system layer (e.g. a state machine)\n * owns the instance and the React tree should consume it without managing its lifecycle.\n *\n * All SDK hooks (`useSanityInstance`, `useDocuments`, etc.) will read from the provided instance.\n *\n * @example Providing a pre-created instance\n * ```tsx\n * import { createSanityInstance, type SanityConfig } from '@sanity/sdk'\n * import { SanityInstanceProvider } from '@sanity/sdk-react'\n *\n * const config: SanityConfig = {\n * projectId: 'my-project-id',\n * dataset: 'production',\n * }\n *\n * const instance = createSanityInstance(config)\n *\n * function App() {\n * return (\n * <SanityInstanceProvider instance={instance} fallback={<div>Loading...</div>}>\n * <MyApp />\n * </SanityInstanceProvider>\n * )\n * }\n * ```\n *\n * @category Components\n */\nexport function SanityInstanceProvider({\n instance,\n fallback,\n children,\n}: SanityInstanceProviderProps): React.ReactNode {\n return (\n <SanityInstanceContext.Provider value={instance}>\n <Suspense fallback={fallback}>{children}</Suspense>\n </SanityInstanceContext.Provider>\n )\n}\n","import {\n createSanityInstance,\n type DatasetResource,\n type DocumentResource,\n isDatasetResource,\n type SanityConfig,\n type SanityInstance,\n} from '@sanity/sdk'\nimport {initTelemetry} from '@sanity/sdk/_internal'\nimport {useContext, useEffect, useMemo, useRef, useState} from 'react'\n\nimport {ResourceContext} from './DefaultResourceContext'\nimport {PerspectiveContext} from './PerspectiveContext'\nimport {ProjectContext} from './ProjectContext'\nimport {SanityInstanceContext} from './SanityInstanceContext'\nimport {SanityInstanceProvider} from './SanityInstanceProvider'\n\nconst DEFAULT_FALLBACK = (\n <>\n Warning: No fallback provided. Please supply a fallback prop to ensure proper Suspense handling.\n </>\n)\n\n/**\n * Props for the ResourceProvider component\n * @internal\n */\nexport interface ResourceProviderProps extends SanityConfig {\n /**\n * The document resource (project/dataset, media library, or canvas)\n * for this subtree. Hooks that don't specify an explicit resource will\n * use this value.\n */\n resource?: DocumentResource\n /**\n * React node to show while content is loading.\n * Used as the fallback for the internal Suspense boundary.\n */\n fallback: React.ReactNode\n children: React.ReactNode\n}\n\n/**\n * Provides Sanity configuration to child components through React Context.\n *\n * @internal\n *\n * @example\n * ```tsx\n * <ResourceProvider\n * resource={{ projectId: 'your-project-id', dataset: 'production' }}\n * fallback={<LoadingSpinner />}\n * >\n * <YourApp />\n * </ResourceProvider>\n * ```\n */\nexport function ResourceProvider({\n children,\n fallback,\n resource,\n ...config\n}: ResourceProviderProps): React.ReactNode {\n const parentPerspective = useContext(PerspectiveContext)\n const parentResource = useContext(ResourceContext)\n const parentInstance = useContext(SanityInstanceContext)\n const parentProjectId = useContext(ProjectContext)\n\n const {projectId, dataset, perspective} = config\n\n const [instance] = useState<SanityInstance>(() => parentInstance ?? createSanityInstance(config))\n\n const configResource: DatasetResource | undefined = useMemo(() => {\n // Historically, we allowed asymmetric merging: If you provided JUST a dataset, we'd merge it with the parent projectId.\n //\n // This backwards-compatible merging should be removed in the next major version.\n if (projectId && dataset) return {projectId, dataset}\n if (dataset && parentProjectId) return {projectId: parentProjectId, dataset}\n return undefined\n }, [projectId, dataset, parentProjectId])\n\n const effectiveResource = useMemo(() => {\n if (resource) return resource\n if (configResource) return configResource\n // A projectId with no dataset historically created its own scope, so no resource is needed.\n if (projectId) return undefined\n return parentResource\n }, [resource, configResource, projectId, parentResource])\n\n // Historically, ResourceProviders allowed a bare `projectId` (no dataset, no resource to complete it) to be provided.\n // This keeps that behavior intact for backwards compatibility, even though we prefer resources everywhere.\n //\n // This should be removed in the next major version.\n const effectiveProjectId = useMemo(() => {\n if (effectiveResource && isDatasetResource(effectiveResource)) {\n return effectiveResource.projectId\n }\n return projectId ?? parentProjectId\n }, [effectiveResource, projectId, parentProjectId])\n\n useEffect(() => {\n if (effectiveResource && isDatasetResource(effectiveResource))\n initTelemetry(instance, effectiveResource.projectId)\n }, [instance, effectiveResource])\n\n // Ref to hold the scheduled disposal timer.\n const disposal = useRef<{\n instance: SanityInstance\n timeoutId: ReturnType<typeof setTimeout>\n } | null>(null)\n\n useEffect(() => {\n // If the component remounts quickly (as in Strict Mode), cancel any pending disposal.\n if (disposal.current !== null && instance === disposal.current.instance) {\n clearTimeout(disposal.current.timeoutId)\n disposal.current = null\n }\n\n return () => {\n disposal.current = {\n instance,\n timeoutId: setTimeout(() => {\n // don't dispose the parent instance when this unmounts\n if (!instance.isDisposed() && instance !== parentInstance) {\n instance.dispose()\n }\n }, 0),\n }\n }\n }, [instance, parentInstance])\n\n return (\n <SanityInstanceProvider\n instance={instance}\n fallback={fallback === undefined ? DEFAULT_FALLBACK : fallback}\n >\n <ResourceContext.Provider value={effectiveResource}>\n <ProjectContext.Provider value={effectiveProjectId}>\n <PerspectiveContext.Provider value={perspective ?? parentPerspective}>\n {children}\n </PerspectiveContext.Provider>\n </ProjectContext.Provider>\n </ResourceContext.Provider>\n </SanityInstanceProvider>\n )\n}\n","import {\n type DocumentResource,\n isDatasetResource,\n isImportError,\n type SanityConfig,\n} from '@sanity/sdk'\nimport {type ReactElement, type ReactNode, useEffect, useMemo} from 'react'\nimport {ErrorBoundary, type FallbackProps} from 'react-error-boundary'\n\nimport {DEFAULT_RESOURCE_NAME} from '../constants'\nimport {OrganizationResourcesProvider} from '../context/OrganizationResourcesProvider'\nimport {ResourceProvider} from '../context/ResourceProvider'\nimport {AuthBoundary, type AuthBoundaryProps} from './auth/AuthBoundary'\nimport {ChunkLoadError} from './errors/ChunkLoadError'\nimport {clearChunkReloadFlag} from './errors/chunkReloadStorage'\n\n/**\n * @internal\n */\nexport interface SDKProviderProps extends AuthBoundaryProps {\n children: ReactNode\n config: SanityConfig | SanityConfig[]\n fallback: ReactNode\n resources?: Record<string, DocumentResource>\n /** When set, automatically fetches and registers the organization's media library and canvas as named resources. */\n inferMediaLibraryAndCanvas?: boolean\n}\n\n/**\n * Clears the chunk-reload flag once children render successfully past the\n * top-level boundary, so a future incident in the same session can trigger\n * another automatic reload.\n */\nfunction ResetChunkReloadFlagOnMount(): null {\n useEffect(() => {\n clearChunkReloadFlag()\n }, [])\n return null\n}\n\n/**\n * @internal\n *\n * Top-level context provider that provides access to the Sanity SDK.\n */\nexport function SDKProvider({\n children,\n config,\n fallback,\n inferMediaLibraryAndCanvas,\n ...props\n}: SDKProviderProps): ReactElement {\n // For legacy config support, extract the first config object as a default resource,\n // matching the legacy behavior nesting ResourceProviders with the first config closest to users' application code.\n // This should be removed when we remove legacy config support.\n const defaultConfig = Array.isArray(config) ? config[0] : config\n const defaultProjectId = defaultConfig?.projectId\n const defaultDataset = defaultConfig?.dataset\n\n const resourcesValue = useMemo(() => {\n const explicit = props.resources ?? {}\n if (defaultProjectId && defaultDataset && !Object.hasOwn(explicit, DEFAULT_RESOURCE_NAME)) {\n return {\n [DEFAULT_RESOURCE_NAME]: {\n projectId: defaultProjectId,\n dataset: defaultDataset,\n },\n ...explicit,\n }\n }\n return explicit\n }, [defaultProjectId, defaultDataset, props.resources])\n\n // Collect all projectIds from both resources and config, deduped so\n // AuthBoundary doesn't verify the same project more than once.\n const projectIds = useMemo(\n () =>\n Array.from(\n new Set(\n [\n ...Object.values(resourcesValue)\n .filter(isDatasetResource)\n .map((resource) => resource.projectId),\n ...(Array.isArray(config) ? config : [config]).map((configObj) => configObj.projectId),\n ].filter((id): id is string => !!id),\n ),\n ),\n [resourcesValue, config],\n )\n\n return (\n <ErrorBoundary FallbackComponent={ChunkAwareFallback}>\n <ResetChunkReloadFlagOnMount />\n {/* Spread the first config so SanityInstance can use the auth,\n perspective, and other config fields; `resource` lets an explicitly\n provided `default` resource override the config-derived resource. */}\n <ResourceProvider\n {...defaultConfig}\n resource={resourcesValue[DEFAULT_RESOURCE_NAME]}\n fallback={fallback}\n >\n <AuthBoundary {...props} projectIds={projectIds}>\n {/* OrganizationResourcesProvider wraps ResourcesContext.\n It merges explicit resources with lazily inferred org resources (media\n library, canvas) and provides the combined map to the subtree. */}\n <OrganizationResourcesProvider\n resources={resourcesValue}\n inferMediaLibraryAndCanvas={inferMediaLibraryAndCanvas}\n >\n {children}\n </OrganizationResourcesProvider>\n </AuthBoundary>\n </ResourceProvider>\n </ErrorBoundary>\n )\n}\n\nfunction ChunkAwareFallback(fallbackProps: FallbackProps): ReactElement {\n if (isImportError(fallbackProps.error)) {\n return <ChunkLoadError {...fallbackProps} />\n }\n // Re-throw so downstream boundaries (e.g. AuthBoundary) handle other errors.\n throw fallbackProps.error\n}\n","import {type DocumentResource, type SanityConfig} from '@sanity/sdk'\nimport {isStudioConfig} from '@sanity/sdk/_internal'\nimport {type ReactElement, useContext, useEffect, useMemo} from 'react'\n\nimport {SDKStudioContext, type StudioWorkspaceHandle} from '../context/SDKStudioContext'\nimport {SDKProvider} from './SDKProvider'\nimport {isInIframe, isLocalUrl} from './utils'\n\n/**\n * @public\n * @category Types\n */\nexport interface SanityAppProps {\n /**\n * One or more SanityConfig objects providing a project ID and dataset name.\n * Optional when `SanityApp` is rendered inside an `SDKStudioContext` provider\n * (e.g. inside Sanity Studio) — the config is derived from the workspace\n * automatically.\n */\n config?: SanityConfig | SanityConfig[]\n resources?: Record<string, DocumentResource>\n children: React.ReactNode\n /* Fallback content to show when child components are suspending. Same as the `fallback` prop for React Suspense. */\n fallback: React.ReactNode\n /**\n * Set this to automatically fetch and register the organization's media library and canvas as named resources.\n * These resources will be available to hooks as `media-library` and `canvas`.\n *\n * The SDK App must be running in the organization's Dashboard to use this feature.\n *\n * @example\n * ```tsx\n *\n * const MyApp = () => {\n * // should \"just work\" because of inferMediaLibraryAndCanvas.\n * const {data: assets} = useDocuments({\n * documentType: 'sanity.asset',\n * resourceName: 'media-library',\n * })\n * return (\n * <div>\n * {assets.map((asset) => (\n * <div key={asset._id}>{asset.originalFilename}</div>\n * ))}\n * </div>\n * )\n * }\n * <SanityApp inferMediaLibraryAndCanvas>\n * <MyApp />\n * </SanityApp>\n * ```\n */\n inferMediaLibraryAndCanvas?: boolean\n}\n\nconst REDIRECT_URL = 'https://sanity.io/welcome'\n\n/**\n * Derive a SanityConfig from a Studio workspace handle.\n * Maps the workspace's projectId, dataset, and reactive auth token into\n * the SDK's config shape.\n */\nfunction deriveConfigFromWorkspace(workspace: StudioWorkspaceHandle): SanityConfig {\n return {\n projectId: workspace.projectId,\n dataset: workspace.dataset,\n studio: {\n authenticated: workspace.authenticated,\n auth: workspace.auth.token ? {token: workspace.auth.token} : undefined,\n },\n }\n}\n\n/**\n * @public\n *\n * The SanityApp component provides your Sanity application with access to your Sanity configuration,\n * as well as application context and state which is used by the Sanity React hooks. Your application\n * must be wrapped with the SanityApp component to function properly.\n *\n * The `config` prop on the SanityApp component accepts either a single {@link SanityConfig} object, or an array of them.\n * This allows your app to work with one or more of your organization's datasets.\n *\n * When rendered inside a Sanity Studio that provides `SDKStudioContext`, the `config` prop is\n * optional — `SanityApp` will automatically derive `projectId`, `dataset`, and auth from the\n * Studio workspace.\n *\n * @remarks\n * When passing multiple SanityConfig objects to the `config` prop, the first configuration in the array becomes the default\n * configuration used by the App SDK Hooks.\n *\n * When both `config` and `SDKStudioContext` are available, the explicit `config` takes precedence.\n *\n * @category Components\n * @param props - Your Sanity configuration and the React children to render\n * @returns Your Sanity application, integrated with your Sanity configuration and application context\n *\n * @example\n * ```tsx\n * import { SanityApp, type SanityConfig } from '@sanity/sdk-react'\n *\n * import MyAppRoot from './Root'\n *\n * // Single project configuration\n * const mySanityConfig: SanityConfig = {\n * projectId: 'my-project-id',\n * dataset: 'production',\n * }\n *\n * // Or multiple project configurations\n * const multipleConfigs: SanityConfig[] = [\n * // Configuration for your main project. This will be used as the default project for hooks.\n * {\n * projectId: 'marketing-website-project',\n * dataset: 'production',\n * },\n * // Configuration for a separate blog project\n * {\n * projectId: 'blog-project',\n * dataset: 'production',\n * },\n * // Configuration for a separate ecommerce project\n * {\n * projectId: 'ecommerce-project',\n * dataset: 'production',\n * }\n * ]\n *\n * export default function MyApp() {\n * return (\n * <SanityApp config={mySanityConfig} fallback={<div>Loading…</div>}>\n * <MyAppRoot />\n * </SanityApp>\n * )\n * }\n * ```\n */\nexport function SanityApp({\n children,\n fallback,\n config: configProp,\n ...props\n}: SanityAppProps): ReactElement {\n const studioWorkspace = useContext(SDKStudioContext)\n\n // Derive config: explicit config takes precedence, then Studio context\n const resolvedConfig = useMemo(() => {\n if (configProp) return configProp\n if (studioWorkspace) return deriveConfigFromWorkspace(studioWorkspace)\n return []\n }, [configProp, studioWorkspace])\n\n useEffect(() => {\n let timeout: NodeJS.Timeout | undefined\n const primaryConfig = Array.isArray(resolvedConfig) ? resolvedConfig[0] : resolvedConfig\n const shouldRedirectWithoutConfig =\n configProp === undefined && !studioWorkspace && !primaryConfig\n\n if (\n !isInIframe() &&\n !isLocalUrl(window) &&\n (shouldRedirectWithoutConfig || (!!primaryConfig && !isStudioConfig(primaryConfig)))\n ) {\n // If the app is not running in an iframe and is not a local url, redirect to core.\n timeout = setTimeout(() => {\n // eslint-disable-next-line no-console\n console.warn('Redirecting to core', REDIRECT_URL)\n window.location.replace(REDIRECT_URL)\n }, 1000)\n }\n return () => clearTimeout(timeout)\n }, [configProp, resolvedConfig, studioWorkspace])\n\n return (\n <SDKProvider {...props} fallback={fallback} config={resolvedConfig}>\n {children}\n </SDKProvider>\n )\n}\n","import {type SanityConfig} from '@sanity/sdk'\nimport {StrictMode} from 'react'\nimport {createRoot} from 'react-dom/client'\n\nimport {SanityApp} from '../components/SanityApp'\n\ninterface RenderSanitySDKAppOptions {\n reactStrictMode?: boolean\n}\n\n/** In-flight CLI PR is using named sources since it's aspirational.\n * We can transform the shape in this function until it's finalized.\n */\ninterface NamedSources {\n [key: string]: SanityConfig\n}\n/** @internal */\nexport function renderSanityApp(\n rootElement: HTMLElement | null,\n namedSources: NamedSources,\n options: RenderSanitySDKAppOptions,\n children: React.ReactNode,\n): () => void {\n if (!rootElement) {\n throw new Error('Missing root element to mount application into')\n }\n const {reactStrictMode = false} = options\n\n const root = createRoot(rootElement)\n const config = Object.values(namedSources)\n\n root.render(\n reactStrictMode ? (\n <StrictMode>\n {/* TODO: think about a loading component we want to be \"universal\" */}\n <SanityApp config={config} fallback={<div>Loading...</div>}>\n {children}\n </SanityApp>\n </StrictMode>\n ) : (\n <SanityApp config={config} fallback={<div>Loading...</div>}>\n {children}\n </SanityApp>\n ),\n )\n\n return () => root.unmount()\n}\n","import {type Fetcher, type FetcherSnapshot, isDeepEqual} from '@sanity/sdk/_internal'\nimport {useRef, useSyncExternalStore} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n * The value returned by a fetcher-backed hook. The hook suspends until the\n * first fetch succeeds, so `data` is always present once your component renders.\n *\n * @public\n */\nexport interface FetcherHookResult<TData> {\n /** The resolved data. Guaranteed present — the hook suspends until the first fetch succeeds. */\n data: TData\n /** A fetch for this entry is in flight (background revalidation or a `refetch()`). */\n isFetching: boolean\n /** The most recent background-fetch failure while data still renders; cleared by the next success. */\n error: unknown\n /** Imperatively refetch, bypassing staleness. Resolves with the refreshed data. */\n refetch: () => Promise<TData>\n}\n\n/**\n * Builds a Suspense hook over a {@link Fetcher}: it suspends until the first\n * success via the snapshot's `status`, throws the error arm to the nearest error\n * boundary, and returns the live `{data, isFetching, error, refetch}` envelope.\n *\n * @internal\n */\nexport function createFetcherHook<TParams extends unknown[], TData>(\n fetcher: Fetcher<TParams, TData>,\n): (...params: TParams) => FetcherHookResult<TData> {\n return function useFetcherHook(...params: TParams): FetcherHookResult<TData> {\n const instance = useSanityInstance()\n const source = fetcher.getState(instance, ...params)\n\n // No entry/data yet — suspend on the first fetch (matches an 'error' below never reaching here).\n if (source.getCurrent().status === 'pending') {\n throw fetcher.resolveState(instance, ...params)\n }\n\n // The store replaces its cache entry on every (un)subscribe (it bumps a\n // subscription counter), so `getCurrent()` hands back a fresh snapshot object\n // with identical fields on each commit. Passed raw to `useSyncExternalStore`\n // — which compares by `Object.is` — that reads as a perpetual change and\n // re-renders forever. Reuse the previous snapshot while its fields are\n // unchanged so React sees a stable reference.\n const previous = useRef<FetcherSnapshot<TData> | null>(null)\n const snapshot = useSyncExternalStore(source.subscribe, () => {\n const next = source.getCurrent()\n const prev = previous.current\n if (prev && isDeepEqual(prev, next)) return prev\n previous.current = next\n return next\n })\n\n if (snapshot.status !== 'success') {\n // 'pending' already suspended above; 'error' surfaces to the error boundary.\n throw snapshot.status === 'error' ? snapshot.error : fetcher.resolveState(instance, ...params)\n }\n\n return {\n data: snapshot.data,\n isFetching: snapshot.isFetching,\n error: snapshot.error,\n refetch: () => fetcher.refetch(instance, ...params),\n }\n }\n}\n","import {type AccessResourceType, checkPermissions} from '@sanity/sdk'\n\nimport {createFetcherHook, type FetcherHookResult} from '../helpers/createFetcherHook'\n\n/**\n * Checks whether the current user holds the given permissions on a resource.\n *\n * The hook suspends until the first fetch succeeds, so `data` is always present.\n * `data` maps each requested permission to whether the user has it — keyed by\n * exactly the permission strings you passed.\n *\n * @public\n * @param resourceType - The type of resource (e.g. `'project'`, `'organization'`).\n * @param resourceId - The resource id.\n * @param permissions - The permission names to check.\n * @returns The result envelope `{data, isFetching, error, refetch}`.\n */\nexport const useCheckPermissions = createFetcherHook(checkPermissions) as <\n Permission extends string,\n>(\n resourceType: AccessResourceType,\n resourceId: string,\n permissions: Permission[],\n) => FetcherHookResult<Record<Permission, boolean>>\n","import {type DocumentResource, type PerspectiveHandle} from '@sanity/sdk'\nimport {useContext, useMemo} from 'react'\n\nimport {ResourceContext} from '../../context/DefaultResourceContext'\nimport {PerspectiveContext} from '../../context/PerspectiveContext'\nimport {ResourcesContext} from '../../context/ResourcesContext'\nimport {SanityInstanceContext} from '../../context/SanityInstanceContext'\n\ntype NormalizedResourceFields = 'resourceName' | 'projectId' | 'dataset'\n\n/**\n * Adds React hook support (resourceName resolution) to core types.\n * Prefer using the React-layer handle types (ResourceHandle, DocumentHandle)\n * from `@sanity/sdk-react` — this wrapper is kept for cases where overloads\n * don't fit (e.g. non-handle options objects).\n *\n * @typeParam T - The core type to extend (must have optional `resource` field)\n * @beta\n */\nexport type WithResourceNameSupport<T extends {resource?: DocumentResource}> = T & {\n /**\n * Optional name of a resource to resolve from context.\n * If provided, will be resolved to a `DocumentResource` via `ResourcesContext`.\n * @beta\n */\n resourceName?: string\n}\n\n/**\n * Pure function that normalizes options by resolving `resourceName` to a `DocumentResource`\n * using the provided resources map. Use this when options are only available at call time\n * (e.g. inside a callback) and you cannot call the {@link useNormalizedResourceOptions} hook.\n *\n * @typeParam T - The options type (must include optional resource field)\n * @param options - Options that may include `resourceName` and/or `resource`\n * @param resources - Map of resource names to DocumentResource (e.g. from ResourcesContext)\n * @param contextResource - Resource from context (from ResourceContext)\n * @param contextPerspective - Perspective from context (from PerspectiveContext)\n * @returns Normalized options with `resourceName` removed and `resource` resolved\n * @internal\n */\nexport function normalizeResourceOptions<\n T extends {\n resource?: DocumentResource\n resourceName?: string\n projectId?: string\n dataset?: string\n perspective?: unknown\n },\n>(\n options: T,\n resources: Record<string, DocumentResource>,\n contextResource?: DocumentResource,\n contextPerspective?: PerspectiveHandle['perspective'],\n): Omit<T, NormalizedResourceFields> {\n const {resourceName, projectId, dataset, ...rest} = options\n const resource = options.resource\n\n if (resourceName && resource) {\n throw new Error(\n `Resource name ${JSON.stringify(resourceName)} and resource ${JSON.stringify(resource)} cannot be used together.`,\n )\n }\n\n let resolvedResource: DocumentResource | undefined\n\n // Tier (a): explicit resource object or resourceName lookup\n if (resource) {\n resolvedResource = resource\n } else if (resourceName) {\n if (!Object.hasOwn(resources, resourceName)) {\n throw new Error(\n `There's no resource named ${JSON.stringify(resourceName)} in context. Please use <ResourceProvider>.`,\n )\n }\n resolvedResource = resources[resourceName]\n }\n\n // Tier (b): projectId or dataset in options → synthesize a resource\n if (!resolvedResource && projectId && dataset) {\n resolvedResource = {\n projectId,\n dataset,\n }\n }\n\n // Tier (c): fall back to whatever ResourceContext provides\n if (!resolvedResource) {\n resolvedResource = contextResource\n }\n\n // Inject perspective from context when not explicitly provided in options\n const resolvedPerspective = Object.hasOwn(options, 'perspective')\n ? options.perspective\n : contextPerspective\n\n return {\n ...rest,\n ...(resolvedResource !== undefined && {resource: resolvedResource}),\n ...(resolvedPerspective !== undefined && {perspective: resolvedPerspective}),\n }\n}\n\n/**\n * Returns the effective context resource: the `ResourceContext` value if set,\n * otherwise a resource synthesized from the current `SanityInstance` config\n * (tier-d fallback — returns `undefined` for studio-style configs with no project).\n *\n * @internal\n */\nexport function useEffectiveContextResource(): DocumentResource | undefined {\n const contextResource = useContext(ResourceContext)\n const instance = useContext(SanityInstanceContext)\n const {projectId, dataset, resource: configResource} = instance?.config ?? {}\n\n return useMemo(() => {\n if (contextResource) return contextResource\n if (configResource) return configResource\n if (projectId && dataset) return {projectId, dataset}\n return undefined\n }, [contextResource, configResource, projectId, dataset])\n}\n\n/**\n * Normalizes hook options by resolving `resourceName` to a `DocumentResource`.\n *\n * Resolution priority for resource:\n * 1. Explicit `resource` or `resourceName` in options\n * 2. Bare `projectId`/`dataset` pair in options → synthesized into a resource\n * 3. `ResourceContext` value (set by `ResourceProvider` / `SDKProvider`)\n * 4. Current `SanityInstance` config — falls back to `undefined` for studio configs\n *\n * Resolution priority for perspective:\n * 1. Explicit `perspective` in options\n * 2. `PerspectiveContext` value (set by `ResourceProvider`)\n *\n * @internal\n */\nexport function useNormalizedResourceOptions<\n T extends {\n resource?: DocumentResource\n resourceName?: string\n projectId?: string\n dataset?: string\n perspective?: PerspectiveHandle['perspective']\n },\n>(\n options: T,\n): Omit<T, NormalizedResourceFields> & {\n resource?: DocumentResource\n perspective?: PerspectiveHandle['perspective']\n} {\n const resources = useContext(ResourcesContext)\n const effectiveContextResource = useEffectiveContextResource()\n const contextPerspective = useContext(PerspectiveContext)\n\n return normalizeResourceOptions(options, resources, effectiveContextResource, contextPerspective)\n}\n","import {\n agentGenerate,\n type AgentGenerateOptions,\n agentPatch,\n type AgentPatchOptions,\n type AgentPatchResult,\n agentPrompt,\n type AgentPromptOptions,\n type AgentPromptResult,\n agentTransform,\n type AgentTransformOptions,\n agentTranslate,\n type AgentTranslateOptions,\n} from '@sanity/sdk/agent'\nimport {useCallback} from 'react'\nimport {firstValueFrom} from 'rxjs'\n\nimport {type ResourceHandle} from '../../config/handles'\nimport {useSanityInstance} from '../context/useSanityInstance'\nimport {useNormalizedResourceOptions} from '../helpers/useNormalizedResourceOptions'\n\ninterface Subscription {\n unsubscribe(): void\n}\n\ninterface Observer<T> {\n next?: (value: T) => void\n error?: (err: unknown) => void\n complete?: () => void\n}\n\ninterface Subscribable<T> {\n subscribe(observer: Observer<T>): Subscription\n subscribe(\n next: (value: T) => void,\n error?: (err: unknown) => void,\n complete?: () => void,\n ): Subscription\n}\n\n/**\n * @alpha\n * Generates content for a document (or specific fields) via Sanity Agent Actions.\n *\n * @remarks\n * This hook provides a stable callback to trigger AI-powered content generation for documents.\n *\n * Features:\n * - Uses instruction templates with `$variables` and supports `instructionParams` (constants, fields, documents, GROQ queries).\n * - Can target specific paths/fields; supports image generation when targeting image fields.\n * - Supports optional `temperature`, `async`, `noWrite`, and `conditionalPaths`.\n * - Returns a Subscribable stream for tracking generation progress.\n *\n * @returns A stable callback that triggers the action and yields a Subscribable stream.\n *\n * @example Basic content generation\n * ```tsx\n * import {useAgentGenerate} from '@sanity/sdk-react'\n *\n * function GenerateDescription({documentId}: {documentId: string}) {\n * const generate = useAgentGenerate()\n *\n * const handleGenerate = () => {\n * generate({\n * documentId,\n * instruction: 'Write a compelling product description based on the title: $title',\n * instructionParams: {\n * title: {type: 'field', path: 'title'},\n * },\n * targetPaths: ['description'],\n * }).subscribe({\n * next: (result) => console.log('Generation progress:', result),\n * complete: () => console.log('Generation complete'),\n * error: (err) => console.error('Generation failed:', err),\n * })\n * }\n *\n * return <button onClick={handleGenerate}>Generate Description</button>\n * }\n * ```\n *\n * @example Image generation\n * ```tsx\n * import {useAgentGenerate} from '@sanity/sdk-react'\n *\n * function GenerateProductImage({documentId}: {documentId: string}) {\n * const generate = useAgentGenerate()\n *\n * const handleGenerateImage = () => {\n * generate({\n * documentId,\n * instruction: 'Generate a product photo for: $productName',\n * instructionParams: {\n * productName: {type: 'field', path: 'name'},\n * },\n * targetPaths: ['mainImage'],\n * }).subscribe({\n * complete: () => console.log('Image generated'),\n * })\n * }\n *\n * return <button onClick={handleGenerateImage}>Generate Image</button>\n * }\n * ```\n *\n * @category Agent Actions\n */\nexport function useAgentGenerate(\n resourceHandle?: ResourceHandle,\n): (options: AgentGenerateOptions) => Subscribable<unknown> {\n const instance = useSanityInstance()\n const {resource} = useNormalizedResourceOptions(resourceHandle ?? {})\n return useCallback(\n (options: AgentGenerateOptions) =>\n agentGenerate(instance, options, resource) as unknown as Subscribable<unknown>,\n [instance, resource],\n )\n}\n\n/**\n * @alpha\n * Transforms an existing document or selected fields using Sanity Agent Actions.\n *\n * @remarks\n * This hook provides a stable callback to apply AI-powered transformations to document content.\n *\n * Features:\n * - Accepts `instruction` and `instructionParams` (constants, fields, documents, GROQ queries).\n * - Can write to the same or a different `targetDocument` (create/edit), and target specific paths.\n * - Supports per-path image transform instructions and image description operations.\n * - Optional `temperature`, `async`, `noWrite`, `conditionalPaths`.\n *\n * @returns A stable callback that triggers the action and yields a Subscribable stream.\n *\n * @example Transform text content\n * ```tsx\n * import {useAgentTransform} from '@sanity/sdk-react'\n *\n * function SummarizeArticle({documentId}: {documentId: string}) {\n * const transform = useAgentTransform()\n *\n * const handleSummarize = () => {\n * transform({\n * documentId,\n * instruction: 'Summarize the following content into 2-3 sentences: $body',\n * instructionParams: {\n * body: {type: 'field', path: 'body'},\n * },\n * targetPaths: ['summary'],\n * }).subscribe({\n * complete: () => console.log('Summary generated'),\n * error: (err) => console.error('Transform failed:', err),\n * })\n * }\n *\n * return <button onClick={handleSummarize}>Generate Summary</button>\n * }\n * ```\n *\n * @example Transform and write to a different document\n * ```tsx\n * import {useAgentTransform} from '@sanity/sdk-react'\n *\n * function CreateVariant({sourceDocumentId}: {sourceDocumentId: string}) {\n * const transform = useAgentTransform()\n *\n * const handleCreateVariant = () => {\n * transform({\n * documentId: sourceDocumentId,\n * instruction: 'Rewrite this product description for a younger audience: $description',\n * instructionParams: {\n * description: {type: 'field', path: 'description'},\n * },\n * targetDocument: {\n * operation: 'create',\n * _type: 'product',\n * },\n * targetPaths: ['description'],\n * }).subscribe({\n * next: (result) => console.log('New document:', result),\n * complete: () => console.log('Variant created'),\n * })\n * }\n *\n * return <button onClick={handleCreateVariant}>Create Youth Variant</button>\n * }\n * ```\n *\n * @category Agent Actions\n */\nexport function useAgentTransform(\n resourceHandle?: ResourceHandle,\n): (options: AgentTransformOptions) => Subscribable<unknown> {\n const instance = useSanityInstance()\n const {resource} = useNormalizedResourceOptions(resourceHandle ?? {})\n return useCallback(\n (options: AgentTransformOptions) =>\n agentTransform(instance, options, resource) as unknown as Subscribable<unknown>,\n [instance, resource],\n )\n}\n\n/**\n * @alpha\n * Translates documents or fields using Sanity Agent Actions.\n *\n * @remarks\n * This hook provides a stable callback to translate document content between languages using AI.\n *\n * Features:\n * - Configure `fromLanguage`/`toLanguage`, optional `styleGuide`, and `protectedPhrases`.\n * - Can write into a different `targetDocument`, and/or store language in a field.\n * - Optional `temperature`, `async`, `noWrite`, `conditionalPaths`.\n *\n * @returns A stable callback that triggers the action and yields a Subscribable stream.\n *\n * @example Basic translation\n * ```tsx\n * import {useAgentTranslate} from '@sanity/sdk-react'\n *\n * function TranslateArticle({documentId}: {documentId: string}) {\n * const translate = useAgentTranslate()\n *\n * const handleTranslate = () => {\n * translate({\n * documentId,\n * fromLanguage: 'en',\n * toLanguage: 'es',\n * targetPaths: ['title', 'body'],\n * }).subscribe({\n * complete: () => console.log('Translation complete'),\n * error: (err) => console.error('Translation failed:', err),\n * })\n * }\n *\n * return <button onClick={handleTranslate}>Translate to Spanish</button>\n * }\n * ```\n *\n * @example Translation with style guide and protected phrases\n * ```tsx\n * import {useAgentTranslate} from '@sanity/sdk-react'\n *\n * function TranslateWithBrandTerms({documentId}: {documentId: string}) {\n * const translate = useAgentTranslate()\n *\n * const handleTranslate = () => {\n * translate({\n * documentId,\n * fromLanguage: 'en',\n * toLanguage: 'fr',\n * styleGuide: 'Use formal French appropriate for business communication.',\n * protectedPhrases: ['Acme Corp', 'PowerWidget Pro'],\n * targetPaths: ['title', 'description'],\n * }).subscribe({\n * complete: () => console.log('Translation complete'),\n * })\n * }\n *\n * return <button onClick={handleTranslate}>Translate to French</button>\n * }\n * ```\n *\n * @example Translate to a new document\n * ```tsx\n * import {useAgentTranslate} from '@sanity/sdk-react'\n *\n * function CreateTranslatedCopy({documentId}: {documentId: string}) {\n * const translate = useAgentTranslate()\n *\n * const handleCreateTranslation = () => {\n * translate({\n * documentId,\n * fromLanguage: 'en',\n * toLanguage: 'de',\n * targetDocument: {\n * operation: 'create',\n * _type: 'article',\n * },\n * languageFieldPath: 'language',\n * }).subscribe({\n * next: (result) => console.log('New translated document:', result),\n * complete: () => console.log('Translated copy created'),\n * })\n * }\n *\n * return <button onClick={handleCreateTranslation}>Create German Copy</button>\n * }\n * ```\n *\n * @category Agent Actions\n */\nexport function useAgentTranslate(\n resourceHandle?: ResourceHandle,\n): (options: AgentTranslateOptions) => Subscribable<unknown> {\n const instance = useSanityInstance()\n const {resource} = useNormalizedResourceOptions(resourceHandle ?? {})\n return useCallback(\n (options: AgentTranslateOptions) =>\n agentTranslate(instance, options, resource) as unknown as Subscribable<unknown>,\n [instance, resource],\n )\n}\n\n/**\n * @alpha\n * Prompts the Content Agent using the same instruction template format as other agent actions.\n *\n * @remarks\n * This hook provides a stable callback to send prompts to the Content Agent and receive responses.\n * Unlike the other agent action hooks, this one does not modify documents—it simply\n * returns the AI's response.\n *\n * Features:\n * - Uses the same instruction template format with `$variables` as other actions.\n * - `format`: 'string' or 'json' (instruction must contain the word \"json\" for JSON responses).\n * - Supports `instructionParams` for dynamic content (constants, fields, documents, GROQ queries).\n * - Optional `temperature` for controlling response creativity.\n *\n * @returns A stable callback that triggers the action and resolves a Promise with the prompt result.\n *\n * @example Basic string prompt\n * ```tsx\n * import {useState} from 'react'\n * import {useAgentPrompt} from '@sanity/sdk-react'\n *\n * function AskQuestion() {\n * const prompt = useAgentPrompt()\n * const [answer, setAnswer] = useState<string>('')\n *\n * const handleAsk = async () => {\n * const result = await prompt({\n * instruction: 'What are the top 3 benefits of content modeling?',\n * format: 'string',\n * })\n * setAnswer(result.output)\n * }\n *\n * return (\n * <div>\n * <button onClick={handleAsk}>Ask AI</button>\n * {answer && <p>{answer}</p>}\n * </div>\n * )\n * }\n * ```\n *\n * @example JSON response with instruction params\n * ```tsx\n * import {useState} from 'react'\n * import {useAgentPrompt} from '@sanity/sdk-react'\n *\n * interface TagSuggestions {\n * tags: string[]\n * reasoning: string\n * }\n *\n * function SuggestTags({documentId}: {documentId: string}) {\n * const prompt = useAgentPrompt()\n * const [suggestions, setSuggestions] = useState<TagSuggestions | null>(null)\n *\n * const handleSuggest = async () => {\n * const result = await prompt({\n * instruction: `\n * Based on the following article title and content, suggest relevant tags.\n * Return as json with \"tags\" (array of strings) and \"reasoning\" (string).\n * Title: $title\n * Content: $body\n * `,\n * instructionParams: {\n * title: {type: 'field', path: 'title', documentId},\n * body: {type: 'field', path: 'body', documentId},\n * },\n * format: 'json',\n * })\n * setSuggestions(result.output as TagSuggestions)\n * }\n *\n * return (\n * <div>\n * <button onClick={handleSuggest}>Suggest Tags</button>\n * {suggestions && (\n * <div>\n * <p>Reasoning: {suggestions.reasoning}</p>\n * <ul>\n * {suggestions.tags.map((tag) => (\n * <li key={tag}>{tag}</li>\n * ))}\n * </ul>\n * </div>\n * )}\n * </div>\n * )\n * }\n * ```\n *\n * @category Agent Actions\n */\nexport function useAgentPrompt(\n resourceHandle?: ResourceHandle,\n): (options: AgentPromptOptions) => Promise<AgentPromptResult> {\n const instance = useSanityInstance()\n const {resource} = useNormalizedResourceOptions(resourceHandle ?? {})\n return useCallback(\n (options: AgentPromptOptions) => firstValueFrom(agentPrompt(instance, options, resource)),\n [instance, resource],\n )\n}\n\n/**\n * @alpha\n * Schema-aware patching with Sanity Agent Actions.\n *\n * @remarks\n * This hook provides a stable callback to apply schema-validated patches to documents.\n * Unlike {@link useEditDocument}, this uses the Agent Actions API which provides\n * additional schema validation and safe merging capabilities.\n *\n * Features:\n * - Validates provided paths/values against the document schema and merges object values safely.\n * - Prevents duplicate keys and supports array appends (including after a specific keyed item).\n * - Accepts `documentId` or `targetDocument` (mutually exclusive).\n * - Requires `schemaId` (e.g., `'_.schemas.default'`) and `target` to specify patch operations.\n * - Optional `async`, `noWrite`, `conditionalPaths`.\n *\n * Each entry in `target` specifies a `path`, an `operation` (`'set'`, `'append'`, `'mixed'`, or `'unset'`),\n * and a `value` (required for all operations except `'unset'`).\n *\n * @returns A stable callback that triggers the action and resolves a Promise with the patch result.\n *\n * @example Basic field update\n * ```tsx\n * import {useAgentPatch} from '@sanity/sdk-react'\n *\n * function UpdateTitle({documentId}: {documentId: string}) {\n * const patch = useAgentPatch()\n *\n * const handleUpdate = async () => {\n * const result = await patch({\n * documentId,\n * schemaId: '_.schemas.default',\n * target: [\n * {\n * path: 'title',\n * operation: 'set',\n * value: 'Updated Title',\n * },\n * {\n * path: 'lastModified',\n * operation: 'set',\n * value: new Date().toISOString(),\n * },\n * ],\n * })\n * console.log('Patch result:', result)\n * }\n *\n * return <button onClick={handleUpdate}>Update Title</button>\n * }\n * ```\n *\n * @example Append items to an array\n * ```tsx\n * import {useAgentPatch} from '@sanity/sdk-react'\n *\n * function AddTag({documentId}: {documentId: string}) {\n * const patch = useAgentPatch()\n *\n * const handleAddTag = async (newTag: string) => {\n * await patch({\n * documentId,\n * schemaId: '_.schemas.default',\n * target: {\n * path: 'tags',\n * operation: 'append',\n * value: [newTag],\n * },\n * })\n * }\n *\n * return (\n * <button onClick={() => handleAddTag('featured')}>\n * Add Featured Tag\n * </button>\n * )\n * }\n * ```\n *\n * @example Insert array item after a specific key\n * ```tsx\n * import {useAgentPatch} from '@sanity/sdk-react'\n *\n * function InsertContentBlock({\n * documentId,\n * afterKey,\n * }: {\n * documentId: string\n * afterKey: string\n * }) {\n * const patch = useAgentPatch()\n *\n * const handleInsert = async () => {\n * await patch({\n * documentId,\n * schemaId: '_.schemas.default',\n * target: {\n * path: ['content', {_key: afterKey}],\n * operation: 'append',\n * value: [{_type: 'block', text: 'New paragraph inserted here.'}],\n * },\n * })\n * }\n *\n * return <button onClick={handleInsert}>Insert Block</button>\n * }\n * ```\n *\n * @example Create a new document with targetDocument\n * ```tsx\n * import {useAgentPatch} from '@sanity/sdk-react'\n *\n * function CreateProduct() {\n * const patch = useAgentPatch()\n *\n * const handleCreate = async () => {\n * const result = await patch({\n * targetDocument: {\n * operation: 'create',\n * _type: 'product',\n * },\n * schemaId: '_.schemas.default',\n * target: [\n * {\n * path: 'title',\n * operation: 'set',\n * value: 'New Product',\n * },\n * {\n * path: 'price',\n * operation: 'set',\n * value: 29.99,\n * },\n * {\n * path: 'inStock',\n * operation: 'set',\n * value: true,\n * },\n * ],\n * })\n * console.log('Created document:', result.documentId)\n * }\n *\n * return <button onClick={handleCreate}>Create Product</button>\n * }\n * ```\n *\n * @category Agent Actions\n */\nexport function useAgentPatch(\n resourceHandle?: ResourceHandle,\n): (options: AgentPatchOptions) => Promise<AgentPatchResult> {\n const instance = useSanityInstance()\n const {resource} = useNormalizedResourceOptions(resourceHandle ?? {})\n return useCallback(\n (options: AgentPatchOptions) => firstValueFrom(agentPatch(instance, options, resource)),\n [instance, resource],\n )\n}\n","import {type Application, application, type ApplicationInclude} from '@sanity/sdk'\n\nimport {createFetcherHook, type FetcherHookResult} from '../helpers/createFetcherHook'\n\n/**\n * Returns a single application by id.\n *\n * The hook suspends until the first fetch succeeds, so `data` is always present.\n * The `include` tokens you pass shape `data`: each requested token adds its\n * field, and omitted ones are absent from the type.\n *\n * @public\n * @param applicationId - The application id.\n * @param options - Optional `include` list to expand related resources.\n * @returns The result envelope `{data, isFetching, error, refetch}`.\n */\nexport const useApplication = createFetcherHook(application) as <\n Include extends ApplicationInclude = never,\n>(\n applicationId: string,\n options?: {include?: Include[]},\n) => FetcherHookResult<Application<Include>>\n","import {\n type ApplicationInclude,\n applications,\n type ApplicationsOptions,\n type ApplicationsResponse,\n} from '@sanity/sdk'\n\nimport {createFetcherHook, type FetcherHookResult} from '../helpers/createFetcherHook'\n\n/**\n * Returns the applications matching the given options.\n *\n * The hook suspends until the first fetch succeeds, so `data` is always present.\n * The `include` tokens you pass shape `data.data`: each requested token adds its\n * field, and omitted ones are absent from the type.\n *\n * @public\n * @param options - Filter and include options for the applications list.\n * @returns The result envelope `{data, isFetching, error, refetch}`.\n */\nexport const useApplications = createFetcherHook(applications) as <\n Include extends ApplicationInclude = never,\n>(\n options: ApplicationsOptions<Include>,\n) => FetcherHookResult<ApplicationsResponse<Include>>\n","import {type SanityInstance} from '@sanity/sdk'\nimport {type MutationResult} from '@sanity/sdk/_internal'\nimport {useCallback, useRef, useState} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n * The value returned by a mutation-backed hook. The write-side counterpart to\n * {@link FetcherHookResult}: local `{mutate, isPending, error, data, reset}`\n * state around a core mutation action.\n *\n * @public\n */\nexport interface MutationHookResult<TInput, TResult> {\n /**\n * Runs the mutation. Resolves with the server response; rejects on failure\n * (the failure is also captured in {@link MutationHookResult.error}, so a\n * fire-and-forget caller should read `error` and an `await`ing caller should\n * `try`/`catch`).\n */\n mutate: (input: TInput) => Promise<TResult>\n /** A mutation is currently in flight. */\n isPending: boolean\n /** The most recent failure; cleared by the next `mutate` or `reset`. */\n error: unknown\n /** The last successful server response, or `undefined` before the first success. */\n data: TResult | undefined\n /** Clears state back to idle and abandons any in-flight result. */\n reset: () => void\n}\n\ntype MutationState<TResult> =\n | {status: 'idle'; data: undefined; error: undefined}\n | {status: 'pending'; data: TResult | undefined; error: undefined}\n | {status: 'success'; data: TResult; error: undefined}\n | {status: 'error'; data: TResult | undefined; error: unknown}\n\n/**\n * Builds a hook over a core mutation action (the result of `defineMutation`).\n * The write-side counterpart to {@link createFetcherHook}: it binds the action\n * to the current {@link SanityInstance} and tracks `{isPending, error, data}`\n * locally. `mutate` resolves with the server response only — the mutation's\n * `invalidated` promise is intentionally not exposed, since cache\n * reconciliation is handled by the fetcher stores.\n *\n * @internal\n */\nexport function createMutationHook<TInput, TResult>(\n mutation: (instance: SanityInstance, input: TInput) => Promise<MutationResult<TResult>>,\n): () => MutationHookResult<TInput, TResult> {\n const idle: MutationState<TResult> = {status: 'idle', data: undefined, error: undefined}\n\n return function useMutationHook(): MutationHookResult<TInput, TResult> {\n const instance = useSanityInstance()\n const [state, setState] = useState<MutationState<TResult>>(idle)\n // Increments per call; only the latest call is allowed to write state, so an\n // earlier in-flight mutation can't clobber a later one (or a `reset`).\n const callId = useRef(0)\n\n const mutate = useCallback(\n (input: TInput): Promise<TResult> => {\n const id = ++callId.current\n setState((prev) => ({status: 'pending', data: prev.data, error: undefined}))\n return mutation(instance, input).then(\n ({data}) => {\n if (id === callId.current) setState({status: 'success', data, error: undefined})\n return data\n },\n (error: unknown) => {\n if (id === callId.current) {\n setState((prev) => ({status: 'error', data: prev.data, error}))\n }\n throw error\n },\n )\n },\n [instance],\n )\n\n const reset = useCallback(() => {\n callId.current++ // abandon any in-flight response so it can't revive stale state\n setState(idle)\n }, [])\n\n return {\n mutate,\n isPending: state.status === 'pending',\n error: state.error,\n data: state.data,\n reset,\n }\n }\n}\n","import {deleteApplication} from '@sanity/sdk'\n\nimport {createMutationHook} from '../helpers/createMutationHook'\n\n/**\n * Soft-deletes an application.\n *\n * @internal\n * @returns The mutation envelope `{mutate, isPending, error, data, reset}`.\n */\nexport const useDeleteApplication = createMutationHook(deleteApplication)\n","import {updateApplication} from '@sanity/sdk'\n\nimport {createMutationHook} from '../helpers/createMutationHook'\n\n/**\n * Updates an application's mutable properties (title, icon, visibility).\n *\n * @internal\n * @returns The mutation envelope `{mutate, isPending, error, data, reset}`.\n */\nexport const useUpdateApplication = createMutationHook(updateApplication)\n","import {getTokenState} from '@sanity/sdk'\n\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\n\n/**\n * Hook to get the currently logged in user\n * @internal\n * @returns The current user or null if not authenticated\n */\nexport const useAuthToken = createStateSourceHook(getTokenState)\n","import {type CurrentUser, getCurrentUserState} from '@sanity/sdk'\n\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\n\ntype UseCurrentUser = {\n /**\n * @public\n *\n * Provides the currently authenticated user’s profile information.\n *\n * @category Users\n * @returns The current user data\n *\n * @example Rendering a basic user profile\n * ```\n * const user = useCurrentUser()\n *\n * return (\n * <figure>\n * <img src={user?.profileImage} alt=`Profile image for ${user?.name}` />\n * <h2>{user?.name}</h2>\n * </figure>\n * )\n * ```\n */\n (): CurrentUser | null\n}\n\n/**\n * @public\n * @function\n * @TODO This should not return null — users of a custom app will always be authenticated via Core\n */\nexport const useCurrentUser: UseCurrentUser = createStateSourceHook(getCurrentUserState)\n","import {type ClientOptions, getClientState, type SanityInstance} from '@sanity/sdk'\n\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\n\n/**\n * A React hook that provides a client that subscribes to changes in your application,\n *\n * @remarks\n * This hook is intended for advanced use cases and special API calls that the React SDK\n * does not yet provide hooks for. We welcome you to get in touch with us to let us know\n * your use cases for this!\n *\n * @category Platform\n * @returns A Sanity client\n *\n * @example\n * ```tsx\n * function MyComponent() {\n * const client = useClient({apiVersion: '2024-11-12'})\n * const [document, setDocument] = useState(null)\n * useEffect(async () => {\n * const doc = client.fetch('*[_id == \"myDocumentId\"]')\n * setDocument(doc)\n * }, [])\n * return <div>{JSON.stringify(document) ?? 'Loading...'}</div>\n * }\n * ```\n *\n * @public\n * @function\n */\nexport const useClient = createStateSourceHook({\n getState: (instance: SanityInstance, options: ClientOptions) => {\n if (!options || typeof options !== 'object') {\n throw new Error(\n 'useClient() requires a configuration object with at least an \"apiVersion\" property. ' +\n 'Example: useClient({ apiVersion: \"2024-11-12\" })',\n )\n }\n return getClientState(instance, options)\n },\n getConfig: (options: ClientOptions) => options,\n})\n","import {type ChannelInstance, type Controller, type Status} from '@sanity/comlink'\nimport {\n type FrameMessage,\n getOrCreateChannel,\n getOrCreateController,\n releaseChannel,\n type WindowMessage,\n} from '@sanity/sdk/comlink'\nimport {useCallback, useEffect, useRef} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n * @internal\n */\nexport type FrameMessageHandler<TWindowMessage extends WindowMessage> = (\n event: TWindowMessage['data'],\n) => TWindowMessage['response'] | Promise<TWindowMessage['response']>\n\n/**\n * @internal\n */\nexport interface UseFrameConnectionOptions<TWindowMessage extends WindowMessage> {\n name: string\n connectTo: string\n targetOrigin: string\n onMessage?: {\n [K in TWindowMessage['type']]: (data: Extract<TWindowMessage, {type: K}>['data']) => void\n }\n heartbeat?: boolean\n onStatus?: (status: Status) => void\n}\n\n/**\n * @internal\n */\nexport interface FrameConnection<TFrameMessage extends FrameMessage> {\n connect: (frameWindow: Window) => () => void // Return cleanup function\n sendMessage: <T extends TFrameMessage['type']>(\n ...params: Extract<TFrameMessage, {type: T}>['data'] extends undefined\n ? [type: T]\n : [type: T, data: Extract<TFrameMessage, {type: T}>['data']]\n ) => void\n}\n\n/**\n * @internal\n */\nexport function useFrameConnection<\n TFrameMessage extends FrameMessage,\n TWindowMessage extends WindowMessage,\n>(options: UseFrameConnectionOptions<TWindowMessage>): FrameConnection<TFrameMessage> {\n const {onMessage, targetOrigin, name, connectTo, heartbeat, onStatus} = options\n const instance = useSanityInstance()\n const controllerRef = useRef<Controller | null>(null)\n const channelRef = useRef<ChannelInstance<TFrameMessage, TWindowMessage> | null>(null)\n\n useEffect(() => {\n const controller = getOrCreateController(instance, targetOrigin)\n const channel = getOrCreateChannel(instance, {name, connectTo, heartbeat})\n controllerRef.current = controller\n channelRef.current = channel\n\n channel.onStatus((event) => {\n onStatus?.(event.status)\n })\n\n const messageUnsubscribers: Array<() => void> = []\n\n if (onMessage) {\n Object.entries(onMessage).forEach(([type, handler]) => {\n const unsubscribe = channel.on(type, handler as FrameMessageHandler<TWindowMessage>)\n messageUnsubscribers.push(unsubscribe)\n })\n }\n\n return () => {\n // Clean up all subscriptions and stop controller/channel\n messageUnsubscribers.forEach((unsub) => unsub())\n releaseChannel(instance, name)\n channelRef.current = null\n controllerRef.current = null\n }\n }, [targetOrigin, name, connectTo, heartbeat, onMessage, instance, onStatus])\n\n const connect = useCallback((frameWindow: Window) => {\n const removeTarget = controllerRef.current?.addTarget(frameWindow)\n return () => {\n removeTarget?.()\n }\n }, [])\n\n const sendMessage = useCallback(\n <T extends TFrameMessage['type']>(\n type: T,\n data?: Extract<TFrameMessage, {type: T}>['data'],\n ) => {\n channelRef.current?.post(type, data)\n },\n [],\n )\n\n return {\n connect,\n sendMessage,\n }\n}\n","import {type SanityInstance} from '@sanity/sdk'\nimport {trackHookMounted} from '@sanity/sdk/_internal'\nimport {useRef} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n * Tracks the first usage of a named hook per SDK session.\n * If the telemetry manager hasn't initialized yet, the hook\n * name is buffered and flushed when it becomes available.\n *\n * Uses a ref to ensure the tracking call only happens once per\n * component mount, avoiding repeated WeakMap lookups on re-renders.\n *\n * Call at the top of any public hook whose adoption we want to measure.\n *\n * @internal\n */\nexport function useTrackHookUsage(hookName: string): void {\n const instance = useSanityInstance()\n const tracked = useRef<true | null>(null)\n if (tracked.current === null) {\n tracked.current = true\n trackHookMounted(instance, hookName)\n }\n}\n\n/**\n * Non-hook variant for tracking hook usage when an instance is already\n * available (avoids an extra `useSanityInstance` call in hooks that\n * already have the instance).\n *\n * @internal\n */\nexport function trackHookUsage(instance: SanityInstance, hookName: string): void {\n trackHookMounted(instance, hookName)\n}\n","import {\n type Comment,\n createComment,\n type CreateCommentOptions,\n type DocumentResource,\n type PerspectiveHandle,\n removeComment,\n type RemoveCommentOptions,\n replyToComment,\n type ReplyToCommentOptions,\n setCommentStatus,\n type SetCommentStatusOptions,\n updateComment,\n type UpdateCommentOptions,\n} from '@sanity/sdk'\nimport {useContext, useMemo} from 'react'\n\nimport {PerspectiveContext} from '../../context/PerspectiveContext'\nimport {ResourcesContext} from '../../context/ResourcesContext'\nimport {useSanityInstance} from '../context/useSanityInstance'\nimport {\n normalizeResourceOptions,\n useEffectiveContextResource,\n type WithResourceNameSupport,\n} from '../helpers/useNormalizedResourceOptions'\nimport {trackHookUsage} from '../helpers/useTrackHookUsage'\n\n/**\n * @public\n * @category Types\n */\nexport interface CommentActions {\n /** Starts a thread on a document, or on one of its fields. */\n createComment: (options: WithResourceNameSupport<CreateCommentOptions>) => Promise<Comment>\n /** Adds a reply to an existing thread. */\n replyToComment: (options: WithResourceNameSupport<ReplyToCommentOptions>) => Promise<Comment>\n /** Rewrites a comment's message. */\n updateComment: (options: WithResourceNameSupport<UpdateCommentOptions>) => Promise<void>\n /** Resolves or reopens a thread. Pass the thread's first comment. */\n setCommentStatus: (options: WithResourceNameSupport<SetCommentStatusOptions>) => Promise<void>\n /** Deletes a comment, and its replies when it starts a thread. */\n removeComment: (options: WithResourceNameSupport<RemoveCommentOptions>) => Promise<void>\n}\n\ntype Resolvable = {\n resource?: DocumentResource\n resourceName?: string\n projectId?: string\n dataset?: string\n perspective?: PerspectiveHandle['perspective']\n}\n\n/**\n * Returns the five comment write actions, bound to the current instance.\n *\n * Each writes optimistically: the change shows immediately and is rolled back\n * if the server rejects it, so an app can render straight from\n * {@link useComments} without tracking pending state itself.\n *\n * Creating is the exception, and `replyToComment` counts as creating. A comment\n * that fails to post stays on screen carrying `_state.createError` rather than\n * disappearing, so passing the same `commentId` again retries it instead of\n * losing what someone typed.\n *\n * The resource is resolved when an action is called rather than when the hook\n * runs, so one set of callbacks works across several resources. Pass `resource`\n * or `resourceName` per call to choose; otherwise the surrounding\n * `ResourceProvider` decides.\n *\n * @category Comments\n * @function\n * @returns The five write actions\n *\n * @example Resolve a thread\n * ```tsx\n * function ResolveButton({commentId}: {commentId: string}) {\n * const {setCommentStatus} = useCommentActions()\n *\n * return (\n * <button onClick={() => setCommentStatus({commentId, status: 'resolved'})}>\n * Resolve\n * </button>\n * )\n * }\n * ```\n *\n * @public\n */\nexport function useCommentActions(): CommentActions {\n const instance = useSanityInstance()\n trackHookUsage(instance, 'useCommentActions')\n\n const resources = useContext(ResourcesContext)\n const contextResource = useEffectiveContextResource()\n const contextPerspective = useContext(PerspectiveContext)\n\n return useMemo(() => {\n const resolve = <T extends Resolvable>(options: T) =>\n normalizeResourceOptions(options, resources, contextResource, contextPerspective)\n\n return {\n createComment: (options) => createComment(instance, resolve(options)),\n replyToComment: (options) => replyToComment(instance, resolve(options)),\n updateComment: (options) => updateComment(instance, resolve(options)),\n setCommentStatus: (options) => setCommentStatus(instance, resolve(options)),\n removeComment: (options) => removeComment(instance, resolve(options)),\n }\n }, [contextPerspective, contextResource, instance, resources])\n}\n","import {type CommentsOptions, type SanityInstance, type StateSource} from '@sanity/sdk'\nimport {getCommentsOptionsKey, parseCommentsOptionsKey} from '@sanity/sdk/_internal'\nimport {useEffect, useMemo, useRef, useState, useSyncExternalStore, useTransition} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\nimport {\n useNormalizedResourceOptions,\n type WithResourceNameSupport,\n} from '../helpers/useNormalizedResourceOptions'\nimport {trackHookUsage} from '../helpers/useTrackHookUsage'\n\n/** The pair of core functions backing one read hook. */\nexport interface CommentListSource<T> {\n getState: (instance: SanityInstance, options: CommentsOptions) => StateSource<T | undefined>\n resolve: (\n instance: SanityInstance,\n options: CommentsOptions & {signal?: AbortSignal},\n ) => Promise<T>\n}\n\n/**\n * Shared body of {@link useComments} and {@link useCommentThreads}.\n *\n * Suspends until the first snapshot arrives. Changing documents or filters\n * happens in a transition, so the list already on screen stays put and\n * `isPending` reports the swap instead of the component suspending again. The\n * previous read is aborted, which drops its listener when nothing else is\n * reading it.\n *\n * @internal\n */\nexport function useCommentList<T>(\n hookName: string,\n options: WithResourceNameSupport<CommentsOptions>,\n {getState, resolve}: CommentListSource<T>,\n): {value: T; isPending: boolean} {\n const instance = useSanityInstance()\n trackHookUsage(instance, hookName)\n\n const normalized = useNormalizedResourceOptions(options)\n const [isPending, startTransition] = useTransition()\n\n const key = getCommentsOptionsKey(normalized)\n // Held one render behind `key`, so the swap can happen inside a transition.\n const [deferredKey, setDeferredKey] = useState(key)\n const abortRef = useRef<AbortController>(new AbortController())\n\n useEffect(() => {\n if (key === deferredKey) return\n\n startTransition(() => {\n if (!abortRef.current.signal.aborted) {\n abortRef.current.abort()\n abortRef.current = new AbortController()\n }\n setDeferredKey(key)\n })\n }, [deferredKey, key])\n\n const deferred = useMemo(() => parseCommentsOptionsKey(deferredKey), [deferredKey])\n const {getCurrent, subscribe} = useMemo(\n () => getState(instance, deferred),\n [deferred, getState, instance],\n )\n\n if (getCurrent() === undefined) {\n // Reading the ref mid-render is safe here: React runs no effects for a\n // render that suspends, so the signal captured now cannot be swapped\n // underneath this pass.\n const currentSignal = abortRef.current.signal\n\n // eslint-disable-next-line react-hooks/refs -- intentional during a suspended render; see above\n throw resolve(instance, {...deferred, signal: currentSignal})\n }\n\n // Not memoised: both callers destructure this immediately and memoise their\n // own result object, so a stable identity here would never be observed.\n return {value: useSyncExternalStore(subscribe, getCurrent) as T, isPending}\n}\n","import {type Comment, type CommentsOptions, getCommentsState, resolveComments} from '@sanity/sdk'\nimport {useMemo} from 'react'\n\nimport {type WithResourceNameSupport} from '../helpers/useNormalizedResourceOptions'\nimport {type CommentListSource, useCommentList} from './useCommentList'\n\n/**\n * @public\n * @category Types\n */\nexport interface UseCommentsResult {\n /** Every matching comment, newest first, replies included. */\n comments: Comment[]\n /** True while switching to a different document or filter. */\n isPending: boolean\n}\n\nconst SOURCE: CommentListSource<Comment[]> = {\n getState: getCommentsState,\n resolve: resolveComments,\n}\n\n/**\n * Reads a document's comments and keeps them up to date.\n *\n * Comments are shared with the Studio: they live in the project's comments\n * dataset, so a thread started here shows up there and the other way round. The\n * list is flat, replies included; reach for {@link useCommentThreads} to read it\n * grouped.\n *\n * Suspends until the comments have loaded. Switching document or filter is a\n * transition, so the previous list stays on screen and `isPending` goes true\n * rather than the component suspending again.\n *\n * @category Comments\n * @function\n * @param options - The document to read, optionally narrowed by `fieldPath` or `status`\n * @returns The matching comments, and whether a switch is in flight\n *\n * @example Count the open threads on a field\n * ```tsx\n * function TitleCommentCount({documentId}: {documentId: string}) {\n * const {comments} = useComments({\n * documentId,\n * documentType: 'article',\n * fieldPath: 'title',\n * status: 'open',\n * })\n *\n * return <span>{comments.length}</span>\n * }\n * ```\n *\n * @public\n */\nexport function useComments(options: WithResourceNameSupport<CommentsOptions>): UseCommentsResult {\n const {value, isPending} = useCommentList('useComments', options, SOURCE)\n return useMemo(() => ({comments: value, isPending}), [isPending, value])\n}\n","import {\n type CommentsOptions,\n type CommentThread,\n getCommentThreadsState,\n resolveCommentThreads,\n} from '@sanity/sdk'\nimport {useMemo} from 'react'\n\nimport {type WithResourceNameSupport} from '../helpers/useNormalizedResourceOptions'\nimport {type CommentListSource, useCommentList} from './useCommentList'\n\n/**\n * @public\n * @category Types\n */\nexport interface UseCommentThreadsResult {\n /** Newest thread first, each with its replies oldest first. */\n threads: CommentThread[]\n /** True while switching to a different document or filter. */\n isPending: boolean\n}\n\nconst SOURCE: CommentListSource<CommentThread[]> = {\n getState: getCommentThreadsState,\n resolve: resolveCommentThreads,\n}\n\n/**\n * Reads a document's comments grouped into threads.\n *\n * A thread is one comment plus its replies. Its `status` and `fieldPath` come\n * from the first comment, so filtering by either selects whole threads rather\n * than stray replies.\n *\n * Unlike the Studio, every thread is returned. The Studio hides threads whose\n * field has left the schema or is hidden by a conditional, which it can do\n * because it has the schema to check against. Inspect `fieldPath` yourself if\n * your app needs to do the same.\n *\n * @category Comments\n * @function\n * @param options - The document to read, optionally narrowed by `fieldPath` or `status`\n * @returns The matching threads, and whether a switch is in flight\n *\n * @example Render the open threads on a document\n * ```tsx\n * function Threads({documentId}: {documentId: string}) {\n * const {threads} = useCommentThreads({\n * documentId,\n * documentType: 'article',\n * status: 'open',\n * })\n *\n * return (\n * <ul>\n * {threads.map((thread) => (\n * <li key={thread.threadId}>\n * {thread.fieldPath || 'Document'} — {thread.commentsCount} comments\n * </li>\n * ))}\n * </ul>\n * )\n * }\n * ```\n *\n * @public\n */\nexport function useCommentThreads(\n options: WithResourceNameSupport<CommentsOptions>,\n): UseCommentThreadsResult {\n const {value, isPending} = useCommentList('useCommentThreads', options, SOURCE)\n return useMemo(() => ({threads: value, isPending}), [isPending, value])\n}\n","import {type DocumentResource} from '@sanity/sdk'\n\nimport {useEffectiveContextResource} from '../helpers/useNormalizedResourceOptions'\n\n/**\n * Returns the currently active `DocumentResource` for the nearest resource context.\n *\n * Resolves in priority order:\n * 1. A `resource` prop on the nearest `<ResourceProvider>`\n * 2. The `projectId`/`dataset` from the current `SanityInstance` config\n * 3. `undefined` when neither is available\n *\n * @public\n * @category Platform\n *\n * @example\n * ```tsx\n * const resource = useResource()\n * console.log(resource?.projectId, resource?.dataset)\n * ```\n */\nexport function useResource(): DocumentResource | undefined {\n return useEffectiveContextResource()\n}\n","import {\n type CanvasResource,\n type MediaResource,\n type StudioResource,\n} from '@sanity/message-protocol'\nimport {type DocumentHandle, type FavoriteDocumentContext} from '@sanity/sdk'\nimport {useMemo} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n * Props shared by {@link useFavorite} and {@link useUpdateFavorite}: a document\n * handle plus the resource it lives in.\n *\n * @internal\n */\nexport interface UseFavoriteProps extends DocumentHandle {\n resourceId?: string\n resourceType: StudioResource['type'] | MediaResource['type'] | CanvasResource['type']\n /**\n * The name of the schema collection this document belongs to.\n * Typically is the name of the workspace when used in the context of a studio.\n */\n schemaName?: string\n}\n\n/**\n * Resolves {@link UseFavoriteProps} into the {@link FavoriteDocumentContext}\n * shared by the favorites fetcher and mutation, defaulting a studio `resourceId`\n * from the instance's project and dataset.\n *\n * @internal\n */\nexport function useFavoriteContext({\n documentId,\n documentType,\n projectId: paramProjectId,\n dataset: paramDataset,\n resourceId: paramResourceId,\n resourceType,\n schemaName,\n}: UseFavoriteProps): FavoriteDocumentContext {\n const {config} = useSanityInstance()\n const projectId = paramProjectId ?? config?.projectId\n const dataset = paramDataset ?? config?.dataset\n\n if (resourceType === 'studio' && (!projectId || !dataset)) {\n throw new Error('projectId and dataset are required for studio resources')\n }\n const resourceId =\n resourceType === 'studio' && !paramResourceId ? `${projectId}.${dataset}` : paramResourceId\n\n if (!resourceId) {\n throw new Error('resourceId is required for media-library and canvas resources')\n }\n\n return useMemo(\n () => ({documentId, documentType, resourceId, resourceType, schemaName}),\n [documentId, documentType, resourceId, resourceType, schemaName],\n )\n}\n","import {favorites} from '@sanity/sdk'\n\nimport {createFetcherHook} from '../helpers/createFetcherHook'\nimport {useFavoriteContext, type UseFavoriteProps} from './useFavoriteContext'\n\nconst useFavoriteStatus = createFetcherHook(favorites)\n\n/**\n * @internal\n *\n * Reads whether a document is currently favorited. The write-side counterpart is\n * {@link useUpdateFavorite}.\n *\n * The hook suspends until the first favorite status resolves, so wrap the\n * component in a `<Suspense>` boundary.\n *\n * @param props - The document handle plus the resource it lives in.\n * @returns `true` when the document is favorited, otherwise `false`.\n *\n * @example\n * ```tsx\n * function FavoriteLabel(props: DocumentActionProps) {\n * const {documentId, documentType} = props\n * const isFavorited = useFavorite({documentId, documentType, resourceType: 'studio'})\n *\n * return <span>{isFavorited ? 'Favorited' : 'Not favorited'}</span>\n * }\n * ```\n */\nexport function useFavorite(props: UseFavoriteProps): boolean {\n const context = useFavoriteContext(props)\n const {data} = useFavoriteStatus(context)\n return data.isFavorited\n}\n","/* eslint-disable react-compiler/react-compiler -- the transport branch in `useRecordDocumentHistoryEvent` is a deliberate rules-of-hooks exception; the compiler refuses files that disable it */\nimport {\n type CanvasResource,\n type Events,\n type MediaResource,\n SDK_CHANNEL_NAME,\n SDK_NODE_NAME,\n type StudioResource,\n} from '@sanity/message-protocol'\nimport {type DocumentHandle} from '@sanity/sdk'\nimport {isDashboardEnvironment} from '@sanity/sdk/_internal'\nimport {type FrameMessage} from '@sanity/sdk/comlink'\nimport {useCallback} from 'react'\n\nimport {useWindowConnection} from '../comlink/useWindowConnection'\nimport {useEmit} from './useEmit'\nimport {useTopic} from './useTopic'\n\ninterface DocumentInteractionHistory {\n recordEvent: (eventType: 'viewed' | 'edited' | 'created' | 'deleted') => void\n}\n\n/**\n * @internal\n */\ninterface UseRecordDocumentHistoryEventProps extends DocumentHandle {\n resourceType: StudioResource['type'] | MediaResource['type'] | CanvasResource['type']\n /**\n * The resource the document lives in. Optional for studios over Comlink, where the iframe\n * host fills it from context; always required under the message bus, which has no such\n * context and throws when it is missing.\n */\n resourceId?: string\n /**\n * The name of the schema collection this document belongs to.\n * Typically is the name of the workspace when used in the context of a studio.\n */\n schemaName?: string\n}\n\n/**\n * @internal\n * Hook for recording document interaction history in a Dashboard application.\n * This hook provides functionality to record document interactions.\n *\n * It works in both Dashboard runtimes and picks the transport for the current one:\n *\n * | Runtime | Transport | `resourceId` | Suspends until |\n * | --- | --- | --- | --- |\n * | iframe | Comlink | optional for studios | the node connects |\n * | federated | message bus | required | capabilities publish |\n *\n * Under the message bus the hook always suspends until the host publishes its capabilities;\n * only once they resolve does `recordEvent` run, and it then no-ops on every call when the\n * host does not provide the `history` capability. There is no synchronous no-op path.\n *\n * @category History\n * @param documentHandle - The document handle containing document ID and type, like `{_id: '123', _type: 'book'}`\n * @returns An object containing:\n * - `recordEvent` - Function to record document interactions\n *\n * @example\n * ```tsx\n * import {useRecordDocumentHistoryEvent} from '@sanity/sdk-react'\n * import {Button} from '@sanity/ui'\n * import {Suspense} from 'react'\n *\n * function RecordEventButton(props: DocumentActionProps) {\n * const {documentId, documentType, resourceType, resourceId} = props\n * const {recordEvent} = useRecordDocumentHistoryEvent({\n * documentId,\n * documentType,\n * resourceType,\n * resourceId,\n * })\n * return (\n * <Button\n * onClick={() => recordEvent('viewed')}\n * text=\"Viewed\"\n * />\n * )\n * }\n *\n * // Wrap the component with Suspense since the hook may suspend\n * function MyDocumentAction(props: DocumentActionProps) {\n * return (\n * <Suspense fallback={<Button text=\"Loading...\" disabled />}>\n * <RecordEventButton {...props} />\n * </Suspense>\n * )\n * }\n * ```\n */\nexport function useRecordDocumentHistoryEvent(\n props: UseRecordDocumentHistoryEventProps,\n): DocumentInteractionHistory {\n // The branch is stable: the transport is fixed for the page lifetime, so one set of hooks\n // always runs and the other never does.\n // eslint-disable-next-line react-hooks/rules-of-hooks -- transport is fixed for the page lifetime\n if (isDashboardEnvironment()) return useBusRecordDocumentHistoryEvent(props)\n // eslint-disable-next-line react-hooks/rules-of-hooks -- transport is fixed for the page lifetime\n return useComlinkRecordDocumentHistoryEvent(props)\n}\n\nfunction useComlinkRecordDocumentHistoryEvent({\n documentId,\n documentType,\n resourceType,\n resourceId,\n schemaName,\n}: UseRecordDocumentHistoryEventProps): DocumentInteractionHistory {\n const {sendMessage} = useWindowConnection<Events.HistoryMessage, FrameMessage>({\n name: SDK_NODE_NAME,\n connectTo: SDK_CHANNEL_NAME,\n })\n\n if (resourceType !== 'studio' && !resourceId) {\n throw new Error('resourceId is required for media-library and canvas resources')\n }\n\n const recordEvent = useCallback(\n (eventType: 'viewed' | 'edited' | 'created' | 'deleted') => {\n try {\n const message: Events.HistoryMessage = {\n type: 'dashboard/v1/events/history',\n data: {\n eventType,\n document: {\n id: documentId,\n type: documentType,\n resource: {\n id: resourceId!,\n type: resourceType,\n schemaName,\n },\n },\n },\n }\n\n sendMessage(message.type, message.data)\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error('Failed to record history event:', error)\n throw error\n }\n },\n [documentId, documentType, resourceId, resourceType, sendMessage, schemaName],\n )\n\n return {\n recordEvent,\n }\n}\n\nfunction useBusRecordDocumentHistoryEvent({\n documentId,\n documentType,\n resourceType,\n resourceId,\n schemaName,\n}: UseRecordDocumentHistoryEventProps): DocumentInteractionHistory {\n const emitActivity = useEmit('applications.activity')\n const capabilities = useTopic('applications.capabilities')\n\n // The bus host has no iframe context to fill `projectId.dataset` from, so the resource must\n // be addressed explicitly.\n if (!resourceId) {\n throw new Error('resourceId is required to record document history under the message bus')\n }\n\n // A studio is addressed by its dataset resource over the bus; the workspace name rides along\n // in `schemaName`.\n const type = resourceType === 'studio' ? 'dataset' : resourceType\n\n const recordEvent = useCallback(\n (eventType: 'viewed' | 'edited' | 'created' | 'deleted') => {\n if (!capabilities.history) return\n emitActivity({\n kind: 'document',\n eventType,\n document: {\n id: documentId,\n type: documentType,\n resource: {id: resourceId, type, schemaName},\n },\n })\n },\n [capabilities.history, documentId, documentType, emitActivity, resourceId, schemaName, type],\n )\n\n return {recordEvent}\n}\n","import {type FavoriteStatusResponse, setFavorite} from '@sanity/sdk'\nimport {useCallback} from 'react'\n\nimport {createMutationHook} from '../helpers/createMutationHook'\nimport {useFavoriteContext, type UseFavoriteProps} from './useFavoriteContext'\n\nconst useSetFavorite = createMutationHook(setFavorite)\n\n/**\n * The value returned by {@link useUpdateFavorite}.\n *\n * @internal\n */\nexport interface UpdateFavorite {\n /** Adds the document to favorites. */\n favorite: () => Promise<FavoriteStatusResponse>\n /** Removes the document from favorites. */\n unfavorite: () => Promise<FavoriteStatusResponse>\n /** A favorite or unfavorite mutation is currently in flight. */\n isPending: boolean\n /** The most recent failure; cleared by the next call or `reset`. */\n error: unknown\n /** Clears error and pending state back to idle. */\n reset: () => void\n}\n\n/**\n * @internal\n *\n * Adds or removes a document from favorites. The read-side counterpart is\n * {@link useFavorite}, which reflects the change once the mutation settles.\n *\n * Unlike {@link useFavorite}, this hook does not suspend.\n *\n * @param props - The document handle plus the resource it lives in.\n * @returns `favorite`/`unfavorite` actions and the `{isPending, error, reset}`\n * mutation state.\n *\n * @example\n * ```tsx\n * function FavoriteButton(props: DocumentActionProps) {\n * const {documentId, documentType} = props\n * const handle = {documentId, documentType, resourceType: 'studio'} as const\n * const isFavorited = useFavorite(handle)\n * const {favorite, unfavorite, isPending} = useUpdateFavorite(handle)\n *\n * return (\n * <Button\n * disabled={isPending}\n * onClick={() => (isFavorited ? unfavorite() : favorite())}\n * text={isFavorited ? 'Remove from favorites' : 'Add to favorites'}\n * />\n * )\n * }\n *\n * // Wrap the component with Suspense since useFavorite suspends\n * function MyDocumentAction(props: DocumentActionProps) {\n * return (\n * <Suspense fallback={<Button text=\"Loading...\" disabled />}>\n * <FavoriteButton {...props} />\n * </Suspense>\n * )\n * }\n * ```\n */\nexport function useUpdateFavorite(props: UseFavoriteProps): UpdateFavorite {\n const context = useFavoriteContext(props)\n const {mutate, isPending, error, reset} = useSetFavorite()\n\n const favorite = useCallback(() => mutate({...context, isFavorited: true}), [mutate, context])\n const unfavorite = useCallback(() => mutate({...context, isFavorited: false}), [mutate, context])\n\n return {favorite, unfavorite, isPending, error, reset}\n}\n","import {type DocumentResource, isDatasetResource} from '@sanity/sdk'\nimport {useContext} from 'react'\n\nimport {ProjectContext} from '../../context/ProjectContext'\nimport {useNormalizedResourceOptions} from './useNormalizedResourceOptions'\n\n/**\n * Resolves the effective `projectId` for project-scoped hooks (`useProject`,\n * `useDatasets`, `useUsers`).\n *\n * Precedence:\n * 1. an explicit `projectId` on the options\n * 2. the ambient project scope (`ProjectContext`, e.g. a dataset-less\n * `<ResourceProvider projectId=\"…\">`)\n * 3. the resolved resource's projectId (`ResourceProvider`/`SDKProvider`)\n *\n * Returns `undefined` when none apply, letting callers fall back to core's\n * `instance.config.projectId`.\n *\n * @internal\n */\nexport function useResolvedProjectId(options?: {\n projectId?: string\n dataset?: string\n resource?: DocumentResource\n resourceName?: string\n}): string | undefined {\n const {resource} = useNormalizedResourceOptions(options ?? {})\n const contextProjectId = useContext(ProjectContext)\n return (\n options?.projectId ??\n contextProjectId ??\n (resource && isDatasetResource(resource) ? resource.projectId : undefined)\n )\n}\n","import {type DatasetsResponse} from '@sanity/client'\nimport {datasets, type ProjectHandle} from '@sanity/sdk'\n\nimport {createFetcherHook, type FetcherHookResult} from '../helpers/createFetcherHook'\nimport {useResolvedProjectId} from '../helpers/useResolvedProjectId'\n\nconst useDatasetsBase = createFetcherHook(datasets)\n\n/**\n * Returns metadata for each dataset the current user has access to.\n *\n * @category Datasets\n * @param options - Optional project/resource to read datasets for. Defaults to\n * the resource named in `ResourceProvider`/`SDKProvider`.\n * @returns A {@link FetcherHookResult} whose `data` is the metadata for the\n * datasets.\n *\n * @example\n * ```tsx\n * const {data: datasets} = useDatasets()\n *\n * return (\n * <select>\n * {datasets.map((dataset) => (\n * <option key={dataset.name}>{dataset.name}</option>\n * ))}\n * </select>\n * )\n * ```\n *\n * @remarks\n * The `projectId` is resolved in order from:\n * 1. an explicit `projectId` option\n * 2. A legacy ProjectContext (e.g. a `<ResourceProvider projectId=\"…\">` with no dataset), then\n * 3. The active resource (`ResourceProvider`/`SDKProvider`)\n * 4. `instance.config`.\n * @public\n */\nexport function useDatasets(options?: ProjectHandle): FetcherHookResult<DatasetsResponse> {\n const projectId = useResolvedProjectId(options)\n return useDatasetsBase(projectId ? {...options, projectId} : options)\n}\n","import {type Action, type ActionsResult, applyDocumentActions} from '@sanity/sdk'\nimport {isDeepEqual} from '@sanity/sdk/_internal'\nimport {useContext} from 'react'\n\nimport {type ResourceHandle} from '../../config/handles'\nimport {ResourcesContext} from '../../context/ResourcesContext'\nimport {useSanityInstance} from '../context/useSanityInstance'\nimport {normalizeResourceOptions, useEffectiveContextResource} from './useNormalizedResourceOptions'\n\n/**\n * @internal\n *\n * Shared implementation behind `useApplyDocumentActions` and\n * `useApplyReleaseActions`. Resolves the effective resource from the action\n * handles, top-level `options`, or context (in that order), validates that\n * everything agrees on a single resource, and forwards to\n * `applyDocumentActions`.\n *\n * The two public hooks differ only in their input/output types — at runtime\n * they're identical because core's `applyDocumentActions` accepts the full\n * `Action` union.\n */\nexport function useApplyActions(): (\n actionOrActions: Action | Action[],\n options?: ResourceHandle,\n) => Promise<ActionsResult> {\n const instance = useSanityInstance()\n const resources = useContext(ResourcesContext)\n const effectiveContextResource = useEffectiveContextResource()\n\n return (actionOrActions, options) => {\n const actions = Array.isArray(actionOrActions) ? actionOrActions : [actionOrActions]\n const optionsResource = options\n ? normalizeResourceOptions(options, resources, effectiveContextResource).resource\n : undefined\n\n const normalizedActions = actions.map((action) =>\n normalizeResourceOptions(action, resources, effectiveContextResource),\n )\n\n let resource\n for (const action of normalizedActions) {\n const actionResource = action['resource']\n if (!resource && actionResource) resource = actionResource\n if (!isDeepEqual(actionResource, resource)) {\n throw new Error(\n `Mismatched resources found in actions. All actions must belong to the same resource. Found \"${JSON.stringify(actionResource)}\" but expected \"${JSON.stringify(resource)}\".`,\n )\n }\n }\n\n if (optionsResource && resource && !isDeepEqual(optionsResource, resource)) {\n throw new Error(\n `Mismatched resources found in actions. Found top-level resource \"${JSON.stringify(optionsResource)}\" but expected resource from action handles \"${JSON.stringify(resource)}\".`,\n )\n }\n\n const effectiveResource = resource ?? optionsResource ?? effectiveContextResource\n if (!effectiveResource) {\n throw new Error('No resource found. Provide a resource via the action handle or context.')\n }\n\n return applyDocumentActions(instance, {\n actions: normalizedActions as Action[],\n resource: effectiveResource,\n })\n }\n}\n","import {type ActionsResult, type DocumentAction, type ResolveDocument} from '@sanity/sdk'\n\nimport {type ResourceHandle} from '../../config/handles'\nimport {useApplyActions} from '../helpers/useApplyActions'\n// this import is used in an `{@link useEditDocument}`\n// eslint-disable-next-line import-x/consistent-type-specifier-style\nimport type {useEditDocument} from './useEditDocument'\n\n/**\n * @public\n */\ninterface UseApplyDocumentActions {\n (): <\n TDocumentType extends string = string,\n TDataset extends string = string,\n TProjectId extends string = string,\n >(\n action:\n | DocumentAction<TDocumentType, TDataset, TProjectId>\n | DocumentAction<TDocumentType, TDataset, TProjectId>[],\n options?: ResourceHandle,\n ) => Promise<ActionsResult<ResolveDocument<TDocumentType, `${TProjectId}.${TDataset}`>>>\n}\n\n/**\n * @public\n *\n * Provides a stable callback function for applying one or more document actions.\n *\n * This hook wraps the core `applyDocumentActions` functionality from `@sanity/sdk`,\n * integrating it with the React component lifecycle and {@link SanityInstance}.\n * It allows you to apply actions generated by functions like `createDocument`,\n * `editDocument`, `deleteDocument`, `publishDocument`, `unpublishDocument`,\n * and `discardDocument` to documents.\n *\n * Features:\n * - Applies one or multiple `DocumentAction` objects.\n * - Supports optimistic updates: Local state reflects changes immediately.\n * - Handles batching: Multiple actions passed together are sent as a single atomic transaction.\n * - Integrates with the collaborative editing engine for conflict resolution and state synchronization.\n *\n * @category Documents\n * @returns A stable callback function. When called with a single `DocumentAction` or an array of `DocumentAction`s,\n * it returns a promise that resolves to an {@link ActionsResult}. The `ActionsResult` contains information about the\n * outcome, including optimistic results if applicable.\n *\n * @remarks\n * This hook is a fundamental part of interacting with document state programmatically.\n * It operates within the same unified pipeline as other document hooks like `useDocument` (for reading state)\n * and {@link useEditDocument} (a higher-level hook specifically for edits).\n *\n * When multiple actions are provided in a single call, they are guaranteed to be submitted\n * as a single transaction to Content Lake. This ensures atomicity for related operations (e.g., creating and publishing a document).\n *\n * @function\n *\n * @example Publish or unpublish a document\n * ```tsx\n * import {\n * publishDocument,\n * unpublishDocument,\n * useApplyDocumentActions,\n * type DocumentHandle\n * } from '@sanity/sdk-react'\n *\n * // Define props using the DocumentHandle type\n * interface PublishControlsProps {\n * doc: DocumentHandle\n * }\n *\n * function PublishControls({doc}: PublishControlsProps) {\n * const apply = useApplyDocumentActions()\n *\n * const handlePublish = () => apply(publishDocument(doc))\n * const handleUnpublish = () => apply(unpublishDocument(doc))\n *\n * return (\n * <>\n * <button onClick={handlePublish}>Publish</button>\n * <button onClick={handleUnpublish}>Unpublish</button>\n * </>\n * )\n * }\n * ```\n *\n * @example Create and publish a new document\n * ```tsx\n * import {\n * createDocument,\n * publishDocument,\n * createDocumentHandle,\n * useApplyDocumentActions\n * } from '@sanity/sdk-react'\n *\n * function CreateAndPublishButton({documentType}: {documentType: string}) {\n * const apply = useApplyDocumentActions()\n *\n * const handleCreateAndPublish = () => {\n * // Create a new handle inside the handler\n * const newDocHandle = createDocumentHandle({ documentId: crypto.randomUUID(), documentType })\n *\n * // Apply multiple actions for the new handle as a single transaction\n * apply([\n * createDocument(newDocHandle),\n * publishDocument(newDocHandle),\n * ])\n * }\n *\n * return (\n * <button onClick={handleCreateAndPublish}>\n * I'm feeling lucky\n * </button>\n * )\n * }\n * ```\n *\n * @example Create a document with initial field values\n * ```tsx\n * import {\n * createDocument,\n * createDocumentHandle,\n * useApplyDocumentActions\n * } from '@sanity/sdk-react'\n *\n * function CreateArticleButton() {\n * const apply = useApplyDocumentActions()\n *\n * const handleCreateArticle = () => {\n * const newDocHandle = createDocumentHandle({\n * documentId: crypto.randomUUID(),\n * documentType: 'article'\n * })\n *\n * // Create document with initial values in one action\n * apply(\n * createDocument(newDocHandle, {\n * title: 'New Article',\n * author: 'John Doe',\n * publishedAt: new Date().toISOString(),\n * })\n * )\n * }\n *\n * return <button onClick={handleCreateArticle}>Create Article</button>\n * }\n * ```\n *\n * @example Create a new document in a release\n * ```tsx\n * import {\n * createDocument,\n * createDocumentHandle,\n * useApplyDocumentActions\n * } from '@sanity/sdk-react'\n *\n * function CreateArticleButton() {\n * const apply = useApplyDocumentActions()\n *\n * const handleCreateArticle = () => {\n * // Use any valid document ID — not the internal `versions.<releaseName>.<id>` format or \"drafts.<id>\" format.\n * // New documents must be explicitly created with `createDocument` to become part of a release.\n * const newDocHandle = createDocumentHandle({\n * documentId: crypto.randomUUID(), // or the existing document ID you want to make a release version of\n * documentType: 'article',\n * perspective: {releaseName: 'summer-drop'},\n * })\n *\n * apply(\n * createDocument(newDocHandle, {\n * title: 'New Article',\n * author: 'John Doe',\n * publishedAt: new Date().toISOString(),\n * })\n * )\n * }\n *\n * return <button onClick={handleCreateArticle}>Create Article</button>\n * }\n * ```\n *\n * @example Edit an existing document in a release\n * ```tsx\n * import {\n * editDocument,\n * createDocumentHandle,\n * useApplyDocumentActions\n * } from '@sanity/sdk-react'\n *\n * function EditArticleInReleaseButton({documentId}: {documentId: string}) {\n * const apply = useApplyDocumentActions()\n *\n * const handleEdit = () => {\n * // Pass the document's regular ID — not `versions.<releaseName>.<id>`.\n * // Documents that already have a version in the release can be edited directly with `editDocument`.\n * const docHandle = createDocumentHandle({\n * documentId,\n * documentType: 'article',\n * perspective: {releaseName: 'summer-drop'},\n * })\n *\n * apply(editDocument(docHandle, {set: {title: 'Updated for release'}}))\n * }\n *\n * return <button onClick={handleEdit}>Edit in Release</button>\n * }\n * ```\n */\nexport const useApplyDocumentActions: UseApplyDocumentActions = () => {\n return useApplyActions() as ReturnType<UseApplyDocumentActions>\n}\n","import {createDocument, type ResolveDocument} from '@sanity/sdk'\nimport {randomUuid} from '@sanity/sdk/_internal'\n\nimport {type DocumentHandle, type DocumentTypeHandle} from '../../config/handles'\nimport {useSanityInstance} from '../context/useSanityInstance'\nimport {trackHookUsage} from '../helpers/useTrackHookUsage'\nimport {useApplyDocumentActions} from './useApplyDocumentActions'\n\ntype IgnoredKey = '_id' | '_type' | '_rev' | '_createdAt' | '_updatedAt'\n\n/**\n * Optional per-call overrides for {@link useCreateDocument}'s create function.\n * @public\n */\nexport interface CreateDocumentOverrides {\n /**\n * Use this document ID instead of generating one. Overrides any `documentId`\n * supplied on the handle passed to `useCreateDocument`.\n */\n documentId?: string\n}\n\n// Overload 1: Typegen — infers the document shape from your schema.\n/**\n * @public\n * Create a new document, relying on Typegen for the initial-value type.\n *\n * @param options - A document-type handle including `documentType`, an optional `documentId`, and optionally `projectId`/`dataset`/`perspective`.\n * @returns A function that creates the document. It accepts optional initial field values and an optional `{documentId}` override,\n * and resolves to the {@link DocumentHandle} of the created document (carrying the generated or supplied id).\n */\nexport function useCreateDocument<\n TDocumentType extends string = string,\n TDataset extends string = string,\n TProjectId extends string = string,\n>(\n options: DocumentTypeHandle<TDocumentType, TDataset, TProjectId>,\n): (\n initialValue?: Partial<\n Omit<ResolveDocument<TDocumentType, `${TProjectId}.${TDataset}`>, IgnoredKey>\n >,\n overrides?: CreateDocumentOverrides,\n) => Promise<DocumentHandle<TDocumentType, TDataset, TProjectId>>\n\n// Overload 2: Explicit type `TData`.\n/**\n * @public\n * Create a new document with an explicit type `TData`.\n *\n * @param options - A document-type handle including `documentType` and optionally `projectId`/`dataset`/`perspective`.\n * @returns A function that creates the document. It accepts optional initial field values (typed against `TData`) and an\n * optional `{documentId}` override, and resolves to the {@link DocumentHandle} of the created document.\n */\nexport function useCreateDocument<TData extends Record<string, unknown>>(\n options: DocumentTypeHandle,\n): (\n initialValue?: Partial<Omit<TData, IgnoredKey>>,\n overrides?: CreateDocumentOverrides,\n) => Promise<DocumentHandle>\n\n/**\n * @public\n * Provides a function to create a new document and returns its handle.\n *\n * @category Documents\n * @remarks\n * This is the create counterpart to {@link useEditDocument}. It wraps\n * {@link useApplyDocumentActions} and the `createDocument` action for the common\n * single-document case, so you don't have to assemble the action by hand.\n *\n * It handles the document ID for you: if you don't supply one (on the handle or\n * via the per-call `{documentId}` override), a UUID is generated. Either way the\n * returned {@link DocumentHandle} carries that id, ready to pass to\n * {@link useDocument}, {@link useEditDocument}, or your router.\n *\n * Unlike {@link useEditDocument}, this hook does not read existing document state,\n * so it never suspends.\n *\n * For atomic create-and-publish, or for creating several documents in a single\n * transaction, use {@link useApplyDocumentActions} with the `createDocument` and\n * `publishDocument` action creators directly.\n *\n * @example Create a document and navigate to it\n * ```tsx\n * import {useCreateDocument} from '@sanity/sdk-react'\n * import {useNavigate} from 'react-router-dom'\n *\n * function CreateArticleButton() {\n * const createArticle = useCreateDocument({documentType: 'article'})\n * const navigate = useNavigate()\n *\n * const handleClick = async () => {\n * const handle = await createArticle({title: 'New Article'})\n * navigate(`/articles/${handle.documentId}`)\n * }\n *\n * return <button onClick={handleClick}>Create Article</button>\n * }\n * ```\n */\nexport function useCreateDocument(\n options: DocumentTypeHandle,\n): (\n initialValue?: Record<string, unknown>,\n overrides?: CreateDocumentOverrides,\n) => Promise<DocumentHandle> {\n const instance = useSanityInstance()\n trackHookUsage(instance, 'useCreateDocument')\n const apply = useApplyDocumentActions()\n\n return async (initialValue, overrides) => {\n const documentId = overrides?.documentId ?? options.documentId ?? randomUuid()\n const handle: DocumentHandle = {...options, documentId}\n await apply(createDocument(handle, initialValue))\n return handle\n }\n}\n","import {\n type DocumentOptions,\n getDocumentState,\n type JsonMatch,\n type ResolveDocument,\n resolveDocument,\n} from '@sanity/sdk'\nimport {identity} from 'rxjs'\n\nimport {type DocumentHandle} from '../../config/handles'\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\nimport {useNormalizedResourceOptions} from '../helpers/useNormalizedResourceOptions'\nimport {useTrackHookUsage} from '../helpers/useTrackHookUsage'\n// used in an `{@link useDocumentProjection}` and `{@link useQuery}`\n// eslint-disable-next-line import-x/consistent-type-specifier-style\nimport type {useDocumentProjection} from '../projection/useDocumentProjection'\n// eslint-disable-next-line import-x/consistent-type-specifier-style\nimport type {useQuery} from '../query/useQuery'\n\nconst useDocumentValue = createStateSourceHook({\n // Pass options directly to getDocumentState\n getState: (instance, options: DocumentOptions<string | undefined>) =>\n getDocumentState(instance, options),\n // Pass options directly to getDocumentState for checking current value\n shouldSuspend: (instance, {path: _path, ...options}: DocumentOptions<string | undefined>) =>\n getDocumentState(instance, options).getCurrent() === undefined,\n // Extract handle part for resolveDocument\n suspender: (instance, options: DocumentOptions<string | undefined>) =>\n resolveDocument(instance, options),\n getConfig: identity as (\n options: DocumentOptions<string | undefined>,\n ) => DocumentOptions<string | undefined>,\n})\n\nconst wrapHookWithData = <TParams extends unknown[], TReturn>(\n useValue: (...params: TParams) => TReturn,\n) => {\n function useHook(...params: TParams) {\n return {data: useValue(...params)}\n }\n return useHook\n}\n\ntype UseDocumentOptions<\n TPath extends string | undefined = undefined,\n TDocumentType extends string = string,\n TDataset extends string = string,\n TProjectId extends string = string,\n> = DocumentHandle<TDocumentType, TDataset, TProjectId> & {path?: TPath}\n\ninterface UseDocument {\n /** @internal */\n <TDocumentType extends string, TDataset extends string, TProjectId extends string = string>(\n options: UseDocumentOptions<undefined, TDocumentType, TDataset, TProjectId>,\n ): {data: ResolveDocument<TDocumentType, `${TProjectId}.${TDataset}`> | null}\n\n /** @internal */\n <\n TPath extends string,\n TDocumentType extends string,\n TDataset extends string = string,\n TProjectId extends string = string,\n >(\n options: UseDocumentOptions<TPath, TDocumentType>,\n ): {\n data: JsonMatch<ResolveDocument<TDocumentType, `${TProjectId}.${TDataset}`>, TPath> | undefined\n }\n\n /** @internal */\n <TData>(options: DocumentOptions<undefined>): {data: TData | null}\n /** @internal */\n <TData>(options: DocumentOptions<string>): {data: TData | undefined}\n\n /**\n * ## useDocument via Type Inference (Recommended)\n *\n * @public\n *\n * The preferred way to use this hook when working with Sanity Typegen.\n *\n * Features:\n * - Automatically infers document types from your schema\n * - Provides type-safe access to documents and nested fields\n * - Supports project/dataset-specific type inference\n * - Works seamlessly with Typegen-generated types\n *\n * This hook will suspend while the document data is being fetched and loaded.\n *\n * When fetching a full document:\n * - Returns the complete document object if it exists\n * - Returns `null` if the document doesn't exist\n *\n * When fetching with a path:\n * - Returns the value at the specified path if both the document and path exist\n * - Returns `undefined` if either the document doesn't exist or the path doesn't exist in the document\n *\n * @category Documents\n * @param options - Configuration including `documentId`, `documentType`, and optionally:\n * - `path`: To select a nested value (returns typed value at path)\n * - `projectId`/`dataset`: For multi-project/dataset setups\n * @returns The document state (or nested value if path provided).\n *\n * @example Basic document fetch\n * ```tsx\n * import {useDocument, type DocumentHandle} from '@sanity/sdk-react'\n *\n * interface ProductViewProps {\n * doc: DocumentHandle<'product'> // Typegen infers product type\n * }\n *\n * function ProductView({doc}: ProductViewProps) {\n * const {data: product} = useDocument({...doc}) // Fully typed product\n * return <h1>{product.title ?? 'Untitled'}</h1>\n * }\n * ```\n *\n * @example Fetching a specific field\n * ```tsx\n * import {useDocument, type DocumentHandle} from '@sanity/sdk-react'\n *\n * interface ProductTitleProps {\n * doc: DocumentHandle<'product'>\n * }\n *\n * function ProductTitle({doc}: ProductTitleProps) {\n * const {data: title} = useDocument({\n * ...doc,\n * path: 'title' // Returns just the title field\n * })\n * return <h1>{title ?? 'Untitled'}</h1>\n * }\n * ```\n *\n * @inlineType DocumentOptions\n */\n <\n TPath extends string | undefined = undefined,\n TDocumentType extends string = string,\n TDataset extends string = string,\n TProjectId extends string = string,\n >(\n options: UseDocumentOptions<TPath, TDocumentType>,\n ): TPath extends string\n ? {\n data:\n | JsonMatch<ResolveDocument<TDocumentType, `${TProjectId}.${TDataset}`>, TPath>\n | undefined\n }\n : {data: ResolveDocument<TDocumentType, `${TProjectId}.${TDataset}`> | null}\n\n /**\n * @public\n *\n * ## useDocument via Explicit Types\n *\n * Use this version when:\n * - You're not using Sanity Typegen\n * - You need to manually specify document types\n * - You're working with dynamic document types\n *\n * Key differences from Typegen version:\n * - Requires manual type specification via `TData`\n * - Returns `TData | null` for full documents\n * - Returns `TData | undefined` for nested values\n *\n * This hook will suspend while the document data is being fetched.\n *\n * @typeParam TData - The explicit type for the document or field\n * @typeParam TPath - Optional path to a nested value\n * @param options - Configuration including `documentId` and optionally:\n * - `path`: To select a nested value\n * - `projectId`/`dataset`: For multi-project/dataset setups\n * @returns The document state (or nested value if path provided)\n *\n * @example Basic document fetch with explicit type\n * ```tsx\n * import {useDocument, type DocumentHandle, type SanityDocument} from '@sanity/sdk-react'\n *\n * interface Book extends SanityDocument {\n * _type: 'book'\n * title: string\n * author: string\n * }\n *\n * interface BookViewProps {\n * doc: DocumentHandle\n * }\n *\n * function BookView({doc}: BookViewProps) {\n * const {data: book} = useDocument<Book>({...doc})\n * return <h1>{book?.title ?? 'Untitled'} by {book?.author ?? 'Unknown'}</h1>\n * }\n * ```\n *\n * @example Fetching a specific field with explicit type\n * ```tsx\n * import {useDocument, type DocumentHandle} from '@sanity/sdk-react'\n *\n * interface BookTitleProps {\n * doc: DocumentHandle\n * }\n *\n * function BookTitle({doc}: BookTitleProps) {\n * const {data: title} = useDocument<string>({...doc, path: 'title'})\n * return <h1>{title ?? 'Untitled'}</h1>\n * }\n * ```\n *\n * @inlineType DocumentOptions\n */\n <TData, TPath extends string>(\n options: UseDocumentOptions<TPath>,\n ): TPath extends string ? {data: TData | undefined} : {data: TData | null}\n\n /**\n * @internal\n */\n (options: UseDocumentOptions): {data: unknown}\n}\n\n/**\n * @public\n * Reads and subscribes to a document's realtime state, incorporating both local and remote changes.\n *\n * This hook comes in two main flavors to suit your needs:\n *\n * 1. **[Type Inference](#usedocument-via-type-inference-recommended)** (Recommended) - Automatically gets types from your Sanity schema\n * 2. **[Explicit Types](#usedocument-via-explicit-types)** - Manually specify types when needed\n *\n * @remarks\n * `useDocument` is ideal for realtime editing interfaces where you need immediate feedback on changes.\n * However, it can be resource-intensive since it maintains a realtime connection.\n *\n * For simpler cases where:\n * - You only need to display content\n * - Realtime updates aren't critical\n * - You want better performance\n *\n * …consider using {@link useDocumentProjection} or {@link useQuery} instead. These hooks are more efficient\n * for read-heavy applications.\n *\n * @function\n */\nexport const useDocument = wrapHookWithData((options: UseDocumentOptions) => {\n useTrackHookUsage('useDocument')\n const normalizedOptions = useNormalizedResourceOptions(options)\n return useDocumentValue(normalizedOptions)\n}) as UseDocument\n","import {type DocumentEvent, subscribeDocumentEvents} from '@sanity/sdk'\nimport {useCallback, useEffect, useInsertionEffect, useRef} from 'react'\n\nimport {type ResourceHandle} from '../../config/handles'\nimport {useSanityInstance} from '../context/useSanityInstance'\nimport {useNormalizedResourceOptions} from '../helpers/useNormalizedResourceOptions'\nimport {useTrackHookUsage} from '../helpers/useTrackHookUsage'\n\n/**\n * @public\n */\nexport interface UseDocumentEventOptions<\n TDataset extends string = string,\n TProjectId extends string = string,\n> extends ResourceHandle<TDataset, TProjectId> {\n onEvent: (documentEvent: DocumentEvent) => void\n}\n\n/**\n *\n * @public\n *\n * Subscribes an event handler to events in your application's document store.\n *\n * @category Documents\n * @param options - An object containing the event handler (`onEvent`) and optionally a `DatasetHandle` (projectId and dataset). If the handle is not provided, the nearest Sanity instance from context will be used.\n * @example Creating a custom hook for document event toasts\n * ```tsx\n * import {createDatasetHandle, type DatasetHandle, type DocumentEvent, useDocumentEvent} from '@sanity/sdk-react'\n * import {useToast} from './my-ui-library'\n *\n * // Define options for the custom hook, extending DatasetHandle\n * interface DocumentToastsOptions extends DatasetHandle {\n * // Could add more options, e.g., { includeEvents: DocumentEvent['type'][] }\n * }\n *\n * // Define the custom hook\n * function useDocumentToasts({...datasetHandle}: DocumentToastsOptions = {}) {\n * const showToast = useToast() // Get the toast function\n *\n * // Define the event handler logic to show toasts on specific events\n * const handleEvent = (event: DocumentEvent) => {\n * if (event.type === 'published') {\n * showToast(`Document ${event.documentId} published.`)\n * } else if (event.type === 'unpublished') {\n * showToast(`Document ${event.documentId} unpublished.`)\n * } else if (event.type === 'deleted') {\n * showToast(`Document ${event.documentId} deleted.`)\n * } else {\n * // Optionally log other events for debugging\n * console.log('Document Event:', event.type, event.documentId)\n * }\n * }\n *\n * // Call the original hook, spreading the handle properties\n * useDocumentEvent({\n * ...datasetHandle, // Spread the dataset handle (projectId, dataset)\n * onEvent: handleEvent,\n * })\n * }\n *\n * function MyComponentWithToasts() {\n * // Use the custom hook, passing specific handle info\n * const specificHandle = createDatasetHandle({ projectId: 'p1', dataset: 'ds1' })\n * useDocumentToasts(specificHandle)\n *\n * // // Or use it relying on context for the handle\n * // useDocumentToasts()\n *\n * return <div>...</div>\n * }\n * ```\n */\nexport function useDocumentEvent<\n TDataset extends string = string,\n TProjectId extends string = string,\n>(\n // Single options object parameter\n options: UseDocumentEventOptions<TDataset, TProjectId>,\n): void {\n useTrackHookUsage('useDocumentEvent')\n // Destructure handler and datasetHandle from options\n const normalizedOptions = useNormalizedResourceOptions(options)\n const {onEvent, ...datasetHandle} = normalizedOptions\n const ref = useRef(onEvent)\n\n useInsertionEffect(() => {\n ref.current = onEvent\n })\n\n const stableHandler = useCallback((documentEvent: DocumentEvent) => {\n return ref.current(documentEvent)\n }, [])\n\n const instance = useSanityInstance()\n useEffect(() => {\n return subscribeDocumentEvents(instance, {\n eventHandler: stableHandler,\n resource: datasetHandle.resource,\n })\n }, [instance, datasetHandle.resource, stableHandler])\n}\n","import {type DocumentAction, type DocumentPermissionsResult, getPermissionsState} from '@sanity/sdk'\nimport {isDeepEqual} from '@sanity/sdk/_internal'\nimport {useCallback, useContext, useMemo, useSyncExternalStore} from 'react'\nimport {filter, firstValueFrom} from 'rxjs'\n\nimport {ResourcesContext} from '../../context/ResourcesContext'\nimport {useSanityInstance} from '../context/useSanityInstance'\nimport {\n normalizeResourceOptions,\n useEffectiveContextResource,\n type WithResourceNameSupport,\n} from '../helpers/useNormalizedResourceOptions'\nimport {trackHookUsage} from '../helpers/useTrackHookUsage'\n\nconst noopSubscribe = () => () => {}\nconst returnUndefined = () => undefined\n\n/**\n *\n * @public\n *\n * Check if the current user has the specified permissions for the given document actions.\n *\n * @category Permissions\n * @param actionOrActions - One or more document action functions (e.g., `publishDocument(handle)`).\n * @returns An object that specifies whether the action is allowed; if the action is not allowed, an explanatory message and list of reasons is also provided.\n *\n * @remarks\n * When passing multiple actions, all actions must belong to the same project and dataset.\n * Note, however, that you can check permissions on multiple documents from the same project and dataset (as in the second example below).\n *\n * @example Checking for permission to publish a document\n * ```tsx\n * import {\n * useDocumentPermissions,\n * useApplyDocumentActions,\n * publishDocument,\n * createDocumentHandle,\n * type DocumentHandle\n * } from '@sanity/sdk-react'\n *\n * // Define props using the DocumentHandle type\n * interface PublishButtonProps {\n * doc: DocumentHandle\n * }\n *\n * function PublishButton({doc}: PublishButtonProps) {\n * const publishAction = publishDocument(doc)\n *\n * // Pass the same action call to check permissions\n * const publishPermissions = useDocumentPermissions(publishAction)\n * const apply = useApplyDocumentActions()\n *\n * return (\n * <>\n * <button\n * disabled={!publishPermissions.allowed}\n * // Pass the same action call to apply the action\n * onClick={() => apply(publishAction)}\n * popoverTarget={`${publishPermissions.allowed ? undefined : 'publishButtonPopover'}`}\n * >\n * Publish\n * </button>\n * {!publishPermissions.allowed && (\n * <div popover id=\"publishButtonPopover\">\n * {publishPermissions.message}\n * </div>\n * )}\n * </>\n * )\n * }\n *\n * // Usage:\n * // const doc = createDocumentHandle({ documentId: 'doc1', documentType: 'myType' })\n * // <PublishButton doc={doc} />\n * ```\n *\n * @example Checking for permissions to edit multiple documents\n * ```tsx\n * import {\n * useDocumentPermissions,\n * editDocument,\n * type DocumentHandle\n * } from '@sanity/sdk-react'\n *\n * export default function canEditMultiple(docHandles: DocumentHandle[]) {\n * // Create an array containing an editDocument action for each of the document handles\n * const editActions = docHandles.map(doc => editDocument(doc))\n *\n * // Return the result of checking for edit permissions on all of the document handles\n * return useDocumentPermissions(editActions)\n * }\n * ```\n */\nexport function useDocumentPermissions(\n actionOrActions:\n | WithResourceNameSupport<DocumentAction>\n | WithResourceNameSupport<DocumentAction>[],\n): DocumentPermissionsResult {\n const instance = useSanityInstance()\n trackHookUsage(instance, 'useDocumentPermissions')\n const effectiveContextResource = useEffectiveContextResource()\n const resources = useContext(ResourcesContext)\n\n const {\n actions: normalizedActions,\n resource: actionResource,\n error: validationError,\n } = useMemo(() => {\n const normalized = Array.isArray(actionOrActions)\n ? actionOrActions.map((action) =>\n normalizeResourceOptions(action, resources, effectiveContextResource),\n )\n : [normalizeResourceOptions(actionOrActions, resources, effectiveContextResource)]\n\n let resource\n for (const action of normalized) {\n if (action.resource) {\n if (!resource) resource = action.resource\n if (!isDeepEqual(action.resource, resource)) {\n return {\n actions: normalized,\n resource,\n error: new Error(\n `Mismatched resources found in actions. All actions must belong to the same resource. Found \"${JSON.stringify(action.resource)}\" but expected \"${JSON.stringify(resource)}\".`,\n ),\n }\n }\n }\n }\n return {actions: normalized, resource, error: undefined}\n }, [actionOrActions, resources, effectiveContextResource])\n\n const effectiveResource = actionResource ?? effectiveContextResource\n\n // Keep hooks unconditional — validation errors and missing-resource errors are\n // thrown after all hooks so that the hook call count stays stable across renders.\n const permissionsOptions = useMemo(\n () =>\n effectiveResource\n ? {\n resource: effectiveResource,\n // `Omit<>` on `DocumentAction` loses the discriminant; runtime values are still actions.\n actions: normalizedActions as DocumentAction[],\n }\n : undefined,\n [effectiveResource, normalizedActions],\n )\n\n const stateSource = useMemo(\n () => (permissionsOptions ? getPermissionsState(instance, permissionsOptions) : undefined),\n [permissionsOptions, instance],\n )\n\n const isDocumentReady = useCallback(\n () => stateSource !== undefined && stateSource.getCurrent() !== undefined,\n [stateSource],\n )\n\n const result = useSyncExternalStore(\n stateSource?.subscribe ?? noopSubscribe,\n stateSource?.getCurrent ?? returnUndefined,\n )\n\n // All hooks have been called — safe to throw now.\n if (validationError) throw validationError\n if (!effectiveResource) {\n throw new Error(\n 'No resource found. Provide a resource via the action handle or wrap with a resource context.',\n )\n }\n if (!isDocumentReady()) {\n throw firstValueFrom(\n stateSource!.observable.pipe(filter((permissions) => permissions !== undefined)),\n )\n }\n\n return result as DocumentPermissionsResult\n}\n","import {\n type DocumentHandle,\n type DocumentOptions,\n getDocumentSyncStatus,\n resolveDocument,\n type SanityInstance,\n type StateSource,\n} from '@sanity/sdk'\nimport {identity} from 'rxjs'\n\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\nimport {useNormalizedResourceOptions} from '../helpers/useNormalizedResourceOptions'\n\ntype UseDocumentSyncStatus = {\n /**\n * Exposes the document's sync status between local and remote document states.\n *\n * @category Documents\n * @param doc - The document handle to get sync status for. If you pass a `DocumentHandle` with specified `projectId` and `dataset`,\n * the document will be read from the specified Sanity project and dataset that is included in the handle. If no `projectId` or `dataset` is provided,\n * the document will use the nearest instance from context.\n * @returns `true` if local changes are synced with remote, `false` if changes are pending. Note: Suspense handles loading states.\n * @example Show sync status indicator\n * ```tsx\n * import {useDocumentSyncStatus, createDocumentHandle, type DocumentHandle} from '@sanity/sdk-react'\n *\n * // Define props including the DocumentHandle type\n * interface SyncIndicatorProps {\n * doc: DocumentHandle\n * }\n *\n * function SyncIndicator({doc}: SyncIndicatorProps) {\n * const isSynced = useDocumentSyncStatus(doc)\n *\n * return (\n * <div className={`sync-status ${isSynced ? 'synced' : 'pending'}`}>\n * {isSynced ? '✓ Synced' : 'Saving changes...'}\n * </div>\n * )\n * }\n *\n * // Usage:\n * // const doc = createDocumentHandle({ documentId: 'doc1', documentType: 'myType' })\n * // <SyncIndicator doc={doc} />\n * ```\n */\n (doc: DocumentHandle): boolean\n}\n\nconst useDocumentSyncStatusValue = createStateSourceHook({\n getState: getDocumentSyncStatus as (\n instance: SanityInstance,\n doc: DocumentHandle,\n ) => StateSource<boolean>,\n shouldSuspend: (instance, doc: DocumentHandle) =>\n getDocumentSyncStatus(instance, doc).getCurrent() === undefined,\n suspender: (instance, doc: DocumentHandle) => resolveDocument(instance, doc),\n getConfig: identity,\n})\n\n/**\n * @public\n * @function\n */\nexport const useDocumentSyncStatus: UseDocumentSyncStatus = (\n options: DocumentOptions<string | undefined>,\n) => {\n const normalizedOptions = useNormalizedResourceOptions(options)\n return useDocumentSyncStatusValue(normalizedOptions)\n}\n","import {\n type ActionsResult,\n type DocumentOptions,\n editDocument,\n getDocumentState,\n type JsonMatch,\n type ResolveDocument,\n resolveDocument,\n} from '@sanity/sdk'\nimport {useCallback} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\nimport {useNormalizedResourceOptions} from '../helpers/useNormalizedResourceOptions'\nimport {trackHookUsage} from '../helpers/useTrackHookUsage'\nimport {useApplyDocumentActions} from './useApplyDocumentActions'\n\nconst ignoredKeys = ['_id', '_type', '_createdAt', '_updatedAt', '_rev']\n\ntype Updater<TValue> = TValue | ((currentValue: TValue) => TValue)\n\n// Overload 1: No path, relies on Typegen\n/**\n * @public\n * Edit an entire document, relying on Typegen for the type.\n *\n * @param options - Document options including `documentId`, `documentType`, and optionally `projectId`/`dataset`.\n * @returns A stable function to update the document state. Accepts either the new document state or an updater function `(currentValue) => nextValue`.\n * Returns a promise resolving to the {@link ActionsResult}.\n */\nexport function useEditDocument<\n TDocumentType extends string = string,\n TDataset extends string = string,\n TProjectId extends string = string,\n>(\n options: DocumentOptions<undefined, TDocumentType, TDataset, TProjectId>,\n): (\n nextValue: Updater<ResolveDocument<TDocumentType, `${TProjectId}.${TDataset}`>>,\n) => Promise<ActionsResult<ResolveDocument<TDocumentType, `${TProjectId}.${TDataset}`>>>\n\n// Overload 2: Path provided, relies on Typegen\n/**\n * @public\n * Edit a specific path within a document, relying on Typegen for the type.\n *\n * @param options - Document options including `documentId`, `documentType`, `path`, and optionally `projectId`/`dataset`.\n * @returns A stable function to update the value at the specified path. Accepts either the new value or an updater function `(currentValue) => nextValue`.\n * Returns a promise resolving to the {@link ActionsResult}.\n */\nexport function useEditDocument<\n TPath extends string = string,\n TDocumentType extends string = string,\n TDataset extends string = string,\n TProjectId extends string = string,\n>(\n options: DocumentOptions<TPath, TDocumentType, TDataset, TProjectId>,\n): (\n nextValue: Updater<JsonMatch<ResolveDocument<TDocumentType, `${TProjectId}.${TDataset}`>, TPath>>,\n) => Promise<ActionsResult<ResolveDocument<TDocumentType, `${TProjectId}.${TDataset}`>>>\n\n// Overload 3: Explicit type, no path\n/**\n * @public\n * Edit an entire document with an explicit type `TData`.\n *\n * @param options - Document options including `documentId` and optionally `projectId`/`dataset`.\n * @returns A stable function to update the document state. Accepts either the new document state (`TData`) or an updater function `(currentValue: TData) => nextValue: TData`.\n * Returns a promise resolving to the {@link ActionsResult}.\n */\nexport function useEditDocument<TData>(\n options: DocumentOptions<undefined>,\n): (nextValue: Updater<TData>) => Promise<ActionsResult>\n\n// Overload 4: Explicit type, path provided\n/**\n * @public\n * Edit a specific path within a document with an explicit type `TData`.\n *\n * @param options - Document options including `documentId`, `path`, and optionally `projectId`/`dataset`.\n * @returns A stable function to update the value at the specified path. Accepts either the new value (`TData`) or an updater function `(currentValue: TData) => nextValue: TData`.\n * Returns a promise resolving to the {@link ActionsResult}.\n */\nexport function useEditDocument<TData>(\n options: DocumentOptions<string>,\n): (nextValue: Updater<TData>) => Promise<ActionsResult>\n\n/**\n * @public\n * Provides a stable function to apply edits to a document or a specific path within it.\n *\n * @category Documents\n * @remarks\n * This hook simplifies editing documents by automatically:\n * - Comparing the current and next states to determine the minimal set of `set` and `unset` operations required for the update via `editDocument`.\n * - Handling both full document updates and specific path updates.\n * - Supporting functional updates (e.g., `edit(prev => ({...prev, title: 'New'}))`).\n * - Integrating with the active {@link SanityInstance} context.\n * - Utilizing `useApplyDocumentActions` internally for optimistic updates and transaction handling.\n *\n * It offers several overloads for flexibility:\n * 1. **Typegen (Full Document):** Edit the entire document, inferring types from your schema.\n * 2. **Typegen (Specific Path):** Edit a specific field, inferring types.\n * 3. **Explicit Type (Full Document):** Edit the entire document with a manually specified type.\n * 4. **Explicit Type (Specific Path):** Edit a specific field with a manually specified type.\n *\n * **LiveEdit Documents:**\n * For documents using {@link DocumentHandle.liveEdit | liveEdit mode} (set via `liveEdit: true` in the document handle), edits are applied directly to the published document without creating a draft.\n *\n * This hook relies on the document state being loaded. If the document is not yet available\n * (e.g., during initial load), the component using this hook will suspend.\n *\n * @example Basic Usage (Typegen, Full Document)\n * ```tsx\n * import {useCallback} from 'react';\n * import {useEditDocument, useDocument, type DocumentHandle} from '@sanity/sdk-react'\n *\n * // Assume 'product' schema has a 'title' field (string)\n * interface ProductEditorProps {\n * productHandle: DocumentHandle<'product'> // Typegen infers 'product' type\n * }\n *\n * function ProductEditor({ productHandle }: ProductEditorProps) {\n * // Fetch the document to display its current state (optional)\n * const {data: product} = useDocument(productHandle);\n * // Get the edit function for the full document\n * const editProduct = useEditDocument(productHandle);\n *\n * // Use useCallback for stable event handlers\n * const handleTitleChange = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {\n * const newTitle = event.target.value;\n * // Use the functional updater for safe partial updates\n * editProduct(prev => ({\n * ...prev,\n * title: newTitle,\n * })).\n * }, [editProduct]);\n *\n * return (\n * <div>\n * <label>\n * Product Title:\n * <input\n * type=\"text\"\n * value={product?.title ?? ''}\n * onChange={handleTitleChange}\n * />\n * </label>\n * </div>\n * );\n * }\n * ```\n *\n * @example Editing a Specific Path (Typegen)\n * ```tsx\n * import React, { useCallback } from 'react';\n * import {useEditDocument, useDocument, type DocumentHandle, type DocumentOptions} from '@sanity/sdk-react'\n *\n * // Assume 'product' schema has a 'price' field (number)\n * interface ProductPriceEditorProps {\n * productHandle: DocumentHandle<'product'>;\n * }\n *\n * function ProductPriceEditor({ productHandle }: ProductPriceEditorProps) {\n * // Construct DocumentOptions internally, combining the handle and a hardcoded path\n * const priceOptions {\n * ...productHandle,\n * path: 'price', // Hardcode the path to edit\n * };\n *\n * // Fetch the current price to display it\n * const {data: currentPrice} = useDocument(priceOptions);\n * // Get the edit function for the specific path 'price'\n * const editPrice = useEditDocument(priceOptions);\n *\n * const handleSetFixedPrice = useCallback(() => {\n * // Update the price directly to a hardcoded value\n * editPrice(99.99)\n * }, [editPrice]);\n *\n * return (\n * <div>\n * <p>Current Price: {currentPrice}</p>\n * <button onClick={handleSetFixedPrice}>\n * Set Price to $99.99\n * </button>\n * </div>\n * );\n * }\n *\n * ```\n *\n * @example Usage with Explicit Types (Full Document)\n * ```tsx\n * import React, { useCallback } from 'react';\n * import {useEditDocument, useDocument, type DocumentHandle, type SanityDocument} from '@sanity/sdk-react'\n *\n * interface Book extends SanityDocument { _type: 'book', title: string, author: string }\n *\n * interface BookEditorProps {\n * bookHandle: DocumentHandle // No documentType needed if providing TData\n * }\n *\n * function BookEditor({ bookHandle }: BookEditorProps) {\n * const {data: book} = useDocument<Book>(bookHandle);\n * // Provide the explicit type <Book>\n * const editBook = useEditDocument<Book>(bookHandle);\n *\n * const handleAuthorChange = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {\n * const newAuthor = event.target.value;\n * editBook(prev => ({\n * ...prev,\n * author: newAuthor\n * }))\n * }, [editBook]);\n *\n * return (\n * <div>\n * <label>\n * Book Author:\n * <input\n * type=\"text\"\n * value={book?.author ?? ''}\n * onChange={handleAuthorChange}\n * />\n * </label>\n * </div>\n * );\n * }\n *\n * ```\n *\n * @example Usage with Explicit Types (Specific Path)\n * ```tsx\n * import React, { useCallback } from 'react';\n * import {useEditDocument, useDocument, type DocumentHandle, type DocumentOptions} from '@sanity/sdk-react'\n *\n * // Assume 'book' has 'author.name' (string)\n * interface AuthorNameEditorProps {\n * bookHandle: DocumentHandle; // No documentType needed if providing TData for path\n * }\n *\n * function AuthorNameEditor({ bookHandle }: AuthorNameEditorProps) {*\n * // Fetch current value\n * const {data: currentName} = useDocument<string>({...bookHandle, path: 'author.name'});\n * // Provide the explicit type <string> for the path's value\n * const editAuthorName = useEditDocument<string>({...bookHandle, path: 'author.name'});\n *\n * const handleUpdate = useCallback(() => {\n * // Update with a hardcoded string directly\n * editAuthorName('Jane Doe')\n * }, [editAuthorName]);\n *\n * return (\n * <div>\n * <p>Current Author Name: {currentName}</p>\n * <button onClick={handleUpdate} disabled={currentName === undefined}>\n * Set Author Name to Jane Doe\n * </button>\n * </div>\n * );\n * }\n *\n * ```\n *\n * @example Edit a document in a release\n * ```tsx\n * import {useEditDocument} from '@sanity/sdk-react'\n *\n * function EditArticleInRelease({documentId}: {documentId: string}) {\n * // Use the document's plain ID — not `versions.<releaseName>.<id>`.\n * // The document must already exist in the release (added via `createDocument` first).\n * const editArticle = useEditDocument({\n * documentId,\n * documentType: 'article',\n * perspective: {releaseName: 'summer-drop'},\n * })\n *\n * return (\n * <button onClick={() => editArticle(prev => ({...prev, title: 'Updated for release'}))}>\n * Edit in Release\n * </button>\n * )\n * }\n * ```\n */\nexport function useEditDocument({\n path,\n ...doc\n}: DocumentOptions<string | undefined>): (updater: Updater<unknown>) => Promise<ActionsResult> {\n const instance = useSanityInstance()\n trackHookUsage(instance, 'useEditDocument')\n const normalizedDoc = useNormalizedResourceOptions(doc)\n\n const apply = useApplyDocumentActions()\n const isDocumentReady = useCallback(\n () => getDocumentState(instance, normalizedDoc).getCurrent() !== undefined,\n [instance, normalizedDoc],\n )\n if (!isDocumentReady()) throw resolveDocument(instance, normalizedDoc)\n\n return (updater: Updater<unknown>) => {\n const currentPath = path\n\n if (currentPath) {\n const stateWithOptions = getDocumentState(instance, {...normalizedDoc, path})\n const currentValue = stateWithOptions.getCurrent()\n\n const nextValue =\n typeof updater === 'function'\n ? (updater as (prev: typeof currentValue) => typeof currentValue)(currentValue)\n : updater\n\n return apply(editDocument(normalizedDoc, {set: {[currentPath]: nextValue}}))\n }\n\n const fullDocState = getDocumentState(instance, {...normalizedDoc, path})\n const current = fullDocState.getCurrent() as object | null | undefined\n const nextValue =\n typeof updater === 'function'\n ? (updater as (prev: typeof current) => typeof current)(current)\n : updater\n\n if (typeof nextValue !== 'object' || !nextValue) {\n throw new Error(\n `No path was provided to \\`useEditDocument\\` and the value provided was not a document object.`,\n )\n }\n\n const allKeys = Object.keys({...current, ...nextValue})\n const editActions = allKeys\n .filter((key) => !ignoredKeys.includes(key))\n .filter(\n (key) =>\n current?.[key as keyof typeof current] !== (nextValue as Record<string, unknown>)[key],\n )\n .map((key) =>\n key in nextValue\n ? editDocument(normalizedDoc, {set: {[key]: (nextValue as Record<string, unknown>)[key]}})\n : editDocument(normalizedDoc, {unset: [key]}),\n )\n\n return apply(editActions)\n }\n}\n","import {getQueryState, type QueryOptions, resolveQuery, type ResolveQueryResult} from '@sanity/sdk'\nimport {getQueryKey, parseQueryKey} from '@sanity/sdk/_internal'\nimport {useEffect, useMemo, useRef, useState, useSyncExternalStore, useTransition} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\nimport {\n useNormalizedResourceOptions,\n type WithResourceNameSupport,\n} from '../helpers/useNormalizedResourceOptions'\nimport {trackHookUsage} from '../helpers/useTrackHookUsage'\n/**\n * Hook options for useQuery, supporting both direct resource and resourceName.\n * @beta\n */\ntype UseQueryOptions<\n TQuery extends string = string,\n TDataset extends string = string,\n TProjectId extends string = string,\n> = WithResourceNameSupport<QueryOptions<TQuery, TDataset, TProjectId>>\n\n// Overload 1: Inferred Type (using Typegen)\n/**\n * @public\n * Executes a GROQ query, inferring the result type from the query string and options.\n * Leverages Sanity Typegen if configured for enhanced type safety.\n *\n * @param options - Configuration for the query, including `query`, optional `params`, `projectId`, `dataset`, etc.\n * @returns An object containing `data` (typed based on the query) and `isPending` (for transitions).\n *\n * @example Basic usage (Inferred Type)\n * ```tsx\n * import {useQuery} from '@sanity/sdk-react'\n * import {defineQuery} from 'groq'\n *\n * const myQuery = defineQuery(`*[_type == \"movie\"]{_id, title}`)\n *\n * function MovieList() {\n * // Typegen infers the return type for data\n * const {data} = useQuery({ query: myQuery })\n *\n * return (\n * <div>\n * <h2>Movies</h2>\n * <ul>\n * {data.map(movie => <li key={movie._id}>{movie.title}</li>)}\n * </ul>\n * </div>\n * )\n * }\n * // Suspense boundary should wrap <MovieList /> for initial load\n * ```\n *\n * @example Using parameters (Inferred Type)\n * ```tsx\n * import {useQuery} from '@sanity/sdk-react'\n * import {defineQuery} from 'groq'\n *\n * const myQuery = defineQuery(`*[_type == \"movie\" && _id == $id][0]`)\n *\n * function MovieDetails({movieId}: {movieId: string}) {\n * // Typegen infers the return type based on query and params\n * const {data, isPending} = useQuery({\n * query: myQuery,\n * params: { id: movieId }\n * })\n *\n * return (\n * // utilize `isPending` to signal to users that new data is coming in\n * // (e.g. the `movieId` changed and we're loading in the new one)\n * <div style={{ opacity: isPending ? 0.5 : 1 }}>\n * {data ? <h1>{data.title}</h1> : <p>Movie not found</p>}\n * </div>\n * )\n * }\n * ```\n */\nexport function useQuery<\n TQuery extends string = string,\n TDataset extends string = string,\n TProjectId extends string = string,\n>(\n options: UseQueryOptions<TQuery, TDataset, TProjectId>,\n): {\n /** The query result, typed based on the GROQ query string */\n data: ResolveQueryResult<TQuery, `${TProjectId}.${TDataset}`>\n /** True if a query transition is in progress */\n isPending: boolean\n}\n\n// Overload 2: Explicit Type Provided\n/**\n * @public\n * Executes a GROQ query with an explicitly provided result type `TData`.\n *\n * @param options - Configuration for the query, including `query`, optional `params`, `projectId`, `dataset`, etc.\n * @returns An object containing `data` (cast to `TData`) and `isPending` (indicates whether a query resolution is pending; note that Suspense handles initial loading states). *\n * @example Manually typed query result\n * ```tsx\n * import {useQuery} from '@sanity/sdk-react'\n *\n * interface CustomMovieTitle {\n * movieTitle?: string\n * }\n *\n * function FirstMovieTitle() {\n * // Provide the explicit type TData\n * const {data, isPending} = useQuery<CustomMovieTitle>({\n * query: '*[_type == \"movie\"][0]{ \"movieTitle\": title }'\n * })\n *\n * return (\n * <h1 style={{ opacity: isPending ? 0.5 : 1 }}>\n * {data?.movieTitle ?? 'No title found'}\n * </h1>\n * )\n * }\n * ```\n */\nexport function useQuery<TData>(options: WithResourceNameSupport<QueryOptions>): {\n /** The query result, cast to the provided type TData */\n data: TData\n /** True if another query is resolving in the background (suspense handles the initial loading state) */\n isPending: boolean\n}\n\n/**\n * @public\n * Fetches data and subscribes to real-time updates using a GROQ query.\n *\n * @remarks\n * This hook provides a convenient way to fetch data from your Sanity dataset and\n * automatically receive updates in real-time when the queried data changes.\n *\n * Features:\n * - Executes any valid GROQ query.\n * - Subscribes to changes, providing real-time updates.\n * - Integrates with React Suspense for handling initial loading states.\n * - Uses React Transitions for managing loading states during query/parameter changes (indicated by `isPending`).\n * - Supports type inference based on the GROQ query when using Sanity Typegen.\n * - Allows specifying an explicit return type `TData` for the query result.\n *\n * @category GROQ\n */\nexport function useQuery(options: WithResourceNameSupport<QueryOptions>): {\n data: unknown\n isPending: boolean\n} {\n // Implementation returns unknown, overloads define specifics\n const instance = useSanityInstance()\n trackHookUsage(instance, 'useQuery')\n\n // Normalize options: resolve resourceName to resource and strip resourceName\n const normalized = useNormalizedResourceOptions(options)\n\n // Use React's useTransition to avoid UI jank when queries change\n const [isPending, startTransition] = useTransition()\n\n // Get the unique key for this query and its options (using normalized options)\n const queryKey = getQueryKey(instance, normalized)\n // Use a deferred state to avoid immediate re-renders when the query changes\n const [deferredQueryKey, setDeferredQueryKey] = useState(queryKey)\n\n // Create an AbortController to cancel in-flight requests when needed\n const ref = useRef<AbortController>(new AbortController())\n\n // When the query or options change, start a transition to update the query\n useEffect(() => {\n if (queryKey === deferredQueryKey) return\n\n startTransition(() => {\n // Abort any in-flight requests for the previous query\n if (ref && !ref.current.signal.aborted) {\n ref.current.abort()\n ref.current = new AbortController()\n }\n\n setDeferredQueryKey(queryKey)\n })\n }, [deferredQueryKey, queryKey])\n\n // Get the state source for this query from the query store\n // Memoize the options object by depending on the stable string key instead of the parsed object\n const {getCurrent, subscribe} = useMemo(() => {\n const deferred = parseQueryKey(deferredQueryKey)\n return getQueryState(instance, deferred)\n }, [instance, deferredQueryKey])\n\n // If data isn't available yet, suspend rendering\n if (getCurrent() === undefined) {\n // Normally, reading from a mutable ref during render can be risky in concurrent mode.\n // However, it is safe here because:\n // 1. React guarantees that while the component is suspended (via throwing a promise),\n // no effects or state updates occur during that render pass.\n // 2. We immediately capture the current abort signal in a local variable (currentSignal).\n // 3. Even if a background render updates ref.current (for example, due to a query change),\n // the captured signal remains unchanged for this suspended render.\n // Thus, the promise thrown here uses a stable abort signal, ensuring correct behavior.\n const currentSignal = ref.current.signal\n const deferred = parseQueryKey(deferredQueryKey)\n\n // eslint-disable-next-line react-hooks/refs -- intentional during suspended render; see comment above.\n throw resolveQuery(instance, {...deferred, signal: currentSignal})\n }\n\n // Subscribe to updates and get the current data\n // useSyncExternalStore ensures the component re-renders when the data changes\n const data = useSyncExternalStore(subscribe, getCurrent) as ResolveQueryResult\n return useMemo(() => ({data, isPending}), [data, isPending])\n}\n","import {type DocumentHandle, isDatasetResource, type QueryOptions} from '@sanity/sdk'\nimport {createGroqSearchFilter, pickProperties} from '@sanity/sdk/_internal'\nimport {type SortOrderingItem} from '@sanity/types'\nimport {useCallback, useMemo, useState} from 'react'\n\nimport {type ResourceHandle} from '../../config/handles'\nimport {useNormalizedResourceOptions} from '../helpers/useNormalizedResourceOptions'\nimport {useTrackHookUsage} from '../helpers/useTrackHookUsage'\nimport {useQuery} from '../query/useQuery'\n\nconst DEFAULT_BATCH_SIZE = 25\n\n/**\n * Configuration options for the useDocuments hook\n *\n * @public\n * @category Types\n */\nexport interface DocumentsOptions<\n TDocumentType extends string = string,\n TDataset extends string = string,\n TProjectId extends string = string,\n>\n extends ResourceHandle<TDataset, TProjectId>, Pick<QueryOptions, 'perspective' | 'params'> {\n /**\n * Filter documents by their `_type`. Can be a single type or an array of types.\n */\n documentType?: TDocumentType | TDocumentType[]\n /**\n * GROQ filter expression to apply to the query\n */\n filter?: string\n /**\n * Number of items to load per batch (defaults to 25)\n */\n batchSize?: number\n /**\n * Sorting configuration for the results\n * @beta\n */\n orderings?: SortOrderingItem[]\n /**\n * Text search query to filter results\n */\n search?: string\n}\n\n/**\n * Return value from the useDocuments hook\n *\n * @public\n * @category Types\n */\nexport interface DocumentsResponse<\n TDocumentType extends string = string,\n TDataset extends string = string,\n TProjectId extends string = string,\n> {\n /**\n * Array of document handles for the current batch\n */\n data: DocumentHandle<TDocumentType, TDataset, TProjectId>[]\n /**\n * Whether there are more items available to load\n */\n hasMore: boolean\n /**\n * Total count of items matching the query\n */\n count: number\n /**\n * Whether a query is currently in progress\n */\n isPending: boolean\n /**\n * Function to load the next batch of results\n */\n loadMore: () => void\n}\n\n/**\n * Retrieves batches of {@link DocumentHandle}s, narrowed by optional filters, text searches, and custom ordering,\n * with infinite scrolling support. The number of document handles returned per batch is customizable,\n * and additional batches can be loaded using the supplied `loadMore` function.\n *\n * @public\n * @category Documents\n * @param options - Configuration options for the infinite list\n * @returns An object containing the list of document handles, the loading state, the total count of retrieved document handles, and a function to load more\n *\n * @remarks\n * - The returned document handles include projectId and dataset information from the current Sanity instance\n * - This makes them ready to use with document operations and other document hooks\n * - The hook automatically uses the correct Sanity instance based on the projectId and dataset in the options\n *\n * @example Basic infinite list with loading more\n * ```tsx\n * import {\n * useDocuments,\n * createDatasetHandle,\n * type DatasetHandle,\n * type DocumentHandle,\n * type SortOrderingItem\n * } from '@sanity/sdk-react'\n * import {Suspense} from 'react'\n *\n * // Define a component to display a single document (using useDocumentProjection for efficiency)\n * function MyDocumentComponent({doc}: {doc: DocumentHandle}) {\n * const {data} = useDocumentProjection<{title?: string}>({\n * ...doc, // Pass the full handle\n * projection: '{title}'\n * })\n *\n * return <>{data?.title || 'Untitled'}</>\n * }\n *\n * // Define props for the list component\n * interface DocumentListProps {\n * dataset: DatasetHandle\n * documentType: string\n * search?: string\n * }\n *\n * function DocumentList({dataset, documentType, search}: DocumentListProps) {\n * const { data, hasMore, isPending, loadMore, count } = useDocuments({\n * ...dataset,\n * documentType,\n * search,\n * batchSize: 10,\n * orderings: [{field: '_createdAt', direction: 'desc'}],\n * })\n *\n * return (\n * <div>\n * <p>Total documents: {count}</p>\n * <ol>\n * {data.map((docHandle) => (\n * <li key={docHandle.documentId}>\n * <Suspense fallback=\"Loading…\">\n * <MyDocumentComponent docHandle={docHandle} />\n * </Suspense>\n * </li>\n * ))}\n * </ol>\n * {hasMore && (\n * <button onClick={loadMore}>\n * {isPending ? 'Loading...' : 'Load More'}\n * </button>\n * )}\n * </div>\n * )\n * }\n *\n * // Usage:\n * // const myDatasetHandle = createDatasetHandle({ projectId: 'p1', dataset: 'production' })\n * // <DocumentList dataset={myDatasetHandle} documentType=\"post\" search=\"Sanity\" />\n * ```\n *\n * @example Using `filter` and `params` options for narrowing a collection\n * ```tsx\n * import {useState} from 'react'\n * import {useDocuments} from '@sanity/sdk-react'\n *\n * export default function FilteredAuthors() {\n * const [max, setMax] = useState(2)\n * const {data} = useDocuments({\n * documentType: 'author',\n * filter: 'length(books) <= $max',\n * params: {max},\n * })\n *\n * return (\n * <>\n * <input\n * id=\"maxBooks\"\n * type=\"number\"\n * value={max}\n * onChange={e => setMax(e.currentTarget.value)}\n * />\n * {data.map(author => (\n * <Suspense key={author.documentId}>\n * <MyAuthorComponent documentHandle={author} />\n * </Suspense>\n * ))}\n * </>\n * )\n * }\n * ```\n */\nexport function useDocuments<\n TDocumentType extends string = string,\n TDataset extends string = string,\n TProjectId extends string = string,\n>({\n batchSize = DEFAULT_BATCH_SIZE,\n params,\n search,\n filter,\n orderings,\n documentType,\n ...rawOptions\n}: DocumentsOptions<TDocumentType, TDataset, TProjectId>): DocumentsResponse<\n TDocumentType,\n TDataset,\n TProjectId\n> {\n useTrackHookUsage('useDocuments')\n const options = useNormalizedResourceOptions(rawOptions)\n const [limit, setLimit] = useState(batchSize)\n const documentTypes = useMemo(\n () =>\n (Array.isArray(documentType) ? documentType : [documentType]).filter(\n (i): i is TDocumentType => typeof i === 'string',\n ),\n [documentType],\n )\n\n // Reset the limit to the current batchSize whenever any query parameters\n // (filter, search, params, orderings) or batchSize changes\n const key = JSON.stringify({\n filter,\n search,\n params,\n orderings,\n batchSize,\n types: documentTypes,\n ...options,\n })\n const [prevKey, setPrevKey] = useState(key)\n if (prevKey !== key) {\n setPrevKey(key)\n setLimit(batchSize)\n }\n\n const filterClause = useMemo(() => {\n const conditions: string[] = []\n const trimmedSearch = search?.trim()\n\n // Add search query filter if specified\n if (trimmedSearch) {\n const searchFilter = createGroqSearchFilter(trimmedSearch)\n if (searchFilter) {\n conditions.push(searchFilter)\n }\n }\n\n // Add type filter if specified\n if (documentTypes?.length) {\n conditions.push(`(_type in $__types)`)\n }\n\n // Add additional filter if specified\n if (filter) {\n conditions.push(`(${filter})`)\n }\n\n return conditions.length ? `[${conditions.join(' && ')}]` : ''\n }, [filter, search, documentTypes])\n\n const orderClause = orderings\n ? `| order(${orderings\n .map((ordering) =>\n [ordering.field, ordering.direction.toLowerCase()]\n .map((str) => str.trim())\n .filter(Boolean)\n .join(' '),\n )\n .join(',')})`\n : ''\n\n const dataQuery = `*${filterClause}${orderClause}[0...${limit}]{\"documentId\":_id,\"documentType\":_type,...$__handle}`\n const countQuery = `count(*${filterClause})`\n\n const {\n data: {count, data},\n isPending,\n } = useQuery<{count: number; data: DocumentHandle<TDocumentType, TDataset, TProjectId>[]}>({\n ...options,\n query: `{\"count\":${countQuery},\"data\":${dataQuery}}`,\n params: {\n ...params,\n // these are passed back to the user as part of each document handle\n __handle: {\n // keep projectId/dataset for backward compat until v4; resource is added\n // intentionally so that hook consumers can resolve the correct resource\n ...(options.resource && isDatasetResource(options.resource)\n ? pickProperties(options.resource, ['projectId', 'dataset'])\n : {}),\n ...pickProperties(options, ['perspective', 'resource']),\n },\n __types: documentTypes,\n },\n })\n\n // Now use the correctly typed variables\n const hasMore = data.length < count\n\n const loadMore = useCallback(() => {\n setLimit((prev) => Math.min(prev + batchSize, count))\n }, [count, batchSize])\n\n return useMemo(\n () => ({data, hasMore, count, isPending, loadMore}),\n [count, data, hasMore, isPending, loadMore],\n )\n}\n","import {type Installation, installation, type InstallationInclude} from '@sanity/sdk'\n\nimport {createFetcherHook, type FetcherHookResult} from '../helpers/createFetcherHook'\n\n/**\n * Returns a single installation by id.\n *\n * The hook suspends until the first fetch succeeds, so `data` is always present.\n * The `include` tokens you pass shape `data`: each requested token adds its\n * field, and omitted ones are absent from the type.\n *\n * @public\n * @param installationId - The installation id.\n * @param options - Optional `include` list to expand related resources.\n * @returns The result envelope `{data, isFetching, error, refetch}`.\n */\nexport const useInstallation = createFetcherHook(installation) as <\n Include extends InstallationInclude = never,\n>(\n installationId: string,\n options?: {include?: Include[]},\n) => FetcherHookResult<Installation<Include>>\n","import {\n type InstallationInclude,\n installations,\n type InstallationsOptions,\n type InstallationsResponse,\n} from '@sanity/sdk'\n\nimport {createFetcherHook, type FetcherHookResult} from '../helpers/createFetcherHook'\n\n/**\n * Returns the installations matching the given options.\n *\n * The hook suspends until the first fetch succeeds, so `data` is always present.\n * The `include` tokens you pass shape `data.data`: each requested token adds its\n * field, and omitted ones are absent from the type.\n *\n * @public\n * @param options - Filter and include options for the installations list.\n * @returns The result envelope `{data, isFetching, error, refetch}`.\n */\nexport const useInstallations = createFetcherHook(installations) as <\n Include extends InstallationInclude = never,\n>(\n options: InstallationsOptions<Include>,\n) => FetcherHookResult<InstallationsResponse<Include>>\n","import {type Organization, organization, type OrganizationOptions} from '@sanity/sdk'\n\nimport {createFetcherHook, type FetcherHookResult} from '../helpers/createFetcherHook'\n\n/**\n * Returns metadata for a given organisation.\n *\n * @category Organizations\n * @param options - Configuration options\n * @returns A {@link FetcherHookResult} whose `data` is the metadata for the\n * organisation. `members` is included only when `includeMembers: true`;\n * `features` is included only when `includeFeatures: true`.\n * @example\n * ```tsx\n * function OrganizationName({organizationId}: {organizationId: string}) {\n * const {data: organization} = useOrganization({organizationId})\n *\n * return <h1>{organization.name}</h1>\n * }\n * ```\n * @example\n * ```tsx\n * const {data: organizationWithMembers} = useOrganization({organizationId, includeMembers: true})\n * const {data: organizationWithFeatures} = useOrganization({organizationId, includeFeatures: true})\n * ```\n * @public\n * @function\n */\nexport const useOrganization = createFetcherHook(organization) as <\n IncludeMembers extends boolean = false,\n IncludeFeatures extends boolean = false,\n>(\n options: OrganizationOptions<IncludeMembers, IncludeFeatures>,\n) => FetcherHookResult<Organization<IncludeMembers, IncludeFeatures>>\n","import {type Organizations, organizations, type OrganizationsOptions} from '@sanity/sdk'\n\nimport {createFetcherHook, type FetcherHookResult} from '../helpers/createFetcherHook'\n\n/**\n * Returns metadata for each organisation the current user has access to.\n *\n * @category Organizations\n * @param options - Configuration options\n * @returns A {@link FetcherHookResult} whose `data` is an array of organisation\n * metadata. `members` is included only when `includeMembers: true`; `features`\n * is included only when `includeFeatures: true`.\n * @example\n * ```tsx\n * const {data: organizations} = useOrganizations()\n *\n * return (\n * <select>\n * {organizations.map((organization) => (\n * <option key={organization.id}>{organization.name}</option>\n * ))}\n * </select>\n * )\n * ```\n * @example\n * ```tsx\n * const {data: organizationsWithMembers} = useOrganizations({includeMembers: true})\n * const {data: organizationsWithFeatures} = useOrganizations({includeFeatures: true})\n * const {data: organizationsIncludingImplicit} = useOrganizations({includeImplicitMemberships: true})\n * ```\n * @public\n * @function\n */\nexport const useOrganizations = createFetcherHook(organizations) as <\n IncludeMembers extends boolean = false,\n IncludeFeatures extends boolean = false,\n>(\n options?: OrganizationsOptions<IncludeMembers, IncludeFeatures>,\n) => FetcherHookResult<Organizations<IncludeMembers, IncludeFeatures>>\n","import {type DocumentHandle, isDatasetResource, type QueryOptions} from '@sanity/sdk'\nimport {createGroqSearchFilter, pickProperties} from '@sanity/sdk/_internal'\nimport {type SortOrderingItem} from '@sanity/types'\nimport {useCallback, useMemo, useState} from 'react'\n\nimport {\n useNormalizedResourceOptions,\n type WithResourceNameSupport,\n} from '../helpers/useNormalizedResourceOptions'\nimport {useTrackHookUsage} from '../helpers/useTrackHookUsage'\nimport {useQuery} from '../query/useQuery'\n\n/**\n * Configuration options for the usePaginatedDocuments hook\n *\n * @public\n * @category Types\n */\nexport interface PaginatedDocumentsOptions<\n TDocumentType extends string = string,\n TDataset extends string = string,\n TProjectId extends string = string,\n> extends WithResourceNameSupport<\n Omit<QueryOptions<TDocumentType, TDataset, TProjectId>, 'query'>\n> {\n documentType?: TDocumentType | TDocumentType[]\n /**\n * GROQ filter expression to apply to the query\n */\n filter?: string\n /**\n * Number of items to display per page (defaults to 25)\n */\n pageSize?: number\n /**\n * Sorting configuration for the results\n * @beta\n */\n orderings?: SortOrderingItem[]\n /**\n * Text search query to filter results\n */\n search?: string\n}\n\n/**\n * Return value from the usePaginatedDocuments hook\n *\n * @public\n * @category Types\n */\nexport interface PaginatedDocumentsResponse<\n TDocumentType extends string = string,\n TDataset extends string = string,\n TProjectId extends string = string,\n> {\n /**\n * Array of document handles for the current page\n */\n data: DocumentHandle<TDocumentType, TDataset, TProjectId>[]\n /**\n * Whether a query is currently in progress\n */\n isPending: boolean\n\n /**\n * Number of items displayed per page\n */\n pageSize: number\n /**\n * Current page number (1-indexed)\n */\n currentPage: number\n /**\n * Total number of pages available\n */\n totalPages: number\n\n /**\n * Starting index of the current page (0-indexed)\n */\n startIndex: number\n /**\n * Ending index of the current page (exclusive, 0-indexed)\n */\n endIndex: number\n /**\n * Total count of items matching the query\n */\n count: number\n\n /**\n * Navigate to the first page\n */\n firstPage: () => void\n /**\n * Whether there is a first page available to navigate to\n */\n hasFirstPage: boolean\n\n /**\n * Navigate to the previous page\n */\n previousPage: () => void\n /**\n * Whether there is a previous page available to navigate to\n */\n hasPreviousPage: boolean\n\n /**\n * Navigate to the next page\n */\n nextPage: () => void\n /**\n * Whether there is a next page available to navigate to\n */\n hasNextPage: boolean\n\n /**\n * Navigate to the last page\n */\n lastPage: () => void\n /**\n * Whether there is a last page available to navigate to\n */\n hasLastPage: boolean\n\n /**\n * Navigate to a specific page number\n * @param pageNumber - The page number to navigate to (1-indexed)\n */\n goToPage: (pageNumber: number) => void\n}\n\n/**\n * Retrieves pages of {@link DocumentHandle}s, narrowed by optional filters, text searches, and custom ordering,\n * with support for traditional paginated interfaces. The number of document handles returned per page is customizable,\n * while page navigation is handled via the included navigation functions.\n *\n * @public\n * @category Documents\n * @param options - Configuration options for the paginated list\n * @returns An object containing the list of document handles, pagination details, and functions to navigate between pages\n *\n * @remarks\n * - The returned document handles include projectId and dataset information from the current Sanity instance\n * - This makes them ready to use with document operations and other document hooks\n * - The hook automatically uses the correct Sanity instance based on the projectId and dataset in the options\n *\n * @example Paginated list of documents with navigation\n * ```tsx\n * import {\n * usePaginatedDocuments,\n * createDatasetHandle,\n * type DatasetHandle,\n * type DocumentHandle,\n * type SortOrderingItem,\n * useDocumentProjection\n * } from '@sanity/sdk-react'\n * import {Suspense} from 'react'\n * import {ErrorBoundary} from 'react-error-boundary'\n *\n * // Define a component to display a single document row\n * function MyTableRowComponent({doc}: {doc: DocumentHandle}) {\n * const {data} = useDocumentProjection<{title?: string}>({\n * ...doc,\n * projection: '{title}',\n * })\n *\n * return (\n * <tr>\n * <td>{data?.title ?? 'Untitled'}</td>\n * </tr>\n * )\n * }\n *\n * // Define props for the list component\n * interface PaginatedDocumentListProps {\n * documentType: string\n * dataset?: DatasetHandle\n * }\n *\n * function PaginatedDocumentList({documentType, dataset}: PaginatedDocumentListProps) {\n * const {\n * data,\n * isPending,\n * currentPage,\n * totalPages,\n * nextPage,\n * previousPage,\n * hasNextPage,\n * hasPreviousPage\n * } = usePaginatedDocuments({\n * ...dataset,\n * documentType,\n * pageSize: 10,\n * orderings: [{field: '_createdAt', direction: 'desc'}],\n * })\n *\n * return (\n * <div>\n * <table>\n * <thead>\n * <tr><th>Title</th></tr>\n * </thead>\n * <tbody>\n * {data.map(doc => (\n * <ErrorBoundary key={doc.documentId} fallback={<tr><td>Error loading document</td></tr>}>\n * <Suspense fallback={<tr><td>Loading...</td></tr>}>\n * <MyTableRowComponent doc={doc} />\n * </Suspense>\n * </ErrorBoundary>\n * ))}\n * </tbody>\n * </table>\n * <div style={{opacity: isPending ? 0.5 : 1}}>\n * <button onClick={previousPage} disabled={!hasPreviousPage || isPending}>Previous</button>\n * <span>Page {currentPage} / {totalPages}</span>\n * <button onClick={nextPage} disabled={!hasNextPage || isPending}>Next</button>\n * </div>\n * </div>\n * )\n * }\n *\n * // Usage:\n * // const myDatasetHandle = createDatasetHandle({ projectId: 'p1', dataset: 'production' })\n * // <PaginatedDocumentList dataset={myDatasetHandle} documentType=\"post\" />\n * ```\n */\nexport function usePaginatedDocuments<\n TDocumentType extends string = string,\n TDataset extends string = string,\n TProjectId extends string = string,\n>({\n documentType,\n filter = '',\n pageSize = 25,\n params = {},\n orderings,\n search,\n ...rawOptions\n}: PaginatedDocumentsOptions<TDocumentType, TDataset, TProjectId>): PaginatedDocumentsResponse<\n TDocumentType,\n TDataset,\n TProjectId\n> {\n useTrackHookUsage('usePaginatedDocuments')\n const options = useNormalizedResourceOptions(rawOptions)\n const [pageIndex, setPageIndex] = useState(0)\n const key = JSON.stringify({filter, search, params, orderings, pageSize, ...options})\n // Reset pageIndex to 0 whenever any query parameter changes.\n const [prevKey, setPrevKey] = useState(key)\n if (prevKey !== key) {\n setPrevKey(key)\n setPageIndex(0)\n }\n\n const startIndex = pageIndex * pageSize\n const endIndex = (pageIndex + 1) * pageSize\n const documentTypes = (Array.isArray(documentType) ? documentType : [documentType]).filter(\n (i) => typeof i === 'string',\n )\n\n const filterClause = useMemo(() => {\n const conditions: string[] = []\n const trimmedSearch = search?.trim()\n\n // Add search query filter if specified\n if (trimmedSearch) {\n const searchFilter = createGroqSearchFilter(trimmedSearch)\n if (searchFilter) {\n conditions.push(searchFilter)\n }\n }\n\n if (documentTypes?.length) {\n conditions.push(`(_type in $__types)`)\n }\n\n // Add additional filter if specified\n if (filter) {\n conditions.push(`(${filter})`)\n }\n\n return conditions.length ? `[${conditions.join(' && ')}]` : ''\n }, [filter, search, documentTypes?.length])\n\n const orderClause = orderings\n ? `| order(${orderings\n .map((ordering) =>\n [ordering.field, ordering.direction.toLowerCase()]\n .map((str) => str.trim())\n .filter(Boolean)\n .join(' '),\n )\n .join(',')})`\n : ''\n\n const dataQuery = `*${filterClause}${orderClause}[${startIndex}...${endIndex}]{\"documentId\":_id,\"documentType\":_type,...$__handle}`\n const countQuery = `count(*${filterClause})`\n\n const {\n data: {data, count},\n isPending,\n } = useQuery<{data: DocumentHandle<TDocumentType, TDataset, TProjectId>[]; count: number}>({\n ...options,\n query: `{\"data\":${dataQuery},\"count\":${countQuery}}`,\n params: {\n ...params,\n __types: documentTypes,\n __handle: {\n // keep projectId/dataset for backward compat until v4; resource is added\n // intentionally so that hook consumers can resolve the correct resource\n ...(options.resource && isDatasetResource(options.resource)\n ? pickProperties(options.resource, ['projectId', 'dataset'])\n : {}),\n ...pickProperties(options, ['perspective', 'resource']),\n },\n },\n })\n\n const totalPages = Math.ceil(count / pageSize)\n const currentPage = pageIndex + 1\n\n // Navigation methods\n const firstPage = useCallback(() => setPageIndex(0), [])\n const previousPage = useCallback(() => setPageIndex((prev) => Math.max(prev - 1, 0)), [])\n const nextPage = useCallback(\n () => setPageIndex((prev) => Math.min(prev + 1, totalPages - 1)),\n [totalPages],\n )\n const lastPage = useCallback(() => setPageIndex(totalPages - 1), [totalPages])\n const goToPage = useCallback(\n (pageNumber: number) => {\n if (pageNumber < 1 || pageNumber > totalPages) return\n setPageIndex(pageNumber - 1)\n },\n [totalPages],\n )\n\n // Boolean flags for page availability\n const hasFirstPage = pageIndex > 0\n const hasPreviousPage = pageIndex > 0\n const hasNextPage = pageIndex < totalPages - 1\n const hasLastPage = pageIndex < totalPages - 1\n\n return {\n data,\n isPending,\n pageSize,\n currentPage,\n totalPages,\n startIndex,\n endIndex,\n count,\n firstPage,\n hasFirstPage,\n previousPage,\n hasPreviousPage,\n nextPage,\n hasNextPage,\n lastPage,\n hasLastPage,\n goToPage,\n }\n}\n","import {getPresence, isMediaLibraryResource, type UserPresence} from '@sanity/sdk'\nimport {useCallback, useMemo, useSyncExternalStore} from 'react'\n\nimport {type ResourceHandle} from '../../config/handles'\nimport {useSanityInstance} from '../context/useSanityInstance'\nimport {useNormalizedResourceOptions} from '../helpers/useNormalizedResourceOptions'\nimport {trackHookUsage} from '../helpers/useTrackHookUsage'\n\n/**\n * Every participant in the current project and dataset, or Canvas.\n *\n * Reading presence never announces anything. Call `useReportPresence` to make the\n * current user visible to others, including to the Studio, which shares the same\n * presence room.\n *\n * This returns everyone in the whole resource and leaves the filtering to you.\n * Prefer `usePresenceForDocument` when you care about one document: it scopes and\n * flattens the result for rendering. Note that participants are counted by session,\n * so one person in two tabs appears twice.\n *\n * Presence is scoped to a single project and dataset. It is not a list of everyone\n * signed in to your organization.\n *\n * @public\n */\nexport function usePresence(options: ResourceHandle = {}): {\n locations: UserPresence[]\n} {\n const normalizedOptions = useNormalizedResourceOptions(options)\n if (normalizedOptions.resource && isMediaLibraryResource(normalizedOptions.resource)) {\n throw new Error(\n 'usePresence() does not support media library resources. Presence tracking requires a canvas or dataset resource.',\n )\n }\n\n const sanityInstance = useSanityInstance()\n trackHookUsage(sanityInstance, 'usePresence')\n const source = useMemo(\n () => getPresence(sanityInstance, normalizedOptions),\n [sanityInstance, normalizedOptions],\n )\n const subscribe = useCallback((callback: () => void) => source.subscribe(callback), [source])\n const locations = useSyncExternalStore(\n subscribe,\n () => source.getCurrent(),\n () => source.getCurrent(),\n )\n\n return {locations: locations || []}\n}\n","import {type DocumentPresence, getDocumentPresence, isMediaLibraryResource} from '@sanity/sdk'\nimport {type Path} from '@sanity/types'\nimport {useCallback, useMemo, useSyncExternalStore} from 'react'\n\nimport {type DocumentHandle} from '../../config/handles'\nimport {useSanityInstance} from '../context/useSanityInstance'\nimport {useNormalizedResourceOptions} from '../helpers/useNormalizedResourceOptions'\nimport {trackHookUsage} from '../helpers/useTrackHookUsage'\n\n/** @beta */\nexport interface UsePresenceForDocumentOptions extends DocumentHandle {\n /**\n * Narrows to participants at or below this field path, which is what a field\n * indicator wants. Omit it for everyone in the document.\n */\n path?: Path\n\n /**\n * By default a draft, its published version, and any release versions count as\n * the same document, which is what document lists want. Set this to compare ids\n * exactly, so that a draft and a release version do not bleed into each other.\n */\n excludeVersions?: boolean\n}\n\n/**\n * Who else is in a document, flattened to one entry per participant per location\n * so it can be rendered straight against a field.\n *\n * Reading presence never announces anything. Use `useReportPresence` to make the\n * current user visible to others.\n *\n * Prefer this over `usePresence` when you care about one document: `usePresence`\n * returns every participant in the whole project and dataset, leaving the filtering\n * to you.\n *\n * Resolves the document through its perspective exactly as `useReportPresence` does,\n * so reads match writes. Participants are counted by session, so one person in two\n * tabs appears twice.\n *\n * @example Avatars on a document\n * ```tsx\n * const {presence} = usePresenceForDocument({documentId, documentType})\n * return presence.map((p) => <Avatar key={p.sessionId} user={p.user} />)\n * ```\n *\n * @example Avatars on a single field\n * ```tsx\n * const {presence} = usePresenceForDocument({\n * documentId,\n * documentType,\n * path: ['title'],\n * excludeVersions: true,\n * })\n * ```\n *\n * @beta\n */\nexport function usePresenceForDocument(options: UsePresenceForDocumentOptions): {\n presence: DocumentPresence[]\n} {\n const {path, excludeVersions, ...handle} = options\n\n const normalizedOptions = useNormalizedResourceOptions(handle)\n if (normalizedOptions.resource && isMediaLibraryResource(normalizedOptions.resource)) {\n throw new Error(\n 'usePresenceForDocument() does not support media library resources. Presence tracking requires a canvas or dataset resource.',\n )\n }\n\n const sanityInstance = useSanityInstance()\n trackHookUsage(sanityInstance, 'usePresenceForDocument')\n\n const {resource, perspective} = normalizedOptions\n const {documentId, liveEdit} = options\n\n // Serialized so a caller passing a fresh `path` array each render does not\n // rebuild the state source every render.\n const pathKey = useMemo(() => JSON.stringify(path ?? null), [path])\n\n const source = useMemo(\n () =>\n getDocumentPresence(sanityInstance, {\n ...(resource ? {resource} : {}),\n documentId,\n // Forwarded, not resolved here, so this matches what `useReportPresence`\n // sends. Core owns turning a perspective into a specific document id.\n ...(perspective ? {perspective} : {}),\n ...(liveEdit ? {liveEdit} : {}),\n ...(pathKey === 'null' ? {} : {path: JSON.parse(pathKey) as Path}),\n ...(excludeVersions === undefined ? {} : {excludeVersions}),\n }),\n [sanityInstance, resource, documentId, perspective, liveEdit, pathKey, excludeVersions],\n )\n\n const subscribe = useCallback((callback: () => void) => source.subscribe(callback), [source])\n const presence = useSyncExternalStore(\n subscribe,\n () => source.getCurrent(),\n () => source.getCurrent(),\n )\n\n return {presence: presence || []}\n}\n","import {\n isMediaLibraryResource,\n type PresenceSelection,\n reportPresence,\n type ReportPresenceOptions,\n} from '@sanity/sdk'\nimport {type Path} from '@sanity/types'\nimport {useEffect, useMemo, useRef} from 'react'\n\nimport {type DocumentHandle} from '../../config/handles'\nimport {useSanityInstance} from '../context/useSanityInstance'\nimport {useNormalizedResourceOptions} from '../helpers/useNormalizedResourceOptions'\nimport {trackHookUsage} from '../helpers/useTrackHookUsage'\n\n/**\n * Field focus moves at human speed, so a second between announcements is plenty.\n */\nconst FOCUS_THROTTLE_MS = 1000\n\n/**\n * A caret that trails a second behind reads as broken rather than as latency, so\n * reporting a `selection` announces more often. The Studio uses a flat 1000ms for\n * both, which is why its remote carets feel sluggish.\n */\nconst SELECTION_THROTTLE_MS = 250\n\n/** @beta */\nexport interface UseReportPresenceOptions extends DocumentHandle {\n /**\n * The focused field path. Omit it for document-level presence. Keyed and numeric\n * segments are supported, so array items and Portable Text spans can be\n * addressed.\n */\n path?: Path\n\n /** The Portable Text caret, when the focused field is a Portable Text field. */\n selection?: PresenceSelection\n\n /** Overrides the throttle interval. Mainly useful in tests. */\n throttleMs?: number\n}\n\n/**\n * Announces that the current user is in a document, so that other clients in the\n * same project and dataset can show them.\n *\n * Writing presence is opt-in. Reading it with `usePresenceForDocument` or\n * `usePresence` never announces anything, and this hook is the only thing that\n * makes an app visible to others. That includes the Studio, which shares the same\n * presence room and will show these users in its navbar and field indicators.\n *\n * Announcements are throttled, collapsed over a short window, and then repeated\n * every 30 seconds while the user is idle. That repeat is what tells peers the\n * session is still alive, so the intended usage is to mount this hook for as long\n * as the user is in the document. On unmount the location is cleared, leaving the\n * user present in the app but not in any particular document.\n *\n * The perspective decides which specific document is reported: the draft under\n * `drafts`, the published document under `published`, a version under a release.\n * It is taken from `ResourceProvider` unless you pass one on the handle. That\n * matters for interoperability, because the Studio's field indicators compare the\n * exact id its form is on, so a mismatch shows your user at document level while\n * never lighting up a field.\n *\n * Presence is scoped to a single project and dataset. It is not a list of everyone\n * signed in to your organization.\n *\n * @example Document-level presence\n * ```tsx\n * function DocumentEditor({documentId, documentType}: DocumentHandle) {\n * useReportPresence({documentId, documentType})\n * return <Editor />\n * }\n * ```\n *\n * @example Presence in a release version\n * ```tsx\n * // The document id stays plain; the perspective selects the version.\n * useReportPresence({documentId, documentType, perspective: {releaseName: 'autumn'}})\n * ```\n *\n * @example Field-level presence\n * ```tsx\n * function TitleField({documentId, documentType}: DocumentHandle) {\n * const [focused, setFocused] = useState(false)\n * useReportPresence({documentId, documentType, path: focused ? ['title'] : undefined})\n * return <input onFocus={() => setFocused(true)} onBlur={() => setFocused(false)} />\n * }\n * ```\n *\n * @beta\n */\nexport function useReportPresence(options: UseReportPresenceOptions): void {\n const {path, selection, throttleMs, ...handle} = options\n\n const normalizedOptions = useNormalizedResourceOptions(handle)\n if (normalizedOptions.resource && isMediaLibraryResource(normalizedOptions.resource)) {\n throw new Error(\n 'useReportPresence() does not support media library resources. Presence tracking requires a canvas or dataset resource.',\n )\n }\n\n const sanityInstance = useSanityInstance()\n trackHookUsage(sanityInstance, 'useReportPresence')\n\n const {resource, perspective} = normalizedOptions\n const {documentId, liveEdit} = options\n\n const interval = throttleMs ?? (selection ? SELECTION_THROTTLE_MS : FOCUS_THROTTLE_MS)\n\n // Compared by value, because callers write `path={['title']}` inline and a fresh\n // array identity every render must not mean a fresh announcement every render.\n const locationKey = useMemo(\n () =>\n JSON.stringify([documentId, path ?? [], selection ?? null, perspective ?? null, liveEdit]),\n [documentId, path, selection, perspective, liveEdit],\n )\n\n // Rebuilt from the key rather than from the props, so the effect below can\n // depend on it honestly instead of suppressing the exhaustive-deps rule.\n const location = useMemo<ReportPresenceOptions>(() => {\n const [id, parsedPath, parsedSelection, parsedPerspective, parsedLiveEdit] = JSON.parse(\n locationKey,\n ) as [string, Path, PresenceSelection, ReportPresenceOptions['perspective'] | null, boolean?]\n return {\n documentId: id,\n // Forwarded rather than resolved here: core turns the perspective into the\n // specific document id, so the read and write sides cannot drift apart.\n ...(parsedPerspective ? {perspective: parsedPerspective} : {}),\n ...(parsedLiveEdit ? {liveEdit: parsedLiveEdit} : {}),\n ...(parsedPath.length > 0 ? {path: parsedPath} : {}),\n ...(parsedSelection ? {selection: parsedSelection} : {}),\n }\n }, [locationKey])\n\n const lastSentAt = useRef(0)\n const pending = useRef<ReturnType<typeof setTimeout> | undefined>(undefined)\n\n useEffect(() => {\n // Captured in this effect's closure rather than read from a ref, so nothing is\n // written during render. A newer location re-runs the effect, which clears the\n // pending timeout below and schedules the newer value instead.\n const send = () => {\n lastSentAt.current = Date.now()\n reportPresence(sanityInstance, {\n ...(resource ? {resource} : {}),\n locations: [location],\n })\n }\n\n const elapsed = Date.now() - lastSentAt.current\n if (elapsed >= interval) {\n send()\n } else {\n // Trailing edge, so the position the user settled on is the one announced.\n clearTimeout(pending.current)\n pending.current = setTimeout(send, interval - elapsed)\n }\n\n return () => clearTimeout(pending.current)\n }, [location, interval, sanityInstance, resource])\n\n // Kept separate from the throttled effect so it runs on unmount only, rather\n // than every time the reported location changes.\n useEffect(() => {\n return () => {\n reportPresence(sanityInstance, {...(resource ? {resource} : {}), locations: []})\n }\n }, [sanityInstance, resource])\n}\n","import {getProjectionState, resolveProjection, type ResolveProjectionResult} from '@sanity/sdk'\nimport {useCallback, useMemo, useSyncExternalStore} from 'react'\nimport {distinctUntilChanged, EMPTY, Observable, startWith, switchMap} from 'rxjs'\n\nimport {type DocumentHandle} from '../../config/handles'\nimport {useSanityInstance} from '../context/useSanityInstance'\nimport {useNormalizedResourceOptions} from '../helpers/useNormalizedResourceOptions'\nimport {trackHookUsage} from '../helpers/useTrackHookUsage'\n\n/**\n * @public\n * @category Types\n */\nexport interface useDocumentProjectionOptions<\n TProjection extends string = string,\n TDocumentType extends string = string,\n TDataset extends string = string,\n TProjectId extends string = string,\n> extends DocumentHandle<TDocumentType, TDataset, TProjectId> {\n /** The GROQ projection string */\n projection: TProjection\n /** Optional parameters for the projection query */\n params?: Record<string, unknown>\n /** Optional ref to track viewport intersection for lazy loading */\n ref?: React.RefObject<unknown>\n}\n\n/**\n * @public\n * @category Types\n */\nexport interface useDocumentProjectionResults<TData> {\n /** The projected data */\n data: TData\n /** True if the projection is currently being resolved */\n isPending: boolean\n}\n\n/**\n * @public\n *\n * Returns the projected values of a document based on the provided projection string.\n * These values are live and will update in realtime.\n * To optimize network requests, an optional `ref` can be passed to only resolve the projection\n * when the referenced element is intersecting the viewport.\n *\n * @category Documents\n * @remarks\n * This hook has multiple signatures allowing for fine-grained control over type inference:\n * - Using Typegen: Infers the return type based on the `documentType`, `dataset`, `projectId`, and `projection`.\n * - Using explicit type parameter: Allows specifying a custom return type `TData`.\n *\n * @param options - An object containing the `DocumentHandle` properties (`documentId`, `documentType`, etc.), the `projection` string, optional `params`, and an optional `ref`.\n * @returns An object containing the projection results (`data`) and a boolean indicating whether the resolution is pending (`isPending`). Note: Suspense handles initial loading states; `data` being `undefined` after initial loading means the document doesn't exist or the projection yielded no result.\n */\n\n// Overload 1: Relies on Typegen\n/**\n * @public\n * Fetch a projection, relying on Typegen for the return type based on the handle and projection.\n *\n * @category Documents\n * @param options - Options including the document handle properties (`documentId`, `documentType`, etc.) and the `projection`.\n * @returns The projected data, typed based on Typegen.\n *\n * @example Using an existing experimental Typegen file for a book preview\n * ```tsx\n * // ProjectionComponent.tsx\n * import {defineProjection, useDocumentProjection, type DocumentHandle} from '@sanity/sdk-react'\n * import {useRef} from 'react'\n *\n * // Define props using DocumentHandle with the specific document type\n * type ProjectionComponentProps = {\n * doc: DocumentHandle<'book'> // Typegen knows 'book'\n * }\n *\n * // Keep the projection string identical to its entry in the existing generated file.\n * // Current Typegen does not scan defineProjection imported from the SDK.\n * const myProjection = defineProjection(`{\n * title,\n * 'coverImage': cover.asset->url,\n * 'authors': array::join(authors[]->{'name': firstName + ' ' + lastName}.name, ', ')\n * }`)\n *\n * export default function ProjectionComponent({ doc }: ProjectionComponentProps) {\n * const ref = useRef(null) // Optional ref to track viewport intersection for lazy loading\n *\n * // Spread the doc handle into the options\n * // Typegen infers the return type based on 'book' and the projection\n * const { data } = useDocumentProjection({\n * ...doc, // Pass the handle properties\n * ref,\n * projection: myProjection,\n * })\n *\n * // Suspense handles initial load, check for data existence after\n * return (\n * <article ref={ref}>\n * <h2>{data.title ?? 'Untitled'}</h2>\n * {data.coverImage && <img src={data.coverImage} alt={data.title} />}\n * <p>{data.authors ?? 'Unknown authors'}</p>\n * </article>\n * )\n * }\n *\n * // Usage:\n * // import {createDocumentHandle} from '@sanity/sdk-react'\n * // const myDocHandle = createDocumentHandle({ documentId: 'book123', documentType: 'book' })\n * // <Suspense fallback='Loading preview...'>\n * // <ProjectionComponent doc={myDocHandle} />\n * // </Suspense>\n * ```\n */\nexport function useDocumentProjection<\n TProjection extends string = string,\n TDocumentType extends string = string,\n TDataset extends string = string,\n TProjectId extends string = string,\n>(\n options: useDocumentProjectionOptions<TProjection, TDocumentType, TDataset, TProjectId>,\n): useDocumentProjectionResults<\n ResolveProjectionResult<TProjection, TDocumentType, `${TProjectId}.${TDataset}`>\n>\n\n// Overload 2: Explicit type provided\n/**\n * @public\n * Fetch a projection with an explicitly defined return type `TData`.\n *\n * @param options - Options including the document handle properties (`documentId`, etc.) and the `projection`.\n * @returns The projected data, cast to the explicit type `TData`.\n *\n * @example Explicitly typing the projection result\n * ```tsx\n * import {useDocumentProjection, type DocumentHandle} from '@sanity/sdk-react'\n * import {useRef} from 'react'\n *\n * interface SimpleBookPreview {\n * title?: string;\n * authorName?: string;\n * }\n *\n * type BookPreviewProps = {\n * doc: DocumentHandle\n * }\n *\n * function BookPreview({ doc }: BookPreviewProps) {\n * const ref = useRef(null)\n * const { data } = useDocumentProjection<SimpleBookPreview>({\n * ...doc,\n * ref,\n * projection: `{ title, 'authorName': author->name }`\n * })\n *\n * return (\n * <div ref={ref}>\n * <h3>{data.title ?? 'No Title'}</h3>\n * <p>By: {data.authorName ?? 'Unknown'}</p>\n * </div>\n * )\n * }\n *\n * // Usage:\n * // import {createDocumentHandle} from '@sanity/sdk-react'\n * // const doc = createDocumentHandle({ documentId: 'abc', documentType: 'book' })\n * // <Suspense fallback='Loading...'>\n * // <BookPreview doc={doc} />\n * // </Suspense>\n * ```\n */\nexport function useDocumentProjection<TData extends object>(\n options: useDocumentProjectionOptions, // Uses base options type\n): useDocumentProjectionResults<TData>\n\n// Implementation (no JSDoc needed here as it's covered by overloads)\nexport function useDocumentProjection<TData extends object>({\n ref,\n projection,\n ...docHandle\n}: useDocumentProjectionOptions): useDocumentProjectionResults<TData> {\n const instance = useSanityInstance()\n trackHookUsage(instance, 'useDocumentProjection')\n\n // Normalize projection string to handle template literals with whitespace\n // This ensures that the same projection content produces the same state source\n // even if the string reference changes (e.g., from inline template literals)\n const normalizedProjection = useMemo(() => projection.trim(), [projection])\n\n // Normalize options: resolve resourceName to resource and strip resourceName\n const normalizedDocHandle = useNormalizedResourceOptions(docHandle)\n\n // Memoize stateSource based on normalized projection and docHandle properties\n // This prevents creating a new StateSource on every render when projection content is the same\n const stateSource = useMemo(\n () =>\n getProjectionState<TData>(instance, {\n ...normalizedDocHandle,\n projection: normalizedProjection,\n }),\n [instance, normalizedDocHandle, normalizedProjection],\n )\n\n if (stateSource.getCurrent()?.data === null) {\n throw resolveProjection(instance, {...normalizedDocHandle, projection: normalizedProjection})\n }\n\n // Create subscribe function for useSyncExternalStore\n const subscribe = useCallback(\n (onStoreChanged: () => void) => {\n const subscription = new Observable<boolean>((observer) => {\n // For environments that don't have an intersection observer (e.g. server-side),\n // we pass true to always subscribe since we can't detect visibility\n if (typeof IntersectionObserver === 'undefined' || typeof HTMLElement === 'undefined') {\n observer.next(true)\n return\n }\n\n const intersectionObserver = new IntersectionObserver(\n ([entry]) => observer.next(entry.isIntersecting),\n {rootMargin: '0px', threshold: 0},\n )\n if (ref?.current && ref.current instanceof HTMLElement) {\n intersectionObserver.observe(ref.current)\n } else {\n // If no ref is provided or ref.current isn't an HTML element,\n // pass true to always subscribe since we can't track visibility\n observer.next(true)\n }\n return () => intersectionObserver.disconnect()\n })\n .pipe(\n startWith(false),\n distinctUntilChanged(),\n switchMap((isVisible) =>\n isVisible\n ? new Observable<void>((obs) => {\n // `stateSource.subscribe` skips the value current at subscribe time;\n // (intentionally -- we only want new events)\n // but in this case the store might have updated while the element was off-screen;\n // so we fire an immediate notification here to make useSyncExternalStore\n // re-read getCurrent() and pick up the fresh value.\n obs.next()\n return stateSource.subscribe(() => obs.next())\n })\n : EMPTY,\n ),\n )\n .subscribe({next: onStoreChanged})\n\n return () => subscription.unsubscribe()\n },\n [stateSource, ref],\n )\n\n return useSyncExternalStore(\n subscribe,\n stateSource.getCurrent,\n ) as useDocumentProjectionResults<TData>\n}\n","import {type PreviewQueryResult, type PreviewValue} from '@sanity/sdk'\nimport {PREVIEW_PROJECTION, transformProjectionToPreview} from '@sanity/sdk/_internal'\nimport {useMemo} from 'react'\n\nimport {type DocumentHandle} from '../../config/handles'\nimport {useSanityInstance} from '../context/useSanityInstance'\nimport {useNormalizedResourceOptions} from '../helpers/useNormalizedResourceOptions'\nimport {trackHookUsage} from '../helpers/useTrackHookUsage'\nimport {useDocumentProjection} from '../projection/useDocumentProjection'\n\n/**\n * @public\n * @category Types\n */\nexport interface useDocumentPreviewOptions extends DocumentHandle {\n /**\n * Optional ref object to track visibility. When provided, preview resolution\n * only occurs when the referenced element is visible in the viewport.\n */\n ref?: React.RefObject<unknown>\n}\n\n/**\n * @public\n * @category Types\n */\nexport interface useDocumentPreviewResults {\n /** The results of inferring the document's preview values */\n data: PreviewValue\n /** True when inferred preview values are being refreshed */\n isPending: boolean\n}\n\n/**\n * @public\n *\n * Attempts to infer preview values of a document (specified via a `DocumentHandle`),\n * including the document's `title`, `subtitle`, `media`, and `status`. These values are live and will update in realtime.\n * To reduce unnecessary network requests for resolving the preview values, an optional `ref` can be passed to the hook so that preview\n * resolution will only occur if the `ref` is intersecting the current viewport.\n *\n * See remarks below for futher information.\n *\n * @remarks\n * Values returned by this hook may not be as expected. It is currently unable to read preview values as defined in your schema;\n * instead, it attempts to infer these preview values by checking against a basic set of potential fields on your document.\n * We are anticipating being able to significantly improve this hook's functionality and output in a future release.\n * For now, we recommend using {@link useDocumentProjection} for rendering individual document fields (or projections of those fields).\n *\n * Internally, this hook is implemented as a specialized projection with post-processing logic.\n * It uses a fixed GROQ projection to fetch common preview fields (title, subtitle, media) and\n * transforms the results into the PreviewValue format.\n *\n * @category Documents\n * @param options - The document handle for the document you want to infer preview values for, and an optional ref\n * @returns The inferred values for the given document and a boolean to indicate whether the resolution is pending\n *\n * @example Combining with useDocuments to render a collection of document previews\n * ```\n * // PreviewComponent.jsx\n * export default function PreviewComponent({ document }) {\n * const { data: { title, subtitle, media }, isPending } = useDocumentPreview({ document })\n * return (\n * <article style={{ opacity: isPending ? 0.5 : 1}}>\n * {media?.type === 'image-asset' ? <img src={media.url} alt='' /> : ''}\n * <h2>{title}</h2>\n * <p>{subtitle}</p>\n * </article>\n * )\n * }\n *\n * // DocumentList.jsx\n * const { data } = useDocuments({ filter: '_type == \"movie\"' })\n * return (\n * <div>\n * <h1>Movies</h1>\n * <ul>\n * {data.map(movie => (\n * <li key={movie._id}>\n * <Suspense fallback='Loading…'>\n * <PreviewComponent document={movie} />\n * </Suspense>\n * </li>\n * ))}\n * </ul>\n * </div>\n * )\n * ```\n */\nexport function useDocumentPreview({\n ref,\n ...docHandle\n}: useDocumentPreviewOptions): useDocumentPreviewResults {\n const instance = useSanityInstance()\n trackHookUsage(instance, 'useDocumentPreview')\n const normalizedDocHandle = useNormalizedResourceOptions(docHandle)\n\n // Use the projection hook with the fixed preview projection\n const projectionResult = useDocumentProjection<PreviewQueryResult>({\n ...normalizedDocHandle,\n projection: PREVIEW_PROJECTION,\n ref,\n })\n\n // Contract: useDocumentProjection suspends while data is null, so data is always available here.\n // Keep this non-null assumption aligned with useDocumentPreviewResults.data.\n const previewValue = useMemo(\n () =>\n transformProjectionToPreview(instance, projectionResult.data, normalizedDocHandle.resource),\n [projectionResult.data, instance, normalizedDocHandle.resource],\n )\n\n return {\n data: previewValue,\n isPending: projectionResult.isPending,\n }\n}\n","import {type Project, project, type ProjectOptions} from '@sanity/sdk'\n\nimport {createFetcherHook, type FetcherHookResult} from '../helpers/createFetcherHook'\nimport {useResolvedProjectId} from '../helpers/useResolvedProjectId'\n\nconst useProjectBase = createFetcherHook(project)\n\n/**\n * Returns metadata for a given project.\n *\n * @category Projects\n * @param options - Configuration options\n * @returns A {@link FetcherHookResult} whose `data` is the metadata for the\n * project. `members` is included only when `includeMembers: true`; `features`\n * is included unless `includeFeatures: false`.\n * @example\n * ```tsx\n * function ProjectMetadata({projectId}: {projectId: string}) {\n * const {data: project} = useProject({projectId})\n *\n * return (\n * <figure style={{backgroundColor: project.metadata.color || 'lavender'}}>\n * <h1>{project.displayName}</h1>\n * </figure>\n * )\n * }\n * ```\n * @example\n * ```tsx\n * const {data: projectWithMembersAndFeatures} = useProject({projectId})\n * const {data: projectWithMembers} = useProject({projectId, includeMembers: true})\n * const {data: projectWithoutMembers} = useProject({projectId, includeMembers: false})\n * const {data: projectWithoutFeatures} = useProject({projectId, includeFeatures: false})\n * ```\n * @remarks\n * The `projectId` is resolved in order from:\n * 1. an explicit `projectId` option\n * 2. A legacy ProjectContext (e.g. a `<ResourceProvider projectId=\"…\">` with no dataset), then\n * 3. The active resource (`ResourceProvider`/`SDKProvider`)\n * 4. `instance.config`.\n * @public\n * @function\n */\nexport const useProject = ((options?: ProjectOptions<boolean, boolean>) => {\n const projectId = useResolvedProjectId(options)\n return useProjectBase(projectId ? {...options, projectId} : options)\n}) as <IncludeMembers extends boolean = true, IncludeFeatures extends boolean = true>(\n options?: ProjectOptions<IncludeMembers, IncludeFeatures>,\n) => FetcherHookResult<Project<IncludeMembers, IncludeFeatures>>\n","import {type Project, projects, type ProjectsOptions} from '@sanity/sdk'\n\nimport {createFetcherHook, type FetcherHookResult} from '../helpers/createFetcherHook'\n\n/**\n * Returns metadata for each project you have access to.\n *\n * @category Projects\n * @param options - Configuration options\n * @returns A {@link FetcherHookResult} whose `data` is an array of project\n * metadata. `members` is included only when `includeMembers: true`; `features`\n * is included unless `includeFeatures: false`.\n * @example\n * ```tsx\n * const {data: projects} = useProjects()\n *\n * return (\n * <select>\n * {projects.map((project) => (\n * <option key={project.id}>{project.displayName}</option>\n * ))}\n * </select>\n * )\n * ```\n * @example\n * ```tsx\n * const {data: projects} = useProjects()\n * const {data: projectsWithFeatures} = useProjects()\n * const {data: projectsWithMembers} = useProjects({includeMembers: true})\n * const {data: projectsWithoutMembers} = useProjects({includeMembers: false})\n * const {data: projectsWithoutFeatures} = useProjects({includeFeatures: false})\n * ```\n * @public\n * @function\n */\nexport const useProjects = createFetcherHook(projects) as <\n IncludeMembers extends boolean = false,\n IncludeFeatures extends boolean = true,\n>(\n options?: ProjectsOptions<IncludeMembers, IncludeFeatures>,\n) => FetcherHookResult<Project<IncludeMembers, IncludeFeatures>[]>\n","import {\n type DatasetHandle,\n type DocumentResource,\n getActiveReleasesState,\n type ReleaseDocument,\n type SanityInstance,\n type StateSource,\n} from '@sanity/sdk'\nimport {filter, firstValueFrom} from 'rxjs'\n\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\nimport {\n useNormalizedResourceOptions,\n type WithResourceNameSupport,\n} from '../helpers/useNormalizedResourceOptions'\n\ntype UseActiveReleasesValue = {\n (options?: {resource?: DocumentResource}): ReleaseDocument[]\n}\n\nconst useActiveReleasesValue: UseActiveReleasesValue = createStateSourceHook({\n getState: getActiveReleasesState as (\n instance: SanityInstance,\n options?: {resource?: DocumentResource},\n ) => StateSource<ReleaseDocument[]>,\n shouldSuspend: (instance: SanityInstance, options?: {resource?: DocumentResource}) =>\n getActiveReleasesState(instance, options ?? {}).getCurrent() === undefined,\n suspender: (instance: SanityInstance, options?: {resource?: DocumentResource}) =>\n firstValueFrom(\n getActiveReleasesState(instance, options ?? {}).observable.pipe(filter(Boolean)),\n ),\n})\n\n/**\n * @public\n * @function\n *\n * Returns the active releases for the current project,\n * represented as a list of release documents.\n *\n * @returns The active releases for the current project.\n * @category Releases\n * @example\n * ```tsx\n * import {useActiveReleases} from '@sanity/sdk-react'\n *\n * const activeReleases = useActiveReleases()\n * ```\n */\nexport function useActiveReleases(\n options?: WithResourceNameSupport<DatasetHandle> | undefined,\n): ReleaseDocument[] {\n const normalizedOptions = useNormalizedResourceOptions(options ?? {})\n return useActiveReleasesValue(normalizedOptions)\n}\n","import {\n type DatasetHandle,\n type DocumentResource,\n getAllReleasesState,\n type ReleaseDocument,\n type SanityInstance,\n type StateSource,\n} from '@sanity/sdk'\nimport {filter, firstValueFrom} from 'rxjs'\n\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\nimport {\n useNormalizedResourceOptions,\n type WithResourceNameSupport,\n} from '../helpers/useNormalizedResourceOptions'\n\ntype UseAllReleasesValue = {\n (options?: {resource?: DocumentResource}): ReleaseDocument[]\n}\n\nconst useAllReleasesValue: UseAllReleasesValue = createStateSourceHook({\n getState: getAllReleasesState as (\n instance: SanityInstance,\n options?: {resource?: DocumentResource},\n ) => StateSource<ReleaseDocument[]>,\n shouldSuspend: (instance: SanityInstance, options?: {resource?: DocumentResource}) =>\n getAllReleasesState(instance, options ?? {}).getCurrent() === undefined,\n suspender: (instance: SanityInstance, options?: {resource?: DocumentResource}) =>\n firstValueFrom(getAllReleasesState(instance, options ?? {}).observable.pipe(filter(Boolean))),\n})\n\n/**\n * @public\n * @function\n *\n * Returns every release the dataset has — including `archived`, `published`,\n * and mid-transition states (`archiving`, `unarchiving`, `publishing`,\n * `scheduling`).\n *\n * Use this hook when you're building a release-management UI (listing\n * releases, surfacing lifecycle controls, etc.) so a release stays visible\n * across its full lifecycle — including after it's been published or\n * archived. For perspective / content queries, prefer\n * {@link useActiveReleases}, which filters to releases that still affect\n * what's queryable.\n *\n * @returns Every release for the current project, sorted to match the order\n * used by {@link useActiveReleases}.\n * @category Releases\n * @example\n * ```tsx\n * import {useAllReleases} from '@sanity/sdk-react'\n *\n * const releases = useAllReleases()\n * ```\n */\nexport function useAllReleases(\n options?: WithResourceNameSupport<DatasetHandle> | undefined,\n): ReleaseDocument[] {\n const normalizedOptions = useNormalizedResourceOptions(options ?? {})\n return useAllReleasesValue(normalizedOptions)\n}\n","import {type ActionsResult, type ReleaseAction} from '@sanity/sdk'\n\nimport {type ResourceHandle} from '../../config/handles'\nimport {useApplyActions} from '../helpers/useApplyActions'\n\n/**\n * @public\n */\ninterface UseApplyReleaseActions {\n (): (action: ReleaseAction | ReleaseAction[], options?: ResourceHandle) => Promise<ActionsResult>\n}\n\n/**\n * @public\n *\n * Provides a stable callback function for applying one or more release actions.\n *\n * This hook wraps the core `applyDocumentActions` functionality from `@sanity/sdk`,\n * integrating it with the React component lifecycle and {@link SanityInstance}.\n * It accepts release-lifecycle actions generated by {@link createRelease},\n * {@link editRelease}, {@link publishRelease}, {@link scheduleRelease},\n * {@link unscheduleRelease}, {@link archiveRelease}, {@link unarchiveRelease},\n * and {@link deleteRelease}.\n *\n * Note that actions submitted via this hook will cascade to the documents in the release.\n * For example, if you create a release and then publish it, the documents in the release will be published.\n * If you delete a published release, the version documents will be deleted.\n *\n * Features:\n * - Applies one or multiple `ReleaseAction` objects.\n * - Supports optimistic updates for create/edit/delete: local release state\n * reflects changes immediately while in-flight.\n * - Handles batching: multiple actions passed together are submitted as a\n * single atomic transaction.\n *\n * Release actions cannot be combined with `liveEdit` document actions in the\n * same transaction. Submit them as separate transactions if you need both.\n *\n * @category Releases\n * @returns A stable callback. When called with a single `ReleaseAction` or an\n * array of `ReleaseAction`s, it returns a promise that resolves to an\n * {@link ActionsResult}.\n *\n * @example Create and schedule a release\n * ```tsx\n * import {\n * createRelease,\n * scheduleRelease,\n * useApplyReleaseActions,\n * type ReleaseHandle,\n * } from '@sanity/sdk-react'\n *\n * function ScheduleReleaseButton({release}: {release: ReleaseHandle}) {\n * const applyRelease = useApplyReleaseActions()\n *\n * const handleSchedule = () =>\n * applyRelease([\n * createRelease(release, {title: 'Summer drop', releaseType: 'asap'}),\n * scheduleRelease(release, '2026-06-01T00:00:00Z'),\n * ])\n *\n * return <button onClick={handleSchedule}>Schedule</button>\n * }\n * ```\n *\n * @example Publish a release\n * ```tsx\n * import {publishRelease, useApplyReleaseActions} from '@sanity/sdk-react'\n *\n * function PublishButton({releaseId}: {releaseId: string}) {\n * const applyRelease = useApplyReleaseActions()\n * return (\n * <button onClick={() => applyRelease(publishRelease({releaseId}))}>\n * Publish all documents in the release\n * </button>\n * )\n * }\n * ```\n */\nexport const useApplyReleaseActions: UseApplyReleaseActions = () => {\n return useApplyActions() as ReturnType<UseApplyReleaseActions>\n}\n","import {\n type DocumentResource,\n getPerspectiveState,\n type SanityInstance,\n type StateSource,\n} from '@sanity/sdk'\nimport {filter, firstValueFrom} from 'rxjs'\n\nimport {type ResourceHandle} from '../../config/handles'\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\nimport {useNormalizedResourceOptions} from '../helpers/useNormalizedResourceOptions'\n\n/**\n * @public\n * @function\n *\n * Returns a single or stack of perspectives for the given perspective handle,\n * which can then be used to correctly query the documents\n * via the `perspective` parameter in the client.\n *\n * @param perspectiveHandle - The perspective handle to get the perspective for.\n * @category Documents\n * @example\n * ```tsx\n * import {usePerspective, useQuery} from '@sanity/sdk-react'\n\n * const perspective = usePerspective({perspective: 'rxg1346', projectId: 'abc123', dataset: 'production'})\n * const {data} = useQuery<Movie[]>('*[_type == \"movie\"]', {\n * perspective: perspective,\n * })\n * ```\n *\n * @returns The perspective for the given perspective handle.\n */\ntype UsePerspectiveValue = {\n (perspectiveHandle: {resource?: DocumentResource}): string | string[]\n}\n\nconst usePerspectiveValue: UsePerspectiveValue = createStateSourceHook({\n getState: getPerspectiveState as (\n instance: SanityInstance,\n perspectiveHandle?: {resource?: DocumentResource},\n ) => StateSource<string | string[]>,\n shouldSuspend: (instance: SanityInstance, options: {resource?: DocumentResource}): boolean =>\n getPerspectiveState(instance, options).getCurrent() === undefined,\n suspender: (instance: SanityInstance, _options?: {resource?: DocumentResource}) =>\n firstValueFrom(getPerspectiveState(instance, _options ?? {}).observable.pipe(filter(Boolean))),\n})\n\n/**\n * @public\n * @function\n */\nexport function usePerspective(perspectiveHandle?: ResourceHandle): string | string[] {\n const normalizedOptions = useNormalizedResourceOptions(perspectiveHandle ?? {})\n return usePerspectiveValue(normalizedOptions)\n}\n","import {type GetUserOptions, getUsersState, resolveUsers, type SanityUser} from '@sanity/sdk'\nimport {getUsersKey, parseUsersKey} from '@sanity/sdk/_internal'\nimport {useEffect, useMemo, useState, useSyncExternalStore, useTransition} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\nimport {trackHookUsage} from '../helpers/useTrackHookUsage'\n\n/**\n * @public\n * @category Types\n */\nexport interface UserResult {\n /**\n * The user data fetched, or undefined if not found.\n */\n data: SanityUser | undefined\n /**\n * Whether a user request is currently in progress\n */\n isPending: boolean\n}\n\n/**\n *\n * @public\n *\n * Retrieves a single user by ID for a given resource (either a project or an organization).\n *\n * @category Users\n * @param options - The user ID, resource type, project ID, or organization ID\n * @returns The user data and loading state\n *\n * @example\n * ```\n * const { data, isPending } = useUser({\n * userId: 'gabc123',\n * resourceType: 'project',\n * projectId: 'my-project-id',\n * })\n *\n * return (\n * <div>\n * {isPending && <p>Loading...</p>}\n * {data && (\n * <figure>\n * <img src={data.profile.imageUrl} alt='' />\n * <figcaption>{data.profile.displayName}</figcaption>\n * <address>{data.profile.email}</address>\n * </figure>\n * )}\n * </div>\n * )\n * ```\n */\nexport function useUser(options: GetUserOptions): UserResult {\n const instance = useSanityInstance()\n trackHookUsage(instance, 'useUser')\n // Use React's useTransition to avoid UI jank when user options change\n const [isPending, startTransition] = useTransition()\n\n // Get the unique key for this user request and its options\n const key = getUsersKey(instance, options)\n // Use a deferred state to avoid immediate re-renders when the user request changes\n const [deferredKey, setDeferredKey] = useState(key)\n // Parse the deferred user key back into user options\n const deferred = useMemo(() => parseUsersKey(deferredKey), [deferredKey])\n\n // Create an AbortController to cancel in-flight requests when needed\n const [ref, setRef] = useState<AbortController>(new AbortController())\n\n // When the user request or options change, start a transition to update the request\n useEffect(() => {\n if (key === deferredKey) return\n\n startTransition(() => {\n if (!ref.signal.aborted) {\n ref.abort()\n setRef(new AbortController())\n }\n\n setDeferredKey(key)\n })\n }, [deferredKey, key, ref])\n\n // Get the state source for this user request from the users store\n // We pass the userId as part of options to getUsersState\n const {getCurrent, subscribe} = useMemo(() => {\n return getUsersState(instance, deferred as GetUserOptions)\n }, [instance, deferred])\n\n // If data isn't available yet, suspend rendering until it is\n // This is the React Suspense integration - throwing a promise\n // will cause React to show the nearest Suspense fallback\n if (getCurrent() === undefined) {\n throw resolveUsers(instance, {...(deferred as GetUserOptions), signal: ref.signal})\n }\n\n // Subscribe to updates and get the current data\n // useSyncExternalStore ensures the component re-renders when the data changes\n // Extract the first user from the users array (since we're fetching by userId, there should be only one)\n const result = useSyncExternalStore(subscribe, getCurrent)\n const data = result?.data[0]\n\n return {data, isPending}\n}\n","import {\n type GetUsersOptions,\n getUsersState,\n loadMoreUsers,\n resolveUsers,\n type SanityUser,\n} from '@sanity/sdk'\nimport {getUsersKey, parseUsersKey} from '@sanity/sdk/_internal'\nimport {useCallback, useEffect, useMemo, useState, useSyncExternalStore, useTransition} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\nimport {useResolvedProjectId} from '../helpers/useResolvedProjectId'\nimport {trackHookUsage} from '../helpers/useTrackHookUsage'\n\n/**\n * @public\n * @category Types\n */\nexport interface UsersResult {\n /**\n * The users fetched.\n */\n data: SanityUser[]\n /**\n * Whether there are more users to fetch.\n */\n hasMore: boolean\n\n /**\n * Whether a users request is currently in progress\n */\n isPending: boolean\n /**\n * Load more users.\n */\n loadMore: () => void\n}\n\n/**\n * Injects a resolved `projectId` into project-scoped users options. A missing\n * `projectId` is a no-op, and organization-scoped queries (explicit\n * `resourceType`/`organizationId`) or options that already carry a `projectId`\n * are returned unchanged.\n */\nfunction withResolvedProjectId(\n options: GetUsersOptions | undefined,\n projectId: string | undefined,\n): GetUsersOptions | undefined {\n if (!projectId) return options\n if (!options) return {projectId}\n const isOrgScoped = options.resourceType === 'organization' || !!options.organizationId\n if (isOrgScoped || options.projectId) return options\n return {...options, projectId}\n}\n\n/**\n *\n * @public\n *\n * Retrieves the users for a given resource (either a project or an organization).\n *\n * @category Users\n * @param params - The resource type, project ID, and the limit of users to fetch\n * @returns A list of users, a boolean indicating whether there are more users to fetch, and a function to load more users\n *\n * @example\n * ```\n * const { data, hasMore, loadMore, isPending } = useUsers({\n * resourceType: 'organization',\n * organizationId: 'my-org-id',\n * batchSize: 10,\n * })\n *\n * return (\n * <div>\n * {data.map(user => (\n * <figure key={user.sanityUserId}>\n * <img src={user.profile.imageUrl} alt='' />\n * <figcaption>{user.profile.displayName}</figcaption>\n * <address>{user.profile.email}</address>\n * </figure>\n * ))}\n * {hasMore && <button onClick={loadMore}>{isPending ? 'Loading...' : 'Load More'}</button>}\n * </div>\n * )\n * ```\n * @remarks\n * For project-scoped queries the `projectId` is resolved in order from:\n * 1. an explicit `projectId` option\n * 2. A legacy ProjectContext (e.g. a `<ResourceProvider projectId=\"…\">` with no dataset), then\n * 3. The active resource (`ResourceProvider`/`SDKProvider`)\n * 4. `instance.config`.\n */\nexport function useUsers(options?: GetUsersOptions): UsersResult {\n const instance = useSanityInstance()\n trackHookUsage(instance, 'useUsers')\n // Use React's useTransition to avoid UI jank when user options change\n const [isPending, startTransition] = useTransition()\n\n // Resolve the projectId from the ambient project/resource context so a\n // project-scoped users request can pick it up rather than the top-level config.\n const resolvedProjectId = useResolvedProjectId(options)\n const effectiveOptions = useMemo(\n () => withResolvedProjectId(options, resolvedProjectId),\n [options, resolvedProjectId],\n )\n\n // Get the unique key for this users request and its options\n const key = getUsersKey(instance, effectiveOptions)\n // Use a deferred state to avoid immediate re-renders when the users request changes\n const [deferredKey, setDeferredKey] = useState(key)\n // Parse the deferred users key back into users options\n const deferred = useMemo(() => parseUsersKey(deferredKey), [deferredKey])\n\n // Create an AbortController to cancel in-flight requests when needed\n const [ref, setRef] = useState<AbortController>(new AbortController())\n\n // When the users request or options change, start a transition to update the request\n useEffect(() => {\n if (key === deferredKey) return\n\n startTransition(() => {\n if (!ref.signal.aborted) {\n ref.abort()\n setRef(new AbortController())\n }\n\n setDeferredKey(key)\n })\n }, [deferredKey, key, ref])\n\n // Get the state source for this users request from the users store\n const {getCurrent, subscribe} = useMemo(() => {\n return getUsersState(instance, deferred)\n }, [instance, deferred])\n\n // If data isn't available yet, suspend rendering until it is\n // This is the React Suspense integration - throwing a promise\n // will cause React to show the nearest Suspense fallback\n if (getCurrent() === undefined) {\n throw resolveUsers(instance, {...deferred, signal: ref.signal})\n }\n\n // Subscribe to updates and get the current data\n // useSyncExternalStore ensures the component re-renders when the data changes\n const {data, hasMore} = useSyncExternalStore(subscribe, getCurrent)!\n\n const loadMore = useCallback(() => {\n loadMoreUsers(instance, effectiveOptions)\n }, [instance, effectiveOptions])\n\n return {data, hasMore, isPending, loadMore}\n}\n","","// Local type declaration for Remix\ntype WindowWithEnv = Window &\n typeof globalThis & {\n ENV?: Record<string, unknown>\n }\n\ntype KnownEnvVar = 'DEV' | 'PKG_VERSION'\n\nexport function getEnv(key: KnownEnvVar): unknown {\n if (typeof import.meta !== 'undefined' && import.meta.env) {\n // Vite environment variables\n return (import.meta.env as unknown as Record<string, unknown>)[key]\n } else if (typeof process !== 'undefined' && process.env) {\n // Node.js or server-side environment variables\n return process.env[key]\n } else if (typeof window !== 'undefined' && (window as WindowWithEnv).ENV) {\n // Remix-style client-side environment variables\n return (window as WindowWithEnv).ENV?.[key]\n }\n return undefined\n}\n","import {version} from '../package.json'\nimport {getEnv} from './utils/getEnv'\n\n/**\n * This version is provided by pkg-utils at build time\n * @internal\n */\nexport const REACT_SDK_VERSION = getEnv('PKG_VERSION') || `${version}-development`\n"],"mappings":";;;;;;;;;;;;;;;;;;AAyBA,SAAAuB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AAME,KAAAA,GACnB,MAAMpD,aAAa2B,UAAU;EAAA,GAAIU;EAAQS,QAAUJ,IAAGI;CAAO,CAAC;CAKhE,IAAA,EAAAhC,MAAAC,YAAwBP,qBAAqB2C,WAAWD,UAAU,GAAEG;CAAA,AAAA5B,EAAA,QAAAM,oBAAAN,EAAA,QAAAE,YAEvC0B,WAAA;EAC3BtD,cAAc4B,UAAUI,gBAAgB;CAAC,GAC1CN,EAAA,MAAAM,kBAAAN,EAAA,MAAAE,UAAAF,EAAA,MAAA4B,MAAAA,KAAA5B,EAAA;CAFD,IAAAR,WAAiBoC,IAEeC;CAEW,OAFX7B,EAAA,QAAAX,QAAAW,EAAA,QAAAV,WAAAU,EAAA,QAAAT,aAAAS,EAAA,QAAAR,YAEzBqC,KAAA;EAAAxC;EAAAC;EAAAC;EAAAC;CAAmC,GAACQ,EAAA,MAAAX,MAAAW,EAAA,MAAAV,SAAAU,EAAA,MAAAT,WAAAS,EAAA,MAAAR,UAAAQ,EAAA,MAAA6B,MAAAA,KAAA7B,EAAA,KAApC6B;AAAoC;;AE/I7C,SAAgBO,OAAOC,KAA2B;CAChD,IAA0CC,YAAYE,KAEpD,OAAQF,YAAYE,IAA2CH;CAC1D,IAAI,OAAOI,UAAY,OAAeA,QAAQD,KAEnD,OAAOC,QAAQD,IAAIH;CACd,IAAI,OAAOK,SAAW,OAAgBA,OAAyBT,KAEpE,OAAQS,OAAyBT,MAAMI;AAG3C;;;;;ACbA,MAAaS,oBAAoBD,OAAO,aAAa,KAAK,GAAGD,QAAO"}
1
+ {"version":3,"file":"index.js","names":["ClientError","SDK_CHANNEL_NAME","SDK_NODE_NAME","AuthStateType","getIsInDashboardState","setAuthToken","isStudioConfig","FrameMessage","NewTokenResponseMessage","RequestNewTokenMessage","WindowMessage","React","PropsWithChildren","useCallback","useEffect","useMemo","useRef","useAuthState","useWindowConnection","useSanityInstance","SdkParentComlinkMessage","SdkChildComlinkMessage","DEFAULT_RESPONSE_TIMEOUT","DashboardTokenRefresh","t0","$","_c","children","instance","isTokenRefreshInProgress","timeoutRef","processed401ErrorRef","authState","t1","Symbol","for","current","clearTimeout","clearRefreshTimeout","t2","name","connectTo","windowConnection","t3","setTimeout","res","fetch","token","errorContainer","document","getElementById","hasUnauthorizedError","Array","from","getElementsByTagName","some","_temp","remove","requestNewToken","t4","t5","t6","error","type","has401Error","ERROR","statusCode","isLoggedOut","LOGGED_OUT","undefined","t7","div","textContent","includes","ComlinkTokenRefreshProvider","FC","isInDashboard","getCurrent","isStudio","config","getLoginUrlState","useMemo","useSyncExternalStore","useSanityInstance","useLoginUrl","$","_c","instance","t0","subscribe","getCurrent","observeOrganizationVerificationState","OrgVerificationResult","useEffect","useState","useSanityInstance","useVerifyOrgProjects","t0","projectIds","$","_c","disabled","undefined","instance","error","setError","isInactive","length","prevInactive","setPrevInactive","t1","t2","verificationObservable$","subscription","subscribe","result","unsubscribe","CHUNK_RELOAD_STORAGE_KEY","readChunkReloadFlag","window","sessionStorage","getItem","setChunkReloadFlag","setItem","clearChunkReloadFlag","removeItem","FONT_SANS_SERIF","FONT_MONOSPACE","styles","Record","React","CSSProperties","container","padding","fontFamily","display","flexDirection","gap","fontSize","heading","margin","fontWeight","paragraph","link","appearance","background","border","font","textDecoration","cursor","code","styles","ErrorProps","heading","description","code","cta","text","href","onClick","Error","t0","$","_c","t1","t2","paragraph","__html","t3","t4","link","t5","container","useEffect","FallbackProps","clearChunkReloadFlag","readChunkReloadFlag","setChunkReloadFlag","Error","reload","window","location","ChunkLoadError","_props","$","_c","t0","Symbol","for","alreadyAttempted","t1","t2","t3","text","onClick","_temp","useMemo","FallbackProps","getErrorMessage","Error","CorsErrorComponentProps","projectId","CorsErrorComponent","t0","$","_c","error","origin","window","location","t1","url","URL","searchParams","set","toString","corsUrl","t2","description","code","cta","text","href","isInIframe","window","self","top","isLocalUrl","Window","url","location","href","startsWith","AuthError","Error","constructor","error","message","cause","ConfigurationError","Error","constructor","error","message","cause","SanityInstance","useCallback","useSanityInstance","createCallbackHook","callback","instance","params","TParams","TReturn","useHook","$","_c","t0","t1","handleAuthCallback","createCallbackHook","useHandleAuthCallback","useEffect","useHandleAuthCallback","LoginCallback","$","_c","handleAuthCallback","t0","t1","url","URL","location","href","toString","then","_temp","replacementLocation","history","replaceState","logout","createCallbackHook","useLogOut","SDK_CHANNEL_NAME","SDK_NODE_NAME","useEffect","useWindowConnection","DashboardAccessRequestProps","projectId","DashboardAccessRequest","t0","$","_c","t1","Symbol","for","name","connectTo","fetch","t2","t3","resourceType","resourceId","ClientError","AuthStateType","getIsInDashboardState","getClientErrorApiBody","getClientErrorApiDescription","isProjectUserNotFoundClientError","Suspense","useCallback","useEffect","useMemo","useRef","FallbackProps","useAuthState","useLogOut","useSanityInstance","Error","AuthError","ConfigurationError","DashboardAccessRequest","LoginErrorProps","LoginError","t0","$","_c","error","resetErrorBoundary","logout","authState","instance","config","t1","projectId","clientError","cause","t2","getCurrent","isInDashboard","t3","statusCode","isProjectUserNotFound","dashboardAccessProjectId","t4","handleRetry","message","retry","t5","description","errorMessage","startsWith","endsWith","type","ERROR","authErrorMessage","showRetryCta","hasAutoLoggedOutRef","t6","t7","current","t8","t9","t10","text","onClick","undefined","t11","t12","CorsOriginError","AuthStateType","getCorsErrorProjectId","isImportError","isDashboardEnvironment","isStudioConfig","useEffect","useMemo","ErrorBoundary","FallbackProps","ComlinkTokenRefreshProvider","DashboardTokenRefreshProvider","useAuthState","useLoginUrl","useVerifyOrgProjects","useSanityInstance","ChunkLoadError","CorsErrorComponent","isInIframe","AuthError","ConfigurationError","LoginCallback","LoginError","LoginErrorProps","document","querySelector","parsedUrl","URL","window","location","href","mode","URLSearchParams","hash","slice","get","script","createElement","src","type","async","head","appendChild","AuthBoundaryProps","LoginComponent","React","ComponentType","header","ReactNode","footer","CallbackComponent","LoginErrorComponent","projectIds","children","verifyOrganization","AuthBoundary","t0","$","_c","props","t1","undefined","authState","sessionResetKey","LOGGED_IN","token","t2","LoginComponentWithLayoutProps","fallbackProps","error","FallbackComponent","t3","t4","t5","AuthSwitchProps","AuthSwitch","instance","config","isStudio","disableVerifyOrg","orgError","isLoggedOut","LOGGED_OUT","isDestroyingSession","loginUrl","message","ERROR","LOGGING_IN","t6","Error","TokenSource","createContext","StudioWorkspaceHandle","projectId","dataset","authenticated","auth","token","SDKStudioContext","displayName","DEFAULT_RESOURCE_NAME","CanvasResource","getClientState","MediaLibraryResource","SanityInstance","firstValueFrom","API_VERSION","OrgResourcesApiItem","id","OrgResourcesApiResponse","data","OrgResources","mediaLibrary","canvas","getFirstResourceId","result","PromiseSettledResult","status","undefined","value","resolveOrgResources","instance","organizationId","Promise","client","apiVersion","scope","observable","mediaLibrariesResult","canvasesResult","allSettled","request","url","query","tag","mediaLibraryId","canvasId","DocumentResource","createContext","ResourcesContext","Record","DocumentResource","SanityInstance","ReactElement","ReactNode","use","useMemo","useSanityInstance","useOrganizationId","resolveOrgResources","ResourcesContext","DEFAULT_MEDIA_LIBRARY_RESOURCE_NAME","DEFAULT_CANVAS_RESOURCE_NAME","OrgResource","OrgResourcePromises","Map","PromiseLike","inferredResourceCache","WeakMap","getOrgResourcePromises","instance","organizationId","promises","get","basePromise","then","result","error","console","warn","mediaLibrary","undefined","canvas","r","set","InferredResourcesProvider","t0","$","_c","orgId","explicitResources","children","ml","inferred","t1","resources","t2","OrganizationResourcesProvider","inferMediaLibraryAndCanvas","t3","DocumentResource","createContext","ResourceContext","undefined","PerspectiveHandle","createContext","PerspectiveContext","undefined","createContext","ProjectContext","undefined","SanityInstance","Suspense","SanityInstanceContext","SanityInstanceProviderProps","instance","fallback","React","ReactNode","children","SanityInstanceProvider","t0","$","_c","t1","t2","createSanityInstance","DatasetResource","DocumentResource","isDatasetResource","SanityConfig","SanityInstance","initTelemetry","useContext","useEffect","useMemo","useRef","useState","ResourceContext","PerspectiveContext","ProjectContext","SanityInstanceContext","SanityInstanceProvider","DEFAULT_FALLBACK","ResourceProviderProps","resource","fallback","React","ReactNode","children","ResourceProvider","t0","$","_c","config","parentPerspective","parentResource","parentInstance","parentProjectId","projectId","dataset","perspective","t1","instance","t2","bb0","t3","undefined","configResource","bb1","effectiveResource","t4","bb2","effectiveProjectId","t5","t6","disposal","t7","t8","current","clearTimeout","timeoutId","setTimeout","isDisposed","dispose","t9","t10","t11","t12","t13","t14","DocumentResource","isDatasetResource","isImportError","SanityConfig","ReactElement","ReactNode","useEffect","useMemo","ErrorBoundary","FallbackProps","DEFAULT_RESOURCE_NAME","OrganizationResourcesProvider","ResourceProvider","AuthBoundary","AuthBoundaryProps","ChunkLoadError","clearChunkReloadFlag","SDKProviderProps","children","config","fallback","resources","Record","inferMediaLibraryAndCanvas","ResetChunkReloadFlagOnMount","$","_c","t0","Symbol","for","_temp","SDKProvider","props","defaultConfig","Array","isArray","defaultProjectId","projectId","defaultDataset","dataset","t1","bb0","t2","explicit","Object","hasOwn","t3","t4","resourcesValue","values","filter","map","_temp2","Set","_temp3","_temp4","from","projectIds","t5","t6","t7","ChunkAwareFallback","id","configObj","resource","fallbackProps","error","DocumentResource","SanityConfig","isStudioConfig","ReactElement","useContext","useEffect","useMemo","SDKStudioContext","StudioWorkspaceHandle","SDKProvider","isInIframe","isLocalUrl","SanityAppProps","config","resources","Record","children","React","ReactNode","fallback","inferMediaLibraryAndCanvas","REDIRECT_URL","deriveConfigFromWorkspace","workspace","projectId","dataset","studio","authenticated","auth","token","undefined","SanityApp","t0","$","_c","configProp","props","studioWorkspace","t1","bb0","t2","Symbol","for","resolvedConfig","t3","timeout","primaryConfig","Array","isArray","shouldRedirectWithoutConfig","window","setTimeout","_temp","clearTimeout","t4","console","warn","location","replace","SanityConfig","StrictMode","createRoot","SanityApp","RenderSanitySDKAppOptions","reactStrictMode","NamedSources","key","renderSanityApp","rootElement","HTMLElement","namedSources","options","children","React","ReactNode","Error","root","config","Object","values","render","unmount","Fetcher","FetcherSnapshot","isDeepEqual","useRef","useSyncExternalStore","useSanityInstance","FetcherHookResult","data","TData","isFetching","error","refetch","Promise","createFetcherHook","fetcher","TParams","params","useFetcherHook","instance","source","getState","getCurrent","status","resolveState","previous","snapshot","subscribe","next","prev","current","AccessResourceType","checkPermissions","createFetcherHook","FetcherHookResult","useCheckPermissions","resourceType","resourceId","permissions","Permission","Record","DocumentResource","PerspectiveHandle","useContext","useMemo","ResourceContext","PerspectiveContext","ResourcesContext","SanityInstanceContext","NormalizedResourceFields","WithResourceNameSupport","resource","T","resourceName","normalizeResourceOptions","projectId","dataset","perspective","options","resources","Record","contextResource","contextPerspective","Omit","rest","Error","JSON","stringify","resolvedResource","Object","hasOwn","resolvedPerspective","undefined","useEffectiveContextResource","$","_c","instance","t0","config","configResource","t1","bb0","t2","useNormalizedResourceOptions","effectiveContextResource","agentGenerate","AgentGenerateOptions","agentPatch","AgentPatchOptions","AgentPatchResult","agentPrompt","AgentPromptOptions","AgentPromptResult","agentTransform","AgentTransformOptions","agentTranslate","AgentTranslateOptions","useCallback","firstValueFrom","ResourceHandle","useSanityInstance","useNormalizedResourceOptions","Subscription","unsubscribe","Observer","next","value","T","error","err","complete","Subscribable","subscribe","observer","useAgentGenerate","resourceHandle","$","_c","instance","t0","resource","t1","options","useAgentTransform","useAgentTranslate","useAgentPrompt","useAgentPatch","Application","application","ApplicationInclude","createFetcherHook","FetcherHookResult","useApplication","applicationId","options","include","Include","ApplicationInclude","applications","ApplicationsOptions","ApplicationsResponse","createFetcherHook","FetcherHookResult","useApplications","options","Include","SanityInstance","MutationResult","useCallback","useRef","useState","useSanityInstance","MutationHookResult","mutate","input","TInput","Promise","TResult","isPending","error","data","reset","MutationState","status","createMutationHook","mutation","instance","idle","undefined","useMutationHook","state","setState","callId","id","current","prev","then","deleteApplication","createMutationHook","useDeleteApplication","updateApplication","createMutationHook","useUpdateApplication","getTokenState","createStateSourceHook","useAuthToken","CurrentUser","getCurrentUserState","createStateSourceHook","UseCurrentUser","useCurrentUser","handleOAuthCallback","createCallbackHook","useHandleOAuthCallback","startOAuthAuthorization","createCallbackHook","useOAuthAuthorize","getOAuthTokensState","OAuthTokens","refreshOAuthTokens","revokeOAuthTokens","SanityInstance","createCallbackHook","createStateSourceHook","UseOAuthTokensResult","tokens","Omit","isExpired","refresh","Promise","revoke","useOAuthTokensState","useRefreshOAuthTokens","useRevokeOAuthTokens","useIsOAuthTokenExpired","instance","getCurrent","expiresAt","getTime","Date","now","useOAuthTokens","$","_c","t0","t1","t2","t3","t4","ClientOptions","getClientState","SanityInstance","createStateSourceHook","useClient","getState","instance","options","Error","getConfig","ChannelInstance","Controller","Status","FrameMessage","getOrCreateChannel","getOrCreateController","releaseChannel","WindowMessage","useCallback","useEffect","useRef","useSanityInstance","FrameMessageHandler","event","TWindowMessage","Promise","UseFrameConnectionOptions","name","connectTo","targetOrigin","onMessage","data","Extract","type","K","heartbeat","onStatus","status","FrameConnection","connect","frameWindow","Window","sendMessage","TFrameMessage","params","T","useFrameConnection","options","$","_c","instance","controllerRef","channelRef","t0","t1","controller","channel","current","messageUnsubscribers","Object","entries","forEach","t2","handler","unsubscribe","on","push","_temp","Symbol","for","removeTarget","addTarget","t3","type_0","post","t4","unsub","SanityInstance","trackHookMounted","useRef","useSanityInstance","useTrackHookUsage","hookName","instance","tracked","current","trackHookUsage","Comment","createComment","CreateCommentOptions","DocumentResource","PerspectiveHandle","removeComment","RemoveCommentOptions","replyToComment","ReplyToCommentOptions","setCommentStatus","SetCommentStatusOptions","updateComment","UpdateCommentOptions","useContext","useMemo","PerspectiveContext","ResourcesContext","useSanityInstance","normalizeResourceOptions","useEffectiveContextResource","WithResourceNameSupport","trackHookUsage","CommentActions","options","Promise","Resolvable","resource","resourceName","projectId","dataset","perspective","useCommentActions","$","_c","instance","resources","contextResource","contextPerspective","t0","resolve","t1","options_0","options_1","options_2","options_3","options_4","CommentsOptions","SanityInstance","StateSource","getCommentsOptionsKey","parseCommentsOptionsKey","useEffect","useMemo","useRef","useState","useSyncExternalStore","useTransition","useSanityInstance","useNormalizedResourceOptions","WithResourceNameSupport","trackHookUsage","CommentListSource","getState","instance","options","T","resolve","signal","AbortSignal","Promise","useCommentList","hookName","value","isPending","normalized","startTransition","key","deferredKey","setDeferredKey","abortRef","AbortController","current","aborted","abort","deferred","getCurrent","subscribe","undefined","currentSignal","Comment","CommentsOptions","getCommentsState","resolveComments","useMemo","WithResourceNameSupport","CommentListSource","useCommentList","UseCommentsResult","comments","isPending","SOURCE","getState","resolve","useComments","options","$","_c","value","t0","CommentsOptions","CommentThread","getCommentThreadsState","resolveCommentThreads","useMemo","WithResourceNameSupport","CommentListSource","useCommentList","UseCommentThreadsResult","threads","isPending","SOURCE","getState","resolve","useCommentThreads","options","$","_c","value","t0","DocumentResource","useEffectiveContextResource","useResource","CanvasResource","MediaResource","StudioResource","DocumentHandle","FavoriteDocumentContext","useMemo","useSanityInstance","UseFavoriteProps","resourceId","resourceType","schemaName","useFavoriteContext","t0","$","_c","documentId","documentType","projectId","paramProjectId","dataset","paramDataset","paramResourceId","config","Error","t1","favorites","createFetcherHook","useFavoriteContext","UseFavoriteProps","useFavoriteStatus","useFavorite","props","context","data","isFavorited","CanvasResource","Events","MediaResource","SDK_CHANNEL_NAME","SDK_NODE_NAME","StudioResource","DocumentHandle","isDashboardEnvironment","FrameMessage","useCallback","useWindowConnection","useEmit","useTopic","DocumentInteractionHistory","recordEvent","eventType","UseRecordDocumentHistoryEventProps","resourceType","resourceId","schemaName","useRecordDocumentHistoryEvent","props","useBusRecordDocumentHistoryEvent","useComlinkRecordDocumentHistoryEvent","t0","$","_c","documentId","documentType","t1","Symbol","for","name","connectTo","sendMessage","Error","t2","message","type","data","document","id","resource","t3","error","console","emitActivity","capabilities","history","kind","FavoriteStatusResponse","setFavorite","useCallback","createMutationHook","useFavoriteContext","UseFavoriteProps","useSetFavorite","UpdateFavorite","favorite","Promise","unfavorite","isPending","error","reset","useUpdateFavorite","props","$","_c","context","mutate","t0","isFavorited","t1","t2","DocumentResource","isDatasetResource","useContext","ProjectContext","useNormalizedResourceOptions","useResolvedProjectId","options","$","_c","t0","resource","contextProjectId","t1","projectId","undefined","DatasetsResponse","datasets","ProjectHandle","createFetcherHook","FetcherHookResult","useResolvedProjectId","useDatasetsBase","useDatasets","options","$","_c","projectId","t0","Action","ActionsResult","applyDocumentActions","isDeepEqual","useContext","ResourceHandle","ResourcesContext","useSanityInstance","normalizeResourceOptions","useEffectiveContextResource","useApplyActions","$","_c","instance","resources","effectiveContextResource","t0","actionOrActions","options","actions","Array","isArray","optionsResource","resource","undefined","normalizedActions","map","action","action_0","actionResource","Error","JSON","stringify","effectiveResource","ActionsResult","DocumentAction","ResolveDocument","ResourceHandle","useApplyActions","useEditDocument","UseApplyDocumentActions","action","TDocumentType","TDataset","TProjectId","options","Promise","useApplyDocumentActions","ReturnType","createDocument","ResolveDocument","randomUuid","DocumentHandle","DocumentTypeHandle","useSanityInstance","trackHookUsage","useApplyDocumentActions","IgnoredKey","CreateDocumentOverrides","documentId","useCreateDocument","options","TDocumentType","TDataset","TProjectId","initialValue","Partial","Omit","overrides","Promise","Record","TData","$","_c","instance","apply","t0","handle","DocumentOptions","getDocumentState","JsonMatch","ResolveDocument","resolveDocument","identity","DocumentHandle","createStateSourceHook","useNormalizedResourceOptions","useTrackHookUsage","useDocumentProjection","useQuery","useDocumentValue","getState","instance","options","shouldSuspend","path","_path","getCurrent","undefined","suspender","getConfig","wrapHookWithData","useValue","params","TParams","TReturn","useHook","data","UseDocumentOptions","TDocumentType","TDataset","TProjectId","TPath","UseDocument","TData","useDocument","normalizedOptions","DocumentEvent","subscribeDocumentEvents","useCallback","useEffect","useInsertionEffect","useRef","ResourceHandle","useSanityInstance","useNormalizedResourceOptions","useTrackHookUsage","UseDocumentEventOptions","TDataset","TProjectId","onEvent","documentEvent","useDocumentEvent","options","$","_c","normalizedOptions","datasetHandle","ref","t0","current","t1","Symbol","for","stableHandler","instance","t2","t3","resource","eventHandler","DocumentAction","DocumentPermissionsResult","getPermissionsState","isDeepEqual","useCallback","useContext","useMemo","useSyncExternalStore","filter","firstValueFrom","ResourcesContext","useSanityInstance","normalizeResourceOptions","useEffectiveContextResource","WithResourceNameSupport","trackHookUsage","noopSubscribe","returnUndefined","undefined","useDocumentPermissions","actionOrActions","$","_c","instance","effectiveContextResource","resources","t0","bb0","normalized","Array","isArray","map","action","resource","action_0","actions","error","Error","JSON","stringify","t1","normalizedActions","actionResource","validationError","effectiveResource","permissionsOptions","t2","stateSource","isDocumentReady","getCurrent","result","subscribe","observable","pipe","_temp","permissions","DocumentHandle","DocumentOptions","getDocumentSyncStatus","resolveDocument","SanityInstance","StateSource","identity","createStateSourceHook","useNormalizedResourceOptions","UseDocumentSyncStatus","doc","useDocumentSyncStatusValue","getState","instance","shouldSuspend","getCurrent","undefined","suspender","getConfig","useDocumentSyncStatus","options","normalizedOptions","ActionsResult","DocumentOptions","editDocument","getDocumentState","JsonMatch","ResolveDocument","resolveDocument","useCallback","useSanityInstance","useNormalizedResourceOptions","trackHookUsage","useApplyDocumentActions","ignoredKeys","Updater","TValue","currentValue","useEditDocument","options","TDocumentType","TDataset","TProjectId","nextValue","Promise","TPath","TData","t0","$","_c","doc","path","instance","normalizedDoc","apply","isDocumentReady","getCurrent","undefined","t1","updater","currentPath","stateWithOptions","prev","set","fullDocState","current","nextValue_0","Error","allKeys","Object","keys","editActions","filter","_temp","key_0","key","Record","map","key_1","unset","includes","getQueryState","QueryOptions","resolveQuery","ResolveQueryResult","getQueryKey","parseQueryKey","useEffect","useMemo","useRef","useState","useSyncExternalStore","useTransition","useSanityInstance","useNormalizedResourceOptions","WithResourceNameSupport","trackHookUsage","UseQueryOptions","TQuery","TDataset","TProjectId","useQuery","options","data","isPending","TData","instance","normalized","startTransition","queryKey","deferredQueryKey","setDeferredQueryKey","ref","AbortController","current","signal","aborted","abort","getCurrent","subscribe","deferred","undefined","currentSignal","DocumentHandle","isDatasetResource","QueryOptions","createGroqSearchFilter","pickProperties","SortOrderingItem","useCallback","useMemo","useState","ResourceHandle","useNormalizedResourceOptions","useTrackHookUsage","useQuery","DEFAULT_BATCH_SIZE","DocumentsOptions","TDataset","TProjectId","Pick","documentType","TDocumentType","filter","batchSize","orderings","search","DocumentsResponse","data","hasMore","count","isPending","loadMore","useDocuments","t0","$","_c","params","rawOptions","t1","undefined","options","limit","setLimit","t2","Array","isArray","t3","_temp","documentTypes","t4","JSON","stringify","types","key","prevKey","setPrevKey","conditions","length","trimmedSearch","trim","searchFilter","push","filterClause","join","t5","map","_temp3","orderClause","dataQuery","countQuery","t6","t7","resource","t8","t9","t10","__handle","__types","t11","query","t12","t13","prev","Math","min","t14","ordering","field","direction","toLowerCase","_temp2","Boolean","str","i","Installation","installation","InstallationInclude","createFetcherHook","FetcherHookResult","useInstallation","installationId","options","include","Include","InstallationInclude","installations","InstallationsOptions","InstallationsResponse","createFetcherHook","FetcherHookResult","useInstallations","options","Include","Organization","organization","OrganizationOptions","createFetcherHook","FetcherHookResult","useOrganization","options","IncludeMembers","IncludeFeatures","Organizations","organizations","OrganizationsOptions","createFetcherHook","FetcherHookResult","useOrganizations","options","IncludeMembers","IncludeFeatures","DocumentHandle","isDatasetResource","QueryOptions","createGroqSearchFilter","pickProperties","SortOrderingItem","useCallback","useMemo","useState","useNormalizedResourceOptions","WithResourceNameSupport","useTrackHookUsage","useQuery","PaginatedDocumentsOptions","Omit","TDocumentType","TDataset","TProjectId","documentType","filter","pageSize","orderings","search","PaginatedDocumentsResponse","data","isPending","currentPage","totalPages","startIndex","endIndex","count","firstPage","hasFirstPage","previousPage","hasPreviousPage","nextPage","hasNextPage","lastPage","hasLastPage","goToPage","pageNumber","usePaginatedDocuments","params","rawOptions","options","pageIndex","setPageIndex","key","JSON","stringify","prevKey","setPrevKey","documentTypes","Array","isArray","i","filterClause","conditions","trimmedSearch","trim","searchFilter","push","length","join","orderClause","map","ordering","field","direction","toLowerCase","str","Boolean","dataQuery","countQuery","query","__types","__handle","resource","Math","ceil","prev","max","min","getPresence","isMediaLibraryResource","UserPresence","useCallback","useMemo","useSyncExternalStore","ResourceHandle","useSanityInstance","useNormalizedResourceOptions","trackHookUsage","usePresence","t0","$","_c","t1","undefined","options","normalizedOptions","resource","Error","sanityInstance","t2","source","t3","callback","subscribe","t4","t5","getCurrent","locations","t6","t7","DocumentPresence","getDocumentPresence","isMediaLibraryResource","Path","useCallback","useMemo","useSyncExternalStore","DocumentHandle","useSanityInstance","useNormalizedResourceOptions","trackHookUsage","UsePresenceForDocumentOptions","path","excludeVersions","usePresenceForDocument","options","$","_c","handle","normalizedOptions","resource","Error","sanityInstance","perspective","documentId","liveEdit","t0","JSON","stringify","pathKey","t1","parse","undefined","source","t2","callback","subscribe","t3","t4","getCurrent","presence","t5","t6","isMediaLibraryResource","PresenceSelection","reportPresence","ReportPresenceOptions","Path","useEffect","useMemo","useRef","DocumentHandle","useSanityInstance","useNormalizedResourceOptions","trackHookUsage","FOCUS_THROTTLE_MS","SELECTION_THROTTLE_MS","UseReportPresenceOptions","path","selection","throttleMs","useReportPresence","options","$","_c","handle","normalizedOptions","resource","Error","sanityInstance","perspective","documentId","liveEdit","interval","t0","JSON","stringify","locationKey","t1","parse","id","parsedPath","parsedSelection","parsedPerspective","parsedLiveEdit","t2","t3","t4","length","t5","t6","location","lastSentAt","pending","undefined","t7","t8","send","current","Date","now","locations","elapsed","clearTimeout","setTimeout","t10","t9","getProjectionState","resolveProjection","ResolveProjectionResult","useCallback","useMemo","useSyncExternalStore","distinctUntilChanged","EMPTY","Observable","startWith","switchMap","DocumentHandle","useSanityInstance","useNormalizedResourceOptions","trackHookUsage","useDocumentProjectionOptions","TDocumentType","TDataset","TProjectId","projection","TProjection","params","Record","ref","React","RefObject","useDocumentProjectionResults","data","TData","isPending","useDocumentProjection","options","t0","$","_c","docHandle","instance","t1","trim","normalizedProjection","normalizedDocHandle","t2","stateSource","getCurrent","t3","onStoreChanged","subscription","observer","IntersectionObserver","HTMLElement","next","intersectionObserver","t4","entry","isIntersecting","rootMargin","threshold","current","observe","disconnect","pipe","isVisible","obs","subscribe","unsubscribe","PreviewQueryResult","PreviewValue","PREVIEW_PROJECTION","transformProjectionToPreview","useMemo","DocumentHandle","useSanityInstance","useNormalizedResourceOptions","trackHookUsage","useDocumentProjection","useDocumentPreviewOptions","ref","React","RefObject","useDocumentPreviewResults","data","isPending","useDocumentPreview","t0","$","_c","docHandle","instance","normalizedDocHandle","t1","projection","projectionResult","t2","resource","previewValue","t3","Project","project","ProjectOptions","createFetcherHook","FetcherHookResult","useResolvedProjectId","useProjectBase","useProject","options","projectId","IncludeMembers","IncludeFeatures","Project","projects","ProjectsOptions","createFetcherHook","FetcherHookResult","useProjects","options","IncludeMembers","IncludeFeatures","DatasetHandle","DocumentResource","getActiveReleasesState","ReleaseDocument","SanityInstance","StateSource","filter","firstValueFrom","createStateSourceHook","useNormalizedResourceOptions","WithResourceNameSupport","UseActiveReleasesValue","options","resource","useActiveReleasesValue","getState","instance","shouldSuspend","getCurrent","undefined","suspender","observable","pipe","Boolean","useActiveReleases","$","_c","t0","normalizedOptions","DatasetHandle","DocumentResource","getAllReleasesState","ReleaseDocument","SanityInstance","StateSource","filter","firstValueFrom","createStateSourceHook","useNormalizedResourceOptions","WithResourceNameSupport","UseAllReleasesValue","options","resource","useAllReleasesValue","getState","instance","shouldSuspend","getCurrent","undefined","suspender","observable","pipe","Boolean","useAllReleases","$","_c","t0","normalizedOptions","ActionsResult","ReleaseAction","ResourceHandle","useApplyActions","UseApplyReleaseActions","action","options","Promise","useApplyReleaseActions","ReturnType","DocumentResource","getPerspectiveState","SanityInstance","StateSource","filter","firstValueFrom","ResourceHandle","createStateSourceHook","useNormalizedResourceOptions","UsePerspectiveValue","perspectiveHandle","resource","usePerspectiveValue","getState","instance","shouldSuspend","options","getCurrent","undefined","suspender","_options","observable","pipe","Boolean","usePerspective","$","_c","t0","normalizedOptions","GetUserOptions","getUsersState","resolveUsers","SanityUser","getUsersKey","parseUsersKey","useEffect","useMemo","useState","useSyncExternalStore","useTransition","useSanityInstance","trackHookUsage","UserResult","data","isPending","useUser","options","$","_c","instance","startTransition","t0","key","deferredKey","setDeferredKey","t1","deferred","t2","Symbol","for","AbortController","ref","setRef","t3","t4","signal","aborted","abort","t5","t6","getCurrent","subscribe","undefined","result","t7","GetUsersOptions","getUsersState","loadMoreUsers","resolveUsers","SanityUser","getUsersKey","parseUsersKey","useCallback","useEffect","useMemo","useState","useSyncExternalStore","useTransition","useSanityInstance","useResolvedProjectId","trackHookUsage","UsersResult","data","hasMore","isPending","loadMore","withResolvedProjectId","options","projectId","isOrgScoped","resourceType","organizationId","useUsers","$","_c","instance","startTransition","resolvedProjectId","t0","effectiveOptions","t1","key","deferredKey","setDeferredKey","t2","deferred","t3","Symbol","for","AbortController","ref","setRef","t4","t5","signal","aborted","abort","t6","getCurrent","subscribe","undefined","t7","t8","WindowWithEnv","Window","globalThis","ENV","Record","KnownEnvVar","getEnv","key","import","meta","env","process","window","undefined","version","getEnv","REACT_SDK_VERSION"],"sources":["../src/context/ComlinkTokenRefresh.tsx","../src/hooks/auth/useLoginUrl.tsx","../src/hooks/auth/useVerifyOrgProjects.tsx","../src/components/errors/chunkReloadStorage.ts","../src/components/errors/Error.styles.ts","../src/components/errors/Error.tsx","../src/components/errors/ChunkLoadError.tsx","../src/components/errors/CorsErrorComponent.tsx","../src/components/utils.ts","../src/components/auth/AuthError.ts","../src/components/auth/ConfigurationError.ts","../src/hooks/helpers/createCallbackHook.tsx","../src/hooks/auth/useHandleAuthCallback.tsx","../src/components/auth/LoginCallback.tsx","../src/hooks/auth/useLogOut.tsx","../src/components/auth/DashboardAccessRequest.tsx","../src/components/auth/LoginError.tsx","../src/components/auth/AuthBoundary.tsx","../src/context/SDKStudioContext.ts","../src/constants.ts","../src/utils/resolveOrgResources.ts","../src/context/ResourcesContext.tsx","../src/context/OrganizationResourcesProvider.tsx","../src/context/DefaultResourceContext.ts","../src/context/PerspectiveContext.ts","../src/context/ProjectContext.ts","../src/context/SanityInstanceProvider.tsx","../src/context/ResourceProvider.tsx","../src/components/SDKProvider.tsx","../src/components/SanityApp.tsx","../src/context/renderSanityApp.tsx","../src/hooks/helpers/createFetcherHook.ts","../src/hooks/access/useCheckPermissions.ts","../src/hooks/helpers/useNormalizedResourceOptions.ts","../src/hooks/agent/agentActions.ts","../src/hooks/applications/useApplication.ts","../src/hooks/applications/useApplications.ts","../src/hooks/helpers/createMutationHook.tsx","../src/hooks/applications/useDeleteApplication.ts","../src/hooks/applications/useUpdateApplication.ts","../src/hooks/auth/useAuthToken.tsx","../src/hooks/auth/useCurrentUser.tsx","../src/hooks/auth/useHandleOAuthCallback.tsx","../src/hooks/auth/useOAuthAuthorize.tsx","../src/hooks/auth/useOAuthTokens.tsx","../src/hooks/client/useClient.ts","../src/hooks/comlink/useFrameConnection.ts","../src/hooks/helpers/useTrackHookUsage.ts","../src/hooks/comments/useCommentActions.ts","../src/hooks/comments/useCommentList.ts","../src/hooks/comments/useComments.ts","../src/hooks/comments/useCommentThreads.ts","../src/hooks/context/useResource.ts","../src/hooks/dashboard/useFavoriteContext.ts","../src/hooks/dashboard/useFavorite.ts","../src/hooks/dashboard/useRecordDocumentHistoryEvent.ts","../src/hooks/dashboard/useUpdateFavorite.ts","../src/hooks/helpers/useResolvedProjectId.ts","../src/hooks/datasets/useDatasets.ts","../src/hooks/helpers/useApplyActions.ts","../src/hooks/document/useApplyDocumentActions.ts","../src/hooks/document/useCreateDocument.ts","../src/hooks/document/useDocument.ts","../src/hooks/document/useDocumentEvent.ts","../src/hooks/document/useDocumentPermissions.ts","../src/hooks/document/useDocumentSyncStatus.ts","../src/hooks/document/useEditDocument.ts","../src/hooks/query/useQuery.ts","../src/hooks/documents/useDocuments.ts","../src/hooks/installations/useInstallation.ts","../src/hooks/installations/useInstallations.ts","../src/hooks/organizations/useOrganization.ts","../src/hooks/organizations/useOrganizations.ts","../src/hooks/paginatedDocuments/usePaginatedDocuments.ts","../src/hooks/presence/usePresence.ts","../src/hooks/presence/usePresenceForDocument.ts","../src/hooks/presence/useReportPresence.ts","../src/hooks/projection/useDocumentProjection.ts","../src/hooks/preview/useDocumentPreview.tsx","../src/hooks/projects/useProject.ts","../src/hooks/projects/useProjects.ts","../src/hooks/releases/useActiveReleases.ts","../src/hooks/releases/useAllReleases.ts","../src/hooks/releases/useApplyReleaseActions.ts","../src/hooks/releases/usePerspective.ts","../src/hooks/users/useUser.ts","../src/hooks/users/useUsers.ts","../package.json","../src/utils/getEnv.ts","../src/version.ts"],"sourcesContent":["import {type ClientError} from '@sanity/client'\nimport {SDK_CHANNEL_NAME, SDK_NODE_NAME} from '@sanity/message-protocol'\nimport {AuthStateType, getIsInDashboardState, setAuthToken} from '@sanity/sdk'\nimport {isStudioConfig} from '@sanity/sdk/_internal'\nimport {\n type FrameMessage,\n type NewTokenResponseMessage,\n type RequestNewTokenMessage,\n type WindowMessage,\n} from '@sanity/sdk/comlink'\nimport React, {type PropsWithChildren, useCallback, useEffect, useMemo, useRef} from 'react'\n\nimport {useAuthState} from '../hooks/auth/useAuthState'\nimport {useWindowConnection} from '../hooks/comlink/useWindowConnection'\nimport {useSanityInstance} from '../hooks/context/useSanityInstance'\n\n// Define specific message types extending the base types for clarity\ntype SdkParentComlinkMessage = NewTokenResponseMessage | WindowMessage // Messages received by SDK\ntype SdkChildComlinkMessage = RequestNewTokenMessage | FrameMessage // Messages sent by SDK\n\nconst DEFAULT_RESPONSE_TIMEOUT = 10000 // 10 seconds\n\n/**\n * Component that handles token refresh in dashboard mode\n */\nfunction DashboardTokenRefresh({children}: PropsWithChildren) {\n const instance = useSanityInstance()\n const isTokenRefreshInProgress = useRef(false)\n const timeoutRef = useRef<NodeJS.Timeout | null>(null)\n const processed401ErrorRef = useRef<unknown | null>(null)\n const authState = useAuthState()\n\n const clearRefreshTimeout = useCallback(() => {\n if (timeoutRef.current) {\n clearTimeout(timeoutRef.current)\n timeoutRef.current = null\n }\n }, [])\n\n const windowConnection = useWindowConnection<SdkParentComlinkMessage, SdkChildComlinkMessage>({\n name: SDK_NODE_NAME,\n connectTo: SDK_CHANNEL_NAME,\n })\n\n const requestNewToken = useCallback(async () => {\n if (isTokenRefreshInProgress.current) {\n return\n }\n\n isTokenRefreshInProgress.current = true\n clearRefreshTimeout()\n\n timeoutRef.current = setTimeout(() => {\n if (isTokenRefreshInProgress.current) {\n isTokenRefreshInProgress.current = false\n }\n timeoutRef.current = null\n }, DEFAULT_RESPONSE_TIMEOUT)\n\n try {\n const res = await windowConnection.fetch<{token: string | null; error?: string}>(\n 'dashboard/v1/auth/tokens/create',\n )\n clearRefreshTimeout()\n\n if (res.token) {\n setAuthToken(instance, res.token)\n\n // Remove the unauthorized error from the error container\n const errorContainer = document.getElementById('__sanityError')\n if (errorContainer) {\n const hasUnauthorizedError = Array.from(errorContainer.getElementsByTagName('div')).some(\n (div) =>\n div.textContent?.includes(\n 'Uncaught error: Unauthorized - A valid session is required for this endpoint',\n ),\n )\n\n if (hasUnauthorizedError) {\n errorContainer.remove()\n }\n }\n }\n isTokenRefreshInProgress.current = false\n } catch {\n isTokenRefreshInProgress.current = false\n clearRefreshTimeout()\n }\n }, [windowConnection, clearRefreshTimeout, instance])\n\n useEffect(() => {\n return () => {\n clearRefreshTimeout()\n }\n }, [clearRefreshTimeout])\n\n useEffect(() => {\n const has401Error =\n authState.type === AuthStateType.ERROR &&\n authState.error &&\n (authState.error as ClientError)?.statusCode === 401 &&\n !isTokenRefreshInProgress.current &&\n processed401ErrorRef.current !== authState.error\n\n const isLoggedOut =\n authState.type === AuthStateType.LOGGED_OUT && !isTokenRefreshInProgress.current\n\n if (has401Error || isLoggedOut) {\n processed401ErrorRef.current =\n authState.type === AuthStateType.ERROR ? authState.error : undefined\n requestNewToken()\n } else if (\n authState.type !== AuthStateType.ERROR ||\n processed401ErrorRef.current !==\n (authState.type === AuthStateType.ERROR ? authState.error : undefined)\n ) {\n processed401ErrorRef.current = null\n }\n }, [authState, requestNewToken])\n\n return children\n}\n\n/**\n * This provider is used to provide the Comlink token refresh feature.\n * It is used to automatically request a new token on 401 error if enabled.\n * @public\n */\nexport const ComlinkTokenRefreshProvider: React.FC<PropsWithChildren> = ({children}) => {\n const instance = useSanityInstance()\n const isInDashboard = useMemo(() => getIsInDashboardState(instance).getCurrent(), [instance])\n const isStudio = isStudioConfig(instance.config)\n\n if (isInDashboard && !isStudio) {\n return <DashboardTokenRefresh>{children}</DashboardTokenRefresh>\n }\n\n // If we're not in the dashboard, we don't need to do anything\n return children\n}\n","import {getLoginUrlState} from '@sanity/sdk'\nimport {useMemo, useSyncExternalStore} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n * @internal\n */\nexport function useLoginUrl(): string {\n const instance = useSanityInstance()\n const {subscribe, getCurrent} = useMemo(() => getLoginUrlState(instance), [instance])\n\n return useSyncExternalStore(subscribe, getCurrent as () => string)\n}\n","import {observeOrganizationVerificationState, type OrgVerificationResult} from '@sanity/sdk'\nimport {useEffect, useState} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n * Hook that verifies the current projects belongs to the organization ID specified in the dashboard context.\n *\n * @public\n * @param disabled - When true, disables verification and skips project verification API calls\n * @returns Error message if the project doesn't match the organization ID, or null if all match or verification isn't needed\n * @category Projects\n * @example\n * ```tsx\n * function OrgVerifier() {\n * const error = useVerifyOrgProjects()\n *\n * if (error) {\n * return <div className=\"error\">{error}</div>\n * }\n *\n * return <div>Organization projects verified!</div>\n * }\n * ```\n */\nexport function useVerifyOrgProjects(disabled = false, projectIds?: string[]): string | null {\n const instance = useSanityInstance()\n const [error, setError] = useState<string | null>(null)\n\n const isInactive = disabled || !projectIds || projectIds.length === 0\n\n // Reset stale errors when verification turns off so the next activation\n // doesn't briefly leak the previous result.\n const [prevInactive, setPrevInactive] = useState(isInactive)\n if (prevInactive !== isInactive) {\n setPrevInactive(isInactive)\n if (isInactive) setError(null)\n }\n\n useEffect(() => {\n if (isInactive) return\n\n const verificationObservable$ = observeOrganizationVerificationState(instance, projectIds!)\n\n const subscription = verificationObservable$.subscribe((result: OrgVerificationResult) => {\n setError(result.error)\n })\n\n return () => {\n subscription.unsubscribe()\n }\n }, [instance, isInactive, projectIds])\n\n return error\n}\n","/**\n * Session-storage key tracking whether the SDK has already attempted an\n * automatic reload in response to a chunk-load error during this session.\n *\n * @internal\n */\nexport const CHUNK_RELOAD_STORAGE_KEY = '__sanity_sdk_chunk_reload_attempted'\n\n/**\n * Returns true when this session has already triggered an automatic reload.\n * Returns false if session storage is unreadable.\n *\n * @internal\n */\nexport function readChunkReloadFlag(): boolean {\n try {\n if (typeof window === 'undefined' || typeof window.sessionStorage === 'undefined') {\n return false\n }\n return window.sessionStorage.getItem(CHUNK_RELOAD_STORAGE_KEY) !== null\n } catch {\n return false\n }\n}\n\n/**\n * Marks the session as having attempted an automatic reload, so the next\n * chunk-load error renders the manual reload UI instead of looping.\n *\n * @internal\n */\nexport function setChunkReloadFlag(): void {\n try {\n if (typeof window === 'undefined' || typeof window.sessionStorage === 'undefined') return\n window.sessionStorage.setItem(CHUNK_RELOAD_STORAGE_KEY, '1')\n } catch {\n // Storage may be unavailable (private mode quotas, disabled cookies).\n // Falling through means the user sees the manual-reload UI instead of an\n // automatic reload, which is the correct degradation.\n }\n}\n\n/**\n * Clears the chunk-reload flag. Called from SDKProvider once the SDK\n * mounts successfully past the error boundary so a future incident in the\n * same session can trigger another automatic reload.\n *\n * @internal\n */\nexport function clearChunkReloadFlag(): void {\n try {\n if (typeof window === 'undefined' || typeof window.sessionStorage === 'undefined') return\n window.sessionStorage.removeItem(CHUNK_RELOAD_STORAGE_KEY)\n } catch {\n // No-op: see setChunkReloadFlag.\n }\n}\n","const FONT_SANS_SERIF = `-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Helvetica, Arial, system-ui, sans-serif`\nconst FONT_MONOSPACE = `-apple-system-ui-monospace, 'SF Mono', Menlo, Monaco, Consolas, monospace`\n\nconst styles: Record<string, React.CSSProperties> = {\n container: {\n padding: '28px',\n fontFamily: FONT_SANS_SERIF,\n display: 'flex',\n flexDirection: 'column',\n gap: '21px',\n fontSize: '14px',\n },\n heading: {\n margin: 0,\n fontSize: '28px',\n fontWeight: 700,\n },\n paragraph: {\n margin: 0,\n },\n link: {\n appearance: 'none',\n background: 'transparent',\n border: 0,\n padding: 0,\n font: 'inherit',\n textDecoration: 'underline',\n cursor: 'pointer',\n },\n code: {\n fontFamily: FONT_MONOSPACE,\n },\n}\n\nexport default styles\n","import styles from './Error.styles'\n\ntype ErrorProps = {\n heading: string\n description?: string\n code?: string\n cta?: {\n text: string\n href?: string\n onClick?: () => void\n }\n}\n\nexport function Error({heading, description, code, cta}: ErrorProps): React.ReactNode {\n return (\n <div style={styles['container']}>\n <h1 style={styles['heading']}>{heading}</h1>\n\n {description && (\n <p style={styles['paragraph']} dangerouslySetInnerHTML={{__html: description}} />\n )}\n\n {code && <code style={styles['code']}>{code}</code>}\n\n {cta && (cta.href || cta.onClick) && (\n <p style={styles['paragraph']}>\n {cta.href ? (\n <a style={styles['link']} href={cta.href} target=\"_blank\" rel=\"noopener noreferrer\">\n {cta.text}\n </a>\n ) : (\n <button style={styles['link']} onClick={cta.onClick}>\n {cta.text}\n </button>\n )}\n </p>\n )}\n </div>\n )\n}\n","import {useEffect} from 'react'\nimport {type FallbackProps} from 'react-error-boundary'\n\nimport {clearChunkReloadFlag, readChunkReloadFlag, setChunkReloadFlag} from './chunkReloadStorage'\nimport {Error} from './Error'\n\nfunction reload(): void {\n try {\n window.location.reload()\n } catch {\n // No-op: nothing useful we can do if reload itself throws.\n }\n}\n\n/**\n * Default fallback rendered when a dynamic-import or chunk-load error\n * bubbles up to the SDK's top-level error boundary.\n *\n * On the first occurrence in a session we set a flag and trigger\n * window.location.reload(), since chunk-load errors almost always indicate a\n * stale tab that simply needs a fresh index.html. If the flag is already set\n * we render a manual reload UI instead, which prevents an infinite reload\n * loop in the rare case the error is genuinely unrecoverable (network\n * outage, CSP, etc.).\n *\n * @internal\n */\nexport function ChunkLoadError(_props: FallbackProps): React.ReactNode {\n const alreadyAttempted = readChunkReloadFlag()\n\n useEffect(() => {\n if (alreadyAttempted) return\n setChunkReloadFlag()\n reload()\n }, [alreadyAttempted])\n\n if (!alreadyAttempted) {\n // Render nothing during the brief window before the page reloads so the\n // user does not see a flash of error UI.\n return null\n }\n\n return (\n <Error\n heading=\"A new version is available\"\n description=\"The page tried to load an asset that no longer exists. Reload to continue with the latest version.\"\n cta={{\n text: 'Reload page',\n onClick: () => {\n clearChunkReloadFlag()\n reload()\n },\n }}\n />\n )\n}\n","import {useMemo} from 'react'\nimport {type FallbackProps, getErrorMessage} from 'react-error-boundary'\n\nimport {Error} from './Error'\n\ntype CorsErrorComponentProps = FallbackProps & {\n projectId: string | null\n}\n\nexport function CorsErrorComponent({projectId, error}: CorsErrorComponentProps): React.ReactNode {\n const origin = window.location.origin\n const corsUrl = useMemo(() => {\n const url = new URL(`https://sanity.io/manage/project/${projectId}/api`)\n url.searchParams.set('cors', 'add')\n url.searchParams.set('origin', origin)\n url.searchParams.set('credentials', 'include')\n return url.toString()\n }, [origin, projectId])\n return (\n <Error\n heading=\"Before you continue…\"\n {...(projectId\n ? {\n description:\n 'To access your content, you need to <strong>add the following URL as a CORS origin</strong> to your Sanity project.',\n code: origin,\n cta: {\n text: 'Manage CORS configuration',\n href: corsUrl,\n },\n }\n : {\n description: getErrorMessage(error),\n })}\n />\n )\n}\n","export function isInIframe(): boolean {\n return typeof window !== 'undefined' && window.self !== window.top\n}\n\n/**\n * @internal\n *\n * Checks if the current URL is a local URL.\n *\n * @param window - The window object\n * @returns True if the current URL is a local URL, false otherwise\n */\nexport function isLocalUrl(window: Window): boolean {\n const url = typeof window !== 'undefined' ? window.location.href : ''\n\n return (\n url.startsWith('http://localhost') ||\n url.startsWith('https://localhost') ||\n url.startsWith('http://127.0.0.1') ||\n url.startsWith('https://127.0.0.1')\n )\n}\n","/**\n * Error class for authentication-related errors. Wraps errors thrown during the\n * authentication flow.\n *\n * @remarks\n * This class provides a consistent error type for authentication failures while\n * preserving the original error as the cause. If the original error has a\n * message property, it will be used as the error message.\n *\n * @alpha\n */\nexport class AuthError extends Error {\n constructor(error: unknown) {\n if (\n typeof error === 'object' &&\n !!error &&\n 'message' in error &&\n typeof error.message === 'string'\n ) {\n super(error.message)\n } else {\n super()\n }\n\n this.cause = error\n }\n}\n","/**\n * Error class for configuration-related errors. Wraps errors thrown during the\n * configuration flow.\n *\n * @alpha\n */\nexport class ConfigurationError extends Error {\n constructor(error: unknown) {\n if (\n typeof error === 'object' &&\n !!error &&\n 'message' in error &&\n typeof error.message === 'string'\n ) {\n super(error.message)\n } else {\n super()\n }\n\n this.cause = error\n }\n}\n","import {type SanityInstance} from '@sanity/sdk'\nimport {useCallback} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\nexport function createCallbackHook<TParams extends unknown[], TReturn>(\n callback: (instance: SanityInstance, ...params: TParams) => TReturn,\n): () => (...params: TParams) => TReturn {\n function useHook() {\n const instance = useSanityInstance()\n return useCallback((...params: TParams) => callback(instance, ...params), [instance])\n }\n\n return useHook\n}\n","import {handleAuthCallback} from '@sanity/sdk'\n\nimport {createCallbackHook} from '../helpers/createCallbackHook'\n\n/**\n * @internal\n * A React hook that returns a function for handling authentication callbacks.\n *\n * @remarks\n * This hook provides access to the authentication store's callback handler,\n * which processes auth redirects by extracting the session ID and fetching the\n * authentication token. If fetching the long-lived token is successful,\n * `handleAuthCallback` will return a Promise that resolves a new location that\n * removes the short-lived token from the URL. Use this in combination with\n * `history.replaceState` or your own router's `replace` function to update the\n * current location without triggering a reload.\n *\n * @example\n * ```tsx\n * function AuthCallback() {\n * const handleAuthCallback = useHandleAuthCallback()\n * const router = useRouter() // Example router\n *\n * useEffect(() => {\n * async function processCallback() {\n * // Handle the callback and get the cleaned URL\n * const newUrl = await handleAuthCallback(window.location.href)\n *\n * if (newUrl) {\n * // Replace URL without triggering navigation\n * router.replace(newUrl, {shallow: true})\n * }\n * }\n *\n * processCallback().catch(console.error)\n * }, [handleAuthCallback, router])\n *\n * return <div>Completing login...</div>\n * }\n * ```\n *\n * @returns A callback handler function that processes OAuth redirects\n * @public\n */\nexport const useHandleAuthCallback = createCallbackHook(handleAuthCallback)\n","import {useEffect} from 'react'\n\nimport {useHandleAuthCallback} from '../../hooks/auth/useHandleAuthCallback'\n\n/**\n * Component shown during auth callback processing that handles login completion.\n * Automatically processes the auth callback when mounted and updates the URL\n * to remove callback parameters without triggering a page reload.\n *\n * @alpha\n */\nexport function LoginCallback(): React.ReactNode {\n const handleAuthCallback = useHandleAuthCallback()\n\n useEffect(() => {\n const url = new URL(location.href)\n handleAuthCallback(url.toString()).then((replacementLocation) => {\n if (replacementLocation) {\n // history API with `replaceState` is used to prevent a reload but still\n // remove the short-lived token from the URL\n history.replaceState(null, '', replacementLocation)\n }\n })\n }, [handleAuthCallback])\n\n return null\n}\n","import {logout} from '@sanity/sdk'\n\nimport {createCallbackHook} from '../helpers/createCallbackHook'\n\n/**\n * Hook to log out of the current session\n * @internal\n * @returns A function to log out of the current session\n */\nexport const useLogOut = createCallbackHook(logout)\n","import {SDK_CHANNEL_NAME, SDK_NODE_NAME} from '@sanity/message-protocol'\nimport {useEffect} from 'react'\n\nimport {useWindowConnection} from '../../hooks/comlink/useWindowConnection'\n\ninterface DashboardAccessRequestProps {\n projectId: string\n}\n\n/**\n * Sends a `dashboard/v1/auth/access/request` message to the dashboard via\n * comlink so the user can request access to a project they don't belong to.\n *\n * This is intentionally isolated in its own component because\n * `useWindowConnection` suspends until a comlink node is available, which\n * never happens outside the dashboard. Callers must gate rendering on\n * `getIsInDashboardState(...).getCurrent()` and wrap this in a\n * {@link https://react.dev/reference/react/Suspense | Suspense} boundary\n * so the suspension stays local instead of bubbling up to the app shell.\n *\n * @internal\n */\nexport function DashboardAccessRequest({projectId}: DashboardAccessRequestProps): null {\n const {fetch} = useWindowConnection({\n name: SDK_NODE_NAME,\n connectTo: SDK_CHANNEL_NAME,\n })\n\n useEffect(() => {\n fetch('dashboard/v1/auth/access/request', {\n resourceType: 'project',\n resourceId: projectId,\n })\n }, [fetch, projectId])\n\n return null\n}\n","import {ClientError} from '@sanity/client'\nimport {AuthStateType, getIsInDashboardState} from '@sanity/sdk'\nimport {\n getClientErrorApiBody,\n getClientErrorApiDescription,\n isProjectUserNotFoundClientError,\n} from '@sanity/sdk/_internal'\nimport {Suspense, useCallback, useEffect, useMemo, useRef} from 'react'\nimport {type FallbackProps} from 'react-error-boundary'\n\nimport {useAuthState} from '../../hooks/auth/useAuthState'\nimport {useLogOut} from '../../hooks/auth/useLogOut'\nimport {useSanityInstance} from '../../hooks/context/useSanityInstance'\nimport {Error} from '../errors/Error'\nimport {AuthError} from './AuthError'\nimport {ConfigurationError} from './ConfigurationError'\nimport {DashboardAccessRequest} from './DashboardAccessRequest'\n/**\n * @alpha\n */\nexport type LoginErrorProps = FallbackProps\n\n/**\n * Displays authentication error details and provides retry functionality.\n * Only handles {@link AuthError} instances - rethrows other error types.\n *\n * @alpha\n */\nexport function LoginError({error, resetErrorBoundary}: LoginErrorProps): React.ReactNode {\n if (\n !(\n error instanceof AuthError ||\n error instanceof ConfigurationError ||\n error instanceof ClientError\n )\n )\n throw error\n\n const logout = useLogOut()\n const authState = useAuthState()\n const instance = useSanityInstance()\n const {\n config: {projectId},\n } = instance\n\n // Errors surfaced through `AuthBoundary` arrive wrapped in `AuthError`, with\n // the original `ClientError` tucked under `.cause`. Unwrapping it here lets\n // the 401/404 branches below respond to the real status code instead of\n // silently skipping because `error instanceof ClientError` is false.\n const clientError: ClientError | null =\n error instanceof ClientError\n ? error\n : error instanceof AuthError && error.cause instanceof ClientError\n ? error.cause\n : null\n\n const isInDashboard = getIsInDashboardState(instance).getCurrent()\n\n const isProjectUserNotFound =\n !!clientError && clientError.statusCode === 401 && isProjectUserNotFoundClientError(clientError)\n\n // The dashboard access request flow relies on a comlink connection to the\n // parent window. In standalone apps that connection never materializes, so\n // we must skip it entirely to avoid suspending forever on the parent's\n // Suspense boundary. Resolving to the projectId (or null) here lets the JSX\n // render the child with a single non-null guard.\n const dashboardAccessProjectId =\n isProjectUserNotFound && projectId && isInDashboard ? projectId : null\n\n const handleRetry = useCallback(async () => {\n await logout()\n resetErrorBoundary()\n }, [logout, resetErrorBoundary])\n\n // Display state is fully derived from the inputs above, so we don't need\n // to mirror it through useState/useEffect.\n const {authErrorMessage, showRetryCta} = useMemo(() => {\n let message = 'Please try again or contact support if the problem persists.'\n let retry = true\n\n if (clientError) {\n if (clientError.statusCode === 401) {\n if (isProjectUserNotFound) {\n const description = getClientErrorApiDescription(clientError)\n if (description) message = description\n retry = false\n } else if (!isInDashboard) {\n message = 'Signing you out and returning to login...'\n retry = true\n }\n // Dashboard non-projectUserNotFound 401: leave the current UI in place\n // and let ComlinkTokenRefreshProvider request a fresh token from the\n // parent window. The Retry button remains as a manual fallback.\n } else if (clientError.statusCode === 404) {\n const errorMessage = getClientErrorApiBody(clientError)?.message || ''\n message =\n errorMessage.startsWith('Session with sid') && errorMessage.endsWith('not found')\n ? 'The session ID is invalid or expired.'\n : 'The login link is invalid or expired. Please try again.'\n retry = true\n }\n }\n if (authState.type !== AuthStateType.ERROR && error instanceof ConfigurationError) {\n message = error.message\n retry = true\n }\n return {authErrorMessage: message, showRetryCta: retry}\n }, [authState, clientError, error, isInDashboard, isProjectUserNotFound])\n\n // Guards against re-entering the standalone auto-logout branch below. Once\n // `logout()` flips the auth store to LOGGED_OUT, `useAuthState` emits a new\n // `authState` reference and re-runs this effect; without the ref we'd call\n // `handleRetry` again on every emission and React eventually aborts with\n // \"Maximum update depth exceeded\", leaving a blank page.\n const hasAutoLoggedOutRef = useRef(false)\n\n // Standalone apps: the token is bad and there's no parent window to mint a\n // new one, so log the user out and let `AuthBoundary`'s LOGGED_OUT effect\n // redirect to the Sanity login URL.\n useEffect(() => {\n if (\n clientError &&\n clientError.statusCode === 401 &&\n !isProjectUserNotFound &&\n !isInDashboard &&\n !hasAutoLoggedOutRef.current\n ) {\n hasAutoLoggedOutRef.current = true\n handleRetry()\n }\n }, [clientError, handleRetry, isInDashboard, isProjectUserNotFound])\n\n return (\n <>\n {dashboardAccessProjectId && (\n <Suspense fallback={null}>\n <DashboardAccessRequest projectId={dashboardAccessProjectId} />\n </Suspense>\n )}\n <Error\n heading={\n error instanceof ConfigurationError ? 'Configuration Error' : 'Authentication Error'\n }\n description={authErrorMessage}\n cta={\n showRetryCta\n ? {\n text: 'Retry',\n onClick: handleRetry,\n }\n : undefined\n }\n />\n </>\n )\n}\n","import {CorsOriginError} from '@sanity/client'\nimport {AuthStateType, getCorsErrorProjectId, isImportError} from '@sanity/sdk'\nimport {isDashboardEnvironment, isStudioConfig} from '@sanity/sdk/_internal'\nimport {useEffect, useMemo} from 'react'\nimport {ErrorBoundary, type FallbackProps} from 'react-error-boundary'\n\nimport {ComlinkTokenRefreshProvider} from '../../context/ComlinkTokenRefresh'\nimport {DashboardTokenRefreshProvider} from '../../context/DashboardTokenRefresh'\nimport {useAuthState} from '../../hooks/auth/useAuthState'\nimport {useLoginUrl} from '../../hooks/auth/useLoginUrl'\nimport {useVerifyOrgProjects} from '../../hooks/auth/useVerifyOrgProjects'\nimport {useSanityInstance} from '../../hooks/context/useSanityInstance'\nimport {ChunkLoadError} from '../errors/ChunkLoadError'\nimport {CorsErrorComponent} from '../errors/CorsErrorComponent'\nimport {isInIframe} from '../utils'\nimport {AuthError} from './AuthError'\nimport {ConfigurationError} from './ConfigurationError'\nimport {LoginCallback} from './LoginCallback'\nimport {LoginError, type LoginErrorProps} from './LoginError'\n\n// Only import bridge if we're in an iframe. This assumes that the app is\n// running within SanityOS if it is in an iframe and that the bridge hasn't already been loaded\nif (isInIframe() && !document.querySelector('[data-sanity-core]')) {\n const parsedUrl = new URL(window.location.href)\n const mode = new URLSearchParams(parsedUrl.hash.slice(1)).get('mode')\n const script = document.createElement('script')\n script.src =\n mode === 'core-ui--staging'\n ? 'https://core.sanity-cdn.work/bridge.js'\n : 'https://core.sanity-cdn.com/bridge.js'\n script.type = 'module'\n script.async = true\n document.head.appendChild(script)\n}\n\n/**\n * @internal\n */\nexport interface AuthBoundaryProps {\n /**\n * Custom component to render the login screen.\n * Receives all props. Defaults to {@link Login}.\n */\n LoginComponent?: React.ComponentType<{\n header?: React.ReactNode\n footer?: React.ReactNode\n }>\n\n /**\n * Custom component to render during OAuth callback processing.\n * Receives all props. Defaults to {@link LoginCallback}.\n */\n CallbackComponent?: React.ComponentType<{\n header?: React.ReactNode\n footer?: React.ReactNode\n }>\n\n /**\n * Custom component to render when authentication errors occur.\n * Receives error boundary props and layout props. Defaults to\n * {@link LoginError}\n */\n LoginErrorComponent?: React.ComponentType<LoginErrorProps>\n\n /** Header content to display */\n header?: React.ReactNode\n\n /**\n * The project IDs to use for organization verification.\n */\n projectIds?: string[]\n\n /** Footer content to display */\n footer?: React.ReactNode\n\n /** Protected content to render when authenticated */\n children?: React.ReactNode\n\n /**\n * Whether to verify that the project belongs to the organization specified in the dashboard context.\n * By default, organization verification is enabled when running in a dashboard context.\n *\n * WARNING: Disabling organization verification is NOT RECOMMENDED and may cause your application\n * to break in the future. This should never be disabled in production environments.\n */\n verifyOrganization?: boolean\n}\n\n/**\n * A component that handles authentication flow and error boundaries for a\n * protected section of the application.\n *\n * @remarks\n * This component manages different authentication states and renders the\n * appropriate components based on that state.\n *\n * @example\n * ```tsx\n * function App() {\n * return (\n * <AuthBoundary header={<MyLogo />}>\n * <ProtectedContent />\n * </AuthBoundary>\n * )\n * }\n * ```\n *\n * @internal\n */\nexport function AuthBoundary({\n LoginErrorComponent = LoginError,\n ...props\n}: AuthBoundaryProps): React.ReactNode {\n /**\n * When the session is re-established (e.g. ComlinkTokenRefresh silently mints a\n * fresh token via setAuthToken), the auth store returns to LOGGED_IN but the\n * ErrorBoundary stays latched on its fallback until reset. Keying it on the\n * recovered session lets it clear automatically\n */\n const authState = useAuthState()\n const sessionResetKey =\n authState.type === AuthStateType.LOGGED_IN ? authState.token : authState.type\n\n const FallbackComponent = useMemo(() => {\n return function LoginComponentWithLayoutProps(fallbackProps: FallbackProps) {\n // Chunk-load errors from any lazy-loaded code beneath this boundary\n // (typically the consumer's app) get the chunk-aware fallback instead\n // of being misreported as auth errors.\n if (isImportError(fallbackProps.error)) {\n return <ChunkLoadError {...fallbackProps} />\n }\n if (fallbackProps.error instanceof CorsOriginError) {\n return (\n <CorsErrorComponent\n {...fallbackProps}\n projectId={getCorsErrorProjectId(fallbackProps.error)}\n />\n )\n }\n return <LoginErrorComponent {...fallbackProps} />\n }\n }, [LoginErrorComponent])\n\n return (\n <ComlinkTokenRefreshProvider>\n <DashboardTokenRefreshProvider>\n <ErrorBoundary FallbackComponent={FallbackComponent} resetKeys={[sessionResetKey]}>\n <AuthSwitch {...props} />\n </ErrorBoundary>\n </DashboardTokenRefreshProvider>\n </ComlinkTokenRefreshProvider>\n )\n}\n\ninterface AuthSwitchProps {\n LoginComponent?: React.ComponentType<{\n header?: React.ReactNode\n footer?: React.ReactNode\n }>\n CallbackComponent?: React.ComponentType<{\n header?: React.ReactNode\n footer?: React.ReactNode\n }>\n header?: React.ReactNode\n footer?: React.ReactNode\n children?: React.ReactNode\n verifyOrganization?: boolean\n projectIds?: string[]\n}\n\nfunction AuthSwitch({\n CallbackComponent = LoginCallback,\n children,\n verifyOrganization = true,\n projectIds,\n ...props\n}: AuthSwitchProps) {\n const authState = useAuthState()\n const instance = useSanityInstance()\n const isStudio = isStudioConfig(instance.config)\n const disableVerifyOrg =\n !verifyOrganization || isStudio || authState.type !== AuthStateType.LOGGED_IN\n const orgError = useVerifyOrgProjects(disableVerifyOrg, projectIds)\n\n const isLoggedOut = authState.type === AuthStateType.LOGGED_OUT && !authState.isDestroyingSession\n const loginUrl = useLoginUrl()\n\n useEffect(() => {\n if (isLoggedOut && !isInIframe() && !isStudio && !isDashboardEnvironment()) {\n // We don't want to redirect to login if we're in the Dashboard, in studio\n // mode, or in the workbench (the OS owns the session and mints the token)\n window.location.href = loginUrl\n }\n }, [isLoggedOut, loginUrl, isStudio])\n\n // Only check the error if verification is enabled\n if (verifyOrganization && orgError) {\n throw new ConfigurationError({message: orgError})\n }\n\n switch (authState.type) {\n case AuthStateType.ERROR: {\n throw new AuthError(authState.error)\n }\n case AuthStateType.LOGGING_IN: {\n return <CallbackComponent {...props} />\n }\n case AuthStateType.LOGGED_IN: {\n return children\n }\n case AuthStateType.LOGGED_OUT: {\n return null\n }\n default: {\n // @ts-expect-error - This state should never happen\n throw new Error(`Invalid auth state: ${authState.type}`)\n }\n }\n}\n","import {type TokenSource} from '@sanity/sdk'\nimport {createContext} from 'react'\n\n/**\n * Minimal duck-typed interface representing a Sanity Studio workspace.\n * The Studio's `Workspace` type satisfies this naturally — no import\n * dependency on the `sanity` package is required.\n *\n * @public\n */\nexport interface StudioWorkspaceHandle {\n /** The Sanity project ID for this workspace. */\n projectId: string\n /** The dataset name for this workspace. */\n dataset: string\n /**\n * Whether the Studio has determined the user is authenticated.\n * When `true` and the token source emits `null`, the SDK infers\n * cookie-based auth is in use and skips the logged-out state.\n */\n authenticated?: boolean\n /** Authentication state for this workspace. */\n auth: {\n /**\n * Reactive token source from the Studio's auth store.\n * When present, the SDK subscribes for ongoing token sync — the Studio\n * is the single authority for auth and handles token refresh.\n *\n * Optional because Studios before Aug 2022 may not expose it. When\n * absent, the SDK falls back to localStorage/cookie discovery.\n */\n token?: TokenSource\n }\n}\n\n/**\n * React context that allows the SDK to auto-detect when it is running\n * inside a Sanity Studio. The Studio provides a workspace handle via this\n * context, and `SanityApp` reads it to derive `projectId`, `dataset`, and\n * a reactive auth token — eliminating the need for manual configuration.\n *\n * @remarks\n * This context is defined in `@sanity/sdk-react` and provided by the Studio.\n * The Studio imports it from this package and wraps its component tree:\n *\n * ```tsx\n * import {SDKStudioContext} from '@sanity/sdk-react'\n *\n * function StudioRoot({children}) {\n * const workspace = useWorkspace()\n * return (\n * <SDKStudioContext.Provider value={workspace}>\n * {children}\n * </SDKStudioContext.Provider>\n * )\n * }\n * ```\n *\n * When `SanityApp` is rendered inside this provider, it auto-configures\n * without any `config` prop:\n *\n * ```tsx\n * <SanityApp fallback={<Loading />}>\n * <MyComponent />\n * </SanityApp>\n * ```\n *\n * @public\n */\nexport const SDKStudioContext = createContext<StudioWorkspaceHandle | null>(null)\nSDKStudioContext.displayName = 'SDKStudioContext'\n","/**\n * The name of the resource automatically registered from a single-config `<SanityApp>`.\n * Hooks that receive no resource information fall back to this named resource.\n */\nexport const DEFAULT_RESOURCE_NAME = 'default'\n","import {\n type CanvasResource,\n getClientState,\n type MediaLibraryResource,\n type SanityInstance,\n} from '@sanity/sdk'\nimport {firstValueFrom} from 'rxjs'\n\nconst API_VERSION = 'v2026-07-09'\n\ninterface OrgResourcesApiItem {\n id: string\n}\n\ninterface OrgResourcesApiResponse {\n data: OrgResourcesApiItem[]\n}\n\ninterface OrgResources {\n mediaLibrary?: MediaLibraryResource\n canvas?: CanvasResource\n}\n\n/**\n * Gets the id of the first resource from a settled request result. The request\n * is already scoped to a single organization, so the first item is the one we want.\n */\nfunction getFirstResourceId(\n result: PromiseSettledResult<OrgResourcesApiResponse>,\n): string | undefined {\n if (result.status !== 'fulfilled') return undefined\n return result.value.data?.[0]?.id\n}\n\n/**\n * Fetches the media library and canvas resources for the given organization.\n * Both requests are scoped to `organizationId` so each response contains only\n * that org's resources. Each resource is fetched independently — a failure for\n * one does not prevent the other from resolving.\n */\nexport async function resolveOrgResources(\n instance: SanityInstance,\n organizationId: string,\n): Promise<OrgResources> {\n const client = await firstValueFrom(\n getClientState(instance, {apiVersion: API_VERSION, scope: 'global'}).observable,\n )\n\n const [mediaLibrariesResult, canvasesResult] = await Promise.allSettled([\n client.request<OrgResourcesApiResponse>({\n url: `/media-libraries`,\n query: {organizationId},\n tag: 'org-resources.media-libraries',\n }),\n client.request<OrgResourcesApiResponse>({\n url: `/canvases`,\n query: {organizationId},\n tag: 'org-resources.canvases',\n }),\n ])\n\n const mediaLibraryId = getFirstResourceId(mediaLibrariesResult)\n const canvasId = getFirstResourceId(canvasesResult)\n\n return {\n mediaLibrary: mediaLibraryId ? {mediaLibraryId} : undefined,\n canvas: canvasId ? {canvasId} : undefined,\n }\n}\n","import {type DocumentResource} from '@sanity/sdk'\nimport {createContext} from 'react'\n\n/** Context for resources.\n * @beta\n */\nexport const ResourcesContext = createContext<Record<string, DocumentResource>>({})\n","import {type DocumentResource, type SanityInstance} from '@sanity/sdk'\nimport {type ReactElement, type ReactNode, use, useMemo} from 'react'\n\nimport {useSanityInstance} from '../hooks/context/useSanityInstance'\nimport {useOrganizationId} from '../hooks/dashboard/useOrganizationId'\nimport {resolveOrgResources} from '../utils/resolveOrgResources'\nimport {ResourcesContext} from './ResourcesContext'\n\nconst DEFAULT_MEDIA_LIBRARY_RESOURCE_NAME = 'media-library'\nconst DEFAULT_CANVAS_RESOURCE_NAME = 'canvas'\n\ntype OrgResource = typeof DEFAULT_MEDIA_LIBRARY_RESOURCE_NAME | typeof DEFAULT_CANVAS_RESOURCE_NAME\ntype OrgResourcePromises = Map<OrgResource, PromiseLike<DocumentResource | undefined>>\n\n// Module-level cache keyed by SanityInstance so Promise references are stable\n// across Suspense unmount/remount cycles. React's use() tracks promises by\n// identity, so stable references prevent unnecessary re-suspensions.\n// WeakMap entries are GC'd when the instance is disposed.\n// There is only ever one org at a time, so the instance alone is a sufficient\n// key — organizationId only scopes the fetch, it doesn't need to key the cache.\nconst inferredResourceCache = new WeakMap<SanityInstance, OrgResourcePromises>()\n\nfunction getOrgResourcePromises(\n instance: SanityInstance,\n organizationId: string,\n): OrgResourcePromises {\n let promises = inferredResourceCache.get(instance)\n if (!promises) {\n const basePromise = resolveOrgResources(instance, organizationId).then(\n (result) => result,\n (error) => {\n // eslint-disable-next-line no-console\n console.warn('[sanity/sdk] Failed to infer org resources:', error)\n return {mediaLibrary: undefined, canvas: undefined}\n },\n )\n promises = new Map([\n [DEFAULT_MEDIA_LIBRARY_RESOURCE_NAME, basePromise.then((r) => r.mediaLibrary)],\n [DEFAULT_CANVAS_RESOURCE_NAME, basePromise.then((r) => r.canvas)],\n ])\n inferredResourceCache.set(instance, promises)\n }\n\n return promises\n}\n\n/**\n * Inner component that suspends via use() until both inference promises settle.\n * Requires a Suspense boundary from the caller (usually a top ResourceProvider).\n */\nfunction InferredResourcesProvider({\n instance,\n orgId,\n explicitResources,\n children,\n}: {\n instance: SanityInstance\n orgId: string\n explicitResources: Record<string, DocumentResource>\n children: ReactNode\n}): ReactElement {\n const promises = getOrgResourcePromises(instance, orgId)\n const ml = use(promises.get(DEFAULT_MEDIA_LIBRARY_RESOURCE_NAME)!)\n const canvas = use(promises.get(DEFAULT_CANVAS_RESOURCE_NAME)!)\n\n const resources = useMemo(() => {\n const inferred: Record<string, DocumentResource> = {}\n if (ml !== undefined) inferred[DEFAULT_MEDIA_LIBRARY_RESOURCE_NAME] = ml\n if (canvas !== undefined) inferred[DEFAULT_CANVAS_RESOURCE_NAME] = canvas\n return {...inferred, ...explicitResources}\n }, [ml, canvas, explicitResources])\n\n return <ResourcesContext.Provider value={resources}>{children}</ResourcesContext.Provider>\n}\n\n/**\n * When `inferMediaLibraryAndCanvas` is set, this component suspends until\n * inference resolves. The nearest Suspense boundary (e.g. from ResourceProvider)\n * shows its fallback during that window.\n\n * If a user explicitly names a 'media-library' or 'canvas' resource,\n * this component will use that resource instead of inferring it.\n */\nexport function OrganizationResourcesProvider({\n resources: explicitResources = {},\n inferMediaLibraryAndCanvas,\n children,\n}: {\n resources?: Record<string, DocumentResource>\n inferMediaLibraryAndCanvas?: boolean\n children: ReactNode\n}): ReactElement {\n const instance = useSanityInstance()\n const orgId = useOrganizationId()\n\n if (!inferMediaLibraryAndCanvas || !orgId) {\n return (\n <ResourcesContext.Provider value={explicitResources}>{children}</ResourcesContext.Provider>\n )\n }\n\n return (\n <InferredResourcesProvider\n instance={instance}\n orgId={orgId}\n explicitResources={explicitResources}\n >\n {children}\n </InferredResourcesProvider>\n )\n}\n","import {type DocumentResource} from '@sanity/sdk'\nimport {createContext} from 'react'\n\n/**\n * Provides the active DocumentResource for a subtree.\n * Set by ResourceProvider; read by useNormalizedResourceOptions as a fallback\n * when hooks receive no explicit resource or resourceName.\n * @internal\n */\nexport const ResourceContext = createContext<DocumentResource | undefined>(undefined)\n","import {type PerspectiveHandle} from '@sanity/sdk'\nimport {createContext} from 'react'\n\n/**\n * Provides the active perspective for a subtree.\n * Set by ResourceProvider; injected by useNormalizedResourceOptions when\n * the hook's options don't include an explicit perspective.\n * @internal\n */\nexport const PerspectiveContext = createContext<PerspectiveHandle['perspective'] | undefined>(\n undefined,\n)\n","import {createContext} from 'react'\n\n/**\n * Carries a `projectId` for a subtree even when a complete\n * `DatasetResource` can't be formed — e.g. a `<ResourceProvider projectId=\"…\">`\n * with no `dataset` and no parent resource to inherit one from.\n *\n * Project-scoped hooks (`useProject`, `useDatasets`, `useUsers`) read this as a\n * fallback so they can still resolve a project in that case (the only hooks that would work with a config like this.)\n *\n * @remarks Temporary bridge for the dataset-less project scope.\n * Remove in the next major version; those hooks should just always use a projectId or default to a resource available.\n * @internal\n */\nexport const ProjectContext = createContext<string | undefined>(undefined)\n","import {type SanityInstance} from '@sanity/sdk'\nimport {Suspense} from 'react'\n\nimport {SanityInstanceContext} from './SanityInstanceContext'\n\n/**\n * Props for the SanityInstanceProvider component\n * @public\n */\nexport interface SanityInstanceProviderProps {\n /**\n * A pre-created SanityInstance to provide to child components.\n * The caller owns the instance lifecycle — SanityInstanceProvider\n * will not dispose it on unmount.\n */\n instance: SanityInstance\n /**\n * React node to show while content is loading.\n * Used as the fallback for the internal Suspense boundary.\n */\n fallback: React.ReactNode\n children: React.ReactNode\n}\n\n/**\n * Provides an externally-created Sanity instance to child components through React Context.\n *\n * @internal\n *\n * @remarks\n * Unlike {@link ResourceProvider}, this component does not create or dispose a SanityInstance.\n * The caller is responsible for creating the instance via `createSanityInstance` and disposing\n * it when appropriate. This is useful when a non-React system layer (e.g. a state machine)\n * owns the instance and the React tree should consume it without managing its lifecycle.\n *\n * All SDK hooks (`useSanityInstance`, `useDocuments`, etc.) will read from the provided instance.\n *\n * @example Providing a pre-created instance\n * ```tsx\n * import { createSanityInstance, type SanityConfig } from '@sanity/sdk'\n * import { SanityInstanceProvider } from '@sanity/sdk-react'\n *\n * const config: SanityConfig = {\n * projectId: 'my-project-id',\n * dataset: 'production',\n * }\n *\n * const instance = createSanityInstance(config)\n *\n * function App() {\n * return (\n * <SanityInstanceProvider instance={instance} fallback={<div>Loading...</div>}>\n * <MyApp />\n * </SanityInstanceProvider>\n * )\n * }\n * ```\n *\n * @category Components\n */\nexport function SanityInstanceProvider({\n instance,\n fallback,\n children,\n}: SanityInstanceProviderProps): React.ReactNode {\n return (\n <SanityInstanceContext.Provider value={instance}>\n <Suspense fallback={fallback}>{children}</Suspense>\n </SanityInstanceContext.Provider>\n )\n}\n","import {\n createSanityInstance,\n type DatasetResource,\n type DocumentResource,\n isDatasetResource,\n type SanityConfig,\n type SanityInstance,\n} from '@sanity/sdk'\nimport {initTelemetry} from '@sanity/sdk/_internal'\nimport {useContext, useEffect, useMemo, useRef, useState} from 'react'\n\nimport {ResourceContext} from './DefaultResourceContext'\nimport {PerspectiveContext} from './PerspectiveContext'\nimport {ProjectContext} from './ProjectContext'\nimport {SanityInstanceContext} from './SanityInstanceContext'\nimport {SanityInstanceProvider} from './SanityInstanceProvider'\n\nconst DEFAULT_FALLBACK = (\n <>\n Warning: No fallback provided. Please supply a fallback prop to ensure proper Suspense handling.\n </>\n)\n\n/**\n * Props for the ResourceProvider component\n * @internal\n */\nexport interface ResourceProviderProps extends SanityConfig {\n /**\n * The document resource (project/dataset, media library, or canvas)\n * for this subtree. Hooks that don't specify an explicit resource will\n * use this value.\n */\n resource?: DocumentResource\n /**\n * React node to show while content is loading.\n * Used as the fallback for the internal Suspense boundary.\n */\n fallback: React.ReactNode\n children: React.ReactNode\n}\n\n/**\n * Provides Sanity configuration to child components through React Context.\n *\n * @internal\n *\n * @example\n * ```tsx\n * <ResourceProvider\n * resource={{ projectId: 'your-project-id', dataset: 'production' }}\n * fallback={<LoadingSpinner />}\n * >\n * <YourApp />\n * </ResourceProvider>\n * ```\n */\nexport function ResourceProvider({\n children,\n fallback,\n resource,\n ...config\n}: ResourceProviderProps): React.ReactNode {\n const parentPerspective = useContext(PerspectiveContext)\n const parentResource = useContext(ResourceContext)\n const parentInstance = useContext(SanityInstanceContext)\n const parentProjectId = useContext(ProjectContext)\n\n const {projectId, dataset, perspective} = config\n\n const [instance] = useState<SanityInstance>(() => parentInstance ?? createSanityInstance(config))\n\n const configResource: DatasetResource | undefined = useMemo(() => {\n // Historically, we allowed asymmetric merging: If you provided JUST a dataset, we'd merge it with the parent projectId.\n //\n // This backwards-compatible merging should be removed in the next major version.\n if (projectId && dataset) return {projectId, dataset}\n if (dataset && parentProjectId) return {projectId: parentProjectId, dataset}\n return undefined\n }, [projectId, dataset, parentProjectId])\n\n const effectiveResource = useMemo(() => {\n if (resource) return resource\n if (configResource) return configResource\n // A projectId with no dataset historically created its own scope, so no resource is needed.\n if (projectId) return undefined\n return parentResource\n }, [resource, configResource, projectId, parentResource])\n\n // Historically, ResourceProviders allowed a bare `projectId` (no dataset, no resource to complete it) to be provided.\n // This keeps that behavior intact for backwards compatibility, even though we prefer resources everywhere.\n //\n // This should be removed in the next major version.\n const effectiveProjectId = useMemo(() => {\n if (effectiveResource && isDatasetResource(effectiveResource)) {\n return effectiveResource.projectId\n }\n return projectId ?? parentProjectId\n }, [effectiveResource, projectId, parentProjectId])\n\n useEffect(() => {\n if (effectiveResource && isDatasetResource(effectiveResource))\n initTelemetry(instance, effectiveResource.projectId)\n }, [instance, effectiveResource])\n\n // Ref to hold the scheduled disposal timer.\n const disposal = useRef<{\n instance: SanityInstance\n timeoutId: ReturnType<typeof setTimeout>\n } | null>(null)\n\n useEffect(() => {\n // If the component remounts quickly (as in Strict Mode), cancel any pending disposal.\n if (disposal.current !== null && instance === disposal.current.instance) {\n clearTimeout(disposal.current.timeoutId)\n disposal.current = null\n }\n\n return () => {\n disposal.current = {\n instance,\n timeoutId: setTimeout(() => {\n // don't dispose the parent instance when this unmounts\n if (!instance.isDisposed() && instance !== parentInstance) {\n instance.dispose()\n }\n }, 0),\n }\n }\n }, [instance, parentInstance])\n\n return (\n <SanityInstanceProvider\n instance={instance}\n fallback={fallback === undefined ? DEFAULT_FALLBACK : fallback}\n >\n <ResourceContext.Provider value={effectiveResource}>\n <ProjectContext.Provider value={effectiveProjectId}>\n <PerspectiveContext.Provider value={perspective ?? parentPerspective}>\n {children}\n </PerspectiveContext.Provider>\n </ProjectContext.Provider>\n </ResourceContext.Provider>\n </SanityInstanceProvider>\n )\n}\n","import {\n type DocumentResource,\n isDatasetResource,\n isImportError,\n type SanityConfig,\n} from '@sanity/sdk'\nimport {type ReactElement, type ReactNode, useEffect, useMemo} from 'react'\nimport {ErrorBoundary, type FallbackProps} from 'react-error-boundary'\n\nimport {DEFAULT_RESOURCE_NAME} from '../constants'\nimport {OrganizationResourcesProvider} from '../context/OrganizationResourcesProvider'\nimport {ResourceProvider} from '../context/ResourceProvider'\nimport {AuthBoundary, type AuthBoundaryProps} from './auth/AuthBoundary'\nimport {ChunkLoadError} from './errors/ChunkLoadError'\nimport {clearChunkReloadFlag} from './errors/chunkReloadStorage'\n\n/**\n * @internal\n */\nexport interface SDKProviderProps extends AuthBoundaryProps {\n children: ReactNode\n config: SanityConfig | SanityConfig[]\n fallback: ReactNode\n resources?: Record<string, DocumentResource>\n /** When set, automatically fetches and registers the organization's media library and canvas as named resources. */\n inferMediaLibraryAndCanvas?: boolean\n}\n\n/**\n * Clears the chunk-reload flag once children render successfully past the\n * top-level boundary, so a future incident in the same session can trigger\n * another automatic reload.\n */\nfunction ResetChunkReloadFlagOnMount(): null {\n useEffect(() => {\n clearChunkReloadFlag()\n }, [])\n return null\n}\n\n/**\n * @internal\n *\n * Top-level context provider that provides access to the Sanity SDK.\n */\nexport function SDKProvider({\n children,\n config,\n fallback,\n inferMediaLibraryAndCanvas,\n ...props\n}: SDKProviderProps): ReactElement {\n // For legacy config support, extract the first config object as a default resource,\n // matching the legacy behavior nesting ResourceProviders with the first config closest to users' application code.\n // This should be removed when we remove legacy config support.\n const defaultConfig = Array.isArray(config) ? config[0] : config\n const defaultProjectId = defaultConfig?.projectId\n const defaultDataset = defaultConfig?.dataset\n\n const resourcesValue = useMemo(() => {\n const explicit = props.resources ?? {}\n if (defaultProjectId && defaultDataset && !Object.hasOwn(explicit, DEFAULT_RESOURCE_NAME)) {\n return {\n [DEFAULT_RESOURCE_NAME]: {\n projectId: defaultProjectId,\n dataset: defaultDataset,\n },\n ...explicit,\n }\n }\n return explicit\n }, [defaultProjectId, defaultDataset, props.resources])\n\n // Collect all projectIds from both resources and config, deduped so\n // AuthBoundary doesn't verify the same project more than once.\n const projectIds = useMemo(\n () =>\n Array.from(\n new Set(\n [\n ...Object.values(resourcesValue)\n .filter(isDatasetResource)\n .map((resource) => resource.projectId),\n ...(Array.isArray(config) ? config : [config]).map((configObj) => configObj.projectId),\n ].filter((id): id is string => !!id),\n ),\n ),\n [resourcesValue, config],\n )\n\n return (\n <ErrorBoundary FallbackComponent={ChunkAwareFallback}>\n <ResetChunkReloadFlagOnMount />\n {/* Spread the first config so SanityInstance can use the auth,\n perspective, and other config fields; `resource` lets an explicitly\n provided `default` resource override the config-derived resource. */}\n <ResourceProvider\n {...defaultConfig}\n resource={resourcesValue[DEFAULT_RESOURCE_NAME]}\n fallback={fallback}\n >\n <AuthBoundary {...props} projectIds={projectIds}>\n {/* OrganizationResourcesProvider wraps ResourcesContext.\n It merges explicit resources with lazily inferred org resources (media\n library, canvas) and provides the combined map to the subtree. */}\n <OrganizationResourcesProvider\n resources={resourcesValue}\n inferMediaLibraryAndCanvas={inferMediaLibraryAndCanvas}\n >\n {children}\n </OrganizationResourcesProvider>\n </AuthBoundary>\n </ResourceProvider>\n </ErrorBoundary>\n )\n}\n\nfunction ChunkAwareFallback(fallbackProps: FallbackProps): ReactElement {\n if (isImportError(fallbackProps.error)) {\n return <ChunkLoadError {...fallbackProps} />\n }\n // Re-throw so downstream boundaries (e.g. AuthBoundary) handle other errors.\n throw fallbackProps.error\n}\n","import {type DocumentResource, type SanityConfig} from '@sanity/sdk'\nimport {isStudioConfig} from '@sanity/sdk/_internal'\nimport {type ReactElement, useContext, useEffect, useMemo} from 'react'\n\nimport {SDKStudioContext, type StudioWorkspaceHandle} from '../context/SDKStudioContext'\nimport {SDKProvider} from './SDKProvider'\nimport {isInIframe, isLocalUrl} from './utils'\n\n/**\n * @public\n * @category Types\n */\nexport interface SanityAppProps {\n /**\n * One or more SanityConfig objects providing a project ID and dataset name.\n * Optional when `SanityApp` is rendered inside an `SDKStudioContext` provider\n * (e.g. inside Sanity Studio) — the config is derived from the workspace\n * automatically.\n */\n config?: SanityConfig | SanityConfig[]\n resources?: Record<string, DocumentResource>\n children: React.ReactNode\n /* Fallback content to show when child components are suspending. Same as the `fallback` prop for React Suspense. */\n fallback: React.ReactNode\n /**\n * Set this to automatically fetch and register the organization's media library and canvas as named resources.\n * These resources will be available to hooks as `media-library` and `canvas`.\n *\n * The SDK App must be running in the organization's Dashboard to use this feature.\n *\n * @example\n * ```tsx\n *\n * const MyApp = () => {\n * // should \"just work\" because of inferMediaLibraryAndCanvas.\n * const {data: assets} = useDocuments({\n * documentType: 'sanity.asset',\n * resourceName: 'media-library',\n * })\n * return (\n * <div>\n * {assets.map((asset) => (\n * <div key={asset._id}>{asset.originalFilename}</div>\n * ))}\n * </div>\n * )\n * }\n * <SanityApp inferMediaLibraryAndCanvas>\n * <MyApp />\n * </SanityApp>\n * ```\n */\n inferMediaLibraryAndCanvas?: boolean\n}\n\nconst REDIRECT_URL = 'https://sanity.io/welcome'\n\n/**\n * Derive a SanityConfig from a Studio workspace handle.\n * Maps the workspace's projectId, dataset, and reactive auth token into\n * the SDK's config shape.\n */\nfunction deriveConfigFromWorkspace(workspace: StudioWorkspaceHandle): SanityConfig {\n return {\n projectId: workspace.projectId,\n dataset: workspace.dataset,\n studio: {\n authenticated: workspace.authenticated,\n auth: workspace.auth.token ? {token: workspace.auth.token} : undefined,\n },\n }\n}\n\n/**\n * @public\n *\n * The SanityApp component provides your Sanity application with access to your Sanity configuration,\n * as well as application context and state which is used by the Sanity React hooks. Your application\n * must be wrapped with the SanityApp component to function properly.\n *\n * The `config` prop on the SanityApp component accepts either a single {@link SanityConfig} object, or an array of them.\n * This allows your app to work with one or more of your organization's datasets.\n *\n * When rendered inside a Sanity Studio that provides `SDKStudioContext`, the `config` prop is\n * optional — `SanityApp` will automatically derive `projectId`, `dataset`, and auth from the\n * Studio workspace.\n *\n * @remarks\n * When passing multiple SanityConfig objects to the `config` prop, the first configuration in the array becomes the default\n * configuration used by the App SDK Hooks.\n *\n * When both `config` and `SDKStudioContext` are available, the explicit `config` takes precedence.\n *\n * @category Components\n * @param props - Your Sanity configuration and the React children to render\n * @returns Your Sanity application, integrated with your Sanity configuration and application context\n *\n * @example\n * ```tsx\n * import { SanityApp, type SanityConfig } from '@sanity/sdk-react'\n *\n * import MyAppRoot from './Root'\n *\n * // Single project configuration\n * const mySanityConfig: SanityConfig = {\n * projectId: 'my-project-id',\n * dataset: 'production',\n * }\n *\n * // Or multiple project configurations\n * const multipleConfigs: SanityConfig[] = [\n * // Configuration for your main project. This will be used as the default project for hooks.\n * {\n * projectId: 'marketing-website-project',\n * dataset: 'production',\n * },\n * // Configuration for a separate blog project\n * {\n * projectId: 'blog-project',\n * dataset: 'production',\n * },\n * // Configuration for a separate ecommerce project\n * {\n * projectId: 'ecommerce-project',\n * dataset: 'production',\n * }\n * ]\n *\n * export default function MyApp() {\n * return (\n * <SanityApp config={mySanityConfig} fallback={<div>Loading…</div>}>\n * <MyAppRoot />\n * </SanityApp>\n * )\n * }\n * ```\n */\nexport function SanityApp({\n children,\n fallback,\n config: configProp,\n ...props\n}: SanityAppProps): ReactElement {\n const studioWorkspace = useContext(SDKStudioContext)\n\n // Derive config: explicit config takes precedence, then Studio context\n const resolvedConfig = useMemo(() => {\n if (configProp) return configProp\n if (studioWorkspace) return deriveConfigFromWorkspace(studioWorkspace)\n return []\n }, [configProp, studioWorkspace])\n\n useEffect(() => {\n let timeout: NodeJS.Timeout | undefined\n const primaryConfig = Array.isArray(resolvedConfig) ? resolvedConfig[0] : resolvedConfig\n const shouldRedirectWithoutConfig =\n configProp === undefined && !studioWorkspace && !primaryConfig\n\n if (\n !isInIframe() &&\n !isLocalUrl(window) &&\n (shouldRedirectWithoutConfig || (!!primaryConfig && !isStudioConfig(primaryConfig)))\n ) {\n // If the app is not running in an iframe and is not a local url, redirect to core.\n timeout = setTimeout(() => {\n // eslint-disable-next-line no-console\n console.warn('Redirecting to core', REDIRECT_URL)\n window.location.replace(REDIRECT_URL)\n }, 1000)\n }\n return () => clearTimeout(timeout)\n }, [configProp, resolvedConfig, studioWorkspace])\n\n return (\n <SDKProvider {...props} fallback={fallback} config={resolvedConfig}>\n {children}\n </SDKProvider>\n )\n}\n","import {type SanityConfig} from '@sanity/sdk'\nimport {StrictMode} from 'react'\nimport {createRoot} from 'react-dom/client'\n\nimport {SanityApp} from '../components/SanityApp'\n\ninterface RenderSanitySDKAppOptions {\n reactStrictMode?: boolean\n}\n\n/** In-flight CLI PR is using named sources since it's aspirational.\n * We can transform the shape in this function until it's finalized.\n */\ninterface NamedSources {\n [key: string]: SanityConfig\n}\n/** @internal */\nexport function renderSanityApp(\n rootElement: HTMLElement | null,\n namedSources: NamedSources,\n options: RenderSanitySDKAppOptions,\n children: React.ReactNode,\n): () => void {\n if (!rootElement) {\n throw new Error('Missing root element to mount application into')\n }\n const {reactStrictMode = false} = options\n\n const root = createRoot(rootElement)\n const config = Object.values(namedSources)\n\n root.render(\n reactStrictMode ? (\n <StrictMode>\n {/* TODO: think about a loading component we want to be \"universal\" */}\n <SanityApp config={config} fallback={<div>Loading...</div>}>\n {children}\n </SanityApp>\n </StrictMode>\n ) : (\n <SanityApp config={config} fallback={<div>Loading...</div>}>\n {children}\n </SanityApp>\n ),\n )\n\n return () => root.unmount()\n}\n","import {type Fetcher, type FetcherSnapshot, isDeepEqual} from '@sanity/sdk/_internal'\nimport {useRef, useSyncExternalStore} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n * The value returned by a fetcher-backed hook. The hook suspends until the\n * first fetch succeeds, so `data` is always present once your component renders.\n *\n * @public\n */\nexport interface FetcherHookResult<TData> {\n /** The resolved data. Guaranteed present — the hook suspends until the first fetch succeeds. */\n data: TData\n /** A fetch for this entry is in flight (background revalidation or a `refetch()`). */\n isFetching: boolean\n /** The most recent background-fetch failure while data still renders; cleared by the next success. */\n error: unknown\n /** Imperatively refetch, bypassing staleness. Resolves with the refreshed data. */\n refetch: () => Promise<TData>\n}\n\n/**\n * Builds a Suspense hook over a {@link Fetcher}: it suspends until the first\n * success via the snapshot's `status`, throws the error arm to the nearest error\n * boundary, and returns the live `{data, isFetching, error, refetch}` envelope.\n *\n * @internal\n */\nexport function createFetcherHook<TParams extends unknown[], TData>(\n fetcher: Fetcher<TParams, TData>,\n): (...params: TParams) => FetcherHookResult<TData> {\n return function useFetcherHook(...params: TParams): FetcherHookResult<TData> {\n const instance = useSanityInstance()\n const source = fetcher.getState(instance, ...params)\n\n // No entry/data yet — suspend on the first fetch (matches an 'error' below never reaching here).\n if (source.getCurrent().status === 'pending') {\n throw fetcher.resolveState(instance, ...params)\n }\n\n // The store replaces its cache entry on every (un)subscribe (it bumps a\n // subscription counter), so `getCurrent()` hands back a fresh snapshot object\n // with identical fields on each commit. Passed raw to `useSyncExternalStore`\n // — which compares by `Object.is` — that reads as a perpetual change and\n // re-renders forever. Reuse the previous snapshot while its fields are\n // unchanged so React sees a stable reference.\n const previous = useRef<FetcherSnapshot<TData> | null>(null)\n const snapshot = useSyncExternalStore(source.subscribe, () => {\n const next = source.getCurrent()\n const prev = previous.current\n if (prev && isDeepEqual(prev, next)) return prev\n previous.current = next\n return next\n })\n\n if (snapshot.status !== 'success') {\n // 'pending' already suspended above; 'error' surfaces to the error boundary.\n throw snapshot.status === 'error' ? snapshot.error : fetcher.resolveState(instance, ...params)\n }\n\n return {\n data: snapshot.data,\n isFetching: snapshot.isFetching,\n error: snapshot.error,\n refetch: () => fetcher.refetch(instance, ...params),\n }\n }\n}\n","import {type AccessResourceType, checkPermissions} from '@sanity/sdk'\n\nimport {createFetcherHook, type FetcherHookResult} from '../helpers/createFetcherHook'\n\n/**\n * Checks whether the current user holds the given permissions on a resource.\n *\n * The hook suspends until the first fetch succeeds, so `data` is always present.\n * `data` maps each requested permission to whether the user has it — keyed by\n * exactly the permission strings you passed.\n *\n * @public\n * @param resourceType - The type of resource (e.g. `'project'`, `'organization'`).\n * @param resourceId - The resource id.\n * @param permissions - The permission names to check.\n * @returns The result envelope `{data, isFetching, error, refetch}`.\n */\nexport const useCheckPermissions = createFetcherHook(checkPermissions) as <\n Permission extends string,\n>(\n resourceType: AccessResourceType,\n resourceId: string,\n permissions: Permission[],\n) => FetcherHookResult<Record<Permission, boolean>>\n","import {type DocumentResource, type PerspectiveHandle} from '@sanity/sdk'\nimport {useContext, useMemo} from 'react'\n\nimport {ResourceContext} from '../../context/DefaultResourceContext'\nimport {PerspectiveContext} from '../../context/PerspectiveContext'\nimport {ResourcesContext} from '../../context/ResourcesContext'\nimport {SanityInstanceContext} from '../../context/SanityInstanceContext'\n\ntype NormalizedResourceFields = 'resourceName' | 'projectId' | 'dataset'\n\n/**\n * Adds React hook support (resourceName resolution) to core types.\n * Prefer using the React-layer handle types (ResourceHandle, DocumentHandle)\n * from `@sanity/sdk-react` — this wrapper is kept for cases where overloads\n * don't fit (e.g. non-handle options objects).\n *\n * @typeParam T - The core type to extend (must have optional `resource` field)\n * @beta\n */\nexport type WithResourceNameSupport<T extends {resource?: DocumentResource}> = T & {\n /**\n * Optional name of a resource to resolve from context.\n * If provided, will be resolved to a `DocumentResource` via `ResourcesContext`.\n * @beta\n */\n resourceName?: string\n}\n\n/**\n * Pure function that normalizes options by resolving `resourceName` to a `DocumentResource`\n * using the provided resources map. Use this when options are only available at call time\n * (e.g. inside a callback) and you cannot call the {@link useNormalizedResourceOptions} hook.\n *\n * @typeParam T - The options type (must include optional resource field)\n * @param options - Options that may include `resourceName` and/or `resource`\n * @param resources - Map of resource names to DocumentResource (e.g. from ResourcesContext)\n * @param contextResource - Resource from context (from ResourceContext)\n * @param contextPerspective - Perspective from context (from PerspectiveContext)\n * @returns Normalized options with `resourceName` removed and `resource` resolved\n * @internal\n */\nexport function normalizeResourceOptions<\n T extends {\n resource?: DocumentResource\n resourceName?: string\n projectId?: string\n dataset?: string\n perspective?: unknown\n },\n>(\n options: T,\n resources: Record<string, DocumentResource>,\n contextResource?: DocumentResource,\n contextPerspective?: PerspectiveHandle['perspective'],\n): Omit<T, NormalizedResourceFields> {\n const {resourceName, projectId, dataset, ...rest} = options\n const resource = options.resource\n\n if (resourceName && resource) {\n throw new Error(\n `Resource name ${JSON.stringify(resourceName)} and resource ${JSON.stringify(resource)} cannot be used together.`,\n )\n }\n\n let resolvedResource: DocumentResource | undefined\n\n // Tier (a): explicit resource object or resourceName lookup\n if (resource) {\n resolvedResource = resource\n } else if (resourceName) {\n if (!Object.hasOwn(resources, resourceName)) {\n throw new Error(\n `There's no resource named ${JSON.stringify(resourceName)} in context. Please use <ResourceProvider>.`,\n )\n }\n resolvedResource = resources[resourceName]\n }\n\n // Tier (b): projectId or dataset in options → synthesize a resource\n if (!resolvedResource && projectId && dataset) {\n resolvedResource = {\n projectId,\n dataset,\n }\n }\n\n // Tier (c): fall back to whatever ResourceContext provides\n if (!resolvedResource) {\n resolvedResource = contextResource\n }\n\n // Inject perspective from context when not explicitly provided in options\n const resolvedPerspective = Object.hasOwn(options, 'perspective')\n ? options.perspective\n : contextPerspective\n\n return {\n ...rest,\n ...(resolvedResource !== undefined && {resource: resolvedResource}),\n ...(resolvedPerspective !== undefined && {perspective: resolvedPerspective}),\n }\n}\n\n/**\n * Returns the effective context resource: the `ResourceContext` value if set,\n * otherwise a resource synthesized from the current `SanityInstance` config\n * (tier-d fallback — returns `undefined` for studio-style configs with no project).\n *\n * @internal\n */\nexport function useEffectiveContextResource(): DocumentResource | undefined {\n const contextResource = useContext(ResourceContext)\n const instance = useContext(SanityInstanceContext)\n const {projectId, dataset, resource: configResource} = instance?.config ?? {}\n\n return useMemo(() => {\n if (contextResource) return contextResource\n if (configResource) return configResource\n if (projectId && dataset) return {projectId, dataset}\n return undefined\n }, [contextResource, configResource, projectId, dataset])\n}\n\n/**\n * Normalizes hook options by resolving `resourceName` to a `DocumentResource`.\n *\n * Resolution priority for resource:\n * 1. Explicit `resource` or `resourceName` in options\n * 2. Bare `projectId`/`dataset` pair in options → synthesized into a resource\n * 3. `ResourceContext` value (set by `ResourceProvider` / `SDKProvider`)\n * 4. Current `SanityInstance` config — falls back to `undefined` for studio configs\n *\n * Resolution priority for perspective:\n * 1. Explicit `perspective` in options\n * 2. `PerspectiveContext` value (set by `ResourceProvider`)\n *\n * @internal\n */\nexport function useNormalizedResourceOptions<\n T extends {\n resource?: DocumentResource\n resourceName?: string\n projectId?: string\n dataset?: string\n perspective?: PerspectiveHandle['perspective']\n },\n>(\n options: T,\n): Omit<T, NormalizedResourceFields> & {\n resource?: DocumentResource\n perspective?: PerspectiveHandle['perspective']\n} {\n const resources = useContext(ResourcesContext)\n const effectiveContextResource = useEffectiveContextResource()\n const contextPerspective = useContext(PerspectiveContext)\n\n return normalizeResourceOptions(options, resources, effectiveContextResource, contextPerspective)\n}\n","import {\n agentGenerate,\n type AgentGenerateOptions,\n agentPatch,\n type AgentPatchOptions,\n type AgentPatchResult,\n agentPrompt,\n type AgentPromptOptions,\n type AgentPromptResult,\n agentTransform,\n type AgentTransformOptions,\n agentTranslate,\n type AgentTranslateOptions,\n} from '@sanity/sdk/agent'\nimport {useCallback} from 'react'\nimport {firstValueFrom} from 'rxjs'\n\nimport {type ResourceHandle} from '../../config/handles'\nimport {useSanityInstance} from '../context/useSanityInstance'\nimport {useNormalizedResourceOptions} from '../helpers/useNormalizedResourceOptions'\n\ninterface Subscription {\n unsubscribe(): void\n}\n\ninterface Observer<T> {\n next?: (value: T) => void\n error?: (err: unknown) => void\n complete?: () => void\n}\n\ninterface Subscribable<T> {\n subscribe(observer: Observer<T>): Subscription\n subscribe(\n next: (value: T) => void,\n error?: (err: unknown) => void,\n complete?: () => void,\n ): Subscription\n}\n\n/**\n * @alpha\n * Generates content for a document (or specific fields) via Sanity Agent Actions.\n *\n * @remarks\n * This hook provides a stable callback to trigger AI-powered content generation for documents.\n *\n * Features:\n * - Uses instruction templates with `$variables` and supports `instructionParams` (constants, fields, documents, GROQ queries).\n * - Can target specific paths/fields; supports image generation when targeting image fields.\n * - Supports optional `temperature`, `async`, `noWrite`, and `conditionalPaths`.\n * - Returns a Subscribable stream for tracking generation progress.\n *\n * @returns A stable callback that triggers the action and yields a Subscribable stream.\n *\n * @example Basic content generation\n * ```tsx\n * import {useAgentGenerate} from '@sanity/sdk-react'\n *\n * function GenerateDescription({documentId}: {documentId: string}) {\n * const generate = useAgentGenerate()\n *\n * const handleGenerate = () => {\n * generate({\n * documentId,\n * instruction: 'Write a compelling product description based on the title: $title',\n * instructionParams: {\n * title: {type: 'field', path: 'title'},\n * },\n * targetPaths: ['description'],\n * }).subscribe({\n * next: (result) => console.log('Generation progress:', result),\n * complete: () => console.log('Generation complete'),\n * error: (err) => console.error('Generation failed:', err),\n * })\n * }\n *\n * return <button onClick={handleGenerate}>Generate Description</button>\n * }\n * ```\n *\n * @example Image generation\n * ```tsx\n * import {useAgentGenerate} from '@sanity/sdk-react'\n *\n * function GenerateProductImage({documentId}: {documentId: string}) {\n * const generate = useAgentGenerate()\n *\n * const handleGenerateImage = () => {\n * generate({\n * documentId,\n * instruction: 'Generate a product photo for: $productName',\n * instructionParams: {\n * productName: {type: 'field', path: 'name'},\n * },\n * targetPaths: ['mainImage'],\n * }).subscribe({\n * complete: () => console.log('Image generated'),\n * })\n * }\n *\n * return <button onClick={handleGenerateImage}>Generate Image</button>\n * }\n * ```\n *\n * @category Agent Actions\n */\nexport function useAgentGenerate(\n resourceHandle?: ResourceHandle,\n): (options: AgentGenerateOptions) => Subscribable<unknown> {\n const instance = useSanityInstance()\n const {resource} = useNormalizedResourceOptions(resourceHandle ?? {})\n return useCallback(\n (options: AgentGenerateOptions) =>\n agentGenerate(instance, options, resource) as unknown as Subscribable<unknown>,\n [instance, resource],\n )\n}\n\n/**\n * @alpha\n * Transforms an existing document or selected fields using Sanity Agent Actions.\n *\n * @remarks\n * This hook provides a stable callback to apply AI-powered transformations to document content.\n *\n * Features:\n * - Accepts `instruction` and `instructionParams` (constants, fields, documents, GROQ queries).\n * - Can write to the same or a different `targetDocument` (create/edit), and target specific paths.\n * - Supports per-path image transform instructions and image description operations.\n * - Optional `temperature`, `async`, `noWrite`, `conditionalPaths`.\n *\n * @returns A stable callback that triggers the action and yields a Subscribable stream.\n *\n * @example Transform text content\n * ```tsx\n * import {useAgentTransform} from '@sanity/sdk-react'\n *\n * function SummarizeArticle({documentId}: {documentId: string}) {\n * const transform = useAgentTransform()\n *\n * const handleSummarize = () => {\n * transform({\n * documentId,\n * instruction: 'Summarize the following content into 2-3 sentences: $body',\n * instructionParams: {\n * body: {type: 'field', path: 'body'},\n * },\n * targetPaths: ['summary'],\n * }).subscribe({\n * complete: () => console.log('Summary generated'),\n * error: (err) => console.error('Transform failed:', err),\n * })\n * }\n *\n * return <button onClick={handleSummarize}>Generate Summary</button>\n * }\n * ```\n *\n * @example Transform and write to a different document\n * ```tsx\n * import {useAgentTransform} from '@sanity/sdk-react'\n *\n * function CreateVariant({sourceDocumentId}: {sourceDocumentId: string}) {\n * const transform = useAgentTransform()\n *\n * const handleCreateVariant = () => {\n * transform({\n * documentId: sourceDocumentId,\n * instruction: 'Rewrite this product description for a younger audience: $description',\n * instructionParams: {\n * description: {type: 'field', path: 'description'},\n * },\n * targetDocument: {\n * operation: 'create',\n * _type: 'product',\n * },\n * targetPaths: ['description'],\n * }).subscribe({\n * next: (result) => console.log('New document:', result),\n * complete: () => console.log('Variant created'),\n * })\n * }\n *\n * return <button onClick={handleCreateVariant}>Create Youth Variant</button>\n * }\n * ```\n *\n * @category Agent Actions\n */\nexport function useAgentTransform(\n resourceHandle?: ResourceHandle,\n): (options: AgentTransformOptions) => Subscribable<unknown> {\n const instance = useSanityInstance()\n const {resource} = useNormalizedResourceOptions(resourceHandle ?? {})\n return useCallback(\n (options: AgentTransformOptions) =>\n agentTransform(instance, options, resource) as unknown as Subscribable<unknown>,\n [instance, resource],\n )\n}\n\n/**\n * @alpha\n * Translates documents or fields using Sanity Agent Actions.\n *\n * @remarks\n * This hook provides a stable callback to translate document content between languages using AI.\n *\n * Features:\n * - Configure `fromLanguage`/`toLanguage`, optional `styleGuide`, and `protectedPhrases`.\n * - Can write into a different `targetDocument`, and/or store language in a field.\n * - Optional `temperature`, `async`, `noWrite`, `conditionalPaths`.\n *\n * @returns A stable callback that triggers the action and yields a Subscribable stream.\n *\n * @example Basic translation\n * ```tsx\n * import {useAgentTranslate} from '@sanity/sdk-react'\n *\n * function TranslateArticle({documentId}: {documentId: string}) {\n * const translate = useAgentTranslate()\n *\n * const handleTranslate = () => {\n * translate({\n * documentId,\n * fromLanguage: 'en',\n * toLanguage: 'es',\n * targetPaths: ['title', 'body'],\n * }).subscribe({\n * complete: () => console.log('Translation complete'),\n * error: (err) => console.error('Translation failed:', err),\n * })\n * }\n *\n * return <button onClick={handleTranslate}>Translate to Spanish</button>\n * }\n * ```\n *\n * @example Translation with style guide and protected phrases\n * ```tsx\n * import {useAgentTranslate} from '@sanity/sdk-react'\n *\n * function TranslateWithBrandTerms({documentId}: {documentId: string}) {\n * const translate = useAgentTranslate()\n *\n * const handleTranslate = () => {\n * translate({\n * documentId,\n * fromLanguage: 'en',\n * toLanguage: 'fr',\n * styleGuide: 'Use formal French appropriate for business communication.',\n * protectedPhrases: ['Acme Corp', 'PowerWidget Pro'],\n * targetPaths: ['title', 'description'],\n * }).subscribe({\n * complete: () => console.log('Translation complete'),\n * })\n * }\n *\n * return <button onClick={handleTranslate}>Translate to French</button>\n * }\n * ```\n *\n * @example Translate to a new document\n * ```tsx\n * import {useAgentTranslate} from '@sanity/sdk-react'\n *\n * function CreateTranslatedCopy({documentId}: {documentId: string}) {\n * const translate = useAgentTranslate()\n *\n * const handleCreateTranslation = () => {\n * translate({\n * documentId,\n * fromLanguage: 'en',\n * toLanguage: 'de',\n * targetDocument: {\n * operation: 'create',\n * _type: 'article',\n * },\n * languageFieldPath: 'language',\n * }).subscribe({\n * next: (result) => console.log('New translated document:', result),\n * complete: () => console.log('Translated copy created'),\n * })\n * }\n *\n * return <button onClick={handleCreateTranslation}>Create German Copy</button>\n * }\n * ```\n *\n * @category Agent Actions\n */\nexport function useAgentTranslate(\n resourceHandle?: ResourceHandle,\n): (options: AgentTranslateOptions) => Subscribable<unknown> {\n const instance = useSanityInstance()\n const {resource} = useNormalizedResourceOptions(resourceHandle ?? {})\n return useCallback(\n (options: AgentTranslateOptions) =>\n agentTranslate(instance, options, resource) as unknown as Subscribable<unknown>,\n [instance, resource],\n )\n}\n\n/**\n * @alpha\n * Prompts the Content Agent using the same instruction template format as other agent actions.\n *\n * @remarks\n * This hook provides a stable callback to send prompts to the Content Agent and receive responses.\n * Unlike the other agent action hooks, this one does not modify documents—it simply\n * returns the AI's response.\n *\n * Features:\n * - Uses the same instruction template format with `$variables` as other actions.\n * - `format`: 'string' or 'json' (instruction must contain the word \"json\" for JSON responses).\n * - Supports `instructionParams` for dynamic content (constants, fields, documents, GROQ queries).\n * - Optional `temperature` for controlling response creativity.\n *\n * @returns A stable callback that triggers the action and resolves a Promise with the prompt result.\n *\n * @example Basic string prompt\n * ```tsx\n * import {useState} from 'react'\n * import {useAgentPrompt} from '@sanity/sdk-react'\n *\n * function AskQuestion() {\n * const prompt = useAgentPrompt()\n * const [answer, setAnswer] = useState<string>('')\n *\n * const handleAsk = async () => {\n * const result = await prompt({\n * instruction: 'What are the top 3 benefits of content modeling?',\n * format: 'string',\n * })\n * setAnswer(result.output)\n * }\n *\n * return (\n * <div>\n * <button onClick={handleAsk}>Ask AI</button>\n * {answer && <p>{answer}</p>}\n * </div>\n * )\n * }\n * ```\n *\n * @example JSON response with instruction params\n * ```tsx\n * import {useState} from 'react'\n * import {useAgentPrompt} from '@sanity/sdk-react'\n *\n * interface TagSuggestions {\n * tags: string[]\n * reasoning: string\n * }\n *\n * function SuggestTags({documentId}: {documentId: string}) {\n * const prompt = useAgentPrompt()\n * const [suggestions, setSuggestions] = useState<TagSuggestions | null>(null)\n *\n * const handleSuggest = async () => {\n * const result = await prompt({\n * instruction: `\n * Based on the following article title and content, suggest relevant tags.\n * Return as json with \"tags\" (array of strings) and \"reasoning\" (string).\n * Title: $title\n * Content: $body\n * `,\n * instructionParams: {\n * title: {type: 'field', path: 'title', documentId},\n * body: {type: 'field', path: 'body', documentId},\n * },\n * format: 'json',\n * })\n * setSuggestions(result.output as TagSuggestions)\n * }\n *\n * return (\n * <div>\n * <button onClick={handleSuggest}>Suggest Tags</button>\n * {suggestions && (\n * <div>\n * <p>Reasoning: {suggestions.reasoning}</p>\n * <ul>\n * {suggestions.tags.map((tag) => (\n * <li key={tag}>{tag}</li>\n * ))}\n * </ul>\n * </div>\n * )}\n * </div>\n * )\n * }\n * ```\n *\n * @category Agent Actions\n */\nexport function useAgentPrompt(\n resourceHandle?: ResourceHandle,\n): (options: AgentPromptOptions) => Promise<AgentPromptResult> {\n const instance = useSanityInstance()\n const {resource} = useNormalizedResourceOptions(resourceHandle ?? {})\n return useCallback(\n (options: AgentPromptOptions) => firstValueFrom(agentPrompt(instance, options, resource)),\n [instance, resource],\n )\n}\n\n/**\n * @alpha\n * Schema-aware patching with Sanity Agent Actions.\n *\n * @remarks\n * This hook provides a stable callback to apply schema-validated patches to documents.\n * Unlike {@link useEditDocument}, this uses the Agent Actions API which provides\n * additional schema validation and safe merging capabilities.\n *\n * Features:\n * - Validates provided paths/values against the document schema and merges object values safely.\n * - Prevents duplicate keys and supports array appends (including after a specific keyed item).\n * - Accepts `documentId` or `targetDocument` (mutually exclusive).\n * - Requires `schemaId` (e.g., `'_.schemas.default'`) and `target` to specify patch operations.\n * - Optional `async`, `noWrite`, `conditionalPaths`.\n *\n * Each entry in `target` specifies a `path`, an `operation` (`'set'`, `'append'`, `'mixed'`, or `'unset'`),\n * and a `value` (required for all operations except `'unset'`).\n *\n * @returns A stable callback that triggers the action and resolves a Promise with the patch result.\n *\n * @example Basic field update\n * ```tsx\n * import {useAgentPatch} from '@sanity/sdk-react'\n *\n * function UpdateTitle({documentId}: {documentId: string}) {\n * const patch = useAgentPatch()\n *\n * const handleUpdate = async () => {\n * const result = await patch({\n * documentId,\n * schemaId: '_.schemas.default',\n * target: [\n * {\n * path: 'title',\n * operation: 'set',\n * value: 'Updated Title',\n * },\n * {\n * path: 'lastModified',\n * operation: 'set',\n * value: new Date().toISOString(),\n * },\n * ],\n * })\n * console.log('Patch result:', result)\n * }\n *\n * return <button onClick={handleUpdate}>Update Title</button>\n * }\n * ```\n *\n * @example Append items to an array\n * ```tsx\n * import {useAgentPatch} from '@sanity/sdk-react'\n *\n * function AddTag({documentId}: {documentId: string}) {\n * const patch = useAgentPatch()\n *\n * const handleAddTag = async (newTag: string) => {\n * await patch({\n * documentId,\n * schemaId: '_.schemas.default',\n * target: {\n * path: 'tags',\n * operation: 'append',\n * value: [newTag],\n * },\n * })\n * }\n *\n * return (\n * <button onClick={() => handleAddTag('featured')}>\n * Add Featured Tag\n * </button>\n * )\n * }\n * ```\n *\n * @example Insert array item after a specific key\n * ```tsx\n * import {useAgentPatch} from '@sanity/sdk-react'\n *\n * function InsertContentBlock({\n * documentId,\n * afterKey,\n * }: {\n * documentId: string\n * afterKey: string\n * }) {\n * const patch = useAgentPatch()\n *\n * const handleInsert = async () => {\n * await patch({\n * documentId,\n * schemaId: '_.schemas.default',\n * target: {\n * path: ['content', {_key: afterKey}],\n * operation: 'append',\n * value: [{_type: 'block', text: 'New paragraph inserted here.'}],\n * },\n * })\n * }\n *\n * return <button onClick={handleInsert}>Insert Block</button>\n * }\n * ```\n *\n * @example Create a new document with targetDocument\n * ```tsx\n * import {useAgentPatch} from '@sanity/sdk-react'\n *\n * function CreateProduct() {\n * const patch = useAgentPatch()\n *\n * const handleCreate = async () => {\n * const result = await patch({\n * targetDocument: {\n * operation: 'create',\n * _type: 'product',\n * },\n * schemaId: '_.schemas.default',\n * target: [\n * {\n * path: 'title',\n * operation: 'set',\n * value: 'New Product',\n * },\n * {\n * path: 'price',\n * operation: 'set',\n * value: 29.99,\n * },\n * {\n * path: 'inStock',\n * operation: 'set',\n * value: true,\n * },\n * ],\n * })\n * console.log('Created document:', result.documentId)\n * }\n *\n * return <button onClick={handleCreate}>Create Product</button>\n * }\n * ```\n *\n * @category Agent Actions\n */\nexport function useAgentPatch(\n resourceHandle?: ResourceHandle,\n): (options: AgentPatchOptions) => Promise<AgentPatchResult> {\n const instance = useSanityInstance()\n const {resource} = useNormalizedResourceOptions(resourceHandle ?? {})\n return useCallback(\n (options: AgentPatchOptions) => firstValueFrom(agentPatch(instance, options, resource)),\n [instance, resource],\n )\n}\n","import {type Application, application, type ApplicationInclude} from '@sanity/sdk'\n\nimport {createFetcherHook, type FetcherHookResult} from '../helpers/createFetcherHook'\n\n/**\n * Returns a single application by id.\n *\n * The hook suspends until the first fetch succeeds, so `data` is always present.\n * The `include` tokens you pass shape `data`: each requested token adds its\n * field, and omitted ones are absent from the type.\n *\n * @public\n * @param applicationId - The application id.\n * @param options - Optional `include` list to expand related resources.\n * @returns The result envelope `{data, isFetching, error, refetch}`.\n */\nexport const useApplication = createFetcherHook(application) as <\n Include extends ApplicationInclude = never,\n>(\n applicationId: string,\n options?: {include?: Include[]},\n) => FetcherHookResult<Application<Include>>\n","import {\n type ApplicationInclude,\n applications,\n type ApplicationsOptions,\n type ApplicationsResponse,\n} from '@sanity/sdk'\n\nimport {createFetcherHook, type FetcherHookResult} from '../helpers/createFetcherHook'\n\n/**\n * Returns the applications matching the given options.\n *\n * The hook suspends until the first fetch succeeds, so `data` is always present.\n * The `include` tokens you pass shape `data.data`: each requested token adds its\n * field, and omitted ones are absent from the type.\n *\n * @public\n * @param options - Filter and include options for the applications list.\n * @returns The result envelope `{data, isFetching, error, refetch}`.\n */\nexport const useApplications = createFetcherHook(applications) as <\n Include extends ApplicationInclude = never,\n>(\n options: ApplicationsOptions<Include>,\n) => FetcherHookResult<ApplicationsResponse<Include>>\n","import {type SanityInstance} from '@sanity/sdk'\nimport {type MutationResult} from '@sanity/sdk/_internal'\nimport {useCallback, useRef, useState} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n * The value returned by a mutation-backed hook. The write-side counterpart to\n * {@link FetcherHookResult}: local `{mutate, isPending, error, data, reset}`\n * state around a core mutation action.\n *\n * @public\n */\nexport interface MutationHookResult<TInput, TResult> {\n /**\n * Runs the mutation. Resolves with the server response; rejects on failure\n * (the failure is also captured in {@link MutationHookResult.error}, so a\n * fire-and-forget caller should read `error` and an `await`ing caller should\n * `try`/`catch`).\n */\n mutate: (input: TInput) => Promise<TResult>\n /** A mutation is currently in flight. */\n isPending: boolean\n /** The most recent failure; cleared by the next `mutate` or `reset`. */\n error: unknown\n /** The last successful server response, or `undefined` before the first success. */\n data: TResult | undefined\n /** Clears state back to idle and abandons any in-flight result. */\n reset: () => void\n}\n\ntype MutationState<TResult> =\n | {status: 'idle'; data: undefined; error: undefined}\n | {status: 'pending'; data: TResult | undefined; error: undefined}\n | {status: 'success'; data: TResult; error: undefined}\n | {status: 'error'; data: TResult | undefined; error: unknown}\n\n/**\n * Builds a hook over a core mutation action (the result of `defineMutation`).\n * The write-side counterpart to {@link createFetcherHook}: it binds the action\n * to the current {@link SanityInstance} and tracks `{isPending, error, data}`\n * locally. `mutate` resolves with the server response only — the mutation's\n * `invalidated` promise is intentionally not exposed, since cache\n * reconciliation is handled by the fetcher stores.\n *\n * @internal\n */\nexport function createMutationHook<TInput, TResult>(\n mutation: (instance: SanityInstance, input: TInput) => Promise<MutationResult<TResult>>,\n): () => MutationHookResult<TInput, TResult> {\n const idle: MutationState<TResult> = {status: 'idle', data: undefined, error: undefined}\n\n return function useMutationHook(): MutationHookResult<TInput, TResult> {\n const instance = useSanityInstance()\n const [state, setState] = useState<MutationState<TResult>>(idle)\n // Increments per call; only the latest call is allowed to write state, so an\n // earlier in-flight mutation can't clobber a later one (or a `reset`).\n const callId = useRef(0)\n\n const mutate = useCallback(\n (input: TInput): Promise<TResult> => {\n const id = ++callId.current\n setState((prev) => ({status: 'pending', data: prev.data, error: undefined}))\n return mutation(instance, input).then(\n ({data}) => {\n if (id === callId.current) setState({status: 'success', data, error: undefined})\n return data\n },\n (error: unknown) => {\n if (id === callId.current) {\n setState((prev) => ({status: 'error', data: prev.data, error}))\n }\n throw error\n },\n )\n },\n [instance],\n )\n\n const reset = useCallback(() => {\n callId.current++ // abandon any in-flight response so it can't revive stale state\n setState(idle)\n }, [])\n\n return {\n mutate,\n isPending: state.status === 'pending',\n error: state.error,\n data: state.data,\n reset,\n }\n }\n}\n","import {deleteApplication} from '@sanity/sdk'\n\nimport {createMutationHook} from '../helpers/createMutationHook'\n\n/**\n * Soft-deletes an application.\n *\n * @internal\n * @returns The mutation envelope `{mutate, isPending, error, data, reset}`.\n */\nexport const useDeleteApplication = createMutationHook(deleteApplication)\n","import {updateApplication} from '@sanity/sdk'\n\nimport {createMutationHook} from '../helpers/createMutationHook'\n\n/**\n * Updates an application's mutable properties (title, icon, visibility).\n *\n * @internal\n * @returns The mutation envelope `{mutate, isPending, error, data, reset}`.\n */\nexport const useUpdateApplication = createMutationHook(updateApplication)\n","import {getTokenState} from '@sanity/sdk'\n\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\n\n/**\n * Hook to get the currently logged in user\n * @internal\n * @returns The current user or null if not authenticated\n */\nexport const useAuthToken = createStateSourceHook(getTokenState)\n","import {type CurrentUser, getCurrentUserState} from '@sanity/sdk'\n\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\n\ntype UseCurrentUser = {\n /**\n * @public\n *\n * Provides the currently authenticated user’s profile information.\n *\n * @category Users\n * @returns The current user data\n *\n * @example Rendering a basic user profile\n * ```\n * const user = useCurrentUser()\n *\n * return (\n * <figure>\n * <img src={user?.profileImage} alt=`Profile image for ${user?.name}` />\n * <h2>{user?.name}</h2>\n * </figure>\n * )\n * ```\n */\n (): CurrentUser | null\n}\n\n/**\n * @public\n * @function\n * @TODO This should not return null — users of a custom app will always be authenticated via Core\n */\nexport const useCurrentUser: UseCurrentUser = createStateSourceHook(getCurrentUserState)\n","import {handleOAuthCallback} from '@sanity/sdk'\n\nimport {createCallbackHook} from '../helpers/createCallbackHook'\n\n/**\n * A React hook that returns a function for handling the OAuth redirect callback.\n *\n * @remarks\n * This is the OAuth counterpart to `useHandleAuthCallback`. The returned\n * function invokes core's `handleOAuthCallback`, which validates the `state`\n * parameter, surfaces `?error=` redirects, exchanges the authorization `code`\n * for tokens, persists them, and transitions the auth state to `LOGGED_IN` —\n * all in core. It resolves the callback URL cleaned of the OAuth params\n * (`code`, `state`, `error`, `error_description`) so the caller can strip them\n * with `history.replaceState`, or `false` when there was nothing to handle.\n *\n * Concurrent calls are single-flight in core, so React StrictMode's double\n * invocation will not trigger a second code exchange. Calling it again after\n * the exchange has completed, with the OAuth params still in the URL, fails\n * state validation and moves the auth state to `ERROR`, so apply the returned\n * URL before the component can remount.\n *\n * @example\n * ```tsx\n * function OAuthCallback() {\n * const handleCallback = useHandleOAuthCallback()\n *\n * useEffect(() => {\n * handleCallback(window.location.href)\n * .then((cleanedUrl) => {\n * if (cleanedUrl) {\n * // Remove the OAuth params from the URL without a reload\n * history.replaceState(null, '', cleanedUrl)\n * }\n * })\n * .catch(console.error)\n * }, [handleCallback])\n *\n * return <div>Completing sign-in…</div>\n * }\n * ```\n *\n * @returns A callback handler that processes the OAuth redirect\n * @public\n */\nexport const useHandleOAuthCallback = createCallbackHook(handleOAuthCallback)\n","import {startOAuthAuthorization} from '@sanity/sdk'\n\nimport {createCallbackHook} from '../helpers/createCallbackHook'\n\n/**\n * A React hook that returns a function for starting the OAuth authorization-code + PKCE flow.\n *\n * @remarks\n * The returned function invokes core's `startOAuthAuthorization`, which generates\n * the PKCE `code_verifier`, `code_challenge` and `state`, persists the verifier and\n * state to `sessionStorage`, and navigates the browser to the authorize endpoint.\n * `clientId`, `redirectUri` and `organizationId` are read from the instance's\n * `auth.oauth` config. The returned promise rejects if the instance has no `auth.oauth` config.\n *\n * Pair with {@link useHandleOAuthCallback} on the redirect URI to complete the flow.\n *\n * @example\n * ```tsx\n * function LoginButton() {\n * const authorize = useOAuthAuthorize()\n * return <button onClick={() => authorize().catch(console.error)}>Sign in</button>\n * }\n * ```\n *\n * @returns A function that starts the OAuth flow by navigating to the authorization URL\n * @public\n */\nexport const useOAuthAuthorize = createCallbackHook(startOAuthAuthorization)\n","import {\n getOAuthTokensState,\n type OAuthTokens,\n refreshOAuthTokens,\n revokeOAuthTokens,\n type SanityInstance,\n} from '@sanity/sdk'\n\nimport {createCallbackHook} from '../helpers/createCallbackHook'\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\n\n/**\n * The current OAuth token state, plus actions to refresh and revoke it.\n *\n * @public\n */\nexport interface UseOAuthTokensResult {\n /**\n * The stored OAuth tokens, or `null` when not logged in via OAuth. The\n * refresh token is omitted — core retains it internally for `refresh`.\n */\n tokens: Omit<OAuthTokens, 'refreshToken'> | null\n /**\n * Returns whether the access token has expired, comparing the latest stored\n * `expiresAt` against the current time at the moment it is called. Both the\n * tokens and the clock are read at call time, so a reference captured in an\n * earlier render stays accurate after a `refresh`. Reading the clock does not\n * trigger a re-render, so call this in an event handler or effect rather than\n * during render. Returns `false` when there are no tokens.\n */\n isExpired: () => boolean\n /**\n * Refresh via the OAuth `refresh_token` grant. When there is no refresh token,\n * core clears the stored tokens, logs the user out, and this resolves `null`.\n * Rejects on transient failures (network, 5xx, 408, 429), leaving tokens\n * unchanged so the call can be retried. Also rejects when the server rejects\n * the refresh token itself (other 4xx); core clears the tokens and logs out\n * first, so check `tokens` before retrying.\n */\n refresh: () => Promise<Omit<OAuthTokens, 'refreshToken'> | null>\n /** Revoke the tokens at the OAuth server, clear them locally, and log out. */\n revoke: () => Promise<void>\n}\n\nconst useOAuthTokensState = createStateSourceHook(getOAuthTokensState)\nconst useRefreshOAuthTokens = createCallbackHook(refreshOAuthTokens)\nconst useRevokeOAuthTokens = createCallbackHook(revokeOAuthTokens)\n\n// Reads core's state source directly rather than the render-time `tokens`\n// snapshot, so a reference captured in an earlier render (e.g. in an event\n// handler that awaits `refresh()`) still reflects the latest tokens.\nconst useIsOAuthTokenExpired = createCallbackHook((instance: SanityInstance): boolean => {\n const tokens = getOAuthTokensState(instance).getCurrent()\n return tokens ? tokens.expiresAt.getTime() <= Date.now() : false\n})\n\n/**\n * A React hook that exposes the stored OAuth token state along with `refresh`\n * and `revoke` actions.\n *\n * @remarks\n * The token view is a synchronous read over core's token state source, so the\n * hook re-renders whenever tokens change — including changes made in another\n * tab, which core propagates via `storage` events.\n *\n * @returns The current {@link UseOAuthTokensResult}\n *\n * @example\n * ```tsx\n * function TokenStatus() {\n * const {tokens, isExpired, refresh, revoke} = useOAuthTokens()\n *\n * if (!tokens) return <div>Not signed in</div>\n *\n * const handleRefresh = async () => {\n * if (!isExpired()) return\n * try {\n * await refresh()\n * } catch {\n * // Transient failure (tokens unchanged, retry later) or the refresh\n * // token was rejected (tokens now null, user is logged out).\n * }\n * }\n *\n * return (\n * <div>\n * <p>Expires at {tokens.expiresAt.toLocaleTimeString()}</p>\n * <button onClick={handleRefresh}>Refresh if expired</button>\n * <button onClick={() => revoke()}>Revoke tokens</button>\n * </div>\n * )\n * }\n * ```\n *\n * @public\n */\nexport function useOAuthTokens(): UseOAuthTokensResult {\n return {\n tokens: useOAuthTokensState(),\n isExpired: useIsOAuthTokenExpired(),\n refresh: useRefreshOAuthTokens(),\n revoke: useRevokeOAuthTokens(),\n }\n}\n","import {type ClientOptions, getClientState, type SanityInstance} from '@sanity/sdk'\n\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\n\n/**\n * A React hook that provides a client that subscribes to changes in your application,\n *\n * @remarks\n * This hook is intended for advanced use cases and special API calls that the React SDK\n * does not yet provide hooks for. We welcome you to get in touch with us to let us know\n * your use cases for this!\n *\n * @category Platform\n * @returns A Sanity client\n *\n * @example\n * ```tsx\n * function MyComponent() {\n * const client = useClient({apiVersion: '2024-11-12'})\n * const [document, setDocument] = useState(null)\n * useEffect(async () => {\n * const doc = client.fetch('*[_id == \"myDocumentId\"]')\n * setDocument(doc)\n * }, [])\n * return <div>{JSON.stringify(document) ?? 'Loading...'}</div>\n * }\n * ```\n *\n * @public\n * @function\n */\nexport const useClient = createStateSourceHook({\n getState: (instance: SanityInstance, options: ClientOptions) => {\n if (!options || typeof options !== 'object') {\n throw new Error(\n 'useClient() requires a configuration object with at least an \"apiVersion\" property. ' +\n 'Example: useClient({ apiVersion: \"2024-11-12\" })',\n )\n }\n return getClientState(instance, options)\n },\n getConfig: (options: ClientOptions) => options,\n})\n","import {type ChannelInstance, type Controller, type Status} from '@sanity/comlink'\nimport {\n type FrameMessage,\n getOrCreateChannel,\n getOrCreateController,\n releaseChannel,\n type WindowMessage,\n} from '@sanity/sdk/comlink'\nimport {useCallback, useEffect, useRef} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n * @internal\n */\nexport type FrameMessageHandler<TWindowMessage extends WindowMessage> = (\n event: TWindowMessage['data'],\n) => TWindowMessage['response'] | Promise<TWindowMessage['response']>\n\n/**\n * @internal\n */\nexport interface UseFrameConnectionOptions<TWindowMessage extends WindowMessage> {\n name: string\n connectTo: string\n targetOrigin: string\n onMessage?: {\n [K in TWindowMessage['type']]: (data: Extract<TWindowMessage, {type: K}>['data']) => void\n }\n heartbeat?: boolean\n onStatus?: (status: Status) => void\n}\n\n/**\n * @internal\n */\nexport interface FrameConnection<TFrameMessage extends FrameMessage> {\n connect: (frameWindow: Window) => () => void // Return cleanup function\n sendMessage: <T extends TFrameMessage['type']>(\n ...params: Extract<TFrameMessage, {type: T}>['data'] extends undefined\n ? [type: T]\n : [type: T, data: Extract<TFrameMessage, {type: T}>['data']]\n ) => void\n}\n\n/**\n * @internal\n */\nexport function useFrameConnection<\n TFrameMessage extends FrameMessage,\n TWindowMessage extends WindowMessage,\n>(options: UseFrameConnectionOptions<TWindowMessage>): FrameConnection<TFrameMessage> {\n const {onMessage, targetOrigin, name, connectTo, heartbeat, onStatus} = options\n const instance = useSanityInstance()\n const controllerRef = useRef<Controller | null>(null)\n const channelRef = useRef<ChannelInstance<TFrameMessage, TWindowMessage> | null>(null)\n\n useEffect(() => {\n const controller = getOrCreateController(instance, targetOrigin)\n const channel = getOrCreateChannel(instance, {name, connectTo, heartbeat})\n controllerRef.current = controller\n channelRef.current = channel\n\n channel.onStatus((event) => {\n onStatus?.(event.status)\n })\n\n const messageUnsubscribers: Array<() => void> = []\n\n if (onMessage) {\n Object.entries(onMessage).forEach(([type, handler]) => {\n const unsubscribe = channel.on(type, handler as FrameMessageHandler<TWindowMessage>)\n messageUnsubscribers.push(unsubscribe)\n })\n }\n\n return () => {\n // Clean up all subscriptions and stop controller/channel\n messageUnsubscribers.forEach((unsub) => unsub())\n releaseChannel(instance, name)\n channelRef.current = null\n controllerRef.current = null\n }\n }, [targetOrigin, name, connectTo, heartbeat, onMessage, instance, onStatus])\n\n const connect = useCallback((frameWindow: Window) => {\n const removeTarget = controllerRef.current?.addTarget(frameWindow)\n return () => {\n removeTarget?.()\n }\n }, [])\n\n const sendMessage = useCallback(\n <T extends TFrameMessage['type']>(\n type: T,\n data?: Extract<TFrameMessage, {type: T}>['data'],\n ) => {\n channelRef.current?.post(type, data)\n },\n [],\n )\n\n return {\n connect,\n sendMessage,\n }\n}\n","import {type SanityInstance} from '@sanity/sdk'\nimport {trackHookMounted} from '@sanity/sdk/_internal'\nimport {useRef} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n * Tracks the first usage of a named hook per SDK session.\n * If the telemetry manager hasn't initialized yet, the hook\n * name is buffered and flushed when it becomes available.\n *\n * Uses a ref to ensure the tracking call only happens once per\n * component mount, avoiding repeated WeakMap lookups on re-renders.\n *\n * Call at the top of any public hook whose adoption we want to measure.\n *\n * @internal\n */\nexport function useTrackHookUsage(hookName: string): void {\n const instance = useSanityInstance()\n const tracked = useRef<true | null>(null)\n if (tracked.current === null) {\n tracked.current = true\n trackHookMounted(instance, hookName)\n }\n}\n\n/**\n * Non-hook variant for tracking hook usage when an instance is already\n * available (avoids an extra `useSanityInstance` call in hooks that\n * already have the instance).\n *\n * @internal\n */\nexport function trackHookUsage(instance: SanityInstance, hookName: string): void {\n trackHookMounted(instance, hookName)\n}\n","import {\n type Comment,\n createComment,\n type CreateCommentOptions,\n type DocumentResource,\n type PerspectiveHandle,\n removeComment,\n type RemoveCommentOptions,\n replyToComment,\n type ReplyToCommentOptions,\n setCommentStatus,\n type SetCommentStatusOptions,\n updateComment,\n type UpdateCommentOptions,\n} from '@sanity/sdk'\nimport {useContext, useMemo} from 'react'\n\nimport {PerspectiveContext} from '../../context/PerspectiveContext'\nimport {ResourcesContext} from '../../context/ResourcesContext'\nimport {useSanityInstance} from '../context/useSanityInstance'\nimport {\n normalizeResourceOptions,\n useEffectiveContextResource,\n type WithResourceNameSupport,\n} from '../helpers/useNormalizedResourceOptions'\nimport {trackHookUsage} from '../helpers/useTrackHookUsage'\n\n/**\n * @public\n * @category Types\n */\nexport interface CommentActions {\n /** Starts a thread on a document, or on one of its fields. */\n createComment: (options: WithResourceNameSupport<CreateCommentOptions>) => Promise<Comment>\n /** Adds a reply to an existing thread. */\n replyToComment: (options: WithResourceNameSupport<ReplyToCommentOptions>) => Promise<Comment>\n /** Rewrites a comment's message. */\n updateComment: (options: WithResourceNameSupport<UpdateCommentOptions>) => Promise<void>\n /** Resolves or reopens a thread. Pass the thread's first comment. */\n setCommentStatus: (options: WithResourceNameSupport<SetCommentStatusOptions>) => Promise<void>\n /** Deletes a comment, and its replies when it starts a thread. */\n removeComment: (options: WithResourceNameSupport<RemoveCommentOptions>) => Promise<void>\n}\n\ntype Resolvable = {\n resource?: DocumentResource\n resourceName?: string\n projectId?: string\n dataset?: string\n perspective?: PerspectiveHandle['perspective']\n}\n\n/**\n * Returns the five comment write actions, bound to the current instance.\n *\n * Each writes optimistically: the change shows immediately and is rolled back\n * if the server rejects it, so an app can render straight from\n * {@link useComments} without tracking pending state itself.\n *\n * Creating is the exception, and `replyToComment` counts as creating. A comment\n * that fails to post stays on screen carrying `_state.createError` rather than\n * disappearing, so passing the same `commentId` again retries it instead of\n * losing what someone typed.\n *\n * The resource is resolved when an action is called rather than when the hook\n * runs, so one set of callbacks works across several resources. Pass `resource`\n * or `resourceName` per call to choose; otherwise the surrounding\n * `ResourceProvider` decides.\n *\n * @category Comments\n * @function\n * @returns The five write actions\n *\n * @example Resolve a thread\n * ```tsx\n * function ResolveButton({commentId}: {commentId: string}) {\n * const {setCommentStatus} = useCommentActions()\n *\n * return (\n * <button onClick={() => setCommentStatus({commentId, status: 'resolved'})}>\n * Resolve\n * </button>\n * )\n * }\n * ```\n *\n * @public\n */\nexport function useCommentActions(): CommentActions {\n const instance = useSanityInstance()\n trackHookUsage(instance, 'useCommentActions')\n\n const resources = useContext(ResourcesContext)\n const contextResource = useEffectiveContextResource()\n const contextPerspective = useContext(PerspectiveContext)\n\n return useMemo(() => {\n const resolve = <T extends Resolvable>(options: T) =>\n normalizeResourceOptions(options, resources, contextResource, contextPerspective)\n\n return {\n createComment: (options) => createComment(instance, resolve(options)),\n replyToComment: (options) => replyToComment(instance, resolve(options)),\n updateComment: (options) => updateComment(instance, resolve(options)),\n setCommentStatus: (options) => setCommentStatus(instance, resolve(options)),\n removeComment: (options) => removeComment(instance, resolve(options)),\n }\n }, [contextPerspective, contextResource, instance, resources])\n}\n","import {type CommentsOptions, type SanityInstance, type StateSource} from '@sanity/sdk'\nimport {getCommentsOptionsKey, parseCommentsOptionsKey} from '@sanity/sdk/_internal'\nimport {useEffect, useMemo, useRef, useState, useSyncExternalStore, useTransition} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\nimport {\n useNormalizedResourceOptions,\n type WithResourceNameSupport,\n} from '../helpers/useNormalizedResourceOptions'\nimport {trackHookUsage} from '../helpers/useTrackHookUsage'\n\n/** The pair of core functions backing one read hook. */\nexport interface CommentListSource<T> {\n getState: (instance: SanityInstance, options: CommentsOptions) => StateSource<T | undefined>\n resolve: (\n instance: SanityInstance,\n options: CommentsOptions & {signal?: AbortSignal},\n ) => Promise<T>\n}\n\n/**\n * Shared body of {@link useComments} and {@link useCommentThreads}.\n *\n * Suspends until the first snapshot arrives. Changing documents or filters\n * happens in a transition, so the list already on screen stays put and\n * `isPending` reports the swap instead of the component suspending again. The\n * previous read is aborted, which drops its listener when nothing else is\n * reading it.\n *\n * @internal\n */\nexport function useCommentList<T>(\n hookName: string,\n options: WithResourceNameSupport<CommentsOptions>,\n {getState, resolve}: CommentListSource<T>,\n): {value: T; isPending: boolean} {\n const instance = useSanityInstance()\n trackHookUsage(instance, hookName)\n\n const normalized = useNormalizedResourceOptions(options)\n const [isPending, startTransition] = useTransition()\n\n const key = getCommentsOptionsKey(normalized)\n // Held one render behind `key`, so the swap can happen inside a transition.\n const [deferredKey, setDeferredKey] = useState(key)\n const abortRef = useRef<AbortController>(new AbortController())\n\n useEffect(() => {\n if (key === deferredKey) return\n\n startTransition(() => {\n if (!abortRef.current.signal.aborted) {\n abortRef.current.abort()\n abortRef.current = new AbortController()\n }\n setDeferredKey(key)\n })\n }, [deferredKey, key])\n\n const deferred = useMemo(() => parseCommentsOptionsKey(deferredKey), [deferredKey])\n const {getCurrent, subscribe} = useMemo(\n () => getState(instance, deferred),\n [deferred, getState, instance],\n )\n\n if (getCurrent() === undefined) {\n // Reading the ref mid-render is safe here: React runs no effects for a\n // render that suspends, so the signal captured now cannot be swapped\n // underneath this pass.\n const currentSignal = abortRef.current.signal\n\n // eslint-disable-next-line react-hooks/refs -- intentional during a suspended render; see above\n throw resolve(instance, {...deferred, signal: currentSignal})\n }\n\n // Not memoised: both callers destructure this immediately and memoise their\n // own result object, so a stable identity here would never be observed.\n return {value: useSyncExternalStore(subscribe, getCurrent) as T, isPending}\n}\n","import {type Comment, type CommentsOptions, getCommentsState, resolveComments} from '@sanity/sdk'\nimport {useMemo} from 'react'\n\nimport {type WithResourceNameSupport} from '../helpers/useNormalizedResourceOptions'\nimport {type CommentListSource, useCommentList} from './useCommentList'\n\n/**\n * @public\n * @category Types\n */\nexport interface UseCommentsResult {\n /** Every matching comment, newest first, replies included. */\n comments: Comment[]\n /** True while switching to a different document or filter. */\n isPending: boolean\n}\n\nconst SOURCE: CommentListSource<Comment[]> = {\n getState: getCommentsState,\n resolve: resolveComments,\n}\n\n/**\n * Reads a document's comments and keeps them up to date.\n *\n * Comments are shared with the Studio: they live in the project's comments\n * dataset, so a thread started here shows up there and the other way round. The\n * list is flat, replies included; reach for {@link useCommentThreads} to read it\n * grouped.\n *\n * Suspends until the comments have loaded. Switching document or filter is a\n * transition, so the previous list stays on screen and `isPending` goes true\n * rather than the component suspending again.\n *\n * @category Comments\n * @function\n * @param options - The document to read, optionally narrowed by `fieldPath` or `status`\n * @returns The matching comments, and whether a switch is in flight\n *\n * @example Count the open threads on a field\n * ```tsx\n * function TitleCommentCount({documentId}: {documentId: string}) {\n * const {comments} = useComments({\n * documentId,\n * documentType: 'article',\n * fieldPath: 'title',\n * status: 'open',\n * })\n *\n * return <span>{comments.length}</span>\n * }\n * ```\n *\n * @public\n */\nexport function useComments(options: WithResourceNameSupport<CommentsOptions>): UseCommentsResult {\n const {value, isPending} = useCommentList('useComments', options, SOURCE)\n return useMemo(() => ({comments: value, isPending}), [isPending, value])\n}\n","import {\n type CommentsOptions,\n type CommentThread,\n getCommentThreadsState,\n resolveCommentThreads,\n} from '@sanity/sdk'\nimport {useMemo} from 'react'\n\nimport {type WithResourceNameSupport} from '../helpers/useNormalizedResourceOptions'\nimport {type CommentListSource, useCommentList} from './useCommentList'\n\n/**\n * @public\n * @category Types\n */\nexport interface UseCommentThreadsResult {\n /** Newest thread first, each with its replies oldest first. */\n threads: CommentThread[]\n /** True while switching to a different document or filter. */\n isPending: boolean\n}\n\nconst SOURCE: CommentListSource<CommentThread[]> = {\n getState: getCommentThreadsState,\n resolve: resolveCommentThreads,\n}\n\n/**\n * Reads a document's comments grouped into threads.\n *\n * A thread is one comment plus its replies. Its `status` and `fieldPath` come\n * from the first comment, so filtering by either selects whole threads rather\n * than stray replies.\n *\n * Unlike the Studio, every thread is returned. The Studio hides threads whose\n * field has left the schema or is hidden by a conditional, which it can do\n * because it has the schema to check against. Inspect `fieldPath` yourself if\n * your app needs to do the same.\n *\n * @category Comments\n * @function\n * @param options - The document to read, optionally narrowed by `fieldPath` or `status`\n * @returns The matching threads, and whether a switch is in flight\n *\n * @example Render the open threads on a document\n * ```tsx\n * function Threads({documentId}: {documentId: string}) {\n * const {threads} = useCommentThreads({\n * documentId,\n * documentType: 'article',\n * status: 'open',\n * })\n *\n * return (\n * <ul>\n * {threads.map((thread) => (\n * <li key={thread.threadId}>\n * {thread.fieldPath || 'Document'} — {thread.commentsCount} comments\n * </li>\n * ))}\n * </ul>\n * )\n * }\n * ```\n *\n * @public\n */\nexport function useCommentThreads(\n options: WithResourceNameSupport<CommentsOptions>,\n): UseCommentThreadsResult {\n const {value, isPending} = useCommentList('useCommentThreads', options, SOURCE)\n return useMemo(() => ({threads: value, isPending}), [isPending, value])\n}\n","import {type DocumentResource} from '@sanity/sdk'\n\nimport {useEffectiveContextResource} from '../helpers/useNormalizedResourceOptions'\n\n/**\n * Returns the currently active `DocumentResource` for the nearest resource context.\n *\n * Resolves in priority order:\n * 1. A `resource` prop on the nearest `<ResourceProvider>`\n * 2. The `projectId`/`dataset` from the current `SanityInstance` config\n * 3. `undefined` when neither is available\n *\n * @public\n * @category Platform\n *\n * @example\n * ```tsx\n * const resource = useResource()\n * console.log(resource?.projectId, resource?.dataset)\n * ```\n */\nexport function useResource(): DocumentResource | undefined {\n return useEffectiveContextResource()\n}\n","import {\n type CanvasResource,\n type MediaResource,\n type StudioResource,\n} from '@sanity/message-protocol'\nimport {type DocumentHandle, type FavoriteDocumentContext} from '@sanity/sdk'\nimport {useMemo} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\n\n/**\n * Props shared by {@link useFavorite} and {@link useUpdateFavorite}: a document\n * handle plus the resource it lives in.\n *\n * @internal\n */\nexport interface UseFavoriteProps extends DocumentHandle {\n resourceId?: string\n resourceType: StudioResource['type'] | MediaResource['type'] | CanvasResource['type']\n /**\n * The name of the schema collection this document belongs to.\n * Typically is the name of the workspace when used in the context of a studio.\n */\n schemaName?: string\n}\n\n/**\n * Resolves {@link UseFavoriteProps} into the {@link FavoriteDocumentContext}\n * shared by the favorites fetcher and mutation, defaulting a studio `resourceId`\n * from the instance's project and dataset.\n *\n * @internal\n */\nexport function useFavoriteContext({\n documentId,\n documentType,\n projectId: paramProjectId,\n dataset: paramDataset,\n resourceId: paramResourceId,\n resourceType,\n schemaName,\n}: UseFavoriteProps): FavoriteDocumentContext {\n const {config} = useSanityInstance()\n const projectId = paramProjectId ?? config?.projectId\n const dataset = paramDataset ?? config?.dataset\n\n if (resourceType === 'studio' && (!projectId || !dataset)) {\n throw new Error('projectId and dataset are required for studio resources')\n }\n const resourceId =\n resourceType === 'studio' && !paramResourceId ? `${projectId}.${dataset}` : paramResourceId\n\n if (!resourceId) {\n throw new Error('resourceId is required for media-library and canvas resources')\n }\n\n return useMemo(\n () => ({documentId, documentType, resourceId, resourceType, schemaName}),\n [documentId, documentType, resourceId, resourceType, schemaName],\n )\n}\n","import {favorites} from '@sanity/sdk'\n\nimport {createFetcherHook} from '../helpers/createFetcherHook'\nimport {useFavoriteContext, type UseFavoriteProps} from './useFavoriteContext'\n\nconst useFavoriteStatus = createFetcherHook(favorites)\n\n/**\n * @internal\n *\n * Reads whether a document is currently favorited. The write-side counterpart is\n * {@link useUpdateFavorite}.\n *\n * The hook suspends until the first favorite status resolves, so wrap the\n * component in a `<Suspense>` boundary.\n *\n * @param props - The document handle plus the resource it lives in.\n * @returns `true` when the document is favorited, otherwise `false`.\n *\n * @example\n * ```tsx\n * function FavoriteLabel(props: DocumentActionProps) {\n * const {documentId, documentType} = props\n * const isFavorited = useFavorite({documentId, documentType, resourceType: 'studio'})\n *\n * return <span>{isFavorited ? 'Favorited' : 'Not favorited'}</span>\n * }\n * ```\n */\nexport function useFavorite(props: UseFavoriteProps): boolean {\n const context = useFavoriteContext(props)\n const {data} = useFavoriteStatus(context)\n return data.isFavorited\n}\n","/* eslint-disable react-compiler/react-compiler -- the transport branch in `useRecordDocumentHistoryEvent` is a deliberate rules-of-hooks exception; the compiler refuses files that disable it */\nimport {\n type CanvasResource,\n type Events,\n type MediaResource,\n SDK_CHANNEL_NAME,\n SDK_NODE_NAME,\n type StudioResource,\n} from '@sanity/message-protocol'\nimport {type DocumentHandle} from '@sanity/sdk'\nimport {isDashboardEnvironment} from '@sanity/sdk/_internal'\nimport {type FrameMessage} from '@sanity/sdk/comlink'\nimport {useCallback} from 'react'\n\nimport {useWindowConnection} from '../comlink/useWindowConnection'\nimport {useEmit} from './useEmit'\nimport {useTopic} from './useTopic'\n\ninterface DocumentInteractionHistory {\n recordEvent: (eventType: 'viewed' | 'edited' | 'created' | 'deleted') => void\n}\n\n/**\n * @internal\n */\ninterface UseRecordDocumentHistoryEventProps extends DocumentHandle {\n resourceType: StudioResource['type'] | MediaResource['type'] | CanvasResource['type']\n /**\n * The resource the document lives in. Optional for studios over Comlink, where the iframe\n * host fills it from context; always required under the message bus, which has no such\n * context and throws when it is missing.\n */\n resourceId?: string\n /**\n * The name of the schema collection this document belongs to.\n * Typically is the name of the workspace when used in the context of a studio.\n */\n schemaName?: string\n}\n\n/**\n * @internal\n * Hook for recording document interaction history in a Dashboard application.\n * This hook provides functionality to record document interactions.\n *\n * It works in both Dashboard runtimes and picks the transport for the current one:\n *\n * | Runtime | Transport | `resourceId` | Suspends until |\n * | --- | --- | --- | --- |\n * | iframe | Comlink | optional for studios | the node connects |\n * | federated | message bus | required | capabilities publish |\n *\n * Under the message bus the hook always suspends until the host publishes its capabilities;\n * only once they resolve does `recordEvent` run, and it then no-ops on every call when the\n * host does not provide the `history` capability. There is no synchronous no-op path.\n *\n * @category History\n * @param documentHandle - The document handle containing document ID and type, like `{_id: '123', _type: 'book'}`\n * @returns An object containing:\n * - `recordEvent` - Function to record document interactions\n *\n * @example\n * ```tsx\n * import {useRecordDocumentHistoryEvent} from '@sanity/sdk-react'\n * import {Button} from '@sanity/ui'\n * import {Suspense} from 'react'\n *\n * function RecordEventButton(props: DocumentActionProps) {\n * const {documentId, documentType, resourceType, resourceId} = props\n * const {recordEvent} = useRecordDocumentHistoryEvent({\n * documentId,\n * documentType,\n * resourceType,\n * resourceId,\n * })\n * return (\n * <Button\n * onClick={() => recordEvent('viewed')}\n * text=\"Viewed\"\n * />\n * )\n * }\n *\n * // Wrap the component with Suspense since the hook may suspend\n * function MyDocumentAction(props: DocumentActionProps) {\n * return (\n * <Suspense fallback={<Button text=\"Loading...\" disabled />}>\n * <RecordEventButton {...props} />\n * </Suspense>\n * )\n * }\n * ```\n */\nexport function useRecordDocumentHistoryEvent(\n props: UseRecordDocumentHistoryEventProps,\n): DocumentInteractionHistory {\n // The branch is stable: the transport is fixed for the page lifetime, so one set of hooks\n // always runs and the other never does.\n // eslint-disable-next-line react-hooks/rules-of-hooks -- transport is fixed for the page lifetime\n if (isDashboardEnvironment()) return useBusRecordDocumentHistoryEvent(props)\n // eslint-disable-next-line react-hooks/rules-of-hooks -- transport is fixed for the page lifetime\n return useComlinkRecordDocumentHistoryEvent(props)\n}\n\nfunction useComlinkRecordDocumentHistoryEvent({\n documentId,\n documentType,\n resourceType,\n resourceId,\n schemaName,\n}: UseRecordDocumentHistoryEventProps): DocumentInteractionHistory {\n const {sendMessage} = useWindowConnection<Events.HistoryMessage, FrameMessage>({\n name: SDK_NODE_NAME,\n connectTo: SDK_CHANNEL_NAME,\n })\n\n if (resourceType !== 'studio' && !resourceId) {\n throw new Error('resourceId is required for media-library and canvas resources')\n }\n\n const recordEvent = useCallback(\n (eventType: 'viewed' | 'edited' | 'created' | 'deleted') => {\n try {\n const message: Events.HistoryMessage = {\n type: 'dashboard/v1/events/history',\n data: {\n eventType,\n document: {\n id: documentId,\n type: documentType,\n resource: {\n id: resourceId!,\n type: resourceType,\n schemaName,\n },\n },\n },\n }\n\n sendMessage(message.type, message.data)\n } catch (error) {\n // eslint-disable-next-line no-console\n console.error('Failed to record history event:', error)\n throw error\n }\n },\n [documentId, documentType, resourceId, resourceType, sendMessage, schemaName],\n )\n\n return {\n recordEvent,\n }\n}\n\nfunction useBusRecordDocumentHistoryEvent({\n documentId,\n documentType,\n resourceType,\n resourceId,\n schemaName,\n}: UseRecordDocumentHistoryEventProps): DocumentInteractionHistory {\n const emitActivity = useEmit('applications.activity')\n const capabilities = useTopic('applications.capabilities')\n\n // The bus host has no iframe context to fill `projectId.dataset` from, so the resource must\n // be addressed explicitly.\n if (!resourceId) {\n throw new Error('resourceId is required to record document history under the message bus')\n }\n\n // A studio is addressed by its dataset resource over the bus; the workspace name rides along\n // in `schemaName`.\n const type = resourceType === 'studio' ? 'dataset' : resourceType\n\n const recordEvent = useCallback(\n (eventType: 'viewed' | 'edited' | 'created' | 'deleted') => {\n if (!capabilities.history) return\n emitActivity({\n kind: 'document',\n eventType,\n document: {\n id: documentId,\n type: documentType,\n resource: {id: resourceId, type, schemaName},\n },\n })\n },\n [capabilities.history, documentId, documentType, emitActivity, resourceId, schemaName, type],\n )\n\n return {recordEvent}\n}\n","import {type FavoriteStatusResponse, setFavorite} from '@sanity/sdk'\nimport {useCallback} from 'react'\n\nimport {createMutationHook} from '../helpers/createMutationHook'\nimport {useFavoriteContext, type UseFavoriteProps} from './useFavoriteContext'\n\nconst useSetFavorite = createMutationHook(setFavorite)\n\n/**\n * The value returned by {@link useUpdateFavorite}.\n *\n * @internal\n */\nexport interface UpdateFavorite {\n /** Adds the document to favorites. */\n favorite: () => Promise<FavoriteStatusResponse>\n /** Removes the document from favorites. */\n unfavorite: () => Promise<FavoriteStatusResponse>\n /** A favorite or unfavorite mutation is currently in flight. */\n isPending: boolean\n /** The most recent failure; cleared by the next call or `reset`. */\n error: unknown\n /** Clears error and pending state back to idle. */\n reset: () => void\n}\n\n/**\n * @internal\n *\n * Adds or removes a document from favorites. The read-side counterpart is\n * {@link useFavorite}, which reflects the change once the mutation settles.\n *\n * Unlike {@link useFavorite}, this hook does not suspend.\n *\n * @param props - The document handle plus the resource it lives in.\n * @returns `favorite`/`unfavorite` actions and the `{isPending, error, reset}`\n * mutation state.\n *\n * @example\n * ```tsx\n * function FavoriteButton(props: DocumentActionProps) {\n * const {documentId, documentType} = props\n * const handle = {documentId, documentType, resourceType: 'studio'} as const\n * const isFavorited = useFavorite(handle)\n * const {favorite, unfavorite, isPending} = useUpdateFavorite(handle)\n *\n * return (\n * <Button\n * disabled={isPending}\n * onClick={() => (isFavorited ? unfavorite() : favorite())}\n * text={isFavorited ? 'Remove from favorites' : 'Add to favorites'}\n * />\n * )\n * }\n *\n * // Wrap the component with Suspense since useFavorite suspends\n * function MyDocumentAction(props: DocumentActionProps) {\n * return (\n * <Suspense fallback={<Button text=\"Loading...\" disabled />}>\n * <FavoriteButton {...props} />\n * </Suspense>\n * )\n * }\n * ```\n */\nexport function useUpdateFavorite(props: UseFavoriteProps): UpdateFavorite {\n const context = useFavoriteContext(props)\n const {mutate, isPending, error, reset} = useSetFavorite()\n\n const favorite = useCallback(() => mutate({...context, isFavorited: true}), [mutate, context])\n const unfavorite = useCallback(() => mutate({...context, isFavorited: false}), [mutate, context])\n\n return {favorite, unfavorite, isPending, error, reset}\n}\n","import {type DocumentResource, isDatasetResource} from '@sanity/sdk'\nimport {useContext} from 'react'\n\nimport {ProjectContext} from '../../context/ProjectContext'\nimport {useNormalizedResourceOptions} from './useNormalizedResourceOptions'\n\n/**\n * Resolves the effective `projectId` for project-scoped hooks (`useProject`,\n * `useDatasets`, `useUsers`).\n *\n * Precedence:\n * 1. an explicit `projectId` on the options\n * 2. the ambient project scope (`ProjectContext`, e.g. a dataset-less\n * `<ResourceProvider projectId=\"…\">`)\n * 3. the resolved resource's projectId (`ResourceProvider`/`SDKProvider`)\n *\n * Returns `undefined` when none apply, letting callers fall back to core's\n * `instance.config.projectId`.\n *\n * @internal\n */\nexport function useResolvedProjectId(options?: {\n projectId?: string\n dataset?: string\n resource?: DocumentResource\n resourceName?: string\n}): string | undefined {\n const {resource} = useNormalizedResourceOptions(options ?? {})\n const contextProjectId = useContext(ProjectContext)\n return (\n options?.projectId ??\n contextProjectId ??\n (resource && isDatasetResource(resource) ? resource.projectId : undefined)\n )\n}\n","import {type DatasetsResponse} from '@sanity/client'\nimport {datasets, type ProjectHandle} from '@sanity/sdk'\n\nimport {createFetcherHook, type FetcherHookResult} from '../helpers/createFetcherHook'\nimport {useResolvedProjectId} from '../helpers/useResolvedProjectId'\n\nconst useDatasetsBase = createFetcherHook(datasets)\n\n/**\n * Returns metadata for each dataset the current user has access to.\n *\n * @category Datasets\n * @param options - Optional project/resource to read datasets for. Defaults to\n * the resource named in `ResourceProvider`/`SDKProvider`.\n * @returns A {@link FetcherHookResult} whose `data` is the metadata for the\n * datasets.\n *\n * @example\n * ```tsx\n * const {data: datasets} = useDatasets()\n *\n * return (\n * <select>\n * {datasets.map((dataset) => (\n * <option key={dataset.name}>{dataset.name}</option>\n * ))}\n * </select>\n * )\n * ```\n *\n * @remarks\n * The `projectId` is resolved in order from:\n * 1. an explicit `projectId` option\n * 2. A legacy ProjectContext (e.g. a `<ResourceProvider projectId=\"…\">` with no dataset), then\n * 3. The active resource (`ResourceProvider`/`SDKProvider`)\n * 4. `instance.config`.\n * @public\n */\nexport function useDatasets(options?: ProjectHandle): FetcherHookResult<DatasetsResponse> {\n const projectId = useResolvedProjectId(options)\n return useDatasetsBase(projectId ? {...options, projectId} : options)\n}\n","import {type Action, type ActionsResult, applyDocumentActions} from '@sanity/sdk'\nimport {isDeepEqual} from '@sanity/sdk/_internal'\nimport {useContext} from 'react'\n\nimport {type ResourceHandle} from '../../config/handles'\nimport {ResourcesContext} from '../../context/ResourcesContext'\nimport {useSanityInstance} from '../context/useSanityInstance'\nimport {normalizeResourceOptions, useEffectiveContextResource} from './useNormalizedResourceOptions'\n\n/**\n * @internal\n *\n * Shared implementation behind `useApplyDocumentActions` and\n * `useApplyReleaseActions`. Resolves the effective resource from the action\n * handles, top-level `options`, or context (in that order), validates that\n * everything agrees on a single resource, and forwards to\n * `applyDocumentActions`.\n *\n * The two public hooks differ only in their input/output types — at runtime\n * they're identical because core's `applyDocumentActions` accepts the full\n * `Action` union.\n */\nexport function useApplyActions(): (\n actionOrActions: Action | Action[],\n options?: ResourceHandle,\n) => Promise<ActionsResult> {\n const instance = useSanityInstance()\n const resources = useContext(ResourcesContext)\n const effectiveContextResource = useEffectiveContextResource()\n\n return (actionOrActions, options) => {\n const actions = Array.isArray(actionOrActions) ? actionOrActions : [actionOrActions]\n const optionsResource = options\n ? normalizeResourceOptions(options, resources, effectiveContextResource).resource\n : undefined\n\n const normalizedActions = actions.map((action) =>\n normalizeResourceOptions(action, resources, effectiveContextResource),\n )\n\n let resource\n for (const action of normalizedActions) {\n const actionResource = action['resource']\n if (!resource && actionResource) resource = actionResource\n if (!isDeepEqual(actionResource, resource)) {\n throw new Error(\n `Mismatched resources found in actions. All actions must belong to the same resource. Found \"${JSON.stringify(actionResource)}\" but expected \"${JSON.stringify(resource)}\".`,\n )\n }\n }\n\n if (optionsResource && resource && !isDeepEqual(optionsResource, resource)) {\n throw new Error(\n `Mismatched resources found in actions. Found top-level resource \"${JSON.stringify(optionsResource)}\" but expected resource from action handles \"${JSON.stringify(resource)}\".`,\n )\n }\n\n const effectiveResource = resource ?? optionsResource ?? effectiveContextResource\n if (!effectiveResource) {\n throw new Error('No resource found. Provide a resource via the action handle or context.')\n }\n\n return applyDocumentActions(instance, {\n actions: normalizedActions as Action[],\n resource: effectiveResource,\n })\n }\n}\n","import {type ActionsResult, type DocumentAction, type ResolveDocument} from '@sanity/sdk'\n\nimport {type ResourceHandle} from '../../config/handles'\nimport {useApplyActions} from '../helpers/useApplyActions'\n// this import is used in an `{@link useEditDocument}`\n// eslint-disable-next-line import-x/consistent-type-specifier-style\nimport type {useEditDocument} from './useEditDocument'\n\n/**\n * @public\n */\ninterface UseApplyDocumentActions {\n (): <\n TDocumentType extends string = string,\n TDataset extends string = string,\n TProjectId extends string = string,\n >(\n action:\n | DocumentAction<TDocumentType, TDataset, TProjectId>\n | DocumentAction<TDocumentType, TDataset, TProjectId>[],\n options?: ResourceHandle,\n ) => Promise<ActionsResult<ResolveDocument<TDocumentType, `${TProjectId}.${TDataset}`>>>\n}\n\n/**\n * @public\n *\n * Provides a stable callback function for applying one or more document actions.\n *\n * This hook wraps the core `applyDocumentActions` functionality from `@sanity/sdk`,\n * integrating it with the React component lifecycle and {@link SanityInstance}.\n * It allows you to apply actions generated by functions like `createDocument`,\n * `editDocument`, `deleteDocument`, `publishDocument`, `unpublishDocument`,\n * and `discardDocument` to documents.\n *\n * Features:\n * - Applies one or multiple `DocumentAction` objects.\n * - Supports optimistic updates: Local state reflects changes immediately.\n * - Handles batching: Multiple actions passed together are sent as a single atomic transaction.\n * - Integrates with the collaborative editing engine for conflict resolution and state synchronization.\n *\n * @category Documents\n * @returns A stable callback function. When called with a single `DocumentAction` or an array of `DocumentAction`s,\n * it returns a promise that resolves to an {@link ActionsResult}. The `ActionsResult` contains information about the\n * outcome, including optimistic results if applicable.\n *\n * @remarks\n * This hook is a fundamental part of interacting with document state programmatically.\n * It operates within the same unified pipeline as other document hooks like `useDocument` (for reading state)\n * and {@link useEditDocument} (a higher-level hook specifically for edits).\n *\n * When multiple actions are provided in a single call, they are guaranteed to be submitted\n * as a single transaction to Content Lake. This ensures atomicity for related operations (e.g., creating and publishing a document).\n *\n * @function\n *\n * @example Publish or unpublish a document\n * ```tsx\n * import {\n * publishDocument,\n * unpublishDocument,\n * useApplyDocumentActions,\n * type DocumentHandle\n * } from '@sanity/sdk-react'\n *\n * // Define props using the DocumentHandle type\n * interface PublishControlsProps {\n * doc: DocumentHandle\n * }\n *\n * function PublishControls({doc}: PublishControlsProps) {\n * const apply = useApplyDocumentActions()\n *\n * const handlePublish = () => apply(publishDocument(doc))\n * const handleUnpublish = () => apply(unpublishDocument(doc))\n *\n * return (\n * <>\n * <button onClick={handlePublish}>Publish</button>\n * <button onClick={handleUnpublish}>Unpublish</button>\n * </>\n * )\n * }\n * ```\n *\n * @example Create and publish a new document\n * ```tsx\n * import {\n * createDocument,\n * publishDocument,\n * createDocumentHandle,\n * useApplyDocumentActions\n * } from '@sanity/sdk-react'\n *\n * function CreateAndPublishButton({documentType}: {documentType: string}) {\n * const apply = useApplyDocumentActions()\n *\n * const handleCreateAndPublish = () => {\n * // Create a new handle inside the handler\n * const newDocHandle = createDocumentHandle({ documentId: crypto.randomUUID(), documentType })\n *\n * // Apply multiple actions for the new handle as a single transaction\n * apply([\n * createDocument(newDocHandle),\n * publishDocument(newDocHandle),\n * ])\n * }\n *\n * return (\n * <button onClick={handleCreateAndPublish}>\n * I'm feeling lucky\n * </button>\n * )\n * }\n * ```\n *\n * @example Create a document with initial field values\n * ```tsx\n * import {\n * createDocument,\n * createDocumentHandle,\n * useApplyDocumentActions\n * } from '@sanity/sdk-react'\n *\n * function CreateArticleButton() {\n * const apply = useApplyDocumentActions()\n *\n * const handleCreateArticle = () => {\n * const newDocHandle = createDocumentHandle({\n * documentId: crypto.randomUUID(),\n * documentType: 'article'\n * })\n *\n * // Create document with initial values in one action\n * apply(\n * createDocument(newDocHandle, {\n * title: 'New Article',\n * author: 'John Doe',\n * publishedAt: new Date().toISOString(),\n * })\n * )\n * }\n *\n * return <button onClick={handleCreateArticle}>Create Article</button>\n * }\n * ```\n *\n * @example Create a new document in a release\n * ```tsx\n * import {\n * createDocument,\n * createDocumentHandle,\n * useApplyDocumentActions\n * } from '@sanity/sdk-react'\n *\n * function CreateArticleButton() {\n * const apply = useApplyDocumentActions()\n *\n * const handleCreateArticle = () => {\n * // Use any valid document ID — not the internal `versions.<releaseName>.<id>` format or \"drafts.<id>\" format.\n * // New documents must be explicitly created with `createDocument` to become part of a release.\n * const newDocHandle = createDocumentHandle({\n * documentId: crypto.randomUUID(), // or the existing document ID you want to make a release version of\n * documentType: 'article',\n * perspective: {releaseName: 'summer-drop'},\n * })\n *\n * apply(\n * createDocument(newDocHandle, {\n * title: 'New Article',\n * author: 'John Doe',\n * publishedAt: new Date().toISOString(),\n * })\n * )\n * }\n *\n * return <button onClick={handleCreateArticle}>Create Article</button>\n * }\n * ```\n *\n * @example Edit an existing document in a release\n * ```tsx\n * import {\n * editDocument,\n * createDocumentHandle,\n * useApplyDocumentActions\n * } from '@sanity/sdk-react'\n *\n * function EditArticleInReleaseButton({documentId}: {documentId: string}) {\n * const apply = useApplyDocumentActions()\n *\n * const handleEdit = () => {\n * // Pass the document's regular ID — not `versions.<releaseName>.<id>`.\n * // Documents that already have a version in the release can be edited directly with `editDocument`.\n * const docHandle = createDocumentHandle({\n * documentId,\n * documentType: 'article',\n * perspective: {releaseName: 'summer-drop'},\n * })\n *\n * apply(editDocument(docHandle, {set: {title: 'Updated for release'}}))\n * }\n *\n * return <button onClick={handleEdit}>Edit in Release</button>\n * }\n * ```\n */\nexport const useApplyDocumentActions: UseApplyDocumentActions = () => {\n return useApplyActions() as ReturnType<UseApplyDocumentActions>\n}\n","import {createDocument, type ResolveDocument} from '@sanity/sdk'\nimport {randomUuid} from '@sanity/sdk/_internal'\n\nimport {type DocumentHandle, type DocumentTypeHandle} from '../../config/handles'\nimport {useSanityInstance} from '../context/useSanityInstance'\nimport {trackHookUsage} from '../helpers/useTrackHookUsage'\nimport {useApplyDocumentActions} from './useApplyDocumentActions'\n\ntype IgnoredKey = '_id' | '_type' | '_rev' | '_createdAt' | '_updatedAt'\n\n/**\n * Optional per-call overrides for {@link useCreateDocument}'s create function.\n * @public\n */\nexport interface CreateDocumentOverrides {\n /**\n * Use this document ID instead of generating one. Overrides any `documentId`\n * supplied on the handle passed to `useCreateDocument`.\n */\n documentId?: string\n}\n\n// Overload 1: Typegen — infers the document shape from your schema.\n/**\n * @public\n * Create a new document, relying on Typegen for the initial-value type.\n *\n * @param options - A document-type handle including `documentType`, an optional `documentId`, and optionally `projectId`/`dataset`/`perspective`.\n * @returns A function that creates the document. It accepts optional initial field values and an optional `{documentId}` override,\n * and resolves to the {@link DocumentHandle} of the created document (carrying the generated or supplied id).\n */\nexport function useCreateDocument<\n TDocumentType extends string = string,\n TDataset extends string = string,\n TProjectId extends string = string,\n>(\n options: DocumentTypeHandle<TDocumentType, TDataset, TProjectId>,\n): (\n initialValue?: Partial<\n Omit<ResolveDocument<TDocumentType, `${TProjectId}.${TDataset}`>, IgnoredKey>\n >,\n overrides?: CreateDocumentOverrides,\n) => Promise<DocumentHandle<TDocumentType, TDataset, TProjectId>>\n\n// Overload 2: Explicit type `TData`.\n/**\n * @public\n * Create a new document with an explicit type `TData`.\n *\n * @param options - A document-type handle including `documentType` and optionally `projectId`/`dataset`/`perspective`.\n * @returns A function that creates the document. It accepts optional initial field values (typed against `TData`) and an\n * optional `{documentId}` override, and resolves to the {@link DocumentHandle} of the created document.\n */\nexport function useCreateDocument<TData extends Record<string, unknown>>(\n options: DocumentTypeHandle,\n): (\n initialValue?: Partial<Omit<TData, IgnoredKey>>,\n overrides?: CreateDocumentOverrides,\n) => Promise<DocumentHandle>\n\n/**\n * @public\n * Provides a function to create a new document and returns its handle.\n *\n * @category Documents\n * @remarks\n * This is the create counterpart to {@link useEditDocument}. It wraps\n * {@link useApplyDocumentActions} and the `createDocument` action for the common\n * single-document case, so you don't have to assemble the action by hand.\n *\n * It handles the document ID for you: if you don't supply one (on the handle or\n * via the per-call `{documentId}` override), a UUID is generated. Either way the\n * returned {@link DocumentHandle} carries that id, ready to pass to\n * {@link useDocument}, {@link useEditDocument}, or your router.\n *\n * Unlike {@link useEditDocument}, this hook does not read existing document state,\n * so it never suspends.\n *\n * For atomic create-and-publish, or for creating several documents in a single\n * transaction, use {@link useApplyDocumentActions} with the `createDocument` and\n * `publishDocument` action creators directly.\n *\n * @example Create a document and navigate to it\n * ```tsx\n * import {useCreateDocument} from '@sanity/sdk-react'\n * import {useNavigate} from 'react-router-dom'\n *\n * function CreateArticleButton() {\n * const createArticle = useCreateDocument({documentType: 'article'})\n * const navigate = useNavigate()\n *\n * const handleClick = async () => {\n * const handle = await createArticle({title: 'New Article'})\n * navigate(`/articles/${handle.documentId}`)\n * }\n *\n * return <button onClick={handleClick}>Create Article</button>\n * }\n * ```\n */\nexport function useCreateDocument(\n options: DocumentTypeHandle,\n): (\n initialValue?: Record<string, unknown>,\n overrides?: CreateDocumentOverrides,\n) => Promise<DocumentHandle> {\n const instance = useSanityInstance()\n trackHookUsage(instance, 'useCreateDocument')\n const apply = useApplyDocumentActions()\n\n return async (initialValue, overrides) => {\n const documentId = overrides?.documentId ?? options.documentId ?? randomUuid()\n const handle: DocumentHandle = {...options, documentId}\n await apply(createDocument(handle, initialValue))\n return handle\n }\n}\n","import {\n type DocumentOptions,\n getDocumentState,\n type JsonMatch,\n type ResolveDocument,\n resolveDocument,\n} from '@sanity/sdk'\nimport {identity} from 'rxjs'\n\nimport {type DocumentHandle} from '../../config/handles'\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\nimport {useNormalizedResourceOptions} from '../helpers/useNormalizedResourceOptions'\nimport {useTrackHookUsage} from '../helpers/useTrackHookUsage'\n// used in an `{@link useDocumentProjection}` and `{@link useQuery}`\n// eslint-disable-next-line import-x/consistent-type-specifier-style\nimport type {useDocumentProjection} from '../projection/useDocumentProjection'\n// eslint-disable-next-line import-x/consistent-type-specifier-style\nimport type {useQuery} from '../query/useQuery'\n\nconst useDocumentValue = createStateSourceHook({\n // Pass options directly to getDocumentState\n getState: (instance, options: DocumentOptions<string | undefined>) =>\n getDocumentState(instance, options),\n // Pass options directly to getDocumentState for checking current value\n shouldSuspend: (instance, {path: _path, ...options}: DocumentOptions<string | undefined>) =>\n getDocumentState(instance, options).getCurrent() === undefined,\n // Extract handle part for resolveDocument\n suspender: (instance, options: DocumentOptions<string | undefined>) =>\n resolveDocument(instance, options),\n getConfig: identity as (\n options: DocumentOptions<string | undefined>,\n ) => DocumentOptions<string | undefined>,\n})\n\nconst wrapHookWithData = <TParams extends unknown[], TReturn>(\n useValue: (...params: TParams) => TReturn,\n) => {\n function useHook(...params: TParams) {\n return {data: useValue(...params)}\n }\n return useHook\n}\n\ntype UseDocumentOptions<\n TPath extends string | undefined = undefined,\n TDocumentType extends string = string,\n TDataset extends string = string,\n TProjectId extends string = string,\n> = DocumentHandle<TDocumentType, TDataset, TProjectId> & {path?: TPath}\n\ninterface UseDocument {\n /** @internal */\n <TDocumentType extends string, TDataset extends string, TProjectId extends string = string>(\n options: UseDocumentOptions<undefined, TDocumentType, TDataset, TProjectId>,\n ): {data: ResolveDocument<TDocumentType, `${TProjectId}.${TDataset}`> | null}\n\n /** @internal */\n <\n TPath extends string,\n TDocumentType extends string,\n TDataset extends string = string,\n TProjectId extends string = string,\n >(\n options: UseDocumentOptions<TPath, TDocumentType>,\n ): {\n data: JsonMatch<ResolveDocument<TDocumentType, `${TProjectId}.${TDataset}`>, TPath> | undefined\n }\n\n /** @internal */\n <TData>(options: DocumentOptions<undefined>): {data: TData | null}\n /** @internal */\n <TData>(options: DocumentOptions<string>): {data: TData | undefined}\n\n /**\n * ## useDocument via Type Inference (Recommended)\n *\n * @public\n *\n * The preferred way to use this hook when working with Sanity Typegen.\n *\n * Features:\n * - Automatically infers document types from your schema\n * - Provides type-safe access to documents and nested fields\n * - Supports project/dataset-specific type inference\n * - Works seamlessly with Typegen-generated types\n *\n * This hook will suspend while the document data is being fetched and loaded.\n *\n * When fetching a full document:\n * - Returns the complete document object if it exists\n * - Returns `null` if the document doesn't exist\n *\n * When fetching with a path:\n * - Returns the value at the specified path if both the document and path exist\n * - Returns `undefined` if either the document doesn't exist or the path doesn't exist in the document\n *\n * @category Documents\n * @param options - Configuration including `documentId`, `documentType`, and optionally:\n * - `path`: To select a nested value (returns typed value at path)\n * - `projectId`/`dataset`: For multi-project/dataset setups\n * @returns The document state (or nested value if path provided).\n *\n * @example Basic document fetch\n * ```tsx\n * import {useDocument, type DocumentHandle} from '@sanity/sdk-react'\n *\n * interface ProductViewProps {\n * doc: DocumentHandle<'product'> // Typegen infers product type\n * }\n *\n * function ProductView({doc}: ProductViewProps) {\n * const {data: product} = useDocument({...doc}) // Fully typed product\n * return <h1>{product.title ?? 'Untitled'}</h1>\n * }\n * ```\n *\n * @example Fetching a specific field\n * ```tsx\n * import {useDocument, type DocumentHandle} from '@sanity/sdk-react'\n *\n * interface ProductTitleProps {\n * doc: DocumentHandle<'product'>\n * }\n *\n * function ProductTitle({doc}: ProductTitleProps) {\n * const {data: title} = useDocument({\n * ...doc,\n * path: 'title' // Returns just the title field\n * })\n * return <h1>{title ?? 'Untitled'}</h1>\n * }\n * ```\n *\n * @inlineType DocumentOptions\n */\n <\n TPath extends string | undefined = undefined,\n TDocumentType extends string = string,\n TDataset extends string = string,\n TProjectId extends string = string,\n >(\n options: UseDocumentOptions<TPath, TDocumentType>,\n ): TPath extends string\n ? {\n data:\n | JsonMatch<ResolveDocument<TDocumentType, `${TProjectId}.${TDataset}`>, TPath>\n | undefined\n }\n : {data: ResolveDocument<TDocumentType, `${TProjectId}.${TDataset}`> | null}\n\n /**\n * @public\n *\n * ## useDocument via Explicit Types\n *\n * Use this version when:\n * - You're not using Sanity Typegen\n * - You need to manually specify document types\n * - You're working with dynamic document types\n *\n * Key differences from Typegen version:\n * - Requires manual type specification via `TData`\n * - Returns `TData | null` for full documents\n * - Returns `TData | undefined` for nested values\n *\n * This hook will suspend while the document data is being fetched.\n *\n * @typeParam TData - The explicit type for the document or field\n * @typeParam TPath - Optional path to a nested value\n * @param options - Configuration including `documentId` and optionally:\n * - `path`: To select a nested value\n * - `projectId`/`dataset`: For multi-project/dataset setups\n * @returns The document state (or nested value if path provided)\n *\n * @example Basic document fetch with explicit type\n * ```tsx\n * import {useDocument, type DocumentHandle, type SanityDocument} from '@sanity/sdk-react'\n *\n * interface Book extends SanityDocument {\n * _type: 'book'\n * title: string\n * author: string\n * }\n *\n * interface BookViewProps {\n * doc: DocumentHandle\n * }\n *\n * function BookView({doc}: BookViewProps) {\n * const {data: book} = useDocument<Book>({...doc})\n * return <h1>{book?.title ?? 'Untitled'} by {book?.author ?? 'Unknown'}</h1>\n * }\n * ```\n *\n * @example Fetching a specific field with explicit type\n * ```tsx\n * import {useDocument, type DocumentHandle} from '@sanity/sdk-react'\n *\n * interface BookTitleProps {\n * doc: DocumentHandle\n * }\n *\n * function BookTitle({doc}: BookTitleProps) {\n * const {data: title} = useDocument<string>({...doc, path: 'title'})\n * return <h1>{title ?? 'Untitled'}</h1>\n * }\n * ```\n *\n * @inlineType DocumentOptions\n */\n <TData, TPath extends string>(\n options: UseDocumentOptions<TPath>,\n ): TPath extends string ? {data: TData | undefined} : {data: TData | null}\n\n /**\n * @internal\n */\n (options: UseDocumentOptions): {data: unknown}\n}\n\n/**\n * @public\n * Reads and subscribes to a document's realtime state, incorporating both local and remote changes.\n *\n * This hook comes in two main flavors to suit your needs:\n *\n * 1. **[Type Inference](#usedocument-via-type-inference-recommended)** (Recommended) - Automatically gets types from your Sanity schema\n * 2. **[Explicit Types](#usedocument-via-explicit-types)** - Manually specify types when needed\n *\n * @remarks\n * `useDocument` is ideal for realtime editing interfaces where you need immediate feedback on changes.\n * However, it can be resource-intensive since it maintains a realtime connection.\n *\n * For simpler cases where:\n * - You only need to display content\n * - Realtime updates aren't critical\n * - You want better performance\n *\n * …consider using {@link useDocumentProjection} or {@link useQuery} instead. These hooks are more efficient\n * for read-heavy applications.\n *\n * @function\n */\nexport const useDocument = wrapHookWithData((options: UseDocumentOptions) => {\n useTrackHookUsage('useDocument')\n const normalizedOptions = useNormalizedResourceOptions(options)\n return useDocumentValue(normalizedOptions)\n}) as UseDocument\n","import {type DocumentEvent, subscribeDocumentEvents} from '@sanity/sdk'\nimport {useCallback, useEffect, useInsertionEffect, useRef} from 'react'\n\nimport {type ResourceHandle} from '../../config/handles'\nimport {useSanityInstance} from '../context/useSanityInstance'\nimport {useNormalizedResourceOptions} from '../helpers/useNormalizedResourceOptions'\nimport {useTrackHookUsage} from '../helpers/useTrackHookUsage'\n\n/**\n * @public\n */\nexport interface UseDocumentEventOptions<\n TDataset extends string = string,\n TProjectId extends string = string,\n> extends ResourceHandle<TDataset, TProjectId> {\n onEvent: (documentEvent: DocumentEvent) => void\n}\n\n/**\n *\n * @public\n *\n * Subscribes an event handler to events in your application's document store.\n *\n * @category Documents\n * @param options - An object containing the event handler (`onEvent`) and optionally a `DatasetHandle` (projectId and dataset). If the handle is not provided, the nearest Sanity instance from context will be used.\n * @example Creating a custom hook for document event toasts\n * ```tsx\n * import {createDatasetHandle, type DatasetHandle, type DocumentEvent, useDocumentEvent} from '@sanity/sdk-react'\n * import {useToast} from './my-ui-library'\n *\n * // Define options for the custom hook, extending DatasetHandle\n * interface DocumentToastsOptions extends DatasetHandle {\n * // Could add more options, e.g., { includeEvents: DocumentEvent['type'][] }\n * }\n *\n * // Define the custom hook\n * function useDocumentToasts({...datasetHandle}: DocumentToastsOptions = {}) {\n * const showToast = useToast() // Get the toast function\n *\n * // Define the event handler logic to show toasts on specific events\n * const handleEvent = (event: DocumentEvent) => {\n * if (event.type === 'published') {\n * showToast(`Document ${event.documentId} published.`)\n * } else if (event.type === 'unpublished') {\n * showToast(`Document ${event.documentId} unpublished.`)\n * } else if (event.type === 'deleted') {\n * showToast(`Document ${event.documentId} deleted.`)\n * } else {\n * // Optionally log other events for debugging\n * console.log('Document Event:', event.type, event.documentId)\n * }\n * }\n *\n * // Call the original hook, spreading the handle properties\n * useDocumentEvent({\n * ...datasetHandle, // Spread the dataset handle (projectId, dataset)\n * onEvent: handleEvent,\n * })\n * }\n *\n * function MyComponentWithToasts() {\n * // Use the custom hook, passing specific handle info\n * const specificHandle = createDatasetHandle({ projectId: 'p1', dataset: 'ds1' })\n * useDocumentToasts(specificHandle)\n *\n * // // Or use it relying on context for the handle\n * // useDocumentToasts()\n *\n * return <div>...</div>\n * }\n * ```\n */\nexport function useDocumentEvent<\n TDataset extends string = string,\n TProjectId extends string = string,\n>(\n // Single options object parameter\n options: UseDocumentEventOptions<TDataset, TProjectId>,\n): void {\n useTrackHookUsage('useDocumentEvent')\n // Destructure handler and datasetHandle from options\n const normalizedOptions = useNormalizedResourceOptions(options)\n const {onEvent, ...datasetHandle} = normalizedOptions\n const ref = useRef(onEvent)\n\n useInsertionEffect(() => {\n ref.current = onEvent\n })\n\n const stableHandler = useCallback((documentEvent: DocumentEvent) => {\n return ref.current(documentEvent)\n }, [])\n\n const instance = useSanityInstance()\n useEffect(() => {\n return subscribeDocumentEvents(instance, {\n eventHandler: stableHandler,\n resource: datasetHandle.resource,\n })\n }, [instance, datasetHandle.resource, stableHandler])\n}\n","import {type DocumentAction, type DocumentPermissionsResult, getPermissionsState} from '@sanity/sdk'\nimport {isDeepEqual} from '@sanity/sdk/_internal'\nimport {useCallback, useContext, useMemo, useSyncExternalStore} from 'react'\nimport {filter, firstValueFrom} from 'rxjs'\n\nimport {ResourcesContext} from '../../context/ResourcesContext'\nimport {useSanityInstance} from '../context/useSanityInstance'\nimport {\n normalizeResourceOptions,\n useEffectiveContextResource,\n type WithResourceNameSupport,\n} from '../helpers/useNormalizedResourceOptions'\nimport {trackHookUsage} from '../helpers/useTrackHookUsage'\n\nconst noopSubscribe = () => () => {}\nconst returnUndefined = () => undefined\n\n/**\n *\n * @public\n *\n * Check if the current user has the specified permissions for the given document actions.\n *\n * @category Permissions\n * @param actionOrActions - One or more document action functions (e.g., `publishDocument(handle)`).\n * @returns An object that specifies whether the action is allowed; if the action is not allowed, an explanatory message and list of reasons is also provided.\n *\n * @remarks\n * When passing multiple actions, all actions must belong to the same project and dataset.\n * Note, however, that you can check permissions on multiple documents from the same project and dataset (as in the second example below).\n *\n * @example Checking for permission to publish a document\n * ```tsx\n * import {\n * useDocumentPermissions,\n * useApplyDocumentActions,\n * publishDocument,\n * createDocumentHandle,\n * type DocumentHandle\n * } from '@sanity/sdk-react'\n *\n * // Define props using the DocumentHandle type\n * interface PublishButtonProps {\n * doc: DocumentHandle\n * }\n *\n * function PublishButton({doc}: PublishButtonProps) {\n * const publishAction = publishDocument(doc)\n *\n * // Pass the same action call to check permissions\n * const publishPermissions = useDocumentPermissions(publishAction)\n * const apply = useApplyDocumentActions()\n *\n * return (\n * <>\n * <button\n * disabled={!publishPermissions.allowed}\n * // Pass the same action call to apply the action\n * onClick={() => apply(publishAction)}\n * popoverTarget={`${publishPermissions.allowed ? undefined : 'publishButtonPopover'}`}\n * >\n * Publish\n * </button>\n * {!publishPermissions.allowed && (\n * <div popover id=\"publishButtonPopover\">\n * {publishPermissions.message}\n * </div>\n * )}\n * </>\n * )\n * }\n *\n * // Usage:\n * // const doc = createDocumentHandle({ documentId: 'doc1', documentType: 'myType' })\n * // <PublishButton doc={doc} />\n * ```\n *\n * @example Checking for permissions to edit multiple documents\n * ```tsx\n * import {\n * useDocumentPermissions,\n * editDocument,\n * type DocumentHandle\n * } from '@sanity/sdk-react'\n *\n * export default function canEditMultiple(docHandles: DocumentHandle[]) {\n * // Create an array containing an editDocument action for each of the document handles\n * const editActions = docHandles.map(doc => editDocument(doc))\n *\n * // Return the result of checking for edit permissions on all of the document handles\n * return useDocumentPermissions(editActions)\n * }\n * ```\n */\nexport function useDocumentPermissions(\n actionOrActions:\n | WithResourceNameSupport<DocumentAction>\n | WithResourceNameSupport<DocumentAction>[],\n): DocumentPermissionsResult {\n const instance = useSanityInstance()\n trackHookUsage(instance, 'useDocumentPermissions')\n const effectiveContextResource = useEffectiveContextResource()\n const resources = useContext(ResourcesContext)\n\n const {\n actions: normalizedActions,\n resource: actionResource,\n error: validationError,\n } = useMemo(() => {\n const normalized = Array.isArray(actionOrActions)\n ? actionOrActions.map((action) =>\n normalizeResourceOptions(action, resources, effectiveContextResource),\n )\n : [normalizeResourceOptions(actionOrActions, resources, effectiveContextResource)]\n\n let resource\n for (const action of normalized) {\n if (action.resource) {\n if (!resource) resource = action.resource\n if (!isDeepEqual(action.resource, resource)) {\n return {\n actions: normalized,\n resource,\n error: new Error(\n `Mismatched resources found in actions. All actions must belong to the same resource. Found \"${JSON.stringify(action.resource)}\" but expected \"${JSON.stringify(resource)}\".`,\n ),\n }\n }\n }\n }\n return {actions: normalized, resource, error: undefined}\n }, [actionOrActions, resources, effectiveContextResource])\n\n const effectiveResource = actionResource ?? effectiveContextResource\n\n // Keep hooks unconditional — validation errors and missing-resource errors are\n // thrown after all hooks so that the hook call count stays stable across renders.\n const permissionsOptions = useMemo(\n () =>\n effectiveResource\n ? {\n resource: effectiveResource,\n // `Omit<>` on `DocumentAction` loses the discriminant; runtime values are still actions.\n actions: normalizedActions as DocumentAction[],\n }\n : undefined,\n [effectiveResource, normalizedActions],\n )\n\n const stateSource = useMemo(\n () => (permissionsOptions ? getPermissionsState(instance, permissionsOptions) : undefined),\n [permissionsOptions, instance],\n )\n\n const isDocumentReady = useCallback(\n () => stateSource !== undefined && stateSource.getCurrent() !== undefined,\n [stateSource],\n )\n\n const result = useSyncExternalStore(\n stateSource?.subscribe ?? noopSubscribe,\n stateSource?.getCurrent ?? returnUndefined,\n )\n\n // All hooks have been called — safe to throw now.\n if (validationError) throw validationError\n if (!effectiveResource) {\n throw new Error(\n 'No resource found. Provide a resource via the action handle or wrap with a resource context.',\n )\n }\n if (!isDocumentReady()) {\n throw firstValueFrom(\n stateSource!.observable.pipe(filter((permissions) => permissions !== undefined)),\n )\n }\n\n return result as DocumentPermissionsResult\n}\n","import {\n type DocumentHandle,\n type DocumentOptions,\n getDocumentSyncStatus,\n resolveDocument,\n type SanityInstance,\n type StateSource,\n} from '@sanity/sdk'\nimport {identity} from 'rxjs'\n\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\nimport {useNormalizedResourceOptions} from '../helpers/useNormalizedResourceOptions'\n\ntype UseDocumentSyncStatus = {\n /**\n * Exposes the document's sync status between local and remote document states.\n *\n * @category Documents\n * @param doc - The document handle to get sync status for. If you pass a `DocumentHandle` with specified `projectId` and `dataset`,\n * the document will be read from the specified Sanity project and dataset that is included in the handle. If no `projectId` or `dataset` is provided,\n * the document will use the nearest instance from context.\n * @returns `true` if local changes are synced with remote, `false` if changes are pending. Note: Suspense handles loading states.\n * @example Show sync status indicator\n * ```tsx\n * import {useDocumentSyncStatus, createDocumentHandle, type DocumentHandle} from '@sanity/sdk-react'\n *\n * // Define props including the DocumentHandle type\n * interface SyncIndicatorProps {\n * doc: DocumentHandle\n * }\n *\n * function SyncIndicator({doc}: SyncIndicatorProps) {\n * const isSynced = useDocumentSyncStatus(doc)\n *\n * return (\n * <div className={`sync-status ${isSynced ? 'synced' : 'pending'}`}>\n * {isSynced ? '✓ Synced' : 'Saving changes...'}\n * </div>\n * )\n * }\n *\n * // Usage:\n * // const doc = createDocumentHandle({ documentId: 'doc1', documentType: 'myType' })\n * // <SyncIndicator doc={doc} />\n * ```\n */\n (doc: DocumentHandle): boolean\n}\n\nconst useDocumentSyncStatusValue = createStateSourceHook({\n getState: getDocumentSyncStatus as (\n instance: SanityInstance,\n doc: DocumentHandle,\n ) => StateSource<boolean>,\n shouldSuspend: (instance, doc: DocumentHandle) =>\n getDocumentSyncStatus(instance, doc).getCurrent() === undefined,\n suspender: (instance, doc: DocumentHandle) => resolveDocument(instance, doc),\n getConfig: identity,\n})\n\n/**\n * @public\n * @function\n */\nexport const useDocumentSyncStatus: UseDocumentSyncStatus = (\n options: DocumentOptions<string | undefined>,\n) => {\n const normalizedOptions = useNormalizedResourceOptions(options)\n return useDocumentSyncStatusValue(normalizedOptions)\n}\n","import {\n type ActionsResult,\n type DocumentOptions,\n editDocument,\n getDocumentState,\n type JsonMatch,\n type ResolveDocument,\n resolveDocument,\n} from '@sanity/sdk'\nimport {useCallback} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\nimport {useNormalizedResourceOptions} from '../helpers/useNormalizedResourceOptions'\nimport {trackHookUsage} from '../helpers/useTrackHookUsage'\nimport {useApplyDocumentActions} from './useApplyDocumentActions'\n\nconst ignoredKeys = ['_id', '_type', '_createdAt', '_updatedAt', '_rev']\n\ntype Updater<TValue> = TValue | ((currentValue: TValue) => TValue)\n\n// Overload 1: No path, relies on Typegen\n/**\n * @public\n * Edit an entire document, relying on Typegen for the type.\n *\n * @param options - Document options including `documentId`, `documentType`, and optionally `projectId`/`dataset`.\n * @returns A stable function to update the document state. Accepts either the new document state or an updater function `(currentValue) => nextValue`.\n * Returns a promise resolving to the {@link ActionsResult}.\n */\nexport function useEditDocument<\n TDocumentType extends string = string,\n TDataset extends string = string,\n TProjectId extends string = string,\n>(\n options: DocumentOptions<undefined, TDocumentType, TDataset, TProjectId>,\n): (\n nextValue: Updater<ResolveDocument<TDocumentType, `${TProjectId}.${TDataset}`>>,\n) => Promise<ActionsResult<ResolveDocument<TDocumentType, `${TProjectId}.${TDataset}`>>>\n\n// Overload 2: Path provided, relies on Typegen\n/**\n * @public\n * Edit a specific path within a document, relying on Typegen for the type.\n *\n * @param options - Document options including `documentId`, `documentType`, `path`, and optionally `projectId`/`dataset`.\n * @returns A stable function to update the value at the specified path. Accepts either the new value or an updater function `(currentValue) => nextValue`.\n * Returns a promise resolving to the {@link ActionsResult}.\n */\nexport function useEditDocument<\n TPath extends string = string,\n TDocumentType extends string = string,\n TDataset extends string = string,\n TProjectId extends string = string,\n>(\n options: DocumentOptions<TPath, TDocumentType, TDataset, TProjectId>,\n): (\n nextValue: Updater<JsonMatch<ResolveDocument<TDocumentType, `${TProjectId}.${TDataset}`>, TPath>>,\n) => Promise<ActionsResult<ResolveDocument<TDocumentType, `${TProjectId}.${TDataset}`>>>\n\n// Overload 3: Explicit type, no path\n/**\n * @public\n * Edit an entire document with an explicit type `TData`.\n *\n * @param options - Document options including `documentId` and optionally `projectId`/`dataset`.\n * @returns A stable function to update the document state. Accepts either the new document state (`TData`) or an updater function `(currentValue: TData) => nextValue: TData`.\n * Returns a promise resolving to the {@link ActionsResult}.\n */\nexport function useEditDocument<TData>(\n options: DocumentOptions<undefined>,\n): (nextValue: Updater<TData>) => Promise<ActionsResult>\n\n// Overload 4: Explicit type, path provided\n/**\n * @public\n * Edit a specific path within a document with an explicit type `TData`.\n *\n * @param options - Document options including `documentId`, `path`, and optionally `projectId`/`dataset`.\n * @returns A stable function to update the value at the specified path. Accepts either the new value (`TData`) or an updater function `(currentValue: TData) => nextValue: TData`.\n * Returns a promise resolving to the {@link ActionsResult}.\n */\nexport function useEditDocument<TData>(\n options: DocumentOptions<string>,\n): (nextValue: Updater<TData>) => Promise<ActionsResult>\n\n/**\n * @public\n * Provides a stable function to apply edits to a document or a specific path within it.\n *\n * @category Documents\n * @remarks\n * This hook simplifies editing documents by automatically:\n * - Comparing the current and next states to determine the minimal set of `set` and `unset` operations required for the update via `editDocument`.\n * - Handling both full document updates and specific path updates.\n * - Supporting functional updates (e.g., `edit(prev => ({...prev, title: 'New'}))`).\n * - Integrating with the active {@link SanityInstance} context.\n * - Utilizing `useApplyDocumentActions` internally for optimistic updates and transaction handling.\n *\n * It offers several overloads for flexibility:\n * 1. **Typegen (Full Document):** Edit the entire document, inferring types from your schema.\n * 2. **Typegen (Specific Path):** Edit a specific field, inferring types.\n * 3. **Explicit Type (Full Document):** Edit the entire document with a manually specified type.\n * 4. **Explicit Type (Specific Path):** Edit a specific field with a manually specified type.\n *\n * **LiveEdit Documents:**\n * For documents using {@link DocumentHandle.liveEdit | liveEdit mode} (set via `liveEdit: true` in the document handle), edits are applied directly to the published document without creating a draft.\n *\n * This hook relies on the document state being loaded. If the document is not yet available\n * (e.g., during initial load), the component using this hook will suspend.\n *\n * @example Basic Usage (Typegen, Full Document)\n * ```tsx\n * import {useCallback} from 'react';\n * import {useEditDocument, useDocument, type DocumentHandle} from '@sanity/sdk-react'\n *\n * // Assume 'product' schema has a 'title' field (string)\n * interface ProductEditorProps {\n * productHandle: DocumentHandle<'product'> // Typegen infers 'product' type\n * }\n *\n * function ProductEditor({ productHandle }: ProductEditorProps) {\n * // Fetch the document to display its current state (optional)\n * const {data: product} = useDocument(productHandle);\n * // Get the edit function for the full document\n * const editProduct = useEditDocument(productHandle);\n *\n * // Use useCallback for stable event handlers\n * const handleTitleChange = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {\n * const newTitle = event.target.value;\n * // Use the functional updater for safe partial updates\n * editProduct(prev => ({\n * ...prev,\n * title: newTitle,\n * })).\n * }, [editProduct]);\n *\n * return (\n * <div>\n * <label>\n * Product Title:\n * <input\n * type=\"text\"\n * value={product?.title ?? ''}\n * onChange={handleTitleChange}\n * />\n * </label>\n * </div>\n * );\n * }\n * ```\n *\n * @example Editing a Specific Path (Typegen)\n * ```tsx\n * import React, { useCallback } from 'react';\n * import {useEditDocument, useDocument, type DocumentHandle, type DocumentOptions} from '@sanity/sdk-react'\n *\n * // Assume 'product' schema has a 'price' field (number)\n * interface ProductPriceEditorProps {\n * productHandle: DocumentHandle<'product'>;\n * }\n *\n * function ProductPriceEditor({ productHandle }: ProductPriceEditorProps) {\n * // Construct DocumentOptions internally, combining the handle and a hardcoded path\n * const priceOptions {\n * ...productHandle,\n * path: 'price', // Hardcode the path to edit\n * };\n *\n * // Fetch the current price to display it\n * const {data: currentPrice} = useDocument(priceOptions);\n * // Get the edit function for the specific path 'price'\n * const editPrice = useEditDocument(priceOptions);\n *\n * const handleSetFixedPrice = useCallback(() => {\n * // Update the price directly to a hardcoded value\n * editPrice(99.99)\n * }, [editPrice]);\n *\n * return (\n * <div>\n * <p>Current Price: {currentPrice}</p>\n * <button onClick={handleSetFixedPrice}>\n * Set Price to $99.99\n * </button>\n * </div>\n * );\n * }\n *\n * ```\n *\n * @example Usage with Explicit Types (Full Document)\n * ```tsx\n * import React, { useCallback } from 'react';\n * import {useEditDocument, useDocument, type DocumentHandle, type SanityDocument} from '@sanity/sdk-react'\n *\n * interface Book extends SanityDocument { _type: 'book', title: string, author: string }\n *\n * interface BookEditorProps {\n * bookHandle: DocumentHandle // No documentType needed if providing TData\n * }\n *\n * function BookEditor({ bookHandle }: BookEditorProps) {\n * const {data: book} = useDocument<Book>(bookHandle);\n * // Provide the explicit type <Book>\n * const editBook = useEditDocument<Book>(bookHandle);\n *\n * const handleAuthorChange = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {\n * const newAuthor = event.target.value;\n * editBook(prev => ({\n * ...prev,\n * author: newAuthor\n * }))\n * }, [editBook]);\n *\n * return (\n * <div>\n * <label>\n * Book Author:\n * <input\n * type=\"text\"\n * value={book?.author ?? ''}\n * onChange={handleAuthorChange}\n * />\n * </label>\n * </div>\n * );\n * }\n *\n * ```\n *\n * @example Usage with Explicit Types (Specific Path)\n * ```tsx\n * import React, { useCallback } from 'react';\n * import {useEditDocument, useDocument, type DocumentHandle, type DocumentOptions} from '@sanity/sdk-react'\n *\n * // Assume 'book' has 'author.name' (string)\n * interface AuthorNameEditorProps {\n * bookHandle: DocumentHandle; // No documentType needed if providing TData for path\n * }\n *\n * function AuthorNameEditor({ bookHandle }: AuthorNameEditorProps) {*\n * // Fetch current value\n * const {data: currentName} = useDocument<string>({...bookHandle, path: 'author.name'});\n * // Provide the explicit type <string> for the path's value\n * const editAuthorName = useEditDocument<string>({...bookHandle, path: 'author.name'});\n *\n * const handleUpdate = useCallback(() => {\n * // Update with a hardcoded string directly\n * editAuthorName('Jane Doe')\n * }, [editAuthorName]);\n *\n * return (\n * <div>\n * <p>Current Author Name: {currentName}</p>\n * <button onClick={handleUpdate} disabled={currentName === undefined}>\n * Set Author Name to Jane Doe\n * </button>\n * </div>\n * );\n * }\n *\n * ```\n *\n * @example Edit a document in a release\n * ```tsx\n * import {useEditDocument} from '@sanity/sdk-react'\n *\n * function EditArticleInRelease({documentId}: {documentId: string}) {\n * // Use the document's plain ID — not `versions.<releaseName>.<id>`.\n * // The document must already exist in the release (added via `createDocument` first).\n * const editArticle = useEditDocument({\n * documentId,\n * documentType: 'article',\n * perspective: {releaseName: 'summer-drop'},\n * })\n *\n * return (\n * <button onClick={() => editArticle(prev => ({...prev, title: 'Updated for release'}))}>\n * Edit in Release\n * </button>\n * )\n * }\n * ```\n */\nexport function useEditDocument({\n path,\n ...doc\n}: DocumentOptions<string | undefined>): (updater: Updater<unknown>) => Promise<ActionsResult> {\n const instance = useSanityInstance()\n trackHookUsage(instance, 'useEditDocument')\n const normalizedDoc = useNormalizedResourceOptions(doc)\n\n const apply = useApplyDocumentActions()\n const isDocumentReady = useCallback(\n () => getDocumentState(instance, normalizedDoc).getCurrent() !== undefined,\n [instance, normalizedDoc],\n )\n if (!isDocumentReady()) throw resolveDocument(instance, normalizedDoc)\n\n return (updater: Updater<unknown>) => {\n const currentPath = path\n\n if (currentPath) {\n const stateWithOptions = getDocumentState(instance, {...normalizedDoc, path})\n const currentValue = stateWithOptions.getCurrent()\n\n const nextValue =\n typeof updater === 'function'\n ? (updater as (prev: typeof currentValue) => typeof currentValue)(currentValue)\n : updater\n\n return apply(editDocument(normalizedDoc, {set: {[currentPath]: nextValue}}))\n }\n\n const fullDocState = getDocumentState(instance, {...normalizedDoc, path})\n const current = fullDocState.getCurrent() as object | null | undefined\n const nextValue =\n typeof updater === 'function'\n ? (updater as (prev: typeof current) => typeof current)(current)\n : updater\n\n if (typeof nextValue !== 'object' || !nextValue) {\n throw new Error(\n `No path was provided to \\`useEditDocument\\` and the value provided was not a document object.`,\n )\n }\n\n const allKeys = Object.keys({...current, ...nextValue})\n const editActions = allKeys\n .filter((key) => !ignoredKeys.includes(key))\n .filter(\n (key) =>\n current?.[key as keyof typeof current] !== (nextValue as Record<string, unknown>)[key],\n )\n .map((key) =>\n key in nextValue\n ? editDocument(normalizedDoc, {set: {[key]: (nextValue as Record<string, unknown>)[key]}})\n : editDocument(normalizedDoc, {unset: [key]}),\n )\n\n return apply(editActions)\n }\n}\n","import {getQueryState, type QueryOptions, resolveQuery, type ResolveQueryResult} from '@sanity/sdk'\nimport {getQueryKey, parseQueryKey} from '@sanity/sdk/_internal'\nimport {useEffect, useMemo, useRef, useState, useSyncExternalStore, useTransition} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\nimport {\n useNormalizedResourceOptions,\n type WithResourceNameSupport,\n} from '../helpers/useNormalizedResourceOptions'\nimport {trackHookUsage} from '../helpers/useTrackHookUsage'\n/**\n * Hook options for useQuery, supporting both direct resource and resourceName.\n * @beta\n */\ntype UseQueryOptions<\n TQuery extends string = string,\n TDataset extends string = string,\n TProjectId extends string = string,\n> = WithResourceNameSupport<QueryOptions<TQuery, TDataset, TProjectId>>\n\n// Overload 1: Inferred Type (using Typegen)\n/**\n * @public\n * Executes a GROQ query, inferring the result type from the query string and options.\n * Leverages Sanity Typegen if configured for enhanced type safety.\n *\n * @param options - Configuration for the query, including `query`, optional `params`, `projectId`, `dataset`, etc.\n * @returns An object containing `data` (typed based on the query) and `isPending` (for transitions).\n *\n * @example Basic usage (Inferred Type)\n * ```tsx\n * import {useQuery} from '@sanity/sdk-react'\n * import {defineQuery} from 'groq'\n *\n * const myQuery = defineQuery(`*[_type == \"movie\"]{_id, title}`)\n *\n * function MovieList() {\n * // Typegen infers the return type for data\n * const {data} = useQuery({ query: myQuery })\n *\n * return (\n * <div>\n * <h2>Movies</h2>\n * <ul>\n * {data.map(movie => <li key={movie._id}>{movie.title}</li>)}\n * </ul>\n * </div>\n * )\n * }\n * // Suspense boundary should wrap <MovieList /> for initial load\n * ```\n *\n * @example Using parameters (Inferred Type)\n * ```tsx\n * import {useQuery} from '@sanity/sdk-react'\n * import {defineQuery} from 'groq'\n *\n * const myQuery = defineQuery(`*[_type == \"movie\" && _id == $id][0]`)\n *\n * function MovieDetails({movieId}: {movieId: string}) {\n * // Typegen infers the return type based on query and params\n * const {data, isPending} = useQuery({\n * query: myQuery,\n * params: { id: movieId }\n * })\n *\n * return (\n * // utilize `isPending` to signal to users that new data is coming in\n * // (e.g. the `movieId` changed and we're loading in the new one)\n * <div style={{ opacity: isPending ? 0.5 : 1 }}>\n * {data ? <h1>{data.title}</h1> : <p>Movie not found</p>}\n * </div>\n * )\n * }\n * ```\n */\nexport function useQuery<\n TQuery extends string = string,\n TDataset extends string = string,\n TProjectId extends string = string,\n>(\n options: UseQueryOptions<TQuery, TDataset, TProjectId>,\n): {\n /** The query result, typed based on the GROQ query string */\n data: ResolveQueryResult<TQuery, `${TProjectId}.${TDataset}`>\n /** True if a query transition is in progress */\n isPending: boolean\n}\n\n// Overload 2: Explicit Type Provided\n/**\n * @public\n * Executes a GROQ query with an explicitly provided result type `TData`.\n *\n * @param options - Configuration for the query, including `query`, optional `params`, `projectId`, `dataset`, etc.\n * @returns An object containing `data` (cast to `TData`) and `isPending` (indicates whether a query resolution is pending; note that Suspense handles initial loading states). *\n * @example Manually typed query result\n * ```tsx\n * import {useQuery} from '@sanity/sdk-react'\n *\n * interface CustomMovieTitle {\n * movieTitle?: string\n * }\n *\n * function FirstMovieTitle() {\n * // Provide the explicit type TData\n * const {data, isPending} = useQuery<CustomMovieTitle>({\n * query: '*[_type == \"movie\"][0]{ \"movieTitle\": title }'\n * })\n *\n * return (\n * <h1 style={{ opacity: isPending ? 0.5 : 1 }}>\n * {data?.movieTitle ?? 'No title found'}\n * </h1>\n * )\n * }\n * ```\n */\nexport function useQuery<TData>(options: WithResourceNameSupport<QueryOptions>): {\n /** The query result, cast to the provided type TData */\n data: TData\n /** True if another query is resolving in the background (suspense handles the initial loading state) */\n isPending: boolean\n}\n\n/**\n * @public\n * Fetches data and subscribes to real-time updates using a GROQ query.\n *\n * @remarks\n * This hook provides a convenient way to fetch data from your Sanity dataset and\n * automatically receive updates in real-time when the queried data changes.\n *\n * Features:\n * - Executes any valid GROQ query.\n * - Subscribes to changes, providing real-time updates.\n * - Integrates with React Suspense for handling initial loading states.\n * - Uses React Transitions for managing loading states during query/parameter changes (indicated by `isPending`).\n * - Supports type inference based on the GROQ query when using Sanity Typegen.\n * - Allows specifying an explicit return type `TData` for the query result.\n *\n * @category GROQ\n */\nexport function useQuery(options: WithResourceNameSupport<QueryOptions>): {\n data: unknown\n isPending: boolean\n} {\n // Implementation returns unknown, overloads define specifics\n const instance = useSanityInstance()\n trackHookUsage(instance, 'useQuery')\n\n // Normalize options: resolve resourceName to resource and strip resourceName\n const normalized = useNormalizedResourceOptions(options)\n\n // Use React's useTransition to avoid UI jank when queries change\n const [isPending, startTransition] = useTransition()\n\n // Get the unique key for this query and its options (using normalized options)\n const queryKey = getQueryKey(instance, normalized)\n // Use a deferred state to avoid immediate re-renders when the query changes\n const [deferredQueryKey, setDeferredQueryKey] = useState(queryKey)\n\n // Create an AbortController to cancel in-flight requests when needed\n const ref = useRef<AbortController>(new AbortController())\n\n // When the query or options change, start a transition to update the query\n useEffect(() => {\n if (queryKey === deferredQueryKey) return\n\n startTransition(() => {\n // Abort any in-flight requests for the previous query\n if (ref && !ref.current.signal.aborted) {\n ref.current.abort()\n ref.current = new AbortController()\n }\n\n setDeferredQueryKey(queryKey)\n })\n }, [deferredQueryKey, queryKey])\n\n // Get the state source for this query from the query store\n // Memoize the options object by depending on the stable string key instead of the parsed object\n const {getCurrent, subscribe} = useMemo(() => {\n const deferred = parseQueryKey(deferredQueryKey)\n return getQueryState(instance, deferred)\n }, [instance, deferredQueryKey])\n\n // If data isn't available yet, suspend rendering\n if (getCurrent() === undefined) {\n // Normally, reading from a mutable ref during render can be risky in concurrent mode.\n // However, it is safe here because:\n // 1. React guarantees that while the component is suspended (via throwing a promise),\n // no effects or state updates occur during that render pass.\n // 2. We immediately capture the current abort signal in a local variable (currentSignal).\n // 3. Even if a background render updates ref.current (for example, due to a query change),\n // the captured signal remains unchanged for this suspended render.\n // Thus, the promise thrown here uses a stable abort signal, ensuring correct behavior.\n const currentSignal = ref.current.signal\n const deferred = parseQueryKey(deferredQueryKey)\n\n // eslint-disable-next-line react-hooks/refs -- intentional during suspended render; see comment above.\n throw resolveQuery(instance, {...deferred, signal: currentSignal})\n }\n\n // Subscribe to updates and get the current data\n // useSyncExternalStore ensures the component re-renders when the data changes\n const data = useSyncExternalStore(subscribe, getCurrent) as ResolveQueryResult\n return useMemo(() => ({data, isPending}), [data, isPending])\n}\n","import {type DocumentHandle, isDatasetResource, type QueryOptions} from '@sanity/sdk'\nimport {createGroqSearchFilter, pickProperties} from '@sanity/sdk/_internal'\nimport {type SortOrderingItem} from '@sanity/types'\nimport {useCallback, useMemo, useState} from 'react'\n\nimport {type ResourceHandle} from '../../config/handles'\nimport {useNormalizedResourceOptions} from '../helpers/useNormalizedResourceOptions'\nimport {useTrackHookUsage} from '../helpers/useTrackHookUsage'\nimport {useQuery} from '../query/useQuery'\n\nconst DEFAULT_BATCH_SIZE = 25\n\n/**\n * Configuration options for the useDocuments hook\n *\n * @public\n * @category Types\n */\nexport interface DocumentsOptions<\n TDocumentType extends string = string,\n TDataset extends string = string,\n TProjectId extends string = string,\n>\n extends ResourceHandle<TDataset, TProjectId>, Pick<QueryOptions, 'perspective' | 'params'> {\n /**\n * Filter documents by their `_type`. Can be a single type or an array of types.\n */\n documentType?: TDocumentType | TDocumentType[]\n /**\n * GROQ filter expression to apply to the query\n */\n filter?: string\n /**\n * Number of items to load per batch (defaults to 25)\n */\n batchSize?: number\n /**\n * Sorting configuration for the results\n * @beta\n */\n orderings?: SortOrderingItem[]\n /**\n * Text search query to filter results\n */\n search?: string\n}\n\n/**\n * Return value from the useDocuments hook\n *\n * @public\n * @category Types\n */\nexport interface DocumentsResponse<\n TDocumentType extends string = string,\n TDataset extends string = string,\n TProjectId extends string = string,\n> {\n /**\n * Array of document handles for the current batch\n */\n data: DocumentHandle<TDocumentType, TDataset, TProjectId>[]\n /**\n * Whether there are more items available to load\n */\n hasMore: boolean\n /**\n * Total count of items matching the query\n */\n count: number\n /**\n * Whether a query is currently in progress\n */\n isPending: boolean\n /**\n * Function to load the next batch of results\n */\n loadMore: () => void\n}\n\n/**\n * Retrieves batches of {@link DocumentHandle}s, narrowed by optional filters, text searches, and custom ordering,\n * with infinite scrolling support. The number of document handles returned per batch is customizable,\n * and additional batches can be loaded using the supplied `loadMore` function.\n *\n * @public\n * @category Documents\n * @param options - Configuration options for the infinite list\n * @returns An object containing the list of document handles, the loading state, the total count of retrieved document handles, and a function to load more\n *\n * @remarks\n * - The returned document handles include projectId and dataset information from the current Sanity instance\n * - This makes them ready to use with document operations and other document hooks\n * - The hook automatically uses the correct Sanity instance based on the projectId and dataset in the options\n *\n * @example Basic infinite list with loading more\n * ```tsx\n * import {\n * useDocuments,\n * createDatasetHandle,\n * type DatasetHandle,\n * type DocumentHandle,\n * type SortOrderingItem\n * } from '@sanity/sdk-react'\n * import {Suspense} from 'react'\n *\n * // Define a component to display a single document (using useDocumentProjection for efficiency)\n * function MyDocumentComponent({doc}: {doc: DocumentHandle}) {\n * const {data} = useDocumentProjection<{title?: string}>({\n * ...doc, // Pass the full handle\n * projection: '{title}'\n * })\n *\n * return <>{data?.title || 'Untitled'}</>\n * }\n *\n * // Define props for the list component\n * interface DocumentListProps {\n * dataset: DatasetHandle\n * documentType: string\n * search?: string\n * }\n *\n * function DocumentList({dataset, documentType, search}: DocumentListProps) {\n * const { data, hasMore, isPending, loadMore, count } = useDocuments({\n * ...dataset,\n * documentType,\n * search,\n * batchSize: 10,\n * orderings: [{field: '_createdAt', direction: 'desc'}],\n * })\n *\n * return (\n * <div>\n * <p>Total documents: {count}</p>\n * <ol>\n * {data.map((docHandle) => (\n * <li key={docHandle.documentId}>\n * <Suspense fallback=\"Loading…\">\n * <MyDocumentComponent docHandle={docHandle} />\n * </Suspense>\n * </li>\n * ))}\n * </ol>\n * {hasMore && (\n * <button onClick={loadMore}>\n * {isPending ? 'Loading...' : 'Load More'}\n * </button>\n * )}\n * </div>\n * )\n * }\n *\n * // Usage:\n * // const myDatasetHandle = createDatasetHandle({ projectId: 'p1', dataset: 'production' })\n * // <DocumentList dataset={myDatasetHandle} documentType=\"post\" search=\"Sanity\" />\n * ```\n *\n * @example Using `filter` and `params` options for narrowing a collection\n * ```tsx\n * import {useState} from 'react'\n * import {useDocuments} from '@sanity/sdk-react'\n *\n * export default function FilteredAuthors() {\n * const [max, setMax] = useState(2)\n * const {data} = useDocuments({\n * documentType: 'author',\n * filter: 'length(books) <= $max',\n * params: {max},\n * })\n *\n * return (\n * <>\n * <input\n * id=\"maxBooks\"\n * type=\"number\"\n * value={max}\n * onChange={e => setMax(e.currentTarget.value)}\n * />\n * {data.map(author => (\n * <Suspense key={author.documentId}>\n * <MyAuthorComponent documentHandle={author} />\n * </Suspense>\n * ))}\n * </>\n * )\n * }\n * ```\n */\nexport function useDocuments<\n TDocumentType extends string = string,\n TDataset extends string = string,\n TProjectId extends string = string,\n>({\n batchSize = DEFAULT_BATCH_SIZE,\n params,\n search,\n filter,\n orderings,\n documentType,\n ...rawOptions\n}: DocumentsOptions<TDocumentType, TDataset, TProjectId>): DocumentsResponse<\n TDocumentType,\n TDataset,\n TProjectId\n> {\n useTrackHookUsage('useDocuments')\n const options = useNormalizedResourceOptions(rawOptions)\n const [limit, setLimit] = useState(batchSize)\n const documentTypes = useMemo(\n () =>\n (Array.isArray(documentType) ? documentType : [documentType]).filter(\n (i): i is TDocumentType => typeof i === 'string',\n ),\n [documentType],\n )\n\n // Reset the limit to the current batchSize whenever any query parameters\n // (filter, search, params, orderings) or batchSize changes\n const key = JSON.stringify({\n filter,\n search,\n params,\n orderings,\n batchSize,\n types: documentTypes,\n ...options,\n })\n const [prevKey, setPrevKey] = useState(key)\n if (prevKey !== key) {\n setPrevKey(key)\n setLimit(batchSize)\n }\n\n const filterClause = useMemo(() => {\n const conditions: string[] = []\n const trimmedSearch = search?.trim()\n\n // Add search query filter if specified\n if (trimmedSearch) {\n const searchFilter = createGroqSearchFilter(trimmedSearch)\n if (searchFilter) {\n conditions.push(searchFilter)\n }\n }\n\n // Add type filter if specified\n if (documentTypes?.length) {\n conditions.push(`(_type in $__types)`)\n }\n\n // Add additional filter if specified\n if (filter) {\n conditions.push(`(${filter})`)\n }\n\n return conditions.length ? `[${conditions.join(' && ')}]` : ''\n }, [filter, search, documentTypes])\n\n const orderClause = orderings\n ? `| order(${orderings\n .map((ordering) =>\n [ordering.field, ordering.direction.toLowerCase()]\n .map((str) => str.trim())\n .filter(Boolean)\n .join(' '),\n )\n .join(',')})`\n : ''\n\n const dataQuery = `*${filterClause}${orderClause}[0...${limit}]{\"documentId\":_id,\"documentType\":_type,...$__handle}`\n const countQuery = `count(*${filterClause})`\n\n const {\n data: {count, data},\n isPending,\n } = useQuery<{count: number; data: DocumentHandle<TDocumentType, TDataset, TProjectId>[]}>({\n ...options,\n query: `{\"count\":${countQuery},\"data\":${dataQuery}}`,\n params: {\n ...params,\n // these are passed back to the user as part of each document handle\n __handle: {\n // keep projectId/dataset for backward compat until v4; resource is added\n // intentionally so that hook consumers can resolve the correct resource\n ...(options.resource && isDatasetResource(options.resource)\n ? pickProperties(options.resource, ['projectId', 'dataset'])\n : {}),\n ...pickProperties(options, ['perspective', 'resource']),\n },\n __types: documentTypes,\n },\n })\n\n // Now use the correctly typed variables\n const hasMore = data.length < count\n\n const loadMore = useCallback(() => {\n setLimit((prev) => Math.min(prev + batchSize, count))\n }, [count, batchSize])\n\n return useMemo(\n () => ({data, hasMore, count, isPending, loadMore}),\n [count, data, hasMore, isPending, loadMore],\n )\n}\n","import {type Installation, installation, type InstallationInclude} from '@sanity/sdk'\n\nimport {createFetcherHook, type FetcherHookResult} from '../helpers/createFetcherHook'\n\n/**\n * Returns a single installation by id.\n *\n * The hook suspends until the first fetch succeeds, so `data` is always present.\n * The `include` tokens you pass shape `data`: each requested token adds its\n * field, and omitted ones are absent from the type.\n *\n * @public\n * @param installationId - The installation id.\n * @param options - Optional `include` list to expand related resources.\n * @returns The result envelope `{data, isFetching, error, refetch}`.\n */\nexport const useInstallation = createFetcherHook(installation) as <\n Include extends InstallationInclude = never,\n>(\n installationId: string,\n options?: {include?: Include[]},\n) => FetcherHookResult<Installation<Include>>\n","import {\n type InstallationInclude,\n installations,\n type InstallationsOptions,\n type InstallationsResponse,\n} from '@sanity/sdk'\n\nimport {createFetcherHook, type FetcherHookResult} from '../helpers/createFetcherHook'\n\n/**\n * Returns the installations matching the given options.\n *\n * The hook suspends until the first fetch succeeds, so `data` is always present.\n * The `include` tokens you pass shape `data.data`: each requested token adds its\n * field, and omitted ones are absent from the type.\n *\n * @public\n * @param options - Filter and include options for the installations list.\n * @returns The result envelope `{data, isFetching, error, refetch}`.\n */\nexport const useInstallations = createFetcherHook(installations) as <\n Include extends InstallationInclude = never,\n>(\n options: InstallationsOptions<Include>,\n) => FetcherHookResult<InstallationsResponse<Include>>\n","import {type Organization, organization, type OrganizationOptions} from '@sanity/sdk'\n\nimport {createFetcherHook, type FetcherHookResult} from '../helpers/createFetcherHook'\n\n/**\n * Returns metadata for a given organisation.\n *\n * @category Organizations\n * @param options - Configuration options\n * @returns A {@link FetcherHookResult} whose `data` is the metadata for the\n * organisation. `members` is included only when `includeMembers: true`;\n * `features` is included only when `includeFeatures: true`.\n * @example\n * ```tsx\n * function OrganizationName({organizationId}: {organizationId: string}) {\n * const {data: organization} = useOrganization({organizationId})\n *\n * return <h1>{organization.name}</h1>\n * }\n * ```\n * @example\n * ```tsx\n * const {data: organizationWithMembers} = useOrganization({organizationId, includeMembers: true})\n * const {data: organizationWithFeatures} = useOrganization({organizationId, includeFeatures: true})\n * ```\n * @public\n * @function\n */\nexport const useOrganization = createFetcherHook(organization) as <\n IncludeMembers extends boolean = false,\n IncludeFeatures extends boolean = false,\n>(\n options: OrganizationOptions<IncludeMembers, IncludeFeatures>,\n) => FetcherHookResult<Organization<IncludeMembers, IncludeFeatures>>\n","import {type Organizations, organizations, type OrganizationsOptions} from '@sanity/sdk'\n\nimport {createFetcherHook, type FetcherHookResult} from '../helpers/createFetcherHook'\n\n/**\n * Returns metadata for each organisation the current user has access to.\n *\n * @category Organizations\n * @param options - Configuration options\n * @returns A {@link FetcherHookResult} whose `data` is an array of organisation\n * metadata. `members` is included only when `includeMembers: true`; `features`\n * is included only when `includeFeatures: true`.\n * @example\n * ```tsx\n * const {data: organizations} = useOrganizations()\n *\n * return (\n * <select>\n * {organizations.map((organization) => (\n * <option key={organization.id}>{organization.name}</option>\n * ))}\n * </select>\n * )\n * ```\n * @example\n * ```tsx\n * const {data: organizationsWithMembers} = useOrganizations({includeMembers: true})\n * const {data: organizationsWithFeatures} = useOrganizations({includeFeatures: true})\n * const {data: organizationsIncludingImplicit} = useOrganizations({includeImplicitMemberships: true})\n * ```\n * @public\n * @function\n */\nexport const useOrganizations = createFetcherHook(organizations) as <\n IncludeMembers extends boolean = false,\n IncludeFeatures extends boolean = false,\n>(\n options?: OrganizationsOptions<IncludeMembers, IncludeFeatures>,\n) => FetcherHookResult<Organizations<IncludeMembers, IncludeFeatures>>\n","import {type DocumentHandle, isDatasetResource, type QueryOptions} from '@sanity/sdk'\nimport {createGroqSearchFilter, pickProperties} from '@sanity/sdk/_internal'\nimport {type SortOrderingItem} from '@sanity/types'\nimport {useCallback, useMemo, useState} from 'react'\n\nimport {\n useNormalizedResourceOptions,\n type WithResourceNameSupport,\n} from '../helpers/useNormalizedResourceOptions'\nimport {useTrackHookUsage} from '../helpers/useTrackHookUsage'\nimport {useQuery} from '../query/useQuery'\n\n/**\n * Configuration options for the usePaginatedDocuments hook\n *\n * @public\n * @category Types\n */\nexport interface PaginatedDocumentsOptions<\n TDocumentType extends string = string,\n TDataset extends string = string,\n TProjectId extends string = string,\n> extends WithResourceNameSupport<\n Omit<QueryOptions<TDocumentType, TDataset, TProjectId>, 'query'>\n> {\n documentType?: TDocumentType | TDocumentType[]\n /**\n * GROQ filter expression to apply to the query\n */\n filter?: string\n /**\n * Number of items to display per page (defaults to 25)\n */\n pageSize?: number\n /**\n * Sorting configuration for the results\n * @beta\n */\n orderings?: SortOrderingItem[]\n /**\n * Text search query to filter results\n */\n search?: string\n}\n\n/**\n * Return value from the usePaginatedDocuments hook\n *\n * @public\n * @category Types\n */\nexport interface PaginatedDocumentsResponse<\n TDocumentType extends string = string,\n TDataset extends string = string,\n TProjectId extends string = string,\n> {\n /**\n * Array of document handles for the current page\n */\n data: DocumentHandle<TDocumentType, TDataset, TProjectId>[]\n /**\n * Whether a query is currently in progress\n */\n isPending: boolean\n\n /**\n * Number of items displayed per page\n */\n pageSize: number\n /**\n * Current page number (1-indexed)\n */\n currentPage: number\n /**\n * Total number of pages available\n */\n totalPages: number\n\n /**\n * Starting index of the current page (0-indexed)\n */\n startIndex: number\n /**\n * Ending index of the current page (exclusive, 0-indexed)\n */\n endIndex: number\n /**\n * Total count of items matching the query\n */\n count: number\n\n /**\n * Navigate to the first page\n */\n firstPage: () => void\n /**\n * Whether there is a first page available to navigate to\n */\n hasFirstPage: boolean\n\n /**\n * Navigate to the previous page\n */\n previousPage: () => void\n /**\n * Whether there is a previous page available to navigate to\n */\n hasPreviousPage: boolean\n\n /**\n * Navigate to the next page\n */\n nextPage: () => void\n /**\n * Whether there is a next page available to navigate to\n */\n hasNextPage: boolean\n\n /**\n * Navigate to the last page\n */\n lastPage: () => void\n /**\n * Whether there is a last page available to navigate to\n */\n hasLastPage: boolean\n\n /**\n * Navigate to a specific page number\n * @param pageNumber - The page number to navigate to (1-indexed)\n */\n goToPage: (pageNumber: number) => void\n}\n\n/**\n * Retrieves pages of {@link DocumentHandle}s, narrowed by optional filters, text searches, and custom ordering,\n * with support for traditional paginated interfaces. The number of document handles returned per page is customizable,\n * while page navigation is handled via the included navigation functions.\n *\n * @public\n * @category Documents\n * @param options - Configuration options for the paginated list\n * @returns An object containing the list of document handles, pagination details, and functions to navigate between pages\n *\n * @remarks\n * - The returned document handles include projectId and dataset information from the current Sanity instance\n * - This makes them ready to use with document operations and other document hooks\n * - The hook automatically uses the correct Sanity instance based on the projectId and dataset in the options\n *\n * @example Paginated list of documents with navigation\n * ```tsx\n * import {\n * usePaginatedDocuments,\n * createDatasetHandle,\n * type DatasetHandle,\n * type DocumentHandle,\n * type SortOrderingItem,\n * useDocumentProjection\n * } from '@sanity/sdk-react'\n * import {Suspense} from 'react'\n * import {ErrorBoundary} from 'react-error-boundary'\n *\n * // Define a component to display a single document row\n * function MyTableRowComponent({doc}: {doc: DocumentHandle}) {\n * const {data} = useDocumentProjection<{title?: string}>({\n * ...doc,\n * projection: '{title}',\n * })\n *\n * return (\n * <tr>\n * <td>{data?.title ?? 'Untitled'}</td>\n * </tr>\n * )\n * }\n *\n * // Define props for the list component\n * interface PaginatedDocumentListProps {\n * documentType: string\n * dataset?: DatasetHandle\n * }\n *\n * function PaginatedDocumentList({documentType, dataset}: PaginatedDocumentListProps) {\n * const {\n * data,\n * isPending,\n * currentPage,\n * totalPages,\n * nextPage,\n * previousPage,\n * hasNextPage,\n * hasPreviousPage\n * } = usePaginatedDocuments({\n * ...dataset,\n * documentType,\n * pageSize: 10,\n * orderings: [{field: '_createdAt', direction: 'desc'}],\n * })\n *\n * return (\n * <div>\n * <table>\n * <thead>\n * <tr><th>Title</th></tr>\n * </thead>\n * <tbody>\n * {data.map(doc => (\n * <ErrorBoundary key={doc.documentId} fallback={<tr><td>Error loading document</td></tr>}>\n * <Suspense fallback={<tr><td>Loading...</td></tr>}>\n * <MyTableRowComponent doc={doc} />\n * </Suspense>\n * </ErrorBoundary>\n * ))}\n * </tbody>\n * </table>\n * <div style={{opacity: isPending ? 0.5 : 1}}>\n * <button onClick={previousPage} disabled={!hasPreviousPage || isPending}>Previous</button>\n * <span>Page {currentPage} / {totalPages}</span>\n * <button onClick={nextPage} disabled={!hasNextPage || isPending}>Next</button>\n * </div>\n * </div>\n * )\n * }\n *\n * // Usage:\n * // const myDatasetHandle = createDatasetHandle({ projectId: 'p1', dataset: 'production' })\n * // <PaginatedDocumentList dataset={myDatasetHandle} documentType=\"post\" />\n * ```\n */\nexport function usePaginatedDocuments<\n TDocumentType extends string = string,\n TDataset extends string = string,\n TProjectId extends string = string,\n>({\n documentType,\n filter = '',\n pageSize = 25,\n params = {},\n orderings,\n search,\n ...rawOptions\n}: PaginatedDocumentsOptions<TDocumentType, TDataset, TProjectId>): PaginatedDocumentsResponse<\n TDocumentType,\n TDataset,\n TProjectId\n> {\n useTrackHookUsage('usePaginatedDocuments')\n const options = useNormalizedResourceOptions(rawOptions)\n const [pageIndex, setPageIndex] = useState(0)\n const key = JSON.stringify({filter, search, params, orderings, pageSize, ...options})\n // Reset pageIndex to 0 whenever any query parameter changes.\n const [prevKey, setPrevKey] = useState(key)\n if (prevKey !== key) {\n setPrevKey(key)\n setPageIndex(0)\n }\n\n const startIndex = pageIndex * pageSize\n const endIndex = (pageIndex + 1) * pageSize\n const documentTypes = (Array.isArray(documentType) ? documentType : [documentType]).filter(\n (i) => typeof i === 'string',\n )\n\n const filterClause = useMemo(() => {\n const conditions: string[] = []\n const trimmedSearch = search?.trim()\n\n // Add search query filter if specified\n if (trimmedSearch) {\n const searchFilter = createGroqSearchFilter(trimmedSearch)\n if (searchFilter) {\n conditions.push(searchFilter)\n }\n }\n\n if (documentTypes?.length) {\n conditions.push(`(_type in $__types)`)\n }\n\n // Add additional filter if specified\n if (filter) {\n conditions.push(`(${filter})`)\n }\n\n return conditions.length ? `[${conditions.join(' && ')}]` : ''\n }, [filter, search, documentTypes?.length])\n\n const orderClause = orderings\n ? `| order(${orderings\n .map((ordering) =>\n [ordering.field, ordering.direction.toLowerCase()]\n .map((str) => str.trim())\n .filter(Boolean)\n .join(' '),\n )\n .join(',')})`\n : ''\n\n const dataQuery = `*${filterClause}${orderClause}[${startIndex}...${endIndex}]{\"documentId\":_id,\"documentType\":_type,...$__handle}`\n const countQuery = `count(*${filterClause})`\n\n const {\n data: {data, count},\n isPending,\n } = useQuery<{data: DocumentHandle<TDocumentType, TDataset, TProjectId>[]; count: number}>({\n ...options,\n query: `{\"data\":${dataQuery},\"count\":${countQuery}}`,\n params: {\n ...params,\n __types: documentTypes,\n __handle: {\n // keep projectId/dataset for backward compat until v4; resource is added\n // intentionally so that hook consumers can resolve the correct resource\n ...(options.resource && isDatasetResource(options.resource)\n ? pickProperties(options.resource, ['projectId', 'dataset'])\n : {}),\n ...pickProperties(options, ['perspective', 'resource']),\n },\n },\n })\n\n const totalPages = Math.ceil(count / pageSize)\n const currentPage = pageIndex + 1\n\n // Navigation methods\n const firstPage = useCallback(() => setPageIndex(0), [])\n const previousPage = useCallback(() => setPageIndex((prev) => Math.max(prev - 1, 0)), [])\n const nextPage = useCallback(\n () => setPageIndex((prev) => Math.min(prev + 1, totalPages - 1)),\n [totalPages],\n )\n const lastPage = useCallback(() => setPageIndex(totalPages - 1), [totalPages])\n const goToPage = useCallback(\n (pageNumber: number) => {\n if (pageNumber < 1 || pageNumber > totalPages) return\n setPageIndex(pageNumber - 1)\n },\n [totalPages],\n )\n\n // Boolean flags for page availability\n const hasFirstPage = pageIndex > 0\n const hasPreviousPage = pageIndex > 0\n const hasNextPage = pageIndex < totalPages - 1\n const hasLastPage = pageIndex < totalPages - 1\n\n return {\n data,\n isPending,\n pageSize,\n currentPage,\n totalPages,\n startIndex,\n endIndex,\n count,\n firstPage,\n hasFirstPage,\n previousPage,\n hasPreviousPage,\n nextPage,\n hasNextPage,\n lastPage,\n hasLastPage,\n goToPage,\n }\n}\n","import {getPresence, isMediaLibraryResource, type UserPresence} from '@sanity/sdk'\nimport {useCallback, useMemo, useSyncExternalStore} from 'react'\n\nimport {type ResourceHandle} from '../../config/handles'\nimport {useSanityInstance} from '../context/useSanityInstance'\nimport {useNormalizedResourceOptions} from '../helpers/useNormalizedResourceOptions'\nimport {trackHookUsage} from '../helpers/useTrackHookUsage'\n\n/**\n * Every participant in the current project and dataset, or Canvas.\n *\n * Reading presence never announces anything. Call `useReportPresence` to make the\n * current user visible to others, including to the Studio, which shares the same\n * presence room.\n *\n * This returns everyone in the whole resource and leaves the filtering to you.\n * Prefer `usePresenceForDocument` when you care about one document: it scopes and\n * flattens the result for rendering. Note that participants are counted by session,\n * so one person in two tabs appears twice.\n *\n * Presence is scoped to a single project and dataset. It is not a list of everyone\n * signed in to your organization.\n *\n * @public\n */\nexport function usePresence(options: ResourceHandle = {}): {\n locations: UserPresence[]\n} {\n const normalizedOptions = useNormalizedResourceOptions(options)\n if (normalizedOptions.resource && isMediaLibraryResource(normalizedOptions.resource)) {\n throw new Error(\n 'usePresence() does not support media library resources. Presence tracking requires a canvas or dataset resource.',\n )\n }\n\n const sanityInstance = useSanityInstance()\n trackHookUsage(sanityInstance, 'usePresence')\n const source = useMemo(\n () => getPresence(sanityInstance, normalizedOptions),\n [sanityInstance, normalizedOptions],\n )\n const subscribe = useCallback((callback: () => void) => source.subscribe(callback), [source])\n const locations = useSyncExternalStore(\n subscribe,\n () => source.getCurrent(),\n () => source.getCurrent(),\n )\n\n return {locations: locations || []}\n}\n","import {type DocumentPresence, getDocumentPresence, isMediaLibraryResource} from '@sanity/sdk'\nimport {type Path} from '@sanity/types'\nimport {useCallback, useMemo, useSyncExternalStore} from 'react'\n\nimport {type DocumentHandle} from '../../config/handles'\nimport {useSanityInstance} from '../context/useSanityInstance'\nimport {useNormalizedResourceOptions} from '../helpers/useNormalizedResourceOptions'\nimport {trackHookUsage} from '../helpers/useTrackHookUsage'\n\n/** @beta */\nexport interface UsePresenceForDocumentOptions extends DocumentHandle {\n /**\n * Narrows to participants at or below this field path, which is what a field\n * indicator wants. Omit it for everyone in the document.\n */\n path?: Path\n\n /**\n * By default a draft, its published version, and any release versions count as\n * the same document, which is what document lists want. Set this to compare ids\n * exactly, so that a draft and a release version do not bleed into each other.\n */\n excludeVersions?: boolean\n}\n\n/**\n * Who else is in a document, flattened to one entry per participant per location\n * so it can be rendered straight against a field.\n *\n * Reading presence never announces anything. Use `useReportPresence` to make the\n * current user visible to others.\n *\n * Prefer this over `usePresence` when you care about one document: `usePresence`\n * returns every participant in the whole project and dataset, leaving the filtering\n * to you.\n *\n * Resolves the document through its perspective exactly as `useReportPresence` does,\n * so reads match writes. Participants are counted by session, so one person in two\n * tabs appears twice.\n *\n * @example Avatars on a document\n * ```tsx\n * const {presence} = usePresenceForDocument({documentId, documentType})\n * return presence.map((p) => <Avatar key={p.sessionId} user={p.user} />)\n * ```\n *\n * @example Avatars on a single field\n * ```tsx\n * const {presence} = usePresenceForDocument({\n * documentId,\n * documentType,\n * path: ['title'],\n * excludeVersions: true,\n * })\n * ```\n *\n * @beta\n */\nexport function usePresenceForDocument(options: UsePresenceForDocumentOptions): {\n presence: DocumentPresence[]\n} {\n const {path, excludeVersions, ...handle} = options\n\n const normalizedOptions = useNormalizedResourceOptions(handle)\n if (normalizedOptions.resource && isMediaLibraryResource(normalizedOptions.resource)) {\n throw new Error(\n 'usePresenceForDocument() does not support media library resources. Presence tracking requires a canvas or dataset resource.',\n )\n }\n\n const sanityInstance = useSanityInstance()\n trackHookUsage(sanityInstance, 'usePresenceForDocument')\n\n const {resource, perspective} = normalizedOptions\n const {documentId, liveEdit} = options\n\n // Serialized so a caller passing a fresh `path` array each render does not\n // rebuild the state source every render.\n const pathKey = useMemo(() => JSON.stringify(path ?? null), [path])\n\n const source = useMemo(\n () =>\n getDocumentPresence(sanityInstance, {\n ...(resource ? {resource} : {}),\n documentId,\n // Forwarded, not resolved here, so this matches what `useReportPresence`\n // sends. Core owns turning a perspective into a specific document id.\n ...(perspective ? {perspective} : {}),\n ...(liveEdit ? {liveEdit} : {}),\n ...(pathKey === 'null' ? {} : {path: JSON.parse(pathKey) as Path}),\n ...(excludeVersions === undefined ? {} : {excludeVersions}),\n }),\n [sanityInstance, resource, documentId, perspective, liveEdit, pathKey, excludeVersions],\n )\n\n const subscribe = useCallback((callback: () => void) => source.subscribe(callback), [source])\n const presence = useSyncExternalStore(\n subscribe,\n () => source.getCurrent(),\n () => source.getCurrent(),\n )\n\n return {presence: presence || []}\n}\n","import {\n isMediaLibraryResource,\n type PresenceSelection,\n reportPresence,\n type ReportPresenceOptions,\n} from '@sanity/sdk'\nimport {type Path} from '@sanity/types'\nimport {useEffect, useMemo, useRef} from 'react'\n\nimport {type DocumentHandle} from '../../config/handles'\nimport {useSanityInstance} from '../context/useSanityInstance'\nimport {useNormalizedResourceOptions} from '../helpers/useNormalizedResourceOptions'\nimport {trackHookUsage} from '../helpers/useTrackHookUsage'\n\n/**\n * Field focus moves at human speed, so a second between announcements is plenty.\n */\nconst FOCUS_THROTTLE_MS = 1000\n\n/**\n * A caret that trails a second behind reads as broken rather than as latency, so\n * reporting a `selection` announces more often. The Studio uses a flat 1000ms for\n * both, which is why its remote carets feel sluggish.\n */\nconst SELECTION_THROTTLE_MS = 250\n\n/** @beta */\nexport interface UseReportPresenceOptions extends DocumentHandle {\n /**\n * The focused field path. Omit it for document-level presence. Keyed and numeric\n * segments are supported, so array items and Portable Text spans can be\n * addressed.\n */\n path?: Path\n\n /** The Portable Text caret, when the focused field is a Portable Text field. */\n selection?: PresenceSelection\n\n /** Overrides the throttle interval. Mainly useful in tests. */\n throttleMs?: number\n}\n\n/**\n * Announces that the current user is in a document, so that other clients in the\n * same project and dataset can show them.\n *\n * Writing presence is opt-in. Reading it with `usePresenceForDocument` or\n * `usePresence` never announces anything, and this hook is the only thing that\n * makes an app visible to others. That includes the Studio, which shares the same\n * presence room and will show these users in its navbar and field indicators.\n *\n * Announcements are throttled, collapsed over a short window, and then repeated\n * every 30 seconds while the user is idle. That repeat is what tells peers the\n * session is still alive, so the intended usage is to mount this hook for as long\n * as the user is in the document. On unmount the location is cleared, leaving the\n * user present in the app but not in any particular document.\n *\n * The perspective decides which specific document is reported: the draft under\n * `drafts`, the published document under `published`, a version under a release.\n * It is taken from `ResourceProvider` unless you pass one on the handle. That\n * matters for interoperability, because the Studio's field indicators compare the\n * exact id its form is on, so a mismatch shows your user at document level while\n * never lighting up a field.\n *\n * Presence is scoped to a single project and dataset. It is not a list of everyone\n * signed in to your organization.\n *\n * @example Document-level presence\n * ```tsx\n * function DocumentEditor({documentId, documentType}: DocumentHandle) {\n * useReportPresence({documentId, documentType})\n * return <Editor />\n * }\n * ```\n *\n * @example Presence in a release version\n * ```tsx\n * // The document id stays plain; the perspective selects the version.\n * useReportPresence({documentId, documentType, perspective: {releaseName: 'autumn'}})\n * ```\n *\n * @example Field-level presence\n * ```tsx\n * function TitleField({documentId, documentType}: DocumentHandle) {\n * const [focused, setFocused] = useState(false)\n * useReportPresence({documentId, documentType, path: focused ? ['title'] : undefined})\n * return <input onFocus={() => setFocused(true)} onBlur={() => setFocused(false)} />\n * }\n * ```\n *\n * @beta\n */\nexport function useReportPresence(options: UseReportPresenceOptions): void {\n const {path, selection, throttleMs, ...handle} = options\n\n const normalizedOptions = useNormalizedResourceOptions(handle)\n if (normalizedOptions.resource && isMediaLibraryResource(normalizedOptions.resource)) {\n throw new Error(\n 'useReportPresence() does not support media library resources. Presence tracking requires a canvas or dataset resource.',\n )\n }\n\n const sanityInstance = useSanityInstance()\n trackHookUsage(sanityInstance, 'useReportPresence')\n\n const {resource, perspective} = normalizedOptions\n const {documentId, liveEdit} = options\n\n const interval = throttleMs ?? (selection ? SELECTION_THROTTLE_MS : FOCUS_THROTTLE_MS)\n\n // Compared by value, because callers write `path={['title']}` inline and a fresh\n // array identity every render must not mean a fresh announcement every render.\n const locationKey = useMemo(\n () =>\n JSON.stringify([documentId, path ?? [], selection ?? null, perspective ?? null, liveEdit]),\n [documentId, path, selection, perspective, liveEdit],\n )\n\n // Rebuilt from the key rather than from the props, so the effect below can\n // depend on it honestly instead of suppressing the exhaustive-deps rule.\n const location = useMemo<ReportPresenceOptions>(() => {\n const [id, parsedPath, parsedSelection, parsedPerspective, parsedLiveEdit] = JSON.parse(\n locationKey,\n ) as [string, Path, PresenceSelection, ReportPresenceOptions['perspective'] | null, boolean?]\n return {\n documentId: id,\n // Forwarded rather than resolved here: core turns the perspective into the\n // specific document id, so the read and write sides cannot drift apart.\n ...(parsedPerspective ? {perspective: parsedPerspective} : {}),\n ...(parsedLiveEdit ? {liveEdit: parsedLiveEdit} : {}),\n ...(parsedPath.length > 0 ? {path: parsedPath} : {}),\n ...(parsedSelection ? {selection: parsedSelection} : {}),\n }\n }, [locationKey])\n\n const lastSentAt = useRef(0)\n const pending = useRef<ReturnType<typeof setTimeout> | undefined>(undefined)\n\n useEffect(() => {\n // Captured in this effect's closure rather than read from a ref, so nothing is\n // written during render. A newer location re-runs the effect, which clears the\n // pending timeout below and schedules the newer value instead.\n const send = () => {\n lastSentAt.current = Date.now()\n reportPresence(sanityInstance, {\n ...(resource ? {resource} : {}),\n locations: [location],\n })\n }\n\n const elapsed = Date.now() - lastSentAt.current\n if (elapsed >= interval) {\n send()\n } else {\n // Trailing edge, so the position the user settled on is the one announced.\n clearTimeout(pending.current)\n pending.current = setTimeout(send, interval - elapsed)\n }\n\n return () => clearTimeout(pending.current)\n }, [location, interval, sanityInstance, resource])\n\n // Kept separate from the throttled effect so it runs on unmount only, rather\n // than every time the reported location changes.\n useEffect(() => {\n return () => {\n reportPresence(sanityInstance, {...(resource ? {resource} : {}), locations: []})\n }\n }, [sanityInstance, resource])\n}\n","import {getProjectionState, resolveProjection, type ResolveProjectionResult} from '@sanity/sdk'\nimport {useCallback, useMemo, useSyncExternalStore} from 'react'\nimport {distinctUntilChanged, EMPTY, Observable, startWith, switchMap} from 'rxjs'\n\nimport {type DocumentHandle} from '../../config/handles'\nimport {useSanityInstance} from '../context/useSanityInstance'\nimport {useNormalizedResourceOptions} from '../helpers/useNormalizedResourceOptions'\nimport {trackHookUsage} from '../helpers/useTrackHookUsage'\n\n/**\n * @public\n * @category Types\n */\nexport interface useDocumentProjectionOptions<\n TProjection extends string = string,\n TDocumentType extends string = string,\n TDataset extends string = string,\n TProjectId extends string = string,\n> extends DocumentHandle<TDocumentType, TDataset, TProjectId> {\n /** The GROQ projection string */\n projection: TProjection\n /** Optional parameters for the projection query */\n params?: Record<string, unknown>\n /** Optional ref to track viewport intersection for lazy loading */\n ref?: React.RefObject<unknown>\n}\n\n/**\n * @public\n * @category Types\n */\nexport interface useDocumentProjectionResults<TData> {\n /** The projected data */\n data: TData\n /** True if the projection is currently being resolved */\n isPending: boolean\n}\n\n/**\n * @public\n *\n * Returns the projected values of a document based on the provided projection string.\n * These values are live and will update in realtime.\n * To optimize network requests, an optional `ref` can be passed to only resolve the projection\n * when the referenced element is intersecting the viewport.\n *\n * @category Documents\n * @remarks\n * This hook has multiple signatures allowing for fine-grained control over type inference:\n * - Using Typegen: Infers the return type based on the `documentType`, `dataset`, `projectId`, and `projection`.\n * - Using explicit type parameter: Allows specifying a custom return type `TData`.\n *\n * @param options - An object containing the `DocumentHandle` properties (`documentId`, `documentType`, etc.), the `projection` string, optional `params`, and an optional `ref`.\n * @returns An object containing the projection results (`data`) and a boolean indicating whether the resolution is pending (`isPending`). Note: Suspense handles initial loading states; `data` being `undefined` after initial loading means the document doesn't exist or the projection yielded no result.\n */\n\n// Overload 1: Relies on Typegen\n/**\n * @public\n * Fetch a projection, relying on Typegen for the return type based on the handle and projection.\n *\n * @category Documents\n * @param options - Options including the document handle properties (`documentId`, `documentType`, etc.) and the `projection`.\n * @returns The projected data, typed based on Typegen.\n *\n * @example Using an existing experimental Typegen file for a book preview\n * ```tsx\n * // ProjectionComponent.tsx\n * import {defineProjection, useDocumentProjection, type DocumentHandle} from '@sanity/sdk-react'\n * import {useRef} from 'react'\n *\n * // Define props using DocumentHandle with the specific document type\n * type ProjectionComponentProps = {\n * doc: DocumentHandle<'book'> // Typegen knows 'book'\n * }\n *\n * // Keep the projection string identical to its entry in the existing generated file.\n * // Current Typegen does not scan defineProjection imported from the SDK.\n * const myProjection = defineProjection(`{\n * title,\n * 'coverImage': cover.asset->url,\n * 'authors': array::join(authors[]->{'name': firstName + ' ' + lastName}.name, ', ')\n * }`)\n *\n * export default function ProjectionComponent({ doc }: ProjectionComponentProps) {\n * const ref = useRef(null) // Optional ref to track viewport intersection for lazy loading\n *\n * // Spread the doc handle into the options\n * // Typegen infers the return type based on 'book' and the projection\n * const { data } = useDocumentProjection({\n * ...doc, // Pass the handle properties\n * ref,\n * projection: myProjection,\n * })\n *\n * // Suspense handles initial load, check for data existence after\n * return (\n * <article ref={ref}>\n * <h2>{data.title ?? 'Untitled'}</h2>\n * {data.coverImage && <img src={data.coverImage} alt={data.title} />}\n * <p>{data.authors ?? 'Unknown authors'}</p>\n * </article>\n * )\n * }\n *\n * // Usage:\n * // import {createDocumentHandle} from '@sanity/sdk-react'\n * // const myDocHandle = createDocumentHandle({ documentId: 'book123', documentType: 'book' })\n * // <Suspense fallback='Loading preview...'>\n * // <ProjectionComponent doc={myDocHandle} />\n * // </Suspense>\n * ```\n */\nexport function useDocumentProjection<\n TProjection extends string = string,\n TDocumentType extends string = string,\n TDataset extends string = string,\n TProjectId extends string = string,\n>(\n options: useDocumentProjectionOptions<TProjection, TDocumentType, TDataset, TProjectId>,\n): useDocumentProjectionResults<\n ResolveProjectionResult<TProjection, TDocumentType, `${TProjectId}.${TDataset}`>\n>\n\n// Overload 2: Explicit type provided\n/**\n * @public\n * Fetch a projection with an explicitly defined return type `TData`.\n *\n * @param options - Options including the document handle properties (`documentId`, etc.) and the `projection`.\n * @returns The projected data, cast to the explicit type `TData`.\n *\n * @example Explicitly typing the projection result\n * ```tsx\n * import {useDocumentProjection, type DocumentHandle} from '@sanity/sdk-react'\n * import {useRef} from 'react'\n *\n * interface SimpleBookPreview {\n * title?: string;\n * authorName?: string;\n * }\n *\n * type BookPreviewProps = {\n * doc: DocumentHandle\n * }\n *\n * function BookPreview({ doc }: BookPreviewProps) {\n * const ref = useRef(null)\n * const { data } = useDocumentProjection<SimpleBookPreview>({\n * ...doc,\n * ref,\n * projection: `{ title, 'authorName': author->name }`\n * })\n *\n * return (\n * <div ref={ref}>\n * <h3>{data.title ?? 'No Title'}</h3>\n * <p>By: {data.authorName ?? 'Unknown'}</p>\n * </div>\n * )\n * }\n *\n * // Usage:\n * // import {createDocumentHandle} from '@sanity/sdk-react'\n * // const doc = createDocumentHandle({ documentId: 'abc', documentType: 'book' })\n * // <Suspense fallback='Loading...'>\n * // <BookPreview doc={doc} />\n * // </Suspense>\n * ```\n */\nexport function useDocumentProjection<TData extends object>(\n options: useDocumentProjectionOptions, // Uses base options type\n): useDocumentProjectionResults<TData>\n\n// Implementation (no JSDoc needed here as it's covered by overloads)\nexport function useDocumentProjection<TData extends object>({\n ref,\n projection,\n ...docHandle\n}: useDocumentProjectionOptions): useDocumentProjectionResults<TData> {\n const instance = useSanityInstance()\n trackHookUsage(instance, 'useDocumentProjection')\n\n // Normalize projection string to handle template literals with whitespace\n // This ensures that the same projection content produces the same state source\n // even if the string reference changes (e.g., from inline template literals)\n const normalizedProjection = useMemo(() => projection.trim(), [projection])\n\n // Normalize options: resolve resourceName to resource and strip resourceName\n const normalizedDocHandle = useNormalizedResourceOptions(docHandle)\n\n // Memoize stateSource based on normalized projection and docHandle properties\n // This prevents creating a new StateSource on every render when projection content is the same\n const stateSource = useMemo(\n () =>\n getProjectionState<TData>(instance, {\n ...normalizedDocHandle,\n projection: normalizedProjection,\n }),\n [instance, normalizedDocHandle, normalizedProjection],\n )\n\n if (stateSource.getCurrent()?.data === null) {\n throw resolveProjection(instance, {...normalizedDocHandle, projection: normalizedProjection})\n }\n\n // Create subscribe function for useSyncExternalStore\n const subscribe = useCallback(\n (onStoreChanged: () => void) => {\n const subscription = new Observable<boolean>((observer) => {\n // For environments that don't have an intersection observer (e.g. server-side),\n // we pass true to always subscribe since we can't detect visibility\n if (typeof IntersectionObserver === 'undefined' || typeof HTMLElement === 'undefined') {\n observer.next(true)\n return\n }\n\n const intersectionObserver = new IntersectionObserver(\n ([entry]) => observer.next(entry.isIntersecting),\n {rootMargin: '0px', threshold: 0},\n )\n if (ref?.current && ref.current instanceof HTMLElement) {\n intersectionObserver.observe(ref.current)\n } else {\n // If no ref is provided or ref.current isn't an HTML element,\n // pass true to always subscribe since we can't track visibility\n observer.next(true)\n }\n return () => intersectionObserver.disconnect()\n })\n .pipe(\n startWith(false),\n distinctUntilChanged(),\n switchMap((isVisible) =>\n isVisible\n ? new Observable<void>((obs) => {\n // `stateSource.subscribe` skips the value current at subscribe time;\n // (intentionally -- we only want new events)\n // but in this case the store might have updated while the element was off-screen;\n // so we fire an immediate notification here to make useSyncExternalStore\n // re-read getCurrent() and pick up the fresh value.\n obs.next()\n return stateSource.subscribe(() => obs.next())\n })\n : EMPTY,\n ),\n )\n .subscribe({next: onStoreChanged})\n\n return () => subscription.unsubscribe()\n },\n [stateSource, ref],\n )\n\n return useSyncExternalStore(\n subscribe,\n stateSource.getCurrent,\n ) as useDocumentProjectionResults<TData>\n}\n","import {type PreviewQueryResult, type PreviewValue} from '@sanity/sdk'\nimport {PREVIEW_PROJECTION, transformProjectionToPreview} from '@sanity/sdk/_internal'\nimport {useMemo} from 'react'\n\nimport {type DocumentHandle} from '../../config/handles'\nimport {useSanityInstance} from '../context/useSanityInstance'\nimport {useNormalizedResourceOptions} from '../helpers/useNormalizedResourceOptions'\nimport {trackHookUsage} from '../helpers/useTrackHookUsage'\nimport {useDocumentProjection} from '../projection/useDocumentProjection'\n\n/**\n * @public\n * @category Types\n */\nexport interface useDocumentPreviewOptions extends DocumentHandle {\n /**\n * Optional ref object to track visibility. When provided, preview resolution\n * only occurs when the referenced element is visible in the viewport.\n */\n ref?: React.RefObject<unknown>\n}\n\n/**\n * @public\n * @category Types\n */\nexport interface useDocumentPreviewResults {\n /** The results of inferring the document's preview values */\n data: PreviewValue\n /** True when inferred preview values are being refreshed */\n isPending: boolean\n}\n\n/**\n * @public\n *\n * Attempts to infer preview values of a document (specified via a `DocumentHandle`),\n * including the document's `title`, `subtitle`, `media`, and `status`. These values are live and will update in realtime.\n * To reduce unnecessary network requests for resolving the preview values, an optional `ref` can be passed to the hook so that preview\n * resolution will only occur if the `ref` is intersecting the current viewport.\n *\n * See remarks below for futher information.\n *\n * @remarks\n * Values returned by this hook may not be as expected. It is currently unable to read preview values as defined in your schema;\n * instead, it attempts to infer these preview values by checking against a basic set of potential fields on your document.\n * We are anticipating being able to significantly improve this hook's functionality and output in a future release.\n * For now, we recommend using {@link useDocumentProjection} for rendering individual document fields (or projections of those fields).\n *\n * Internally, this hook is implemented as a specialized projection with post-processing logic.\n * It uses a fixed GROQ projection to fetch common preview fields (title, subtitle, media) and\n * transforms the results into the PreviewValue format.\n *\n * @category Documents\n * @param options - The document handle for the document you want to infer preview values for, and an optional ref\n * @returns The inferred values for the given document and a boolean to indicate whether the resolution is pending\n *\n * @example Combining with useDocuments to render a collection of document previews\n * ```\n * // PreviewComponent.jsx\n * export default function PreviewComponent({ document }) {\n * const { data: { title, subtitle, media }, isPending } = useDocumentPreview({ document })\n * return (\n * <article style={{ opacity: isPending ? 0.5 : 1}}>\n * {media?.type === 'image-asset' ? <img src={media.url} alt='' /> : ''}\n * <h2>{title}</h2>\n * <p>{subtitle}</p>\n * </article>\n * )\n * }\n *\n * // DocumentList.jsx\n * const { data } = useDocuments({ filter: '_type == \"movie\"' })\n * return (\n * <div>\n * <h1>Movies</h1>\n * <ul>\n * {data.map(movie => (\n * <li key={movie._id}>\n * <Suspense fallback='Loading…'>\n * <PreviewComponent document={movie} />\n * </Suspense>\n * </li>\n * ))}\n * </ul>\n * </div>\n * )\n * ```\n */\nexport function useDocumentPreview({\n ref,\n ...docHandle\n}: useDocumentPreviewOptions): useDocumentPreviewResults {\n const instance = useSanityInstance()\n trackHookUsage(instance, 'useDocumentPreview')\n const normalizedDocHandle = useNormalizedResourceOptions(docHandle)\n\n // Use the projection hook with the fixed preview projection\n const projectionResult = useDocumentProjection<PreviewQueryResult>({\n ...normalizedDocHandle,\n projection: PREVIEW_PROJECTION,\n ref,\n })\n\n // Contract: useDocumentProjection suspends while data is null, so data is always available here.\n // Keep this non-null assumption aligned with useDocumentPreviewResults.data.\n const previewValue = useMemo(\n () =>\n transformProjectionToPreview(instance, projectionResult.data, normalizedDocHandle.resource),\n [projectionResult.data, instance, normalizedDocHandle.resource],\n )\n\n return {\n data: previewValue,\n isPending: projectionResult.isPending,\n }\n}\n","import {type Project, project, type ProjectOptions} from '@sanity/sdk'\n\nimport {createFetcherHook, type FetcherHookResult} from '../helpers/createFetcherHook'\nimport {useResolvedProjectId} from '../helpers/useResolvedProjectId'\n\nconst useProjectBase = createFetcherHook(project)\n\n/**\n * Returns metadata for a given project.\n *\n * @category Projects\n * @param options - Configuration options\n * @returns A {@link FetcherHookResult} whose `data` is the metadata for the\n * project. `members` is included only when `includeMembers: true`; `features`\n * is included unless `includeFeatures: false`.\n * @example\n * ```tsx\n * function ProjectMetadata({projectId}: {projectId: string}) {\n * const {data: project} = useProject({projectId})\n *\n * return (\n * <figure style={{backgroundColor: project.metadata.color || 'lavender'}}>\n * <h1>{project.displayName}</h1>\n * </figure>\n * )\n * }\n * ```\n * @example\n * ```tsx\n * const {data: projectWithMembersAndFeatures} = useProject({projectId})\n * const {data: projectWithMembers} = useProject({projectId, includeMembers: true})\n * const {data: projectWithoutMembers} = useProject({projectId, includeMembers: false})\n * const {data: projectWithoutFeatures} = useProject({projectId, includeFeatures: false})\n * ```\n * @remarks\n * The `projectId` is resolved in order from:\n * 1. an explicit `projectId` option\n * 2. A legacy ProjectContext (e.g. a `<ResourceProvider projectId=\"…\">` with no dataset), then\n * 3. The active resource (`ResourceProvider`/`SDKProvider`)\n * 4. `instance.config`.\n * @public\n * @function\n */\nexport const useProject = ((options?: ProjectOptions<boolean, boolean>) => {\n const projectId = useResolvedProjectId(options)\n return useProjectBase(projectId ? {...options, projectId} : options)\n}) as <IncludeMembers extends boolean = true, IncludeFeatures extends boolean = true>(\n options?: ProjectOptions<IncludeMembers, IncludeFeatures>,\n) => FetcherHookResult<Project<IncludeMembers, IncludeFeatures>>\n","import {type Project, projects, type ProjectsOptions} from '@sanity/sdk'\n\nimport {createFetcherHook, type FetcherHookResult} from '../helpers/createFetcherHook'\n\n/**\n * Returns metadata for each project you have access to.\n *\n * @category Projects\n * @param options - Configuration options\n * @returns A {@link FetcherHookResult} whose `data` is an array of project\n * metadata. `members` is included only when `includeMembers: true`; `features`\n * is included unless `includeFeatures: false`.\n * @example\n * ```tsx\n * const {data: projects} = useProjects()\n *\n * return (\n * <select>\n * {projects.map((project) => (\n * <option key={project.id}>{project.displayName}</option>\n * ))}\n * </select>\n * )\n * ```\n * @example\n * ```tsx\n * const {data: projects} = useProjects()\n * const {data: projectsWithFeatures} = useProjects()\n * const {data: projectsWithMembers} = useProjects({includeMembers: true})\n * const {data: projectsWithoutMembers} = useProjects({includeMembers: false})\n * const {data: projectsWithoutFeatures} = useProjects({includeFeatures: false})\n * ```\n * @public\n * @function\n */\nexport const useProjects = createFetcherHook(projects) as <\n IncludeMembers extends boolean = false,\n IncludeFeatures extends boolean = true,\n>(\n options?: ProjectsOptions<IncludeMembers, IncludeFeatures>,\n) => FetcherHookResult<Project<IncludeMembers, IncludeFeatures>[]>\n","import {\n type DatasetHandle,\n type DocumentResource,\n getActiveReleasesState,\n type ReleaseDocument,\n type SanityInstance,\n type StateSource,\n} from '@sanity/sdk'\nimport {filter, firstValueFrom} from 'rxjs'\n\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\nimport {\n useNormalizedResourceOptions,\n type WithResourceNameSupport,\n} from '../helpers/useNormalizedResourceOptions'\n\ntype UseActiveReleasesValue = {\n (options?: {resource?: DocumentResource}): ReleaseDocument[]\n}\n\nconst useActiveReleasesValue: UseActiveReleasesValue = createStateSourceHook({\n getState: getActiveReleasesState as (\n instance: SanityInstance,\n options?: {resource?: DocumentResource},\n ) => StateSource<ReleaseDocument[]>,\n shouldSuspend: (instance: SanityInstance, options?: {resource?: DocumentResource}) =>\n getActiveReleasesState(instance, options ?? {}).getCurrent() === undefined,\n suspender: (instance: SanityInstance, options?: {resource?: DocumentResource}) =>\n firstValueFrom(\n getActiveReleasesState(instance, options ?? {}).observable.pipe(filter(Boolean)),\n ),\n})\n\n/**\n * @public\n * @function\n *\n * Returns the active releases for the current project,\n * represented as a list of release documents.\n *\n * @returns The active releases for the current project.\n * @category Releases\n * @example\n * ```tsx\n * import {useActiveReleases} from '@sanity/sdk-react'\n *\n * const activeReleases = useActiveReleases()\n * ```\n */\nexport function useActiveReleases(\n options?: WithResourceNameSupport<DatasetHandle> | undefined,\n): ReleaseDocument[] {\n const normalizedOptions = useNormalizedResourceOptions(options ?? {})\n return useActiveReleasesValue(normalizedOptions)\n}\n","import {\n type DatasetHandle,\n type DocumentResource,\n getAllReleasesState,\n type ReleaseDocument,\n type SanityInstance,\n type StateSource,\n} from '@sanity/sdk'\nimport {filter, firstValueFrom} from 'rxjs'\n\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\nimport {\n useNormalizedResourceOptions,\n type WithResourceNameSupport,\n} from '../helpers/useNormalizedResourceOptions'\n\ntype UseAllReleasesValue = {\n (options?: {resource?: DocumentResource}): ReleaseDocument[]\n}\n\nconst useAllReleasesValue: UseAllReleasesValue = createStateSourceHook({\n getState: getAllReleasesState as (\n instance: SanityInstance,\n options?: {resource?: DocumentResource},\n ) => StateSource<ReleaseDocument[]>,\n shouldSuspend: (instance: SanityInstance, options?: {resource?: DocumentResource}) =>\n getAllReleasesState(instance, options ?? {}).getCurrent() === undefined,\n suspender: (instance: SanityInstance, options?: {resource?: DocumentResource}) =>\n firstValueFrom(getAllReleasesState(instance, options ?? {}).observable.pipe(filter(Boolean))),\n})\n\n/**\n * @public\n * @function\n *\n * Returns every release the dataset has — including `archived`, `published`,\n * and mid-transition states (`archiving`, `unarchiving`, `publishing`,\n * `scheduling`).\n *\n * Use this hook when you're building a release-management UI (listing\n * releases, surfacing lifecycle controls, etc.) so a release stays visible\n * across its full lifecycle — including after it's been published or\n * archived. For perspective / content queries, prefer\n * {@link useActiveReleases}, which filters to releases that still affect\n * what's queryable.\n *\n * @returns Every release for the current project, sorted to match the order\n * used by {@link useActiveReleases}.\n * @category Releases\n * @example\n * ```tsx\n * import {useAllReleases} from '@sanity/sdk-react'\n *\n * const releases = useAllReleases()\n * ```\n */\nexport function useAllReleases(\n options?: WithResourceNameSupport<DatasetHandle> | undefined,\n): ReleaseDocument[] {\n const normalizedOptions = useNormalizedResourceOptions(options ?? {})\n return useAllReleasesValue(normalizedOptions)\n}\n","import {type ActionsResult, type ReleaseAction} from '@sanity/sdk'\n\nimport {type ResourceHandle} from '../../config/handles'\nimport {useApplyActions} from '../helpers/useApplyActions'\n\n/**\n * @public\n */\ninterface UseApplyReleaseActions {\n (): (action: ReleaseAction | ReleaseAction[], options?: ResourceHandle) => Promise<ActionsResult>\n}\n\n/**\n * @public\n *\n * Provides a stable callback function for applying one or more release actions.\n *\n * This hook wraps the core `applyDocumentActions` functionality from `@sanity/sdk`,\n * integrating it with the React component lifecycle and {@link SanityInstance}.\n * It accepts release-lifecycle actions generated by {@link createRelease},\n * {@link editRelease}, {@link publishRelease}, {@link scheduleRelease},\n * {@link unscheduleRelease}, {@link archiveRelease}, {@link unarchiveRelease},\n * and {@link deleteRelease}.\n *\n * Note that actions submitted via this hook will cascade to the documents in the release.\n * For example, if you create a release and then publish it, the documents in the release will be published.\n * If you delete a published release, the version documents will be deleted.\n *\n * Features:\n * - Applies one or multiple `ReleaseAction` objects.\n * - Supports optimistic updates for create/edit/delete: local release state\n * reflects changes immediately while in-flight.\n * - Handles batching: multiple actions passed together are submitted as a\n * single atomic transaction.\n *\n * Release actions cannot be combined with `liveEdit` document actions in the\n * same transaction. Submit them as separate transactions if you need both.\n *\n * @category Releases\n * @returns A stable callback. When called with a single `ReleaseAction` or an\n * array of `ReleaseAction`s, it returns a promise that resolves to an\n * {@link ActionsResult}.\n *\n * @example Create and schedule a release\n * ```tsx\n * import {\n * createRelease,\n * scheduleRelease,\n * useApplyReleaseActions,\n * type ReleaseHandle,\n * } from '@sanity/sdk-react'\n *\n * function ScheduleReleaseButton({release}: {release: ReleaseHandle}) {\n * const applyRelease = useApplyReleaseActions()\n *\n * const handleSchedule = () =>\n * applyRelease([\n * createRelease(release, {title: 'Summer drop', releaseType: 'asap'}),\n * scheduleRelease(release, '2026-06-01T00:00:00Z'),\n * ])\n *\n * return <button onClick={handleSchedule}>Schedule</button>\n * }\n * ```\n *\n * @example Publish a release\n * ```tsx\n * import {publishRelease, useApplyReleaseActions} from '@sanity/sdk-react'\n *\n * function PublishButton({releaseId}: {releaseId: string}) {\n * const applyRelease = useApplyReleaseActions()\n * return (\n * <button onClick={() => applyRelease(publishRelease({releaseId}))}>\n * Publish all documents in the release\n * </button>\n * )\n * }\n * ```\n */\nexport const useApplyReleaseActions: UseApplyReleaseActions = () => {\n return useApplyActions() as ReturnType<UseApplyReleaseActions>\n}\n","import {\n type DocumentResource,\n getPerspectiveState,\n type SanityInstance,\n type StateSource,\n} from '@sanity/sdk'\nimport {filter, firstValueFrom} from 'rxjs'\n\nimport {type ResourceHandle} from '../../config/handles'\nimport {createStateSourceHook} from '../helpers/createStateSourceHook'\nimport {useNormalizedResourceOptions} from '../helpers/useNormalizedResourceOptions'\n\n/**\n * @public\n * @function\n *\n * Returns a single or stack of perspectives for the given perspective handle,\n * which can then be used to correctly query the documents\n * via the `perspective` parameter in the client.\n *\n * @param perspectiveHandle - The perspective handle to get the perspective for.\n * @category Documents\n * @example\n * ```tsx\n * import {usePerspective, useQuery} from '@sanity/sdk-react'\n\n * const perspective = usePerspective({perspective: 'rxg1346', projectId: 'abc123', dataset: 'production'})\n * const {data} = useQuery<Movie[]>('*[_type == \"movie\"]', {\n * perspective: perspective,\n * })\n * ```\n *\n * @returns The perspective for the given perspective handle.\n */\ntype UsePerspectiveValue = {\n (perspectiveHandle: {resource?: DocumentResource}): string | string[]\n}\n\nconst usePerspectiveValue: UsePerspectiveValue = createStateSourceHook({\n getState: getPerspectiveState as (\n instance: SanityInstance,\n perspectiveHandle?: {resource?: DocumentResource},\n ) => StateSource<string | string[]>,\n shouldSuspend: (instance: SanityInstance, options: {resource?: DocumentResource}): boolean =>\n getPerspectiveState(instance, options).getCurrent() === undefined,\n suspender: (instance: SanityInstance, _options?: {resource?: DocumentResource}) =>\n firstValueFrom(getPerspectiveState(instance, _options ?? {}).observable.pipe(filter(Boolean))),\n})\n\n/**\n * @public\n * @function\n */\nexport function usePerspective(perspectiveHandle?: ResourceHandle): string | string[] {\n const normalizedOptions = useNormalizedResourceOptions(perspectiveHandle ?? {})\n return usePerspectiveValue(normalizedOptions)\n}\n","import {type GetUserOptions, getUsersState, resolveUsers, type SanityUser} from '@sanity/sdk'\nimport {getUsersKey, parseUsersKey} from '@sanity/sdk/_internal'\nimport {useEffect, useMemo, useState, useSyncExternalStore, useTransition} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\nimport {trackHookUsage} from '../helpers/useTrackHookUsage'\n\n/**\n * @public\n * @category Types\n */\nexport interface UserResult {\n /**\n * The user data fetched, or undefined if not found.\n */\n data: SanityUser | undefined\n /**\n * Whether a user request is currently in progress\n */\n isPending: boolean\n}\n\n/**\n *\n * @public\n *\n * Retrieves a single user by ID for a given resource (either a project or an organization).\n *\n * @category Users\n * @param options - The user ID, resource type, project ID, or organization ID\n * @returns The user data and loading state\n *\n * @example\n * ```\n * const { data, isPending } = useUser({\n * userId: 'gabc123',\n * resourceType: 'project',\n * projectId: 'my-project-id',\n * })\n *\n * return (\n * <div>\n * {isPending && <p>Loading...</p>}\n * {data && (\n * <figure>\n * <img src={data.profile.imageUrl} alt='' />\n * <figcaption>{data.profile.displayName}</figcaption>\n * <address>{data.profile.email}</address>\n * </figure>\n * )}\n * </div>\n * )\n * ```\n */\nexport function useUser(options: GetUserOptions): UserResult {\n const instance = useSanityInstance()\n trackHookUsage(instance, 'useUser')\n // Use React's useTransition to avoid UI jank when user options change\n const [isPending, startTransition] = useTransition()\n\n // Get the unique key for this user request and its options\n const key = getUsersKey(instance, options)\n // Use a deferred state to avoid immediate re-renders when the user request changes\n const [deferredKey, setDeferredKey] = useState(key)\n // Parse the deferred user key back into user options\n const deferred = useMemo(() => parseUsersKey(deferredKey), [deferredKey])\n\n // Create an AbortController to cancel in-flight requests when needed\n const [ref, setRef] = useState<AbortController>(new AbortController())\n\n // When the user request or options change, start a transition to update the request\n useEffect(() => {\n if (key === deferredKey) return\n\n startTransition(() => {\n if (!ref.signal.aborted) {\n ref.abort()\n setRef(new AbortController())\n }\n\n setDeferredKey(key)\n })\n }, [deferredKey, key, ref])\n\n // Get the state source for this user request from the users store\n // We pass the userId as part of options to getUsersState\n const {getCurrent, subscribe} = useMemo(() => {\n return getUsersState(instance, deferred as GetUserOptions)\n }, [instance, deferred])\n\n // If data isn't available yet, suspend rendering until it is\n // This is the React Suspense integration - throwing a promise\n // will cause React to show the nearest Suspense fallback\n if (getCurrent() === undefined) {\n throw resolveUsers(instance, {...(deferred as GetUserOptions), signal: ref.signal})\n }\n\n // Subscribe to updates and get the current data\n // useSyncExternalStore ensures the component re-renders when the data changes\n // Extract the first user from the users array (since we're fetching by userId, there should be only one)\n const result = useSyncExternalStore(subscribe, getCurrent)\n const data = result?.data[0]\n\n return {data, isPending}\n}\n","import {\n type GetUsersOptions,\n getUsersState,\n loadMoreUsers,\n resolveUsers,\n type SanityUser,\n} from '@sanity/sdk'\nimport {getUsersKey, parseUsersKey} from '@sanity/sdk/_internal'\nimport {useCallback, useEffect, useMemo, useState, useSyncExternalStore, useTransition} from 'react'\n\nimport {useSanityInstance} from '../context/useSanityInstance'\nimport {useResolvedProjectId} from '../helpers/useResolvedProjectId'\nimport {trackHookUsage} from '../helpers/useTrackHookUsage'\n\n/**\n * @public\n * @category Types\n */\nexport interface UsersResult {\n /**\n * The users fetched.\n */\n data: SanityUser[]\n /**\n * Whether there are more users to fetch.\n */\n hasMore: boolean\n\n /**\n * Whether a users request is currently in progress\n */\n isPending: boolean\n /**\n * Load more users.\n */\n loadMore: () => void\n}\n\n/**\n * Injects a resolved `projectId` into project-scoped users options. A missing\n * `projectId` is a no-op, and organization-scoped queries (explicit\n * `resourceType`/`organizationId`) or options that already carry a `projectId`\n * are returned unchanged.\n */\nfunction withResolvedProjectId(\n options: GetUsersOptions | undefined,\n projectId: string | undefined,\n): GetUsersOptions | undefined {\n if (!projectId) return options\n if (!options) return {projectId}\n const isOrgScoped = options.resourceType === 'organization' || !!options.organizationId\n if (isOrgScoped || options.projectId) return options\n return {...options, projectId}\n}\n\n/**\n *\n * @public\n *\n * Retrieves the users for a given resource (either a project or an organization).\n *\n * @category Users\n * @param params - The resource type, project ID, and the limit of users to fetch\n * @returns A list of users, a boolean indicating whether there are more users to fetch, and a function to load more users\n *\n * @example\n * ```\n * const { data, hasMore, loadMore, isPending } = useUsers({\n * resourceType: 'organization',\n * organizationId: 'my-org-id',\n * batchSize: 10,\n * })\n *\n * return (\n * <div>\n * {data.map(user => (\n * <figure key={user.sanityUserId}>\n * <img src={user.profile.imageUrl} alt='' />\n * <figcaption>{user.profile.displayName}</figcaption>\n * <address>{user.profile.email}</address>\n * </figure>\n * ))}\n * {hasMore && <button onClick={loadMore}>{isPending ? 'Loading...' : 'Load More'}</button>}\n * </div>\n * )\n * ```\n * @remarks\n * For project-scoped queries the `projectId` is resolved in order from:\n * 1. an explicit `projectId` option\n * 2. A legacy ProjectContext (e.g. a `<ResourceProvider projectId=\"…\">` with no dataset), then\n * 3. The active resource (`ResourceProvider`/`SDKProvider`)\n * 4. `instance.config`.\n */\nexport function useUsers(options?: GetUsersOptions): UsersResult {\n const instance = useSanityInstance()\n trackHookUsage(instance, 'useUsers')\n // Use React's useTransition to avoid UI jank when user options change\n const [isPending, startTransition] = useTransition()\n\n // Resolve the projectId from the ambient project/resource context so a\n // project-scoped users request can pick it up rather than the top-level config.\n const resolvedProjectId = useResolvedProjectId(options)\n const effectiveOptions = useMemo(\n () => withResolvedProjectId(options, resolvedProjectId),\n [options, resolvedProjectId],\n )\n\n // Get the unique key for this users request and its options\n const key = getUsersKey(instance, effectiveOptions)\n // Use a deferred state to avoid immediate re-renders when the users request changes\n const [deferredKey, setDeferredKey] = useState(key)\n // Parse the deferred users key back into users options\n const deferred = useMemo(() => parseUsersKey(deferredKey), [deferredKey])\n\n // Create an AbortController to cancel in-flight requests when needed\n const [ref, setRef] = useState<AbortController>(new AbortController())\n\n // When the users request or options change, start a transition to update the request\n useEffect(() => {\n if (key === deferredKey) return\n\n startTransition(() => {\n if (!ref.signal.aborted) {\n ref.abort()\n setRef(new AbortController())\n }\n\n setDeferredKey(key)\n })\n }, [deferredKey, key, ref])\n\n // Get the state source for this users request from the users store\n const {getCurrent, subscribe} = useMemo(() => {\n return getUsersState(instance, deferred)\n }, [instance, deferred])\n\n // If data isn't available yet, suspend rendering until it is\n // This is the React Suspense integration - throwing a promise\n // will cause React to show the nearest Suspense fallback\n if (getCurrent() === undefined) {\n throw resolveUsers(instance, {...deferred, signal: ref.signal})\n }\n\n // Subscribe to updates and get the current data\n // useSyncExternalStore ensures the component re-renders when the data changes\n const {data, hasMore} = useSyncExternalStore(subscribe, getCurrent)!\n\n const loadMore = useCallback(() => {\n loadMoreUsers(instance, effectiveOptions)\n }, [instance, effectiveOptions])\n\n return {data, hasMore, isPending, loadMore}\n}\n","","// Local type declaration for Remix\ntype WindowWithEnv = Window &\n typeof globalThis & {\n ENV?: Record<string, unknown>\n }\n\ntype KnownEnvVar = 'DEV' | 'PKG_VERSION'\n\nexport function getEnv(key: KnownEnvVar): unknown {\n if (typeof import.meta !== 'undefined' && import.meta.env) {\n // Vite environment variables\n return (import.meta.env as unknown as Record<string, unknown>)[key]\n } else if (typeof process !== 'undefined' && process.env) {\n // Node.js or server-side environment variables\n return process.env[key]\n } else if (typeof window !== 'undefined' && (window as WindowWithEnv).ENV) {\n // Remix-style client-side environment variables\n return (window as WindowWithEnv).ENV?.[key]\n }\n return undefined\n}\n","import {version} from '../package.json'\nimport {getEnv} from './utils/getEnv'\n\n/**\n * This version is provided by pkg-utils at build time\n * @internal\n */\nexport const REACT_SDK_VERSION = getEnv('PKG_VERSION') || `${version}-development`\n"],"mappings":";;;;;;;;;;;;;;;;;;AAyBA,SAAAuB,sBAAAC,IAAA;CAAA,IAAAC,IAAAC,EAAA,EAAA,GAA+B,EAAAC,aAAAH,IAC7BI,WAAiBT,kBAAkB,GACnCU,2BAAiCb,OAAO,EAAK,GAC7Cc,aAAmBd,OAA8B,IAAI,GACrDe,uBAA6Bf,OAAuB,IAAI,GACxDgB,YAAkBf,aAAa,GAACgB;CAAA,AAAAR,EAAA,OAAAS,OAAAC,IAAA,2BAAA,KAEQF,WAAA;EACtC,AAEEH,WAAUM,aADVC,aAAaP,WAAUM,OAAQ,GACV;CACtB,GACFX,EAAA,KAAAQ,MAAAA,KAAAR,EAAA;CALD,IAAAa,sBAA4BL,IAKtB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