@sanity/sdk 3.2.0 → 3.3.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/dist/_exports/_internal.d.ts +3 -3
  2. package/dist/_exports/_internal.js +4 -4
  3. package/dist/_exports/agent.d.ts +1 -1
  4. package/dist/_exports/agent.js +1 -1
  5. package/dist/_exports/comlink.d.ts +1 -1
  6. package/dist/_exports/dashboard.d.ts +1 -1
  7. package/dist/{authStore-BO2vch3I.d.ts → authStore-7dZCfKUq.d.ts} +20 -5
  8. package/dist/authStore-7dZCfKUq.d.ts.map +1 -0
  9. package/dist/{clientStore-BI4D8HhJ.js → clientStore-QDrJNTM4.js} +14 -10
  10. package/dist/clientStore-QDrJNTM4.js.map +1 -0
  11. package/dist/{createSanityInstance-BQIqyGLX.d.ts → createSanityInstance--Lrldto8.d.ts} +6 -3
  12. package/dist/createSanityInstance--Lrldto8.d.ts.map +1 -0
  13. package/dist/index.d.ts +2 -2
  14. package/dist/index.js +182 -142
  15. package/dist/index.js.map +1 -1
  16. package/dist/{topicStore-D0WqhQGF.d.ts → topicStore-CAnJsiqI.d.ts} +2 -2
  17. package/dist/{topicStore-D0WqhQGF.d.ts.map → topicStore-CAnJsiqI.d.ts.map} +1 -1
  18. package/dist/{version-BcRmCiYi.js → version-CYs30C7v.js} +3 -3
  19. package/dist/{version-BcRmCiYi.js.map → version-CYs30C7v.js.map} +1 -1
  20. package/package.json +3 -3
  21. package/src/auth/authStore.test.ts +18 -0
  22. package/src/auth/authStore.ts +4 -1
  23. package/src/auth/handleAuthCallback.test.ts +33 -0
  24. package/src/auth/handleAuthCallback.ts +11 -1
  25. package/src/auth/logout.test.ts +9 -1
  26. package/src/auth/logout.ts +18 -1
  27. package/src/auth/oauth/oauthActions.test.ts +178 -1
  28. package/src/auth/oauth/oauthActions.ts +111 -46
  29. package/src/auth/oauth/oauthAuth.test.ts +23 -0
  30. package/src/auth/oauth/oauthAuth.ts +18 -8
  31. package/src/config/authConfig.ts +5 -2
  32. package/dist/authStore-BO2vch3I.d.ts.map +0 -1
  33. package/dist/clientStore-BI4D8HhJ.js.map +0 -1
  34. package/dist/createSanityInstance-BQIqyGLX.d.ts.map +0 -1
@@ -1,6 +1,6 @@
1
- import { m as SanityConfig, s as DocumentResource, t as SanityInstance } from "../createSanityInstance-BQIqyGLX.js";
2
- import { Ai as CacheWriter, Bi as BoundStoreAction, Er as parseCommentsOptionsKey, Fi as MutationResult, Ii as defineFetcher, Li as defineMutation, Mi as FetcherDefinition, Ni as FetcherSnapshot, Pi as MutationDefinition, V as parseQueryKey, bt as GetUsersOptions, gr as createLogger, ji as Fetcher, ki as CacheTag, nt as PreviewValue, tt as PreviewQueryResult, wr as getCommentsOptionsKey, z as getQueryKey } from "../authStore-BO2vch3I.js";
3
- import { S as resetMessageBus, i as resolveTopic, o as InstallMessageBusOptions, r as getTopicState, u as MessageBusConnection, x as installMessageBus } from "../topicStore-D0WqhQGF.js";
1
+ import { m as SanityConfig, s as DocumentResource, t as SanityInstance } from "../createSanityInstance--Lrldto8.js";
2
+ import { Ai as CacheWriter, Bi as BoundStoreAction, Er as parseCommentsOptionsKey, Fi as MutationResult, Ii as defineFetcher, Li as defineMutation, Mi as FetcherDefinition, Ni as FetcherSnapshot, Pi as MutationDefinition, V as parseQueryKey, bt as GetUsersOptions, gr as createLogger, ji as Fetcher, ki as CacheTag, nt as PreviewValue, tt as PreviewQueryResult, wr as getCommentsOptionsKey, z as getQueryKey } from "../authStore-7dZCfKUq.js";
3
+ import { S as resetMessageBus, i as resolveTopic, o as InstallMessageBusOptions, r as getTopicState, u as MessageBusConnection, x as installMessageBus } from "../topicStore-CAnJsiqI.js";
4
4
  import { ClientError, SanityClient } from "@sanity/client";
5
5
  import { Observable } from "rxjs";
6
6
  import { CurrentUser } from "@sanity/types";
@@ -1,5 +1,5 @@
1
- import { A as __exportAll, C as isStudioConfig, _ as getClientErrorApiDescription, g as getClientErrorApiBody, k as createLogger, n as getClient, v as getClientErrorApiType, x as isProjectUserNotFoundClientError } from "../clientStore-BI4D8HhJ.js";
2
- import { G as defineMutation, K as randomId, S as getCommentsOptionsKey, W as defineFetcher, d as getUsersKey, i as parseQueryKey, n as getQueryKey, p as parseUsersKey, q as randomUuid, t as CORE_SDK_VERSION, w as parseCommentsOptionsKey } from "../version-BcRmCiYi.js";
1
+ import { A as __exportAll, C as isStudioConfig, _ as getClientErrorApiDescription, g as getClientErrorApiBody, k as createLogger, n as getClient, v as getClientErrorApiType, x as isProjectUserNotFoundClientError } from "../clientStore-QDrJNTM4.js";
2
+ import { G as defineMutation, K as randomId, S as getCommentsOptionsKey, W as defineFetcher, d as getUsersKey, i as parseQueryKey, n as getQueryKey, p as parseUsersKey, q as randomUuid, t as CORE_SDK_VERSION, w as parseCommentsOptionsKey } from "../version-CYs30C7v.js";
3
3
  import { i as pickProperties, n as isObject, t as isDeepEqual } from "../object-CxXlSVg7.js";
4
4
  import { a as isDashboardEnvironment, i as getDashboardMessageBus, l as installMessageBus, n as getTopicState, o as requireDashboardMessageBus, r as resolveTopic, u as resetMessageBus } from "../topicStore-Ct7IFNtY.js";
5
5
  import "@sanity/client";
@@ -310,8 +310,8 @@ function initTelemetry(instance, projectId) {
310
310
  environment
311
311
  }), Promise.all([
312
312
  Promise.resolve().then(() => telemetryManager_exports),
313
- import("../clientStore-BI4D8HhJ.js").then((n) => n.t),
314
- import("../clientStore-BI4D8HhJ.js").then((n) => n.a)
313
+ import("../clientStore-QDrJNTM4.js").then((n) => n.t),
314
+ import("../clientStore-QDrJNTM4.js").then((n) => n.a)
315
315
  ]).then(async ([{ createTelemetryManager }, { getClient }, { getTokenState }]) => {
316
316
  if (instance.isDisposed()) {
317
317
  initInFlight.delete(instance), logger.debug("telemetry skipped: instance disposed before imports resolved");
@@ -1,4 +1,4 @@
1
- import { s as DocumentResource, t as SanityInstance } from "../createSanityInstance-BQIqyGLX.js";
1
+ import { s as DocumentResource, t as SanityInstance } from "../createSanityInstance--Lrldto8.js";
2
2
  import { SanityClient } from "@sanity/client";
3
3
  import { Observable } from "rxjs";
4
4
  /** @alpha */
@@ -1,4 +1,4 @@
1
- import { r as getClientState } from "../clientStore-BI4D8HhJ.js";
1
+ import { r as getClientState } from "../clientStore-QDrJNTM4.js";
2
2
  import "@sanity/client";
3
3
  import { from, switchMap } from "rxjs";
4
4
  /**
@@ -1,4 +1,4 @@
1
- import { Bi as BoundStoreAction, zi as StateSource } from "../authStore-BO2vch3I.js";
1
+ import { Bi as BoundStoreAction, zi as StateSource } from "../authStore-7dZCfKUq.js";
2
2
  import { ChannelInput, ChannelInstance, Controller, Message, Node, NodeInput, Status } from "@sanity/comlink";
3
3
  /**
4
4
  * Message sent from a containing app to an iframe
@@ -1,2 +1,2 @@
1
- import { A as PayloadOf, C as ApplicationConfig, D as EventTopicDef, E as EventTopic, F as TopicName, I as TopicResult, L as Topics, M as ReplyOf, N as StateTopic, O as NavigationLocation, P as StateTopicDef, R as ValueOf, T as DashboardTopics, _ as MessageBusMeta, a as ConnectMessageBusOptions, b as connectMessageBus, c as MessageBusAbortOptions, d as MessageBusEmitOptions, f as MessageBusEmitResult, g as MessageBusMessage, h as MessageBusHost, j as RemoteModuleRef, k as NavigationTarget, l as MessageBusClient, m as MessageBusErrorCode, n as TopicError, p as MessageBusError, s as MessageBus, t as TopicData, u as MessageBusConnection, v as MessageBusQueryOptions, w as ApplicationConfigAppType, y as MessageBusStateSource } from "../topicStore-D0WqhQGF.js";
1
+ import { A as PayloadOf, C as ApplicationConfig, D as EventTopicDef, E as EventTopic, F as TopicName, I as TopicResult, L as Topics, M as ReplyOf, N as StateTopic, O as NavigationLocation, P as StateTopicDef, R as ValueOf, T as DashboardTopics, _ as MessageBusMeta, a as ConnectMessageBusOptions, b as connectMessageBus, c as MessageBusAbortOptions, d as MessageBusEmitOptions, f as MessageBusEmitResult, g as MessageBusMessage, h as MessageBusHost, j as RemoteModuleRef, k as NavigationTarget, l as MessageBusClient, m as MessageBusErrorCode, n as TopicError, p as MessageBusError, s as MessageBus, t as TopicData, u as MessageBusConnection, v as MessageBusQueryOptions, w as ApplicationConfigAppType, y as MessageBusStateSource } from "../topicStore-CAnJsiqI.js";
2
2
  export { type ApplicationConfig, type ApplicationConfigAppType, type ConnectMessageBusOptions, type DashboardTopics, type EventTopic, type EventTopicDef, type MessageBus, type MessageBusAbortOptions, type MessageBusClient, type MessageBusConnection, type MessageBusEmitOptions, type MessageBusEmitResult, MessageBusError, type MessageBusErrorCode, type MessageBusHost, type MessageBusMessage, type MessageBusMeta, type MessageBusQueryOptions, type MessageBusStateSource, type NavigationLocation, type NavigationTarget, type PayloadOf, type RemoteModuleRef, type ReplyOf, type StateTopic, type StateTopicDef, type TopicData, TopicError, type TopicName, type TopicResult, type Topics, type ValueOf, connectMessageBus };
@@ -1,4 +1,4 @@
1
- import { b as AuthConfig, c as DocumentTypeHandle, d as ProjectHandle, f as ReleaseHandle, i as DatasetHandle, o as DocumentHandle, s as DocumentResource, t as SanityInstance, u as PerspectiveHandle, x as AuthProvider } from "./createSanityInstance-BQIqyGLX.js";
1
+ import { b as AuthConfig, c as DocumentTypeHandle, d as ProjectHandle, f as ReleaseHandle, i as DatasetHandle, o as DocumentHandle, s as DocumentResource, t as SanityInstance, u as PerspectiveHandle, x as AuthProvider } from "./createSanityInstance--Lrldto8.js";
2
2
  import { ClientConfig, ClientPerspective, DatasetsResponse, ListenEvent, MultipleMutationResult, ReleaseDocument, ReleaseDocument as ReleaseDocument$1, ResponseQueryOptions, SanityClient, SanityDocument, SanityProject } from "@sanity/client";
3
3
  import { Observable, Subject } from "rxjs";
4
4
  import { CurrentUser, CurrentUser as CurrentUser$1, InsertPatch, Mutation, PatchOperations, Path, PortableTextBlock, Role, SanityDocument as SanityDocument$1, SanityDocument as SanityDocument$3, SanityDocumentLike } from "@sanity/types";
@@ -704,10 +704,20 @@ interface OrgVerificationResult {
704
704
  */
705
705
  declare function observeOrganizationVerificationState(instance: SanityInstance, projectIds: string[]): Observable<OrgVerificationResult>;
706
706
  /**
707
+ * Handles the auth redirect callback. In OAuth mode this delegates to
708
+ * {@link handleOAuthCallback}; otherwise it exchanges the legacy `sid` for a
709
+ * long-lived token.
710
+ *
707
711
  * @public
708
712
  */
709
713
  declare const handleAuthCallback: BoundStoreAction<AuthStoreState, [locationHref?: string | undefined], Promise<string | false>>;
710
714
  /**
715
+ * Logs the current user out. In OAuth mode this revokes the OAuth tokens
716
+ * instead of calling the legacy `/auth/logout` endpoint; revocation is
717
+ * best-effort, so the OAuth path resolves even if the revoke request fails,
718
+ * whereas the legacy path rejects when `/auth/logout` fails. Local state and
719
+ * storage are cleared in both cases.
720
+ *
711
721
  * @public
712
722
  */
713
723
  declare const logout: BoundStoreAction<AuthStoreState, [], Promise<void>>;
@@ -736,9 +746,14 @@ declare const startOAuthAuthorization: BoundStoreAction<AuthStoreState, [], Prom
736
746
  * responses, exchanges the authorization `code` for tokens, persists them, and
737
747
  * transitions to `LOGGED_IN`.
738
748
  *
739
- * Returns the callback URL cleaned of OAuth params (for the caller to
740
- * `history.replaceState`) when a callback was processed, or `false` when there
741
- * was nothing to handle (no code, or an exchange already in progress).
749
+ * Returns the URL for the caller to `history.replaceState` to when a callback
750
+ * was processed: on success, the same-origin location the user was on when
751
+ * the flow started (if any), otherwise the callback URL cleaned of OAuth
752
+ * params. Returns `false` when there was nothing to handle (no code, or an
753
+ * exchange already in progress). A callback that fails validation while a
754
+ * session is already `LOGGED_IN` (e.g. a remount before the params were
755
+ * stripped) is ignored with a warning and still returns the cleaned URL, so a
756
+ * string result does not imply an exchange ran.
742
757
  *
743
758
  * @public
744
759
  */
@@ -3615,4 +3630,4 @@ declare const getIsInDashboardState: BoundStoreAction<AuthStoreState, [], StateS
3615
3630
  */
3616
3631
  declare const setAuthToken: BoundStoreAction<AuthStoreState, [token: string | null], void>;
3617
3632
  export { project as $, publishDocument as $n, refreshOAuthTokens as $r, ApplyDocumentActionsOptions as $t, loadMoreUsers as A, CacheWriter as Ai, CreateReleaseAction as An, RemoveCommentOptions as Ar, OrganizationsOptions as At, getQueryState as B, BoundStoreAction as Bi, ReleaseAction as Bn, CommentLocalState as Br, InstallationBase as Bt, slicePath$1 as C, application as Ci, ProcessMutationsOptions as Cn, getCommentThreadsState as Cr, ResolveUsersOptions as Ct, getCorsErrorProjectId as D, AccessResourceType as Di, Action as Dn, resolveCommentThreads as Dr, UsersGroupState as Dt, isImportError as E, updateApplication as Ei, JsonMatch as En, parseCommentsOptionsKey as Er, UserProfile as Et, ReleaseState as F, MutationResult as Fi, EditDocumentAction as Fn, removeComment as Fr, OrganizationOptions as Ft, resolveProjection as G, archiveRelease as Gn, CommentTextSelectionItem as Gr, installations as Gt, resolveQuery as H, UnarchiveReleaseAction as Hn, CommentReaction as Hr, InstallationsOptions as Ht, getActiveReleasesState as I, defineFetcher as Ii, EditDocumentOptions as In, replyToComment as Ir, organization as It, ProjectBase as J, deleteDocument as Jn, ClientStoreState as Jr, SetFavoriteInput as Jt, getProjectionState as K, createDocument as Kn, CommentThread as Kr, FavoriteDocumentContext as Kt, getAllReleasesState as L, defineMutation as Li, EditReleaseAction as Ln, setCommentStatus as Lr, Installation as Lt, resolveUsers as M, FetcherDefinition as Mi, DeleteReleaseAction as Mn, SetCommentStatusOptions as Mr, Organization as Mt, defineProjection as N, FetcherSnapshot as Ni, DiscardDocumentAction as Nn, UpdateCommentOptions as Nr, OrganizationBase as Nt, getUserState as O, checkPermissions as Oi, ArchiveReleaseAction as On, resolveComments as Or, UsersStoreState as Ot, getPerspectiveState as P, MutationDefinition as Pi, DocumentAction as Pn, createComment as Pr, OrganizationMember as Pt, ProjectOptions as Q, editRelease as Qn, handleOAuthCallback as Qr, ActionsResult as Qt, QueryOptions as R, Selector as Ri, PublishDocumentAction as Rn, updateComment as Rr, InstallationAccess as Rt, jsonMatch$1 as S, UpdateApplicationInput as Si, DocumentSet as Sn, ResolveCommentsOptions as Sr, ResolveUserOptions as St, CORE_SDK_VERSION as T, deleteApplication as Ti, processMutations as Tn, getCommentsState as Tr, SanityUserResponse as Tt, ProjectsOptions as U, UnpublishDocumentAction as Un, CommentStatus as Ur, InstallationsResponse as Ut, parseQueryKey as V, ScheduleReleaseAction as Vn, CommentMessage as Vr, InstallationInclude as Vt, projects as W, UnscheduleReleaseAction as Wn, CommentTextSelection as Wr, installation as Wt, ProjectMemberRole as X, discardDocument as Xn, getClientState as Xr, setFavorite as Xt, ProjectMember as Y, deleteRelease as Yn, getClient as Yr, favorites as Yt, ProjectMetadata as Z, editDocument as Zn, getOAuthTokensState as Zr, getReleaseDocumentId as Zt, SanityDocument$3 as _, ApplicationWorkspace as _i, resolveDocument as _n, createDatasetHandle as _r, TransportEvent as _t, LoggedOutAuthState as a, observeOrganizationVerificationState as ai, DocumentEditedEvent as an, ResolveDocument as ar, getPresence as at, getPathDepth as b, DeleteApplicationInput as bi, DocumentPermissionsResult as bn, createProjectHandle as br, GetUsersOptions as bt, getCurrentUserState as c, Application as ci, DocumentRemotePatchesEvent as cn, datasets as cr, DocumentPresence as ct, getLoginUrlState as d, ApplicationDeployment as di, TransactionAcceptedEvent as dn, LogContext as dr, PresencePerspectiveOptions as dt, revokeOAuthTokens as ei, applyDocumentActions as en, publishRelease as er, PreviewMedia as et, getTokenState as f, ApplicationInclude as fi, TransactionRevertedEvent as fn, LogLevel as fr, PresenceSelection as ft, Role as g, ApplicationVisibility as gi, getPermissionsState as gn, createLogger as gr, StateEvent as gt, ReleaseDocument$1 as h, ApplicationStudioConfig as hi, getDocumentSyncStatus as hn, LoggerConfig as hr, RollCallEvent as ht, LoggedInAuthState as i, handleAuthCallback as ii, DocumentDiscardedEvent as in, unscheduleRelease as ir, getDocumentPresence as it, resolveUser as j, Fetcher as ji, DeleteDocumentAction as jn, ReplyToCommentOptions as jr, organizations as jt, getUsersState as k, CacheTag as ki, CreateDocumentAction as kn, CreateCommentOptions as kr, Organizations as kt, getDashboardOrganizationId as l, ApplicationAccess as li, DocumentTransactionSubmissionResult as ln, configureLogging as lr, DocumentPresenceOptions as lt, CurrentUser$1 as m, ApplicationInterfacePlacementMetadata as mi, getDocumentState as mn, Logger as mr, ReportPresenceOptions as mt, AuthStoreState as n, OAuthTokens as ni, DocumentCreatedEvent as nn, unarchiveRelease as nr, PreviewValue as nt, LoggingInAuthState as o, OrgVerificationResult as oi, DocumentEvent as on, ResolveProjectionResult as or, reportPresence as ot, setAuthToken as p, ApplicationInterface as pi, DocumentOptions as pn, LogNamespace as pr, PresenceSelectionPoint as pt, Project as q, createRelease as qn, ClientOptions as qr, FavoriteStatusResponse as qt, ErrorAuthState as r, logout as ri, DocumentDeletedEvent as rn, unpublishDocument as rr, ProjectionValuePending as rt, getAuthState as s, AuthStateType as si, DocumentPublishedEvent as sn, ResolveQueryResult as sr, DisconnectEvent as st, AuthState as t, startOAuthAuthorization as ti, ActionErrorEvent as tn, scheduleRelease as tr, PreviewQueryResult as tt, getIsInDashboardState as u, ApplicationBase as ui, DocumentUnpublishedEvent as un, InstanceContext as ur, PresenceLocation as ut, SanityProject$1 as v, ApplicationsOptions as vi, resolvePermissions as vn, createDocumentHandle as vr, UserPresence as vt, stringifyPath$1 as w, applications as wi, patchOperations as wn, getCommentsOptionsKey as wr, SanityUser as wt, joinPaths as x, DeletedResult as xi, PermissionDeniedReason as xn, CommentsOptions as xr, Membership as xt, getIndexForKey$1 as y, ApplicationsResponse as yi, subscribeDocumentEvents as yn, createDocumentTypeHandle as yr, GetUserOptions as yt, getQueryKey as z, StateSource as zi, PublishReleaseAction as zn, Comment as zr, InstallationActiveConfig as zt };
3618
- //# sourceMappingURL=authStore-BO2vch3I.d.ts.map
3633
+ //# sourceMappingURL=authStore-7dZCfKUq.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"authStore-7dZCfKUq.d.ts","names":[],"sources":["../src/store/createStoreState.ts","../src/store/defineStore.ts","../src/store/createActionBinder.ts","../src/store/createStateSourceAction.ts","../src/store/fetcherStore.ts","../src/access/checkPermissions.ts","../src/utils/includeShape.ts","../src/applications/applications.ts","../src/auth/authStateType.ts","../src/project/organizationVerification.ts","../src/auth/getOrganizationVerificationState.ts","../src/auth/handleAuthCallback.ts","../src/auth/logout.ts","../src/auth/oauth/types.ts","../src/auth/oauth/oauthActions.ts","../src/client/clientStore.ts","../src/comments/types.ts","../src/comments/commentActions.ts","../src/comments/commentsStore.ts","../src/config/handles.ts","../src/utils/logger.ts","../src/config/loggingConfig.ts","../src/datasets/datasets.ts","../src/typegen/groqCompat.ts","../src/typegen/resolve.ts","../src/document/actions.ts","../src/document/patchOperations.ts","../src/document/processMutations.ts","../src/document/permissions.ts","../src/document/sharedListener.ts","../src/document/documentStore.ts","../src/document/reducers.ts","../src/document/events.ts","../src/document/applyDocumentActions.ts","../src/document/processActions/releaseUtil.ts","../src/favorites/favorites.ts","../src/installations/installations.ts","../src/organization/organization.ts","../src/organizations/organizations.ts","../src/users/types.ts","../src/presence/types.ts","../src/presence/presenceStore.ts","../src/projection/types.ts","../src/preview/types.ts","../src/project/project.ts","../src/projection/getProjectionState.ts","../src/projection/resolveProjection.ts","../src/projects/projects.ts","../src/query/queryStore.ts","../src/releases/releasesStore.ts","../src/releases/getPerspectiveState.ts","../src/typegen/defineProjection.ts","../src/users/usersStore.ts","../src/utils/getCorsErrorProjectId.ts","../src/utils/isImportError.ts","../src/version.ts","../src/_exports/index.ts","../src/auth/authStore.ts"],"mappings":";;;;;;;;;;;;;UAOiB,WAAW;;;;;;;EAO1B,WAAW;;;;;;;;;;EAWX,MAAM,cAAc,cAAc,QAAQ,YAAY,GAAG,WAAW,QAAQ;;;;;;;;;EAU5E,YAAY,WAAW;;;;;UC7BR,aAAa,QAAQ;;;;;;;EAOpC,UAAU;;;;;;;EAQV,OAAO,WAAW;;;;EAKlB,KAAK;;;;;KCAK,YAAY,QAAQ,2BAA2B,SAAS,mBAClE,SAAS,aAAa,QAAQ,UAC3B,QAAQ,YACR;;;;KAKO,iBAAiB,SAAS,2BAA2B,YAC/D,UAAU,mB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;;;KCFD,kBAAgB;;;;;;KCuBhB,YAAY,oBAAoB,qBAAqB,qBAAqB;;;;;KAM1E;EACV,MAAM,cAAc;EACpB;EACA,aAAa;EACb;;;;;;KAOU;EAAsB,MAAM,cAAc;EAAY;;;;;;KAMtD;EAAsB,MAAM,cAAc;EAAY;;;;;;KAMtD;EAAkB,MAAM,cAAc;EAAO;;;;;;;UAOxC;EACf;EACA;EACA;;;;;;KAOU;;;;UAOK;EACf,WAAW;EACX,YAAY;EACZ;IACE;IACA,gBAAgB,QAAQ,iBAAiB;IACzC,iBAAiB;IACjB;IACA,aAAa;IACb;IACA;IACA;IACA;IACA,YAAY;IACZ,OAAO;;EAET,mBAAmB;EACnB,cAAc;;;;;cAkJH,qBAAmB,iBAAA,oBAAA,YAAA;;;;cAUnB,eAAa,iBAAA,oBAAA;;;;cAkBb,kBAAgB,iBAAA,oBAAA;;;;cAQhB,cAAY,iBAAA,oBAAA,YAAA;;;;cAQZ,4BAA0B,iBAAA,oBAAA;;;;;cAS1B,uBAAqB,iBAAA,oBAAA;;;;;;cAcrB,cAAY,iBAAA,iBAAA"}
@@ -573,9 +573,13 @@ function initializeDashboardAuth(context, tokenRefresherRunning) {
573
573
  tokenRefresherStarted: startedRefresher
574
574
  };
575
575
  }
576
+ /** localStorage (or configured `storageArea`) key for persisted OAuth tokens. */
577
+ const OAUTH_TOKENS_KEY = "__sanity_oauth_tokens";
576
578
  /**
577
579
  * Parses persisted token JSON back into {@link OAuthTokens}. Returns `null`
578
- * when the value is missing or malformed.
580
+ * when the value is missing or malformed, including an `expiresAt` that does
581
+ * not parse to a valid date (an `Invalid Date` would otherwise read as never
582
+ * expiring, since `NaN <= now` is always `false`).
579
583
  *
580
584
  * @internal
581
585
  */
@@ -584,12 +588,12 @@ function deserializeTokens(raw) {
584
588
  try {
585
589
  let parsed = JSON.parse(raw);
586
590
  if (typeof parsed != "object" || !parsed || !("accessToken" in parsed) || typeof parsed.accessToken != "string" || !("expiresAt" in parsed) || typeof parsed.expiresAt != "string") return null;
587
- let value = parsed;
588
- return {
591
+ let value = parsed, expiresAt = new Date(value.expiresAt);
592
+ return Number.isNaN(expiresAt.getTime()) ? null : {
589
593
  accessToken: value.accessToken,
590
594
  tokenType: "bearer",
591
595
  expiresIn: value.expiresIn,
592
- expiresAt: new Date(value.expiresAt),
596
+ expiresAt,
593
597
  ...value.refreshToken !== void 0 && { refreshToken: value.refreshToken }
594
598
  };
595
599
  } catch {
@@ -601,15 +605,15 @@ function deserializeTokens(raw) {
601
605
  *
602
606
  * State discovery order:
603
607
  * 1. Persisted tokens in `__sanity_oauth_tokens` → `LOGGED_IN`
604
- * 2. Callback URL (contains `code`/`state`/`error` and matches `redirectUri`)
608
+ * 2. Callback URL (contains `code` or `error` and matches `redirectUri`)
605
609
  * → `LOGGING_IN`
606
610
  * 3. Otherwise → `LOGGED_OUT`
607
611
  *
608
612
  * @internal
609
613
  */
610
614
  function getOauthInitialState(options) {
611
- let { authConfig, initialLocationHref } = options, storageKey = "__sanity_oauth_tokens", storageArea = authConfig.storageArea ?? getDefaultStorage(), redirectUri = authConfig.oauth?.redirectUri, tokens = deserializeTokens(storageArea?.getItem("__sanity_oauth_tokens") ?? null);
612
- if (tokens) return {
615
+ let { authConfig, initialLocationHref } = options, storageKey = OAUTH_TOKENS_KEY, storageArea = authConfig.storageArea ?? getDefaultStorage(), redirectUri = authConfig.oauth?.redirectUri, rawTokens = storageArea?.getItem("__sanity_oauth_tokens") ?? null, tokens = deserializeTokens(rawTokens);
616
+ if (rawTokens && !tokens && storageArea?.removeItem(OAUTH_TOKENS_KEY), tokens) return {
613
617
  authState: createLoggedInAuthState(tokens.accessToken, null),
614
618
  storageKey,
615
619
  storageArea,
@@ -617,7 +621,7 @@ function getOauthInitialState(options) {
617
621
  dashboardContext: {},
618
622
  oauthTokens: tokens
619
623
  };
620
- let { searchParams } = new URL(initialLocationHref, DEFAULT_BASE), isCallback = searchParams.has("code") || searchParams.has("state") || searchParams.has("error");
624
+ let { searchParams } = new URL(initialLocationHref, DEFAULT_BASE), isCallback = searchParams.has("code") || searchParams.has("error");
621
625
  if (redirectUri && isCallback) {
622
626
  let loc = new URL(initialLocationHref, DEFAULT_BASE), redirect = new URL(redirectUri, DEFAULT_BASE);
623
627
  if (loc.origin === redirect.origin && loc.pathname === redirect.pathname) return {
@@ -1005,7 +1009,7 @@ const authStore = defineStore({
1005
1009
  storageKey: result.storageKey,
1006
1010
  storageArea: result.storageArea,
1007
1011
  authMethod: result.authMethod,
1008
- oauth: authConfig.oauth
1012
+ oauth: mode === "oauth" ? authConfig.oauth : void 0
1009
1013
  }
1010
1014
  };
1011
1015
  },
@@ -1126,4 +1130,4 @@ const allowedKeys = Object.keys({
1126
1130
  }), getClientState = bindActionGlobally(clientStore, createStateSourceAction(({ instance }, options) => getClient(instance, options)));
1127
1131
  export { __exportAll as A, isStudioConfig as C, getAuthLogger as D, REQUEST_TAG_PREFIX as E, configureLogging as O, AuthStateType as S, DEFAULT_BASE as T, getClientErrorApiDescription as _, authStore_exports as a, getTokenFromLocation as b, getDashboardOrganizationId as c, getTokenState as d, setAuthToken as f, getClientErrorApiBody as g, getCleanedUrl as h, authStore as i, createLogger as k, getIsInDashboardState as l, getAuthCode as m, getClient as n, getAuthState as o, createLoggedInAuthState as p, getClientState as r, getCurrentUserState as s, clientStore_exports as t, getLoginUrlState as u, getClientErrorApiType as v, DEFAULT_API_VERSION$1 as w, isProjectUserNotFoundClientError as x, getDefaultLocation as y };
1128
1132
 
1129
- //# sourceMappingURL=clientStore-BI4D8HhJ.js.map
1133
+ //# sourceMappingURL=clientStore-QDrJNTM4.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"clientStore-QDrJNTM4.js","names":["DEFAULT_API_VERSION","DEFAULT_API_VERSION","DEFAULT_API_VERSION"],"sources":["../src/utils/logger.ts","../src/utils/getStagingApiHost.ts","../src/auth/authLogger.ts","../src/auth/authConstants.ts","../src/auth/authMode.ts","../src/auth/authStateType.ts","../src/auth/refreshStampedToken.ts","../src/auth/subscribeToStateAndFetchCurrentUser.ts","../src/auth/utils.ts","../src/auth/dashboardAuth.ts","../src/auth/oauth/oauthAuth.ts","../src/auth/subscribeToStorageEventsAndSetToken.ts","../src/auth/standaloneAuth.ts","../src/auth/studioModeAuth.ts","../src/auth/studioAuth.ts","../src/auth/authStore.ts","../src/client/clientStore.ts"],"sourcesContent":["/**\n * Logging infrastructure for the Sanity SDK\n *\n * Provides multi-level, namespace-based logging for both SDK users and maintainers.\n * In production builds, all logging can be stripped via tree-shaking.\n *\n * @example SDK User\n * ```ts\n * import {configureLogging} from '@sanity/sdk'\n *\n * configureLogging({\n * level: 'info',\n * namespaces: ['auth', 'document']\n * })\n * ```\n *\n * @example SDK Maintainer\n * ```ts\n * configureLogging({\n * level: 'trace',\n * namespaces: ['*'],\n * internal: true\n * })\n * ```\n */\n\n/**\n * Log levels in order of verbosity (least to most)\n * - error: Critical failures that prevent operation\n * - warn: Issues that may cause problems but don't stop execution\n * - info: High-level informational messages (SDK user level)\n * - debug: Detailed debugging information (maintainer level)\n * - trace: Very detailed tracing (maintainer level, includes RxJS streams)\n * @public\n */\nexport type LogLevel = 'error' | 'warn' | 'info' | 'debug' | 'trace'\n\n/**\n * Log namespaces organize logs by functional domain\n *\n * @remarks\n * This is an extensible string type. As logging is added to more modules,\n * additional namespaces will be recognized. Currently implemented namespaces\n * will be documented as they are added.\n * @internal\n */\nexport type LogNamespace = string\n\n/**\n * Configuration for the logging system\n * @public\n */\nexport interface LoggerConfig {\n /**\n * Minimum log level to output\n * @defaultValue 'warn'\n */\n level?: LogLevel\n\n /**\n * Namespaces to enable. Use ['*'] for all namespaces\n * @defaultValue []\n * @remarks\n * Available namespaces depend on which modules have logging integrated.\n * Check the SDK documentation for the current list of instrumented modules.\n * @example ['auth', 'document']\n */\n namespaces?: string[]\n\n /**\n * Enable internal/maintainer-level logging\n * Shows RxJS streams, store internals, etc.\n * @defaultValue false\n */\n internal?: boolean\n\n /**\n * Custom log handler (for testing or custom output)\n * @defaultValue console methods\n */\n handler?: LogHandler\n\n /**\n * Enable timestamps in log output\n * @defaultValue true\n */\n timestamps?: boolean\n\n /**\n * Enable in production builds\n * @defaultValue false\n */\n enableInProduction?: boolean\n}\n\n/**\n * Custom log handler interface\n *\n * @internal\n */\nexport interface LogHandler {\n error: (message: string, context?: LogContext) => void\n warn: (message: string, context?: LogContext) => void\n info: (message: string, context?: LogContext) => void\n debug: (message: string, context?: LogContext) => void\n trace: (message: string, context?: LogContext) => void\n}\n\n/**\n * Context object attached to log messages\n *\n * This interface allows you to attach arbitrary contextual data to log messages.\n * The index signature `[key: string]: unknown` enables you to add any custom\n * properties relevant to your log entry (e.g., `userId`, `documentId`, `action`, etc.).\n *\n * **Sensitive data sanitization:**\n * Top-level keys containing sensitive names (`token`, `password`, `secret`, `apiKey`,\n * `authorization`) are automatically redacted to `[REDACTED]` in log output.\n *\n * @example\n * ```ts\n * logger.info('User logged in', {\n * userId: '123', // Custom context\n * action: 'login', // Custom context\n * token: 'secret' // Will be redacted to [REDACTED]\n * })\n * ```\n *\n * @internal\n */\nexport interface LogContext {\n /**\n * Custom context properties that provide additional information about the log entry.\n * Any key-value pairs can be added here (e.g., userId, documentId, requestId, etc.).\n * Keys with sensitive names (token, password, secret, apiKey, authorization) are\n * automatically sanitized.\n */\n [key: string]: unknown\n /** Error object if logging an error */\n error?: Error | unknown\n /** Duration in milliseconds for timed operations */\n duration?: number\n /** Stack trace for debugging */\n stack?: string\n /** Instance context (automatically added when available) */\n instanceContext?: InstanceContext\n}\n\n/**\n * Instance context information automatically added to logs\n * @internal\n */\nexport interface InstanceContext {\n /** Unique instance ID */\n instanceId?: string\n /** Project ID */\n projectId?: string\n /** Dataset name */\n dataset?: string\n}\n\n/**\n * Logger instance for a specific namespace\n * @internal\n */\nexport interface Logger {\n readonly namespace: string\n error: (message: string, context?: LogContext) => void\n warn: (message: string, context?: LogContext) => void\n info: (message: string, context?: LogContext) => void\n debug: (message: string, context?: LogContext) => void\n trace: (message: string, context?: LogContext) => void\n /** Check if a log level is enabled (for performance-sensitive code) */\n isLevelEnabled: (level: LogLevel) => boolean\n /** Create a child logger with extended context */\n child: (context: LogContext) => Logger\n /** Get the instance context if available */\n getInstanceContext: () => InstanceContext | undefined\n}\n\n// Log level priority (lower number = higher priority)\nconst LOG_LEVEL_PRIORITY: Record<LogLevel, number> = {\n error: 0,\n warn: 1,\n info: 2,\n debug: 3,\n trace: 4,\n}\n\n// Default logging configuration\nconst DEFAULT_CONFIG: Required<LoggerConfig> = {\n level: 'warn',\n namespaces: [],\n internal: false,\n timestamps: true,\n enableInProduction: false,\n handler: {\n // eslint-disable-next-line no-console\n error: console.error.bind(console),\n // eslint-disable-next-line no-console\n warn: console.warn.bind(console),\n // eslint-disable-next-line no-console\n info: console.info.bind(console),\n // eslint-disable-next-line no-console\n debug: console.debug.bind(console),\n // eslint-disable-next-line no-console\n trace: console.debug.bind(console), // trace uses console.debug\n },\n}\n\n/**\n * Parse DEBUG environment variable for automatic logging configuration\n *\n * Supports patterns similar to Sanity CLI/Studio:\n * - DEBUG=sanity:* (all namespaces, debug level)\n * - DEBUG=sanity:auth,sanity:document (specific namespaces)\n * - DEBUG=sanity:trace:* (all namespaces, trace level)\n * - DEBUG=sanity:*:internal (enable internal logs)\n *\n * @internal\n */\nexport function parseDebugEnvVar(): Partial<LoggerConfig> | null {\n if (typeof process === 'undefined' || !process.env?.['DEBUG']) {\n return null\n }\n\n const debug = process.env['DEBUG']\n\n // Only process if it includes 'sanity'\n if (!debug.includes('sanity')) {\n return null\n }\n\n const config: Partial<LoggerConfig> = {}\n\n // Parse level from pattern like \"sanity:trace:*\" or \"sanity:debug:*\"\n const levelMatch = debug.match(/sanity:(trace|debug|info|warn|error):/)\n const hasLevelSpecifier = !!levelMatch\n if (levelMatch) {\n config.level = levelMatch[1] as LogLevel\n } else {\n // Default to debug level if just \"sanity:*\" or \"sanity:namespace\"\n config.level = 'debug'\n }\n\n // Parse namespaces\n if (debug === 'sanity') {\n config.namespaces = ['*']\n } else if (hasLevelSpecifier && debug.match(/sanity:(trace|debug|info|warn|error):\\*/)) {\n // Pattern like \"sanity:trace:*\" - wildcard after level\n config.namespaces = ['*']\n } else if (!hasLevelSpecifier && debug.includes('sanity:*')) {\n // Pattern like \"sanity:*\" - wildcard without level\n config.namespaces = ['*']\n } else {\n // Extract specific namespaces like \"sanity:auth,sanity:document\"\n const namespaces = debug\n .split(',')\n .filter((s) => s.includes('sanity:'))\n .map((s) => {\n // Remove 'sanity:' prefix\n const cleaned = s.replace(/^sanity:/, '')\n // If there's a level specifier, skip it\n if (hasLevelSpecifier && cleaned.match(/^(trace|debug|info|warn|error):/)) {\n // Get the part after the level: \"trace:auth\" -> \"auth\"\n return cleaned.split(':').slice(1).join(':')\n }\n // Otherwise get the first part: \"auth:something\" -> \"auth\"\n return cleaned.split(':')[0]\n })\n .filter(Boolean)\n .filter((ns) => ns !== '*') // Filter out wildcards\n\n if (namespaces.length > 0) {\n config.namespaces = namespaces\n }\n }\n\n // Check for internal flag: DEBUG=sanity:*:internal\n if (debug.includes(':internal')) {\n config.internal = true\n }\n\n return config\n}\n\n// Global configuration - initialized with env var settings if present\nconst envConfig = parseDebugEnvVar()\nlet globalConfig: Required<LoggerConfig> = {\n ...DEFAULT_CONFIG,\n ...(envConfig ?? {}),\n}\n\n// Log that env var configuration was detected (only if DEBUG is set)\n// Note: This runs at module initialization, difficult to test without complex module mocking\n/* c8 ignore next 14 */\nif (envConfig) {\n const shouldLog =\n ['info', 'debug', 'trace'].includes(globalConfig.level) || globalConfig.level === 'warn'\n if (shouldLog) {\n // eslint-disable-next-line no-console\n console.info(\n `[${new Date().toISOString()}] [INFO] [sdk] Logging auto-configured from DEBUG environment variable`,\n {\n level: globalConfig.level,\n namespaces: globalConfig.namespaces,\n internal: globalConfig.internal,\n source: 'env:DEBUG',\n value: typeof process !== 'undefined' ? process.env?.['DEBUG'] : undefined,\n },\n )\n }\n}\n\n/**\n * Configure the global logging system\n * @public\n */\nexport function configureLogging(config: LoggerConfig): void {\n globalConfig = {\n ...globalConfig,\n ...config,\n handler: config.handler ?? globalConfig.handler,\n }\n}\n\n/**\n * Get the current logging configuration\n * @internal\n */\nexport function getLoggingConfig(): Readonly<Required<LoggerConfig>> {\n return globalConfig\n}\n\n/**\n * Reset logging to default configuration\n * @internal\n */\nexport function resetLogging(): void {\n globalConfig = {...DEFAULT_CONFIG}\n}\n\n/**\n * Check if logging is enabled in the current environment\n * @internal\n */\nfunction isLoggingEnabled(): boolean {\n // In production, only log if explicitly enabled\n if (typeof process !== 'undefined' && process.env?.['NODE_ENV'] === 'production') {\n return globalConfig.enableInProduction\n }\n return true\n}\n\n/**\n * Check if a namespace is enabled\n * @internal\n */\nfunction isNamespaceEnabled(namespace: string): boolean {\n if (!isLoggingEnabled()) return false\n if (globalConfig.namespaces.includes('*')) return true\n return globalConfig.namespaces.includes(namespace)\n}\n\n/**\n * Check if a log level is enabled\n * @internal\n */\nfunction isLevelEnabled(level: LogLevel): boolean {\n if (!isLoggingEnabled()) return false\n return LOG_LEVEL_PRIORITY[level] <= LOG_LEVEL_PRIORITY[globalConfig.level]\n}\n\n/**\n * Format a log message with timestamp, namespace, and instance context\n * @internal\n */\nfunction formatMessage(\n namespace: LogNamespace,\n level: LogLevel,\n message: string,\n context?: LogContext,\n): [string, LogContext | undefined] {\n const parts: string[] = []\n\n if (globalConfig.timestamps) {\n const timestamp = new Date().toISOString()\n parts.push(`[${timestamp}]`)\n }\n\n parts.push(`[${level.toUpperCase()}]`)\n parts.push(`[${namespace}]`)\n\n // Add instance context if available\n const instanceContext = context?.instanceContext\n if (instanceContext) {\n if (instanceContext.projectId) {\n parts.push(`[project:${instanceContext.projectId}]`)\n }\n if (instanceContext.dataset) {\n parts.push(`[dataset:${instanceContext.dataset}]`)\n }\n if (instanceContext.instanceId) {\n parts.push(`[instance:${instanceContext.instanceId.slice(0, 8)}]`)\n }\n }\n\n parts.push(message)\n\n return [parts.join(' '), context]\n}\n\n/**\n * Sanitize context for logging (remove sensitive data)\n * @internal\n * @remarks\n * This performs shallow sanitization only - it redacts top-level keys that contain\n * sensitive names (token, password, secret, apiKey, authorization).\n * Nested sensitive data (e.g., `\\{auth: \\{token: 'secret'\\}\\}`) will NOT be redacted.\n * If deep sanitization is needed in the future, this can be enhanced to recursively\n * traverse nested objects.\n */\nfunction sanitizeContext(context?: LogContext): LogContext | undefined {\n if (!context || Object.keys(context).length === 0) return undefined\n\n const sanitized = {...context}\n\n // Remove or redact sensitive fields at the top level\n const sensitiveKeys = ['token', 'password', 'secret', 'apiKey', 'authorization']\n for (const key of Object.keys(sanitized)) {\n if (sensitiveKeys.some((sensitive) => key.toLowerCase().includes(sensitive))) {\n sanitized[key] = '[REDACTED]'\n }\n }\n\n return sanitized\n}\n\n/**\n * Create a logger for a specific namespace\n * @param namespace - A string identifier for the logging domain (e.g., 'auth', 'document')\n * @param baseContext - Optional base context to include in all log messages\n * @remarks\n * If baseContext includes an `instanceContext` property (with projectId, dataset, instanceId),\n * it will be automatically formatted into the log output for easier debugging of\n * multi-instance scenarios.\n * @public\n */\nexport function createLogger(namespace: string, baseContext?: LogContext): Logger {\n const logAtLevel = (level: LogLevel, message: string, context?: LogContext) => {\n // Early return if namespace or level not enabled\n if (!isNamespaceEnabled(namespace)) return\n if (!isLevelEnabled(level)) return\n\n // Skip internal logs if not enabled\n if (context?.['internal'] && !globalConfig.internal) return\n\n const mergedContext = {...baseContext, ...context}\n const sanitized = sanitizeContext(mergedContext)\n const [formatted, finalContext] = formatMessage(namespace, level, message, sanitized)\n\n globalConfig.handler[level](formatted, finalContext)\n }\n\n const logger: Logger = {\n namespace,\n error: (message, context) => logAtLevel('error', message, context),\n warn: (message, context) => logAtLevel('warn', message, context),\n info: (message, context) => logAtLevel('info', message, context),\n debug: (message, context) => logAtLevel('debug', message, context),\n trace: (message, context) => logAtLevel('trace', message, {...context, internal: true}),\n isLevelEnabled: (level) => isNamespaceEnabled(namespace) && isLevelEnabled(level),\n child: (childContext) => createLogger(namespace, {...baseContext, ...childContext}),\n getInstanceContext: () => baseContext?.instanceContext,\n }\n\n return logger\n}\n\n/**\n * Create a performance timer for measuring operation duration\n * @internal\n */\nexport function createTimer(\n namespace: string,\n operation: string,\n): {end: (message?: string, context?: LogContext) => number} {\n const logger = createLogger(namespace)\n const start = performance.now()\n\n return {\n end: (message?: string, context?: LogContext): number => {\n const duration = performance.now() - start\n logger.debug(message ?? `${operation} completed`, {\n ...context,\n operation,\n duration,\n })\n return duration\n },\n }\n}\n\n/**\n * Utility to log RxJS operator execution (for maintainers)\n * Will be exported in future PR when logging is added to stores\n * @internal\n */\n/* c8 ignore next 4 */\nfunction logRxJSOperator(namespace: string, operator: string, context?: LogContext): void {\n const logger = createLogger(namespace)\n logger.trace(`RxJS: ${operator}`, {...context, internal: true, operator})\n}\n\n/**\n * Extract instance context from a SanityInstance for logging\n * Will be exported in future PR when logging is added to stores\n * @param instance - The SanityInstance to extract context from\n * @returns Instance context suitable for logging\n * @internal\n */\n/* c8 ignore next 7 */\nfunction getInstanceContext(instance: {\n instanceId?: string\n config?: {projectId?: string; dataset?: string}\n}): InstanceContext {\n return {\n instanceId: instance.instanceId,\n projectId: instance.config?.projectId,\n dataset: instance.config?.dataset,\n }\n}\n\n// Prevent unused function warnings - these will be exported and used in future PRs\n/* c8 ignore next 2 */\nvoid logRxJSOperator\nvoid getInstanceContext\n","declare const __SANITY_STAGING__: boolean | undefined\n\n/**\n * Returns the staging API host if the `__SANITY_STAGING__` build-time flag is\n * set to `true` (mirroring how Sanity Studio detects staging builds).\n *\n * @internal\n */\nexport function getStagingApiHost(): string | undefined {\n if (typeof __SANITY_STAGING__ !== 'undefined' && __SANITY_STAGING__ === true) {\n return 'https://api.sanity.work'\n }\n return undefined\n}\n","import {type SanityInstance} from '../store/createSanityInstance'\nimport {createLogger, type Logger} from '../utils/logger'\n\nconst loggers = new WeakMap<SanityInstance, Logger>()\n\n/**\n * Returns the auth logger for a Sanity instance, creating it on first use.\n *\n * The logger is cached per instance so repeated action calls (logout,\n * setAuthToken, handleAuthCallback) reuse the same logger instead of\n * rebuilding it. The instance details are nested under `instanceContext`,\n * which is what the logger's formatter reads to render the\n * `[project:x] [dataset:y] [instance:z]` prefix.\n *\n * @internal\n */\nexport function getAuthLogger(instance: SanityInstance): Logger {\n let logger = loggers.get(instance)\n if (!logger) {\n logger = createLogger('auth', {\n instanceContext: {\n instanceId: instance.instanceId,\n projectId: instance.config.projectId,\n dataset: instance.config.dataset,\n },\n })\n loggers.set(instance, logger)\n }\n return logger\n}\n","export const DEFAULT_BASE = 'http://localhost'\nexport const AUTH_CODE_PARAM = 'sid'\nexport const DEFAULT_API_VERSION = '2021-06-07'\nexport const REQUEST_TAG_PREFIX = 'sanity.sdk.auth'\n","import {type SanityConfig} from '../config/sanityConfig'\nimport {DEFAULT_BASE} from './authConstants'\n\n/**\n * The runtime auth mode determines which authentication strategy the SDK uses.\n *\n * - `studio` — Running inside Sanity Studio. Token is discovered from\n * Studio's localStorage entry or via cookie auth.\n * - `oauth` — Configured with `auth.oauth`. Authenticates via Sanity's\n * OAuth 2.0 authorization-code + PKCE flow.\n * - `dashboard` — Running inside the Sanity Dashboard iframe. Token is\n * provided by the parent frame via Comlink.\n * - `standalone` — Running as an independent app. Token comes from\n * localStorage or the OAuth login flow.\n *\n * @internal\n */\ntype AuthMode = 'studio' | 'oauth' | 'dashboard' | 'standalone'\n\n/**\n * Determines the auth mode from instance config and environment.\n *\n * Priority:\n * 1. `studio` config provided → `'studio'`\n * 2. `auth.oauth` config provided → `'oauth'` (explicit config wins over\n * environment detection)\n * 3. Dashboard context detected (`_context` URL param with content) → `'dashboard'`\n * 4. Otherwise → `'standalone'`\n *\n * @internal\n */\nexport function resolveAuthMode(config: SanityConfig, locationHref: string): AuthMode {\n if (isStudioConfig(config)) return 'studio'\n if (config.auth?.oauth) return 'oauth'\n if (detectDashboardContext(locationHref)) return 'dashboard'\n return 'standalone'\n}\n\n/**\n * Returns `true` when the config indicates the SDK is running inside a Studio.\n *\n * @internal\n */\nexport function isStudioConfig(config: SanityConfig): boolean {\n return !!config.studio\n}\n\n/**\n * Checks whether the given location href contains a `_context` URL parameter\n * with a non-empty JSON object, indicating the SDK is running inside the\n * Sanity Dashboard.\n *\n * @internal\n */\nfunction detectDashboardContext(locationHref: string): boolean {\n try {\n const parsedUrl = new URL(locationHref, DEFAULT_BASE)\n const contextParam = parsedUrl.searchParams.get('_context')\n if (!contextParam) return false\n\n const parsed: unknown = JSON.parse(contextParam)\n return (\n typeof parsed === 'object' &&\n parsed !== null &&\n !Array.isArray(parsed) &&\n Object.keys(parsed as Record<string, unknown>).length > 0\n )\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error('Failed to parse dashboard context from initial location:', err)\n return false\n }\n}\n","/**\n * Represents the various states the authentication type can be in.\n *\n * @public\n */\nexport enum AuthStateType {\n LOGGED_IN = 'logged-in',\n LOGGING_IN = 'logging-in',\n ERROR = 'error',\n LOGGED_OUT = 'logged-out',\n}\n","import {\n distinctUntilChanged,\n exhaustMap,\n filter,\n map,\n Observable,\n type Subscription,\n switchMap,\n takeWhile,\n timer,\n} from 'rxjs'\n\nimport {type StoreContext} from '../store/defineStore'\nimport {DEFAULT_API_VERSION, REQUEST_TAG_PREFIX} from './authConstants'\nimport {getAuthLogger} from './authLogger'\nimport {AuthStateType} from './authStateType'\nimport {type AuthState, type AuthStoreState} from './authStore'\n\nconst REFRESH_INTERVAL = 12 * 60 * 60 * 1000 // 12 hours in milliseconds\n\nfunction createTokenRefreshStream(\n token: string,\n clientFactory: AuthStoreState['options']['clientFactory'],\n apiHost: string | undefined,\n): Observable<{token: string}> {\n return new Observable((subscriber) => {\n const client = clientFactory({\n apiVersion: DEFAULT_API_VERSION,\n requestTagPrefix: REQUEST_TAG_PREFIX,\n useProjectHostname: false,\n useCdn: false,\n token,\n ignoreBrowserTokenWarning: true,\n ...(apiHost && {apiHost}),\n })\n\n const subscription = client.observable\n .request<{token: string}>({\n url: 'auth/refresh-token',\n method: 'POST',\n tag: 'refresh-token',\n body: {\n token,\n },\n })\n .subscribe(subscriber)\n\n return () => subscription.unsubscribe()\n })\n}\n\nfunction shouldRefreshToken(lastRefresh: number | undefined): boolean {\n if (!lastRefresh) return true\n const timeSinceLastRefresh = Date.now() - lastRefresh\n return timeSinceLastRefresh >= REFRESH_INTERVAL\n}\n\n/**\n * Periodically refreshes stamped auth tokens (those containing `-st`).\n *\n * Two triggers cause a refresh while the user stays logged in:\n * - a 12-hour interval timer (only fires while the tab is visible)\n * - the tab becoming visible again after `lastTokenRefresh` has gone stale\n *\n * Non-stamped tokens (e.g. personal access tokens) are never refreshed.\n *\n * @internal\n */\nexport const refreshStampedToken = ({\n state,\n instance,\n}: StoreContext<AuthStoreState>): Subscription => {\n const logger = getAuthLogger(instance)\n\n const {clientFactory, apiHost, storageArea, storageKey} = state.get().options\n\n const refreshToken$ = state.observable.pipe(\n map((storeState) => storeState.authState),\n filter(\n (authState): authState is Extract<AuthState, {type: AuthStateType.LOGGED_IN}> =>\n authState.type === AuthStateType.LOGGED_IN,\n ),\n distinctUntilChanged((prev, curr) => prev.token === curr.token),\n filter((authState) => authState.token.includes('-st')), // Ensure we only try to refresh stamped tokens\n exhaustMap(() =>\n new Observable<{token: string}>((subscriber) => {\n const visibilityHandler = () => {\n const currentState = state.get()\n if (\n document.visibilityState === 'visible' &&\n currentState.authState.type === AuthStateType.LOGGED_IN &&\n shouldRefreshToken(currentState.authState.lastTokenRefresh)\n ) {\n createTokenRefreshStream(\n currentState.authState.token,\n clientFactory,\n apiHost,\n ).subscribe({\n next: (response) => {\n state.set('setRefreshStampedToken', (prev) => ({\n authState:\n prev.authState.type === AuthStateType.LOGGED_IN\n ? {\n ...prev.authState,\n token: response.token,\n lastTokenRefresh: Date.now(),\n }\n : prev.authState,\n }))\n subscriber.next(response)\n },\n error: (error) => subscriber.error(error),\n })\n }\n }\n\n const timerSubscription = timer(REFRESH_INTERVAL, REFRESH_INTERVAL)\n .pipe(\n filter(() => document.visibilityState === 'visible'),\n switchMap(() => {\n const currentState = state.get().authState\n if (currentState.type !== AuthStateType.LOGGED_IN) {\n throw new Error('User logged out before refresh could complete')\n }\n return createTokenRefreshStream(currentState.token, clientFactory, apiHost)\n }),\n )\n .subscribe({\n next: (response) => {\n state.set('setRefreshStampedToken', (prev) => ({\n authState:\n prev.authState.type === AuthStateType.LOGGED_IN\n ? {\n ...prev.authState,\n token: response.token,\n lastTokenRefresh: Date.now(),\n }\n : prev.authState,\n }))\n subscriber.next(response)\n },\n error: (error) => subscriber.error(error),\n })\n\n document.addEventListener('visibilitychange', visibilityHandler)\n\n return () => {\n document.removeEventListener('visibilitychange', visibilityHandler)\n timerSubscription.unsubscribe()\n }\n }).pipe(\n takeWhile(() => state.get().authState.type === AuthStateType.LOGGED_IN),\n map((response: {token: string}) => ({token: response.token})),\n ),\n ),\n )\n\n return refreshToken$.subscribe({\n next: (response: {token: string}) => {\n logger.debug('Token refresh completed, updating state')\n state.set('setRefreshStampedToken', (prev) => ({\n authState:\n prev.authState.type === AuthStateType.LOGGED_IN\n ? {\n ...prev.authState,\n token: response.token,\n lastTokenRefresh: Date.now(),\n }\n : prev.authState,\n }))\n storageArea?.setItem(storageKey, JSON.stringify({token: response.token}))\n },\n error: (error) => {\n logger.error('Token refresh failed', {error})\n state.set('setRefreshStampedTokenError', {authState: {type: AuthStateType.ERROR, error}})\n },\n })\n}\n","import {type CurrentUser} from '@sanity/types'\nimport {\n catchError,\n distinctUntilChanged,\n EMPTY,\n filter,\n map,\n type Subscription,\n switchMap,\n} from 'rxjs'\n\nimport {type StoreContext} from '../store/defineStore'\nimport {DEFAULT_API_VERSION, REQUEST_TAG_PREFIX} from './authConstants'\nimport {getAuthLogger} from './authLogger'\nimport {isStudioConfig} from './authMode'\nimport {AuthStateType} from './authStateType'\nimport {type AuthMethodOptions, type AuthState, type AuthStoreState} from './authStore'\n\n/**\n * Subscribes to auth state changes and fetches the current user when\n * the state transitions to `LOGGED_IN` without a `currentUser`.\n *\n * @param context - The store context for the auth store.\n * @param fetchOptions - Configuration options. When `useProjectHostname` is\n * `true`, requests use the project-specific hostname (required for Studio\n * cookie auth). Set to `true` for studio mode, `false` otherwise.\n *\n * @internal\n */\nexport const subscribeToStateAndFetchCurrentUser = (\n {state, instance}: StoreContext<AuthStoreState>,\n fetchOptions?: {useProjectHostname?: boolean},\n): Subscription => {\n const logger = getAuthLogger(instance)\n\n const {clientFactory, apiHost} = state.get().options\n const useProjectHostname = fetchOptions?.useProjectHostname ?? isStudioConfig(instance.config)\n const projectId = instance.config.projectId\n\n const currentUser$ = state.observable\n .pipe(\n map(({authState, options: storeOptions}) => ({\n authState,\n authMethod: storeOptions.authMethod,\n })),\n filter(\n (\n value,\n ): value is {\n authState: Extract<AuthState, {type: AuthStateType.LOGGED_IN}>\n authMethod: AuthMethodOptions\n } => value.authState.type === AuthStateType.LOGGED_IN && !value.authState.currentUser,\n ),\n map((value) => ({token: value.authState.token, authMethod: value.authMethod})),\n distinctUntilChanged(\n (prev, curr) => prev.token === curr.token && prev.authMethod === curr.authMethod,\n ),\n )\n .pipe(\n map(({token, authMethod}) =>\n clientFactory({\n apiVersion: DEFAULT_API_VERSION,\n requestTagPrefix: REQUEST_TAG_PREFIX,\n token: authMethod === 'cookie' ? undefined : token,\n ignoreBrowserTokenWarning: true,\n useProjectHostname,\n useCdn: false,\n ...(authMethod === 'cookie' ? {withCredentials: true} : {}),\n ...(useProjectHostname && projectId ? {projectId} : {}),\n ...(apiHost && {apiHost}),\n }),\n ),\n switchMap((client) =>\n client.observable\n .request<CurrentUser>({\n url: '/users/me',\n method: 'GET',\n tag: 'users.get-current',\n })\n .pipe(\n /**\n * Catch inside switchMap so the outer subscription survives.\n * Without this, a 401 terminates the subscription permanently\n * and subsequent token refreshes via comlink never re-fetch /users/me.\n * @see SDK-1409\n */\n catchError((error) => {\n logger.error('Failed to fetch current user', {error})\n state.set('setError', {authState: {type: AuthStateType.ERROR, error}})\n return EMPTY\n }),\n ),\n ),\n )\n\n return currentUser$.subscribe({\n next: (currentUser) => {\n logger.info('Current user fetched successfully', {\n hasEmail: !!currentUser.email,\n })\n // userId is PII, so only surface it at debug level\n logger.debug('Current user details', {userId: currentUser.id})\n state.set('setCurrentUser', (prev) => ({\n authState:\n prev.authState.type === AuthStateType.LOGGED_IN\n ? {...prev.authState, currentUser}\n : prev.authState,\n }))\n },\n })\n}\n","import {type ClientError} from '@sanity/client'\nimport {type CurrentUser} from '@sanity/types'\nimport {EMPTY, fromEvent, Observable} from 'rxjs'\n\nimport {AUTH_CODE_PARAM, DEFAULT_BASE} from './authConstants'\nimport {AuthStateType} from './authStateType'\nimport {type LoggedInAuthState} from './authStore'\n\n/**\n * Creates a properly initialized {@link LoggedInAuthState}.\n *\n * For stamped tokens (containing `\"-st\"`), `lastTokenRefresh` is set to\n * `Date.now()` so that the visibility-change handler in\n * {@link refreshStampedToken} does not trigger an unnecessary refresh the\n * first time the tab becomes visible.\n *\n * @param token - The auth token.\n * @param currentUser - The current user, or `null` if not yet fetched.\n * @param existingLastTokenRefresh - An existing timestamp to preserve\n * (e.g. when updating a token while keeping the previous refresh time).\n * @internal\n */\nexport function createLoggedInAuthState(\n token: string,\n currentUser: CurrentUser | null,\n existingLastTokenRefresh?: number,\n): LoggedInAuthState {\n const isStampedToken = token.includes('-st')\n const lastTokenRefresh = existingLastTokenRefresh ?? (isStampedToken ? Date.now() : undefined)\n\n return {\n type: AuthStateType.LOGGED_IN,\n token,\n currentUser,\n ...(lastTokenRefresh !== undefined && {lastTokenRefresh}),\n }\n}\n\nexport function getAuthCode(callbackUrl: string | undefined, locationHref: string): string | null {\n const loc = new URL(locationHref, DEFAULT_BASE)\n const callbackLocation = callbackUrl ? new URL(callbackUrl, DEFAULT_BASE) : undefined\n const callbackLocationMatches = callbackLocation\n ? loc.pathname.toLowerCase().startsWith(callbackLocation.pathname.toLowerCase())\n : true\n\n // First, try getting the auth code (sid) from hash or search params directly\n let authCode =\n new URLSearchParams(loc.hash.slice(1)).get(AUTH_CODE_PARAM) ||\n new URLSearchParams(loc.search).get(AUTH_CODE_PARAM)\n\n // If not found directly, try extracting it from the _context parameter as a fallback\n if (!authCode) {\n const contextParam = new URLSearchParams(loc.search).get('_context')\n if (contextParam) {\n try {\n const parsedContext = JSON.parse(contextParam)\n if (\n parsedContext &&\n typeof parsedContext === 'object' &&\n typeof parsedContext.sid === 'string' &&\n parsedContext.sid // Ensure it's not an empty string\n ) {\n authCode = parsedContext.sid\n }\n } catch {\n // Silently ignore _context JSON parsing errors; authCode remains null/empty\n }\n }\n }\n\n return authCode && callbackLocationMatches ? authCode : null\n}\n\nexport function getTokenFromLocation(locationHref: string): string | null {\n const loc = new URL(locationHref)\n const token = new URLSearchParams(loc.hash.slice(1)).get('token')\n return token ? token : null\n}\n\n/**\n * Attempts to retrieve a token from the configured storage.\n * If invalid or not present, returns null.\n */\nexport function getTokenFromStorage(\n storageArea: Storage | undefined,\n storageKey: string,\n): string | null {\n if (!storageArea) return null\n const item = storageArea.getItem(storageKey)\n if (item === null) return null\n\n try {\n const parsed: unknown = JSON.parse(item)\n if (\n typeof parsed !== 'object' ||\n parsed === null ||\n !('token' in parsed) ||\n typeof parsed.token !== 'string'\n ) {\n throw new Error('Invalid stored auth data structure')\n }\n return parsed.token\n } catch {\n storageArea.removeItem(storageKey)\n return null\n }\n}\n\n/**\n * Creates an observable stream of storage events. If not in a browser environment,\n * returns an EMPTY observable.\n */\nexport function getStorageEvents(): Observable<StorageEvent> {\n const isBrowser = typeof window !== 'undefined' && typeof window.addEventListener === 'function'\n\n if (!isBrowser) {\n return EMPTY\n }\n\n return fromEvent<StorageEvent>(window, 'storage')\n}\n\n/**\n * Returns a default storage instance (localStorage) if available.\n * If not available or an error occurs, returns undefined.\n */\nexport function getDefaultStorage(): Storage | undefined {\n try {\n if (typeof localStorage !== 'undefined' && typeof localStorage.getItem === 'function') {\n return localStorage\n }\n return undefined\n } catch {\n return undefined\n }\n}\n\n/**\n * Returns the default location to use.\n * Tries accessing `location.href`, falls back to a default base if not available or on error.\n */\nexport function getDefaultLocation(): string {\n try {\n if (typeof location === 'undefined') return DEFAULT_BASE\n if (typeof location.href === 'string') return location.href\n return DEFAULT_BASE\n } catch {\n return DEFAULT_BASE\n }\n}\n\n/**\n * Cleans up the URL by removing the `token` from the hash and the `sid` and `url` search params.\n * @internal\n */\nexport function getCleanedUrl(locationUrl: string): string {\n const loc = new URL(locationUrl)\n // Remove only the `token` param from the hash while preserving other fragments\n const rawHash = loc.hash.startsWith('#') ? loc.hash.slice(1) : loc.hash\n if (rawHash && rawHash.includes('=')) {\n const hashParams = new URLSearchParams(rawHash)\n hashParams.delete('token')\n hashParams.delete('withSid')\n const nextHash = hashParams.toString()\n loc.hash = nextHash ? `#${nextHash}` : ''\n }\n loc.searchParams.delete('sid')\n loc.searchParams.delete('url')\n return loc.toString()\n}\n\n// -----------------------------------------------------------------------------\n// ClientError helpers (shared)\n// -----------------------------------------------------------------------------\n\n/** @internal */\nexport type ApiErrorBody = {\n error?: {type?: string; description?: string}\n type?: string\n description?: string\n message?: string\n}\n\n/** @internal Extracts the structured API error body from a ClientError, if present. */\nexport function getClientErrorApiBody(error: ClientError): ApiErrorBody | undefined {\n const body: unknown = (error as ClientError).response?.body\n return body && typeof body === 'object' ? (body as ApiErrorBody) : undefined\n}\n\n/** @internal Returns the error type string from an API error body, if available. */\nexport function getClientErrorApiType(error: ClientError): string | undefined {\n const body = getClientErrorApiBody(error)\n return body?.error?.type ?? body?.type\n}\n\n/** @internal Returns the error description string from an API error body, if available. */\nexport function getClientErrorApiDescription(error: ClientError): string | undefined {\n const body = getClientErrorApiBody(error)\n return body?.error?.description ?? body?.description\n}\n\n/** @internal True if the error represents a projectUserNotFoundError. */\nexport function isProjectUserNotFoundClientError(error: ClientError): boolean {\n return getClientErrorApiType(error) === 'projectUserNotFoundError'\n}\n","import {type Subscription} from 'rxjs'\n\nimport {type StoreContext} from '../store/defineStore'\nimport {DEFAULT_BASE} from './authConstants'\nimport {AuthStateType} from './authStateType'\nimport {type AuthStoreState, type DashboardContext} from './authStore'\nimport {type AuthStrategyOptions, type AuthStrategyResult} from './authStrategy'\nimport {refreshStampedToken} from './refreshStampedToken'\nimport {subscribeToStateAndFetchCurrentUser} from './subscribeToStateAndFetchCurrentUser'\nimport {createLoggedInAuthState, getAuthCode, getTokenFromLocation} from './utils'\n\n/**\n * Parses the dashboard context from a location href's `_context` URL parameter.\n * Strips the `sid` property from the parsed context (it's handled separately).\n *\n * @internal\n */\nfunction parseDashboardContext(locationHref: string): DashboardContext {\n try {\n const parsedUrl = new URL(locationHref, DEFAULT_BASE)\n const contextParam = parsedUrl.searchParams.get('_context')\n if (contextParam) {\n const parsedContext = JSON.parse(contextParam)\n\n if (\n parsedContext &&\n typeof parsedContext === 'object' &&\n !Array.isArray(parsedContext) &&\n Object.keys(parsedContext).length > 0\n ) {\n // Explicitly remove the 'sid' property before assigning\n delete parsedContext.sid\n return parsedContext as DashboardContext\n }\n }\n } catch (err) {\n // eslint-disable-next-line no-console\n console.error('Failed to parse dashboard context from initial location:', err)\n }\n return {} // Empty dashboard context if parsing fails\n}\n\n/**\n * Resolves the initial auth state for Dashboard mode.\n *\n * In dashboard mode the token is provided by the parent frame via Comlink,\n * so the SDK starts in a `LOGGED_OUT` state and waits for the token to arrive.\n * The `_context` URL parameter provides dashboard metadata (orgId, mode, env).\n *\n * A provided token (`auth.token`) or an auth code/callback still takes\n * precedence, even when running inside the dashboard.\n *\n * @internal\n */\nexport function getDashboardInitialState(options: AuthStrategyOptions): AuthStrategyResult {\n const {authConfig, initialLocationHref} = options\n const providedToken = authConfig.token\n const callbackUrl = authConfig.callbackUrl\n const storageKey = '__sanity_auth_token'\n\n const dashboardContext = parseDashboardContext(initialLocationHref)\n\n // Dashboard does NOT use localStorage — token comes from the parent frame\n const storageArea = undefined\n\n // Provided token always wins, even in dashboard\n if (providedToken) {\n return {\n authState: createLoggedInAuthState(providedToken, null),\n storageKey,\n storageArea,\n authMethod: undefined,\n dashboardContext,\n }\n }\n\n // Check for auth code or token-from-location (callback handling)\n if (getAuthCode(callbackUrl, initialLocationHref) || getTokenFromLocation(initialLocationHref)) {\n return {\n authState: {type: AuthStateType.LOGGING_IN, isExchangingToken: false},\n storageKey,\n storageArea,\n authMethod: undefined,\n dashboardContext,\n }\n }\n\n // Default: logged out, waiting for Comlink to provide token\n return {\n authState: {type: AuthStateType.LOGGED_OUT, isDestroyingSession: false},\n storageKey,\n storageArea,\n authMethod: undefined,\n dashboardContext,\n }\n}\n\n/**\n * Initialize Dashboard auth subscriptions:\n * - Subscribe to state changes and fetch current user\n * - Start stamped token refresh\n *\n * Note: storage events are NOT subscribed in dashboard mode since\n * the dashboard does not use localStorage for token persistence.\n *\n * @internal\n */\nexport function initializeDashboardAuth(\n context: StoreContext<AuthStoreState>,\n tokenRefresherRunning: boolean,\n): {dispose: () => void; tokenRefresherStarted: boolean} {\n const subscriptions: Subscription[] = []\n let startedRefresher = false\n\n subscriptions.push(subscribeToStateAndFetchCurrentUser(context, {useProjectHostname: false}))\n\n // Dashboard does not subscribe to storage events\n\n if (!tokenRefresherRunning) {\n startedRefresher = true\n subscriptions.push(refreshStampedToken(context))\n }\n\n return {\n dispose: () => {\n for (const subscription of subscriptions) {\n subscription.unsubscribe()\n }\n },\n tokenRefresherStarted: startedRefresher,\n }\n}\n","import {defer, distinctUntilChanged, filter, map, type Subscription} from 'rxjs'\n\nimport {type StoreContext} from '../../store/defineStore'\nimport {DEFAULT_BASE} from '../authConstants'\nimport {AuthStateType} from '../authStateType'\nimport {type AuthStoreState} from '../authStore'\nimport {type AuthStrategyOptions, type AuthStrategyResult} from '../authStrategy'\nimport {subscribeToStateAndFetchCurrentUser} from '../subscribeToStateAndFetchCurrentUser'\nimport {createLoggedInAuthState, getDefaultStorage, getStorageEvents} from '../utils'\nimport {type OAuthTokens} from './types'\n\n/** localStorage (or configured `storageArea`) key for persisted OAuth tokens. */\nexport const OAUTH_TOKENS_KEY = '__sanity_oauth_tokens'\n\n/** The persisted JSON shape of {@link OAuthTokens}, `expiresAt` as an ISO string. */\ninterface SerializedOAuthTokens extends Omit<OAuthTokens, 'expiresAt'> {\n expiresAt: string\n}\n\n/**\n * Parses persisted token JSON back into {@link OAuthTokens}. Returns `null`\n * when the value is missing or malformed, including an `expiresAt` that does\n * not parse to a valid date (an `Invalid Date` would otherwise read as never\n * expiring, since `NaN <= now` is always `false`).\n *\n * @internal\n */\nexport function deserializeTokens(raw: string | null): OAuthTokens | null {\n if (!raw) return null\n try {\n const parsed: unknown = JSON.parse(raw)\n if (\n typeof parsed !== 'object' ||\n parsed === null ||\n !('accessToken' in parsed) ||\n typeof (parsed as SerializedOAuthTokens).accessToken !== 'string' ||\n !('expiresAt' in parsed) ||\n typeof (parsed as SerializedOAuthTokens).expiresAt !== 'string'\n ) {\n return null\n }\n const value = parsed as SerializedOAuthTokens\n const expiresAt = new Date(value.expiresAt)\n if (Number.isNaN(expiresAt.getTime())) return null\n return {\n accessToken: value.accessToken,\n tokenType: 'bearer',\n expiresIn: value.expiresIn,\n expiresAt,\n ...(value.refreshToken !== undefined && {refreshToken: value.refreshToken}),\n }\n } catch {\n return null\n }\n}\n\n/**\n * Resolves the initial auth state for OAuth mode.\n *\n * State discovery order:\n * 1. Persisted tokens in `__sanity_oauth_tokens` → `LOGGED_IN`\n * 2. Callback URL (contains `code` or `error` and matches `redirectUri`)\n * → `LOGGING_IN`\n * 3. Otherwise → `LOGGED_OUT`\n *\n * @internal\n */\nexport function getOauthInitialState(options: AuthStrategyOptions): AuthStrategyResult {\n const {authConfig, initialLocationHref} = options\n const storageKey = OAUTH_TOKENS_KEY\n const storageArea = authConfig.storageArea ?? getDefaultStorage()\n const redirectUri = authConfig.oauth?.redirectUri\n\n // Persisted tokens win\n const rawTokens = storageArea?.getItem(OAUTH_TOKENS_KEY) ?? null\n const tokens = deserializeTokens(rawTokens)\n if (rawTokens && !tokens) {\n // Corrupt entry: drop it so it cannot keep shadowing a fresh login\n storageArea?.removeItem(OAUTH_TOKENS_KEY)\n }\n if (tokens) {\n return {\n authState: createLoggedInAuthState(tokens.accessToken, null),\n storageKey,\n storageArea,\n authMethod: 'localstorage',\n dashboardContext: {},\n oauthTokens: tokens,\n }\n }\n\n // Callback URL with code/error whose origin + pathname match our redirect\n // URI (query and hash are ignored). `state` alone is not a callback: the\n // server always sends `code` or `error`, and handleOAuthCallback would\n // otherwise leave the app stuck in LOGGING_IN.\n const {searchParams} = new URL(initialLocationHref, DEFAULT_BASE)\n const isCallback = searchParams.has('code') || searchParams.has('error')\n if (redirectUri && isCallback) {\n const loc = new URL(initialLocationHref, DEFAULT_BASE)\n const redirect = new URL(redirectUri, DEFAULT_BASE)\n if (loc.origin === redirect.origin && loc.pathname === redirect.pathname) {\n return {\n authState: {type: AuthStateType.LOGGING_IN, isExchangingToken: false},\n storageKey,\n storageArea,\n authMethod: undefined,\n dashboardContext: {},\n }\n }\n }\n\n // No tokens, not a callback\n return {\n authState: {type: AuthStateType.LOGGED_OUT, isDestroyingSession: false},\n storageKey,\n storageArea,\n authMethod: undefined,\n dashboardContext: {},\n }\n}\n\n/**\n * Subscribes to cross-tab `storage` events for the OAuth tokens key, syncing\n * this tab's auth state when tokens change in another tab.\n *\n * @internal\n */\nexport function subscribeToOAuthStorageEvents({state}: StoreContext<AuthStoreState>): Subscription {\n const {storageArea} = state.get().options\n\n const tokens$ = defer(getStorageEvents).pipe(\n filter((e) => e.storageArea === storageArea && e.key === OAUTH_TOKENS_KEY),\n map(() => deserializeTokens(storageArea?.getItem(OAUTH_TOKENS_KEY) ?? null)),\n distinctUntilChanged((a, b) => a?.accessToken === b?.accessToken),\n )\n\n return tokens$.subscribe((tokens) => {\n state.set('updateOAuthTokensFromStorageEvent', {\n authState: tokens\n ? createLoggedInAuthState(tokens.accessToken, null)\n : {type: AuthStateType.LOGGED_OUT, isDestroyingSession: false},\n oauthTokens: tokens ?? undefined,\n })\n })\n}\n\n/**\n * Initialize OAuth auth subscriptions:\n * - Subscribe to state changes and fetch current user\n * - Subscribe to cross-tab storage events for the OAuth tokens key\n *\n * OAuth tokens are refreshed via the `refresh_token` grant (see\n * `refreshOAuthTokens`), so the stamped-token refresher is not started here.\n *\n * @internal\n */\nexport function initializeOauthAuth(context: StoreContext<AuthStoreState>): {\n dispose: () => void\n tokenRefresherStarted: boolean\n} {\n const subscriptions: Subscription[] = []\n\n subscriptions.push(subscribeToStateAndFetchCurrentUser(context, {useProjectHostname: false}))\n\n const storageArea = context.state.get().options?.storageArea\n if (storageArea) {\n subscriptions.push(subscribeToOAuthStorageEvents(context))\n }\n\n return {\n dispose: () => {\n for (const subscription of subscriptions) {\n subscription.unsubscribe()\n }\n },\n tokenRefresherStarted: false,\n }\n}\n","import {defer, distinctUntilChanged, filter, map, type Subscription} from 'rxjs'\n\nimport {type StoreContext} from '../store/defineStore'\nimport {AuthStateType} from './authStateType'\nimport {type AuthStoreState} from './authStore'\nimport {createLoggedInAuthState, getStorageEvents, getTokenFromStorage} from './utils'\n\nexport const subscribeToStorageEventsAndSetToken = ({\n state,\n}: StoreContext<AuthStoreState>): Subscription => {\n const {storageArea, storageKey} = state.get().options\n\n const tokenFromStorage$ = defer(getStorageEvents).pipe(\n filter(\n (e): e is StorageEvent & {newValue: string} =>\n e.storageArea === storageArea && e.key === storageKey,\n ),\n map(() => getTokenFromStorage(storageArea, storageKey)),\n distinctUntilChanged(),\n )\n\n return tokenFromStorage$.subscribe((token) => {\n state.set('updateTokenFromStorageEvent', {\n authState: token\n ? createLoggedInAuthState(token, null)\n : {type: AuthStateType.LOGGED_OUT, isDestroyingSession: false},\n })\n })\n}\n","import {type Subscription} from 'rxjs'\n\nimport {type StoreContext} from '../store/defineStore'\nimport {AuthStateType} from './authStateType'\nimport {type AuthStoreState} from './authStore'\nimport {type AuthStrategyOptions, type AuthStrategyResult} from './authStrategy'\nimport {refreshStampedToken} from './refreshStampedToken'\nimport {subscribeToStateAndFetchCurrentUser} from './subscribeToStateAndFetchCurrentUser'\nimport {subscribeToStorageEventsAndSetToken} from './subscribeToStorageEventsAndSetToken'\nimport {\n createLoggedInAuthState,\n getAuthCode,\n getDefaultStorage,\n getTokenFromLocation,\n getTokenFromStorage,\n} from './utils'\n\n/**\n * Resolves the initial auth state for Standalone mode.\n *\n * Token discovery order:\n * 1. Provided token (`auth.token` in config)\n * 2. Auth code or token from location (OAuth callback)\n * 3. localStorage: `__sanity_auth_token`\n * 4. Falls back to `LOGGED_OUT`\n *\n * @internal\n */\nexport function getStandaloneInitialState(options: AuthStrategyOptions): AuthStrategyResult {\n const {authConfig, initialLocationHref} = options\n const providedToken = authConfig.token\n const callbackUrl = authConfig.callbackUrl\n const storageKey = '__sanity_auth_token'\n const storageArea = authConfig.storageArea ?? getDefaultStorage()\n\n // Provided token always wins\n if (providedToken) {\n return {\n authState: createLoggedInAuthState(providedToken, null),\n storageKey,\n storageArea,\n authMethod: undefined,\n dashboardContext: {},\n }\n }\n\n // Check for auth code or token-from-location (OAuth callback)\n if (getAuthCode(callbackUrl, initialLocationHref) || getTokenFromLocation(initialLocationHref)) {\n return {\n authState: {type: AuthStateType.LOGGING_IN, isExchangingToken: false},\n storageKey,\n storageArea,\n authMethod: undefined,\n dashboardContext: {},\n }\n }\n\n // Try localStorage\n const token = getTokenFromStorage(storageArea, storageKey)\n if (token) {\n return {\n authState: createLoggedInAuthState(token, null),\n storageKey,\n storageArea,\n authMethod: 'localstorage',\n dashboardContext: {},\n }\n }\n\n // No token found\n return {\n authState: {type: AuthStateType.LOGGED_OUT, isDestroyingSession: false},\n storageKey,\n storageArea,\n authMethod: undefined,\n dashboardContext: {},\n }\n}\n\n/**\n * Initialize Standalone auth subscriptions:\n * - Subscribe to state changes and fetch current user\n * - Subscribe to storage events for token key\n * - Start stamped token refresh\n *\n * @internal\n */\nexport function initializeStandaloneAuth(\n context: StoreContext<AuthStoreState>,\n tokenRefresherRunning: boolean,\n): {dispose: () => void; tokenRefresherStarted: boolean} {\n const subscriptions: Subscription[] = []\n let startedRefresher = false\n\n subscriptions.push(subscribeToStateAndFetchCurrentUser(context, {useProjectHostname: false}))\n\n const storageArea = context.state.get().options?.storageArea\n if (storageArea) {\n subscriptions.push(subscribeToStorageEventsAndSetToken(context))\n }\n\n if (!tokenRefresherRunning) {\n startedRefresher = true\n subscriptions.push(refreshStampedToken(context))\n }\n\n return {\n dispose: () => {\n for (const subscription of subscriptions) {\n subscription.unsubscribe()\n }\n },\n tokenRefresherStarted: startedRefresher,\n }\n}\n","import {type ClientConfig, type SanityClient} from '@sanity/client'\n\nimport {REQUEST_TAG_PREFIX} from './authConstants'\nimport {getTokenFromStorage} from './utils'\n\n/**\n * Cookie auth is a best-effort probe — if the API doesn't respond quickly,\n * the user likely isn't cookie-authenticated and we should move on rather\n * than block the auth flow indefinitely.\n */\nconst COOKIE_AUTH_TIMEOUT_MS = 10_000\n\n/**\n * Attempts to check for cookie auth by making a withCredentials request to the users endpoint.\n * @param projectId - The project ID to check for cookie auth.\n * @param clientFactory - A factory function that creates a Sanity client.\n * @returns True if the user is authenticated, false otherwise.\n * @internal\n */\nexport async function checkForCookieAuth(\n projectId: string | undefined,\n clientFactory: (config: ClientConfig) => SanityClient,\n): Promise<boolean> {\n if (!projectId) return false\n try {\n const client = clientFactory({\n projectId,\n useCdn: false,\n requestTagPrefix: REQUEST_TAG_PREFIX,\n timeout: COOKIE_AUTH_TIMEOUT_MS,\n })\n const user = await client.request({\n url: '/users/me',\n withCredentials: true,\n tag: 'users.get-current',\n })\n return user != null && typeof user === 'object' && typeof user.id === 'string'\n } catch {\n return false\n }\n}\n\n/**\n * Attempts to retrieve a studio token from local storage.\n * @param storageArea - The storage area to retrieve the token from.\n * @param storageKey - The storage key to retrieve the token from.\n * @returns The studio token or null if it does not exist.\n * @internal\n */\nexport function getStudioTokenFromLocalStorage(\n storageArea: Storage | undefined,\n storageKey: string | undefined,\n): string | null {\n if (!storageArea || !storageKey) return null\n const token = getTokenFromStorage(storageArea, storageKey)\n if (token) {\n return token\n }\n return null\n}\n","import {type Subscription} from 'rxjs'\n\nimport {type TokenSource} from '../config/sanityConfig'\nimport {type StoreContext} from '../store/defineStore'\nimport {AuthStateType} from './authStateType'\nimport {type AuthStoreState, type LoggedInAuthState} from './authStore'\nimport {type AuthStrategyOptions, type AuthStrategyResult} from './authStrategy'\nimport {refreshStampedToken} from './refreshStampedToken'\nimport {checkForCookieAuth, getStudioTokenFromLocalStorage} from './studioModeAuth'\nimport {subscribeToStateAndFetchCurrentUser} from './subscribeToStateAndFetchCurrentUser'\nimport {subscribeToStorageEventsAndSetToken} from './subscribeToStorageEventsAndSetToken'\nimport {createLoggedInAuthState, getDefaultStorage} from './utils'\n\n/**\n * Resolves the initial auth state for Studio mode.\n *\n * When a `tokenSource` is provided (via `config.studio.auth.token`), the\n * initial state is `LOGGING_IN` — the actual token arrives asynchronously\n * via the subscription set up in `initializeStudioAuth`.\n *\n * Fallback token discovery order (no tokenSource):\n * 1. Provided token (`auth.token` in config)\n * 2. localStorage: `__studio_auth_token_${projectId}`\n * 3. Falls back to `LOGGED_OUT` (cookie auth is checked async in `initializeStudioAuth`)\n *\n * @internal\n */\nexport function getStudioInitialState(options: AuthStrategyOptions): AuthStrategyResult {\n const {authConfig, projectId, tokenSource} = options\n const storageArea = authConfig.storageArea ?? getDefaultStorage()\n const studioStorageKey = `__studio_auth_token_${projectId ?? ''}`\n\n // When a reactive token source is available, start in LOGGING_IN state.\n // The actual token will arrive via subscription in initializeStudioAuth.\n if (tokenSource) {\n return {\n authState: {type: AuthStateType.LOGGING_IN, isExchangingToken: false},\n storageKey: studioStorageKey,\n storageArea,\n authMethod: undefined,\n dashboardContext: {},\n }\n }\n\n // Fallback: discover token from config or localStorage\n const providedToken = authConfig.token\n\n // Check localStorage first — mirrors original authStore behavior where\n // the localStorage read always runs before the providedToken check.\n let authMethod: AuthStrategyResult['authMethod'] = undefined\n const token = getStudioTokenFromLocalStorage(storageArea, studioStorageKey)\n if (token) {\n authMethod = 'localstorage'\n }\n\n if (providedToken) {\n return {\n authState: createLoggedInAuthState(providedToken, null),\n storageKey: studioStorageKey,\n storageArea,\n authMethod,\n dashboardContext: {},\n }\n }\n\n if (token) {\n return {\n authState: createLoggedInAuthState(token, null),\n storageKey: studioStorageKey,\n storageArea,\n authMethod: 'localstorage',\n dashboardContext: {},\n }\n }\n\n // No token found — start logged out, cookie auth will be checked asynchronously\n return {\n authState: {type: AuthStateType.LOGGED_OUT, isDestroyingSession: false},\n storageKey: studioStorageKey,\n storageArea,\n authMethod: undefined,\n dashboardContext: {},\n }\n}\n\n/**\n * Initialize Studio auth subscriptions.\n *\n * When a `tokenSource` is available (reactive path), subscribes to it for\n * ongoing token sync. The Studio is the token authority — no independent\n * token refresh or cookie auth probing is needed.\n *\n * Fallback path (no tokenSource):\n * - Subscribe to state changes and fetch current user\n * - Subscribe to storage events for studio token key\n * - Check for cookie auth asynchronously if no token was found\n * - Start stamped token refresh\n *\n * @internal\n */\nexport function initializeStudioAuth(\n context: StoreContext<AuthStoreState>,\n tokenRefresherRunning: boolean,\n): {dispose: () => void; tokenRefresherStarted: boolean} {\n const tokenSource = context.instance.config.studio?.auth?.token\n\n // Reactive token path — Studio provides the token\n if (tokenSource) {\n return initializeWithTokenSource(context, tokenSource)\n }\n\n // Fallback path — discover token from localStorage/cookies\n return initializeWithFallback(context, tokenRefresherRunning)\n}\n\n/**\n * Subscribe to a reactive token source from the Studio workspace.\n *\n * When the token source emits a non-null token, the SDK uses it directly.\n * When it emits `null`, the behavior depends on the `authenticated` flag\n * from the Studio's workspace config:\n *\n * - `authenticated: true` — the Studio has already verified the user is\n * logged in (e.g. via cookie auth). The SDK treats the null token as\n * cookie-based auth and stays in the LOGGED_IN state.\n *\n * - `authenticated` absent/false — the user is genuinely not authenticated;\n * transition to LOGGED_OUT.\n *\n * No async cookie probing is needed here because this code path only runs\n * when a Studio provides SDKStudioContext, and the Studio's Workspace type\n * always includes `authenticated`. The async `checkForCookieAuth` fallback\n * remains in `initializeWithFallback` for the non-Studio path.\n */\nfunction initializeWithTokenSource(\n context: StoreContext<AuthStoreState>,\n tokenSource: TokenSource,\n): {dispose: () => void; tokenRefresherStarted: boolean} {\n const subscriptions: Subscription[] = []\n const studioAuthenticated = context.instance.config.studio?.authenticated === true\n\n // Subscribe to the current user fetcher — runs whenever auth state changes\n subscriptions.push(subscribeToStateAndFetchCurrentUser(context, {useProjectHostname: true}))\n\n // Subscribe to the Studio's token stream\n const tokenSub = tokenSource.subscribe({\n next: (token) => {\n const {state} = context\n if (token) {\n // Studio provided a real token — use it directly\n state.set('studioTokenSource', (prev) => ({\n options: {...prev.options, authMethod: undefined},\n authState: createLoggedInAuthState(token, null),\n }))\n } else if (studioAuthenticated) {\n // The Studio says the user is authenticated — null token means\n // cookie-based auth is in use. Stay logged in with cookie method.\n state.set('studioTokenSourceCookieAuth', (prev) => ({\n options: {...prev.options, authMethod: 'cookie'},\n authState:\n prev.authState.type === AuthStateType.LOGGED_IN\n ? prev.authState\n : createLoggedInAuthState('', null),\n }))\n } else {\n // No token and Studio doesn't confirm authentication — logged out\n state.set('studioTokenSourceLoggedOut', (prev) => ({\n options: {...prev.options, authMethod: undefined},\n authState: {type: AuthStateType.LOGGED_OUT, isDestroyingSession: false},\n }))\n }\n },\n })\n\n return {\n dispose: () => {\n tokenSub.unsubscribe()\n for (const subscription of subscriptions) {\n subscription.unsubscribe()\n }\n },\n // Studio handles token refresh — do not start the SDK's refresher\n tokenRefresherStarted: false,\n }\n}\n\n/**\n * Fallback initialization when no reactive token source is available.\n * Uses localStorage/cookie discovery (existing behavior).\n */\nfunction initializeWithFallback(\n context: StoreContext<AuthStoreState>,\n tokenRefresherRunning: boolean,\n): {dispose: () => void; tokenRefresherStarted: boolean} {\n const subscriptions: Subscription[] = []\n let startedRefresher = false\n\n subscriptions.push(subscribeToStateAndFetchCurrentUser(context, {useProjectHostname: true}))\n\n const storageArea = context.state.get().options?.storageArea\n if (storageArea) {\n subscriptions.push(subscribeToStorageEventsAndSetToken(context))\n }\n\n // If no token found during getInitialState, try cookie auth asynchronously\n try {\n const {instance, state} = context\n const token: string | null =\n state.get().authState?.type === AuthStateType.LOGGED_IN\n ? (state.get().authState as LoggedInAuthState).token\n : null\n\n if (!token) {\n const projectIdValue = instance.config.projectId\n const clientFactory = state.get().options.clientFactory\n checkForCookieAuth(projectIdValue, clientFactory).then((isCookieAuthEnabled) => {\n if (!isCookieAuthEnabled) return\n state.set('enableCookieAuth', (prev) => ({\n options: {...prev.options, authMethod: 'cookie'},\n authState:\n prev.authState.type === AuthStateType.LOGGED_IN\n ? prev.authState\n : createLoggedInAuthState('', null),\n }))\n })\n }\n } catch {\n // best-effort cookie detection\n }\n\n if (!tokenRefresherRunning) {\n startedRefresher = true\n subscriptions.push(refreshStampedToken(context))\n }\n\n return {\n dispose: () => {\n for (const subscription of subscriptions) {\n subscription.unsubscribe()\n }\n },\n tokenRefresherStarted: startedRefresher,\n }\n}\n","import {type ClientConfig, createClient, type SanityClient} from '@sanity/client'\nimport {type CurrentUser} from '@sanity/types'\n\nimport {type AuthConfig, type AuthProvider} from '../config/authConfig'\nimport {bindActionGlobally} from '../store/createActionBinder'\nimport {createStateSourceAction} from '../store/createStateSourceAction'\nimport {defineStore} from '../store/defineStore'\nimport {getStagingApiHost} from '../utils/getStagingApiHost'\nimport {getAuthLogger} from './authLogger'\nimport {resolveAuthMode} from './authMode'\nimport {AuthStateType} from './authStateType'\nimport {type AuthStrategyOptions} from './authStrategy'\nimport {getDashboardInitialState, initializeDashboardAuth} from './dashboardAuth'\nimport {getOauthInitialState, initializeOauthAuth} from './oauth/oauthAuth'\nimport {type OAuthTokens} from './oauth/types'\nimport {getStandaloneInitialState, initializeStandaloneAuth} from './standaloneAuth'\nimport {getStudioInitialState, initializeStudioAuth} from './studioAuth'\nimport {createLoggedInAuthState, getCleanedUrl, getDefaultLocation} from './utils'\n\n// ---------------------------------------------------------------------------\n// Public types\n// ---------------------------------------------------------------------------\n\n/**\n * Represents the various states the authentication can be in.\n *\n * @public\n */\nexport type AuthState = LoggedInAuthState | LoggedOutAuthState | LoggingInAuthState | ErrorAuthState\n\n/**\n * Logged-in state from the auth state.\n * @public\n */\nexport type LoggedInAuthState = {\n type: AuthStateType.LOGGED_IN\n token: string\n currentUser: CurrentUser | null\n lastTokenRefresh?: number\n}\n\n/**\n * Logged-out state from the auth state.\n * @public\n */\nexport type LoggedOutAuthState = {type: AuthStateType.LOGGED_OUT; isDestroyingSession: boolean}\n\n/**\n * Logging-in state from the auth state.\n * @public\n */\nexport type LoggingInAuthState = {type: AuthStateType.LOGGING_IN; isExchangingToken: boolean}\n\n/**\n * Error state from the auth state.\n * @public\n */\nexport type ErrorAuthState = {type: AuthStateType.ERROR; error: unknown}\n\n/**\n * Represents the various states the authentication can be in.\n *\n * @public\n */\nexport interface DashboardContext {\n mode?: string\n env?: string\n orgId?: string\n}\n\n/**\n * The method of authentication used.\n * @internal\n */\nexport type AuthMethodOptions = 'localstorage' | 'cookie' | undefined\n\nlet tokenRefresherRunning = false\n\n/**\n * @public\n */\nexport interface AuthStoreState {\n authState: AuthState\n providers?: AuthProvider[]\n options: {\n initialLocationHref: string\n clientFactory: (config: ClientConfig) => SanityClient\n customProviders: AuthConfig['providers']\n storageKey: string\n storageArea: Storage | undefined\n apiHost: string | undefined\n loginUrl: string\n callbackUrl: string | undefined\n providedToken: string | undefined\n authMethod: AuthMethodOptions\n oauth: AuthConfig['oauth']\n }\n dashboardContext?: DashboardContext\n oauthTokens?: OAuthTokens\n}\n\n// ---------------------------------------------------------------------------\n// Store definition — thin orchestrator\n// ---------------------------------------------------------------------------\n\nexport const authStore = defineStore<AuthStoreState>({\n name: 'Auth',\n\n getInitialState(instance) {\n const logger = getAuthLogger(instance)\n\n logger.debug('Initializing auth store', {\n hasProvidedToken: !!instance.config.auth?.token,\n hasCustomProviders: !!(\n instance.config.auth?.providers && instance.config.auth.providers.length > 0\n ),\n })\n\n const {\n apiHost: configApiHost,\n callbackUrl,\n providers: customProviders,\n token: providedToken,\n clientFactory = createClient,\n initialLocationHref = getDefaultLocation(),\n } = instance.config.auth ?? {}\n\n const apiHost = configApiHost ?? getStagingApiHost()\n const authConfig = instance.config.auth ?? {}\n\n // Build login URL (used by standalone mode, but always computed for the\n // public `getLoginUrlState` accessor)\n let loginDomain = 'https://www.sanity.io'\n try {\n if (apiHost && new URL(apiHost).hostname.endsWith('.sanity.work')) {\n loginDomain = 'https://www.sanity.work'\n }\n } catch {\n /* empty */\n }\n const loginUrl = new URL('/login', loginDomain)\n loginUrl.searchParams.set('origin', getCleanedUrl(initialLocationHref))\n loginUrl.searchParams.set('type', 'stampedToken') // Token must be stamped to have an sid passed back\n loginUrl.searchParams.set('withSid', 'true')\n\n // Resolve auth mode and delegate to the appropriate strategy\n const mode = resolveAuthMode(instance.config, initialLocationHref)\n\n const strategyOptions: AuthStrategyOptions = {\n authConfig,\n projectId: instance.config.projectId,\n initialLocationHref,\n clientFactory,\n tokenSource: instance.config.studio?.auth?.token,\n }\n\n let result\n switch (mode) {\n case 'studio':\n result = getStudioInitialState(strategyOptions)\n break\n case 'oauth':\n result = getOauthInitialState(strategyOptions)\n break\n case 'dashboard':\n result = getDashboardInitialState(strategyOptions)\n break\n case 'standalone':\n result = getStandaloneInitialState(strategyOptions)\n break\n }\n\n logger.debug('Auth state initialized', {\n authStateType: result.authState.type,\n mode,\n authMethod: result.authMethod,\n })\n\n return {\n authState: result.authState,\n dashboardContext: result.dashboardContext,\n oauthTokens: result.oauthTokens,\n options: {\n apiHost,\n loginUrl: loginUrl.toString(),\n callbackUrl,\n customProviders,\n providedToken,\n clientFactory,\n initialLocationHref,\n storageKey: result.storageKey,\n storageArea: result.storageArea,\n authMethod: result.authMethod,\n // Only expose oauth options when the oauth strategy is actually in use,\n // so mode-gated actions (logout, handleAuthCallback) stay consistent\n // with the resolved mode (e.g. `studio` takes precedence over `oauth`).\n oauth: mode === 'oauth' ? authConfig.oauth : undefined,\n },\n }\n },\n\n initialize(context) {\n const logger = getAuthLogger(context.instance)\n\n const initialLocationHref =\n context.state.get().options?.initialLocationHref ?? getDefaultLocation()\n const mode = resolveAuthMode(context.instance.config, initialLocationHref)\n\n logger.debug('Setting up auth subscriptions', {mode})\n\n let initResult\n switch (mode) {\n case 'studio':\n initResult = initializeStudioAuth(context, tokenRefresherRunning)\n break\n case 'oauth':\n initResult = initializeOauthAuth(context)\n break\n case 'dashboard':\n initResult = initializeDashboardAuth(context, tokenRefresherRunning)\n break\n case 'standalone':\n initResult = initializeStandaloneAuth(context, tokenRefresherRunning)\n break\n }\n\n if (initResult.tokenRefresherStarted) {\n tokenRefresherRunning = true\n }\n\n return () => {\n logger.debug('Cleaning up auth subscriptions')\n initResult.dispose()\n }\n },\n})\n\n// ---------------------------------------------------------------------------\n// Public bound actions\n// ---------------------------------------------------------------------------\n\n/**\n * @public\n */\nexport const getCurrentUserState = bindActionGlobally(\n authStore,\n createStateSourceAction(({state: {authState}}) =>\n authState.type === AuthStateType.LOGGED_IN ? authState.currentUser : null,\n ),\n)\n\n/**\n * @public\n */\nexport const getTokenState = bindActionGlobally(\n authStore,\n createStateSourceAction(({state: {authState}}) =>\n authState.type === AuthStateType.LOGGED_IN ? authState.token : null,\n ),\n)\n\n/**\n * @internal\n */\nexport const getAuthMethodState = bindActionGlobally(\n authStore,\n createStateSourceAction(({state: {options}}) => options.authMethod),\n)\n\n/**\n * @public\n */\nexport const getLoginUrlState = bindActionGlobally(\n authStore,\n createStateSourceAction(({state: {options}}) => options.loginUrl),\n)\n\n/**\n * @public\n */\nexport const getAuthState = bindActionGlobally(\n authStore,\n createStateSourceAction(({state: {authState}}) => authState),\n)\n\n/**\n * @public\n */\nexport const getDashboardOrganizationId = bindActionGlobally(\n authStore,\n createStateSourceAction(({state: {dashboardContext}}) => dashboardContext?.orgId),\n)\n\n/**\n * Returns a state source indicating if the SDK is running within a dashboard context.\n * @public\n */\nexport const getIsInDashboardState = bindActionGlobally(\n authStore,\n createStateSourceAction(\n ({state: {dashboardContext}}) =>\n // Check if dashboardContext exists and is not empty\n !!dashboardContext && Object.keys(dashboardContext).length > 0,\n ),\n)\n\n/**\n * Action to explicitly set the authentication token.\n * Used internally by the Comlink token refresh.\n * @internal\n */\nexport const setAuthToken = bindActionGlobally(\n authStore,\n ({state, instance}, token: string | null) => {\n const logger = getAuthLogger(instance)\n\n const currentAuthState = state.get().authState\n if (token) {\n // Update state only if the new token is different or currently logged out\n if (currentAuthState.type !== AuthStateType.LOGGED_IN || currentAuthState.token !== token) {\n logger.info('Setting auth token')\n const currentUser =\n currentAuthState.type === AuthStateType.LOGGED_IN ? currentAuthState.currentUser : null\n const preservedLastTokenRefresh =\n currentAuthState.type === AuthStateType.LOGGED_IN\n ? currentAuthState.lastTokenRefresh\n : undefined\n state.set('setToken', {\n authState: createLoggedInAuthState(token, currentUser, preservedLastTokenRefresh),\n })\n }\n } else {\n // Handle setting token to null (logging out)\n if (currentAuthState.type !== AuthStateType.LOGGED_OUT) {\n logger.info('Clearing auth token')\n state.set('setToken', {\n authState: {type: AuthStateType.LOGGED_OUT, isDestroyingSession: false},\n })\n }\n }\n },\n)\n","import {type ClientConfig, createClient, type SanityClient} from '@sanity/client'\n\nimport {getAuthMethodState, getTokenState} from '../auth/authStore'\nimport {\n type DocumentResource,\n isCanvasResource,\n isDatasetResource,\n isMediaLibraryResource,\n} from '../config/sanityConfig'\nimport {bindActionGlobally} from '../store/createActionBinder'\nimport {createStateSourceAction} from '../store/createStateSourceAction'\nimport {defineStore, type StoreContext} from '../store/defineStore'\nimport {getStagingApiHost} from '../utils/getStagingApiHost'\nimport {pickProperties} from '../utils/object'\n\nconst DEFAULT_API_VERSION = '2024-11-12'\nconst DEFAULT_REQUEST_TAG_PREFIX = 'sanity.sdk'\n\ntype AllowedClientConfigKey =\n | 'useCdn'\n | 'token'\n | 'perspective'\n | 'apiHost'\n | 'proxy'\n | 'withCredentials'\n | 'timeout'\n | 'maxRetries'\n | 'dataset'\n | 'projectId'\n | 'requestTagPrefix'\n | 'useProjectHostname'\n\nconst allowedKeys = Object.keys({\n apiHost: null,\n useCdn: null,\n token: null,\n perspective: null,\n proxy: null,\n withCredentials: null,\n timeout: null,\n maxRetries: null,\n dataset: null,\n projectId: null,\n scope: null,\n apiVersion: null,\n requestTagPrefix: null,\n useProjectHostname: null,\n resource: null,\n} satisfies Record<keyof ClientOptions, null>) as (keyof ClientOptions)[]\n\nconst DEFAULT_CLIENT_CONFIG: ClientConfig = {\n apiVersion: DEFAULT_API_VERSION,\n useCdn: false,\n ignoreBrowserTokenWarning: true,\n allowReconfigure: false,\n requestTagPrefix: DEFAULT_REQUEST_TAG_PREFIX,\n}\n\n/**\n * States tracked by the client store\n * @public\n */\nexport interface ClientStoreState {\n token: string | null\n clients: {[TKey in string]?: SanityClient}\n authMethod?: 'localstorage' | 'cookie'\n}\n\n/**\n * Options used when retrieving a client instance from the client store.\n *\n * This interface extends the base {@link ClientConfig} and adds:\n *\n * - **apiVersion:** A required string indicating the API version for the client.\n * - **scope:** An optional flag to choose between the project-specific client\n * ('project') and the global client ('global'). When set to `'global'`, the\n * global client is used.\n *\n * These options are utilized by `getClient` and `getClientState` to configure and\n * return appropriate client instances that automatically handle authentication\n * updates and configuration changes.\n *\n * @public\n */\nexport interface ClientOptions extends Pick<ClientConfig, AllowedClientConfigKey> {\n /**\n * An optional flag to choose between the default client (typically project-level)\n * and the global client ('global'). When set to `'global'`, the global client\n * is used.\n */\n scope?: 'default' | 'global'\n /**\n * A required string indicating the API version for the client.\n */\n apiVersion: string\n\n /**\n * @internal\n * The SDK resource to use for the client -- this will get transformed into a ClientConfig resource.\n */\n resource?: DocumentResource\n}\n\nconst clientStore = defineStore<ClientStoreState>({\n name: 'clientStore',\n\n getInitialState: (instance) => ({\n clients: {},\n token: getTokenState(instance).getCurrent(),\n }),\n\n initialize(context) {\n const subscription = listenToToken(context)\n const authMethodSubscription = listenToAuthMethod(context)\n return () => {\n subscription.unsubscribe()\n authMethodSubscription.unsubscribe()\n }\n },\n})\n\n/**\n * Updates the client store state when a token is received.\n * @internal\n */\nconst listenToToken = ({instance, state}: StoreContext<ClientStoreState>) => {\n return getTokenState(instance).observable.subscribe((token) => {\n state.set('setTokenAndResetClients', {token, clients: {}})\n })\n}\n\nconst listenToAuthMethod = ({instance, state}: StoreContext<ClientStoreState>) => {\n return getAuthMethodState(instance).observable.subscribe((authMethod) => {\n state.set('setAuthMethod', {authMethod})\n })\n}\n\ntype ClientInstanceCacheKeyInput = ClientConfig &\n Partial<Pick<ClientOptions, 'scope'>> & {\n apiVersion: string\n }\n\nconst getClientConfigKey = (options: ClientInstanceCacheKeyInput) =>\n JSON.stringify(pickProperties(options, allowedKeys))\n\n/**\n * Retrieves a Sanity client instance configured with the provided options.\n *\n * This function returns a client instance configured for the project or as a\n * global client based on the options provided. It ensures efficient reuse of\n * client instances by returning the same instance for the same options.\n * For automatic handling of authentication token updates, consider using\n * `getClientState`.\n *\n * @public\n */\nexport const getClient = bindActionGlobally(\n clientStore,\n ({state, instance}, options: ClientOptions) => {\n if (!options || typeof options !== 'object') {\n throw new Error(\n 'getClient() requires a configuration object with at least an \"apiVersion\" property. ' +\n 'Example: getClient(instance, { apiVersion: \"2024-11-12\" })',\n )\n }\n\n // Check for disallowed keys\n const providedKeys = Object.keys(options) as (keyof ClientOptions)[]\n const disallowedKeys = providedKeys.filter((key) => !allowedKeys.includes(key))\n\n if (disallowedKeys.length > 0) {\n const listFormatter = new Intl.ListFormat('en', {style: 'long', type: 'conjunction'})\n throw new Error(\n `The client options provided contains unsupported properties: ${listFormatter.format(disallowedKeys)}. ` +\n `Allowed keys are: ${listFormatter.format(allowedKeys)}.`,\n )\n }\n\n const tokenFromState = state.get().token\n const {clients, authMethod} = state.get()\n let projectId = options.projectId ?? instance.config.projectId\n let dataset = options.dataset ?? instance.config.dataset\n\n let resource: ClientConfig['resource'] | undefined\n\n if (options.resource) {\n if (isMediaLibraryResource(options.resource)) {\n resource = {type: 'media-library', id: options.resource.mediaLibraryId}\n } else if (isCanvasResource(options.resource)) {\n resource = {type: 'canvas', id: options.resource.canvasId}\n } else if (isDatasetResource(options.resource)) {\n // use project-based routes for datasets to avoid existing CORS and Studio auth cookie issues\n projectId = options.resource.projectId\n dataset = options.resource.dataset\n }\n }\n\n const apiHost = options.apiHost ?? instance.config.auth?.apiHost ?? getStagingApiHost()\n\n const effectiveOptions: ClientConfig & {apiVersion: string} = {\n ...DEFAULT_CLIENT_CONFIG,\n ...((options.scope === 'global' || !projectId || resource) && {useProjectHostname: false}),\n token: authMethod === 'cookie' ? undefined : (tokenFromState ?? undefined),\n ...options,\n ...(projectId && {projectId}),\n ...(dataset && {dataset}),\n ...(resource ? {resource} : {resource: undefined}),\n ...(apiHost && {apiHost}),\n }\n\n // When a resource is provided, don't use projectId/dataset - the client should be \"projectless\"\n // The client code itself will ignore the non-resource config, so we do this to prevent confusing the user.\n // (ref: https://github.com/sanity-io/client/blob/5c23f81f5ab93a53f5b22b39845c867988508d84/src/data/dataMethods.ts#L691)\n if (resource) {\n delete effectiveOptions.projectId\n delete effectiveOptions.dataset\n }\n\n if (effectiveOptions.token === null || typeof effectiveOptions.token === 'undefined') {\n delete effectiveOptions.token\n if (authMethod === 'cookie') {\n effectiveOptions.withCredentials = true\n }\n } else {\n delete effectiveOptions.withCredentials\n }\n\n const key = getClientConfigKey(effectiveOptions)\n\n if (clients[key]) return clients[key]\n\n const client = createClient(effectiveOptions)\n state.set('addClient', (prev) => ({clients: {...prev.clients, [key]: client}}))\n\n return client\n },\n)\n\n/**\n * Returns a state source for the Sanity client instance.\n *\n * This function provides a subscribable state source that emits updated client\n * instances whenever relevant configurations change (such as authentication tokens).\n * Use this when you need to react to client configuration changes in your application.\n *\n * @public\n */\nexport const getClientState = bindActionGlobally(\n clientStore,\n createStateSourceAction(({instance}, options: ClientOptions) => getClient(instance, options)),\n)\n"],"mappings":";;;;;;;;;;;;;AAqLA,MAAM,qBAA+C;CACnD,OAAO;CACP,MAAM;CACN,MAAM;CACN,OAAO;CACP,OAAO;AACT,GAGM,iBAAyC;CAC7C,O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K;EACxF,OAAO,eAAe,WAAW,KAAA,IAAa,kBAAkB,KAAA;EAChE,GAAG;EACH,GAAI,aAAa,EAAC,UAAS;EAC3B,GAAI,WAAW,EAAC,QAAO;EACvB,GAAI,WAAW,EAAC,SAAQ,IAAI,EAAC,UAAU,KAAA,EAAS;EAChD,GAAI,WAAW,EAAC,QAAO;CACzB;CAUA,AALI,aACF,OAAO,iBAAiB,WACxB,OAAO,iBAAiB,UAGtB,iBAAiB,UAAU,QAAe,iBAAiB,UAAU,UACvE,OAAO,iBAAiB,OACpB,eAAe,aACjB,iBAAiB,kBAAkB,OAGrC,OAAO,iBAAiB;CAG1B,IAAM,MAAM,mBAAmB,gBAAgB;CAE/C,IAAI,QAAQ,MAAM,OAAO,QAAQ;CAEjC,IAAM,SAAS,aAAa,gBAAgB;CAG5C,OAFA,MAAM,IAAI,cAAc,UAAU,EAAC,SAAS;EAAC,GAAG,KAAK;GAAU,MAAM;CAAM,EAAC,EAAE,GAEvE;AACT,CACF,GAWa,iBAAiB,mBAC5B,aACA,yBAAyB,EAAC,YAAW,YAA2B,UAAU,UAAU,OAAO,CAAC,CAC9F"}
@@ -76,9 +76,12 @@ interface AuthConfig {
76
76
  */
77
77
  redirectUri: string;
78
78
  /**
79
- * Organisation id used for RFC 8707 resource scoping.
79
+ * Organisation id used for RFC 8707 resource scoping. Optional: when
80
+ * omitted, the `resource` parameter is left off the authorize and token
81
+ * requests, so the issued tokens are not restricted to a single
82
+ * organisation.
80
83
  */
81
- organizationId: string;
84
+ organizationId?: string;
82
85
  };
83
86
  }
84
87
  /**
@@ -290,4 +293,4 @@ interface SanityInstance {
290
293
  */
291
294
  declare function createSanityInstance(config?: SanityConfig): SanityInstance;
292
295
  export { isCanvasResource as _, DatasetResource as a, AuthConfig as b, DocumentTypeHandle as c, ProjectHandle as d, ReleaseHandle as f, TokenSource as g, StudioConfig as h, DatasetHandle as i, MediaLibraryResource as l, SanityConfig as m, createSanityInstance as n, DocumentHandle as o, ReleasePerspective as p, CanvasResource as r, DocumentResource as s, SanityInstance as t, PerspectiveHandle as u, isDatasetResource as v, AuthProvider as x, isMediaLibraryResource as y };
293
- //# sourceMappingURL=createSanityInstance-BQIqyGLX.d.ts.map
296
+ //# sourceMappingURL=createSanityInstance--Lrldto8.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"createSanityInstance--Lrldto8.d.ts","names":[],"sources":["../src/config/authConfig.ts","../src/config/sanityConfig.ts","../src/store/createSanityInstance.ts"],"mappings":";;;;;UAMiB;;;;EAIf;;;;EAKA;;;;EAKA;;;;EAKA;;;;;;;UAQe;;;;;EAKf;;;;;EAMA,iBAAiB,QAAQ,iBAAiB;;;;;;EAO1C,YAAY,mBAAmB,MAAM,mBAAmB,iBAAiB,QAAQ;;;;;EAMjF;;;;;EAMA,cAAc;;;;;;EAOd;;;;;;EAOA;EAEA;;;;IAIE;;;;;IAMA;;;;;;;IAQA;;;;;;;;;;;UCrFa;;EAEf,UAAU;IAAW,OAAO;;IAAkC;;;;;;;;;;UAU/C;;;;;;EAMf;;EAEA;;;;;;;;IAQE,QAAQ;;;;;;;UAQK,cAAc;EAC7B,YAAY;;;;;KAMF;EACV;EACA,uBAAuB;;;;;UAMR;EACf,cAAc,oBAAoB;;;;;UAMnB,cAAc,kCAAkC,4CACvD,cAAc,aAAa;EACnC,UAAU;;;;;;;EAOV,WAAW;;;;;;;;UASI,mBACf,uCACA,kCACA,4CACQ,cAAc,UAAU;EAChC;EACA,cAAc;;;;;;EAMd;;;;;;;;UASe,eACf,uCACA,kCACA,4CACQ,mBAAmB,eAAe,UAAU;EACpD;;;;;;;;;;UAWe,sBAAsB;EACrC;;;;;;UAOe,qBAAqB,eAAe;;;;EAInD,OAAO;;;;;;;;;EASP,SAAS;;;;;;;;KASC,mBAAmB,kBAAkB,uBAAuB;;;;KAK5D;EAAmB;EAAmB;;;;;KAKtC;EAAwB;;;;;KAKxB;EAAkB;;;;;iBAKd,kBAAkB,UAAU,mBAAmB,YAAY;;;;iBAO3D,uBACd,UAAU,mBACT,YAAY;;;;iBAOC,iBAAiB,UAAU,mBAAmB,YAAY;;;;;;UCtLzD;;;;;WAKN;;;;WAKA,QAAQ;;;;;EAMjB;;;;;EAMA;;;;;;EAOA,UAAU;;;;;;;;;iBAUI,qBAAqB,SAAQ,eAAoB"}
package/dist/index.d.ts CHANGED
@@ -1,3 +1,3 @@
1
- import { _ as isCanvasResource, a as DatasetResource, b as AuthConfig, c as DocumentTypeHandle, d as ProjectHandle, f as ReleaseHandle, g as TokenSource, h as StudioConfig, i as DatasetHandle, l as MediaLibraryResource, m as SanityConfig, n as createSanityInstance, o as DocumentHandle, p as ReleasePerspective, r as CanvasResource, s as DocumentResource, t as SanityInstance, u as PerspectiveHandle, v as isDatasetResource, x as AuthProvider, y as isMediaLibraryResource } from "./createSanityInstance-BQIqyGLX.js";
2
- import { $ as project, $n as publishDocument, $r as refreshOAuthTokens, $t as ApplyDocumentActionsOptions, A as loadMoreUsers, An as CreateReleaseAction, Ar as RemoveCommentOptions, At as OrganizationsOptions, B as getQueryState, Bn as ReleaseAction, Br as CommentLocalState, Bt as InstallationBase, C as slicePath, Ci as application, Cn as ProcessMutationsOptions, Cr as getCommentThreadsState, Ct as ResolveUsersOptions, D as getCorsErrorProjectId, Di as AccessResourceType, Dn as Action, Dr as resolveCommentThreads, Dt as UsersGroupState, E as isImportError, Ei as updateApplication, En as JsonMatch, Et as UserProfile, F as ReleaseState, Fn as EditDocumentAction, Fr as removeComment, Ft as OrganizationOptions, G as resolveProjection, Gn as archiveRelease, Gr as CommentTextSelectionItem, Gt as installations, H as resolveQuery, Hn as UnarchiveReleaseAction, Hr as CommentReaction, Ht as InstallationsOptions, I as getActiveReleasesState, In as EditDocumentOptions, Ir as replyToComment, It as organization, J as ProjectBase, Jn as deleteDocument, Jr as ClientStoreState, Jt as SetFavoriteInput, K as getProjectionState, Kn as createDocument, Kr as CommentThread, Kt as FavoriteDocumentContext, L as getAllReleasesState, Ln as EditReleaseAction, Lr as setCommentStatus, Lt as Installation, M as resolveUsers, Mn as DeleteReleaseAction, Mr as SetCommentStatusOptions, Mt as Organization, N as defineProjection, Nn as DiscardDocumentAction, Nr as UpdateCommentOptions, Nt as OrganizationBase, O as getUserState, Oi as checkPermissions, On as ArchiveReleaseAction, Or as resolveComments, Ot as UsersStoreState, P as getPerspectiveState, Pn as DocumentAction, Pr as createComment, Pt as OrganizationMember, Q as ProjectOptions, Qn as editRelease, Qr as handleOAuthCallback, Qt as ActionsResult, R as QueryOptions, Ri as Selector, Rn as PublishDocumentAction, Rr as updateComment, Rt as InstallationAccess, S as jsonMatch, Si as UpdateApplicationInput, Sn as DocumentSet, Sr as ResolveCommentsOptions, St as ResolveUserOptions, T as CORE_SDK_VERSION, Ti as deleteApplication, Tn as processMutations, Tr as getCommentsState, Tt as SanityUserResponse, U as ProjectsOptions, Un as UnpublishDocumentAction, Ur as CommentStatus, Ut as InstallationsResponse, Vn as ScheduleReleaseAction, Vr as CommentMessage, Vt as InstallationInclude, W as projects, Wn as UnscheduleReleaseAction, Wr as CommentTextSelection, Wt as installation, X as ProjectMemberRole, Xn as discardDocument, Xr as getClientState, Xt as setFavorite, Y as ProjectMember, Yn as deleteRelease, Yr as getClient, Yt as favorites, Z as ProjectMetadata, Zn as editDocument, Zr as getOAuthTokensState, Zt as getReleaseDocumentId, _ as SanityDocument, _i as ApplicationWorkspace, _n as resolveDocument, _r as createDatasetHandle, _t as TransportEvent, a as LoggedOutAuthState, ai as observeOrganizationVerificationState, an as DocumentEditedEvent, ar as ResolveDocument, at as getPresence, b as getPathDepth, bi as DeleteApplicationInput, bn as DocumentPermissionsResult, br as createProjectHandle, bt as GetUsersOptions, c as getCurrentUserState, ci as Application, cn as DocumentRemotePatchesEvent, cr as datasets, ct as DocumentPresence, d as getLoginUrlState, di as ApplicationDeployment, dn as TransactionAcceptedEvent, dr as LogContext, dt as PresencePerspectiveOptions, ei as revokeOAuthTokens, en as applyDocumentActions, er as publishRelease, et as PreviewMedia, f as getTokenState, fi as ApplicationInclude, fn as TransactionRevertedEvent, fr as LogLevel, ft as PresenceSelection, g as Role, gi as ApplicationVisibility, gn as getPermissionsState, gt as StateEvent, h as ReleaseDocument, hi as ApplicationStudioConfig, hn as getDocumentSyncStatus, hr as LoggerConfig, ht as RollCallEvent, i as LoggedInAuthState, ii as handleAuthCallback, in as DocumentDiscardedEvent, ir as unscheduleRelease, it as getDocumentPresence, j as resolveUser, jn as DeleteDocumentAction, jr as ReplyToCommentOptions, jt as organizations, k as getUsersState, kn as CreateDocumentAction, kr as CreateCommentOptions, kt as Organizations, l as getDashboardOrganizationId, li as ApplicationAccess, ln as DocumentTransactionSubmissionResult, lr as configureLogging, lt as DocumentPresenceOptions, m as CurrentUser, mi as ApplicationInterfacePlacementMetadata, mn as getDocumentState, mr as Logger, mt as ReportPresenceOptions, n as AuthStoreState, ni as OAuthTokens, nn as DocumentCreatedEvent, nr as unarchiveRelease, nt as PreviewValue, o as LoggingInAuthState, oi as OrgVerificationResult, on as DocumentEvent, or as ResolveProjectionResult, ot as reportPresence, p as setAuthToken, pi as ApplicationInterface, pn as DocumentOptions, pr as LogNamespace, pt as PresenceSelectionPoint, q as Project, qn as createRelease, qr as ClientOptions, qt as FavoriteStatusResponse, r as ErrorAuthState, ri as logout, rn as DocumentDeletedEvent, rr as unpublishDocument, rt as ProjectionValuePending, s as getAuthState, si as AuthStateType, sn as DocumentPublishedEvent, sr as ResolveQueryResult, st as DisconnectEvent, t as AuthState, ti as startOAuthAuthorization, tn as ActionErrorEvent, tr as scheduleRelease, tt as PreviewQueryResult, u as getIsInDashboardState, ui as ApplicationBase, un as DocumentUnpublishedEvent, ur as InstanceContext, ut as PresenceLocation, v as SanityProject, vi as ApplicationsOptions, vn as resolvePermissions, vr as createDocumentHandle, vt as UserPresence, w as stringifyPath, wi as applications, wn as patchOperations, wt as SanityUser, x as joinPaths, xi as DeletedResult, xn as PermissionDeniedReason, xr as CommentsOptions, xt as Membership, y as getIndexForKey, yi as ApplicationsResponse, yn as subscribeDocumentEvents, yr as createDocumentTypeHandle, yt as GetUserOptions, zi as StateSource, zn as PublishReleaseAction, zr as Comment, zt as InstallationActiveConfig } from "./authStore-BO2vch3I.js";
1
+ import { _ as isCanvasResource, a as DatasetResource, b as AuthConfig, c as DocumentTypeHandle, d as ProjectHandle, f as ReleaseHandle, g as TokenSource, h as StudioConfig, i as DatasetHandle, l as MediaLibraryResource, m as SanityConfig, n as createSanityInstance, o as DocumentHandle, p as ReleasePerspective, r as CanvasResource, s as DocumentResource, t as SanityInstance, u as PerspectiveHandle, v as isDatasetResource, x as AuthProvider, y as isMediaLibraryResource } from "./createSanityInstance--Lrldto8.js";
2
+ import { $ as project, $n as publishDocument, $r as refreshOAuthTokens, $t as ApplyDocumentActionsOptions, A as loadMoreUsers, An as CreateReleaseAction, Ar as RemoveCommentOptions, At as OrganizationsOptions, B as getQueryState, Bn as ReleaseAction, Br as CommentLocalState, Bt as InstallationBase, C as slicePath, Ci as application, Cn as ProcessMutationsOptions, Cr as getCommentThreadsState, Ct as ResolveUsersOptions, D as getCorsErrorProjectId, Di as AccessResourceType, Dn as Action, Dr as resolveCommentThreads, Dt as UsersGroupState, E as isImportError, Ei as updateApplication, En as JsonMatch, Et as UserProfile, F as ReleaseState, Fn as EditDocumentAction, Fr as removeComment, Ft as OrganizationOptions, G as resolveProjection, Gn as archiveRelease, Gr as CommentTextSelectionItem, Gt as installations, H as resolveQuery, Hn as UnarchiveReleaseAction, Hr as CommentReaction, Ht as InstallationsOptions, I as getActiveReleasesState, In as EditDocumentOptions, Ir as replyToComment, It as organization, J as ProjectBase, Jn as deleteDocument, Jr as ClientStoreState, Jt as SetFavoriteInput, K as getProjectionState, Kn as createDocument, Kr as CommentThread, Kt as FavoriteDocumentContext, L as getAllReleasesState, Ln as EditReleaseAction, Lr as setCommentStatus, Lt as Installation, M as resolveUsers, Mn as DeleteReleaseAction, Mr as SetCommentStatusOptions, Mt as Organization, N as defineProjection, Nn as DiscardDocumentAction, Nr as UpdateCommentOptions, Nt as OrganizationBase, O as getUserState, Oi as checkPermissions, On as ArchiveReleaseAction, Or as resolveComments, Ot as UsersStoreState, P as getPerspectiveState, Pn as DocumentAction, Pr as createComment, Pt as OrganizationMember, Q as ProjectOptions, Qn as editRelease, Qr as handleOAuthCallback, Qt as ActionsResult, R as QueryOptions, Ri as Selector, Rn as PublishDocumentAction, Rr as updateComment, Rt as InstallationAccess, S as jsonMatch, Si as UpdateApplicationInput, Sn as DocumentSet, Sr as ResolveCommentsOptions, St as ResolveUserOptions, T as CORE_SDK_VERSION, Ti as deleteApplication, Tn as processMutations, Tr as getCommentsState, Tt as SanityUserResponse, U as ProjectsOptions, Un as UnpublishDocumentAction, Ur as CommentStatus, Ut as InstallationsResponse, Vn as ScheduleReleaseAction, Vr as CommentMessage, Vt as InstallationInclude, W as projects, Wn as UnscheduleReleaseAction, Wr as CommentTextSelection, Wt as installation, X as ProjectMemberRole, Xn as discardDocument, Xr as getClientState, Xt as setFavorite, Y as ProjectMember, Yn as deleteRelease, Yr as getClient, Yt as favorites, Z as ProjectMetadata, Zn as editDocument, Zr as getOAuthTokensState, Zt as getReleaseDocumentId, _ as SanityDocument, _i as ApplicationWorkspace, _n as resolveDocument, _r as createDatasetHandle, _t as TransportEvent, a as LoggedOutAuthState, ai as observeOrganizationVerificationState, an as DocumentEditedEvent, ar as ResolveDocument, at as getPresence, b as getPathDepth, bi as DeleteApplicationInput, bn as DocumentPermissionsResult, br as createProjectHandle, bt as GetUsersOptions, c as getCurrentUserState, ci as Application, cn as DocumentRemotePatchesEvent, cr as datasets, ct as DocumentPresence, d as getLoginUrlState, di as ApplicationDeployment, dn as TransactionAcceptedEvent, dr as LogContext, dt as PresencePerspectiveOptions, ei as revokeOAuthTokens, en as applyDocumentActions, er as publishRelease, et as PreviewMedia, f as getTokenState, fi as ApplicationInclude, fn as TransactionRevertedEvent, fr as LogLevel, ft as PresenceSelection, g as Role, gi as ApplicationVisibility, gn as getPermissionsState, gt as StateEvent, h as ReleaseDocument, hi as ApplicationStudioConfig, hn as getDocumentSyncStatus, hr as LoggerConfig, ht as RollCallEvent, i as LoggedInAuthState, ii as handleAuthCallback, in as DocumentDiscardedEvent, ir as unscheduleRelease, it as getDocumentPresence, j as resolveUser, jn as DeleteDocumentAction, jr as ReplyToCommentOptions, jt as organizations, k as getUsersState, kn as CreateDocumentAction, kr as CreateCommentOptions, kt as Organizations, l as getDashboardOrganizationId, li as ApplicationAccess, ln as DocumentTransactionSubmissionResult, lr as configureLogging, lt as DocumentPresenceOptions, m as CurrentUser, mi as ApplicationInterfacePlacementMetadata, mn as getDocumentState, mr as Logger, mt as ReportPresenceOptions, n as AuthStoreState, ni as OAuthTokens, nn as DocumentCreatedEvent, nr as unarchiveRelease, nt as PreviewValue, o as LoggingInAuthState, oi as OrgVerificationResult, on as DocumentEvent, or as ResolveProjectionResult, ot as reportPresence, p as setAuthToken, pi as ApplicationInterface, pn as DocumentOptions, pr as LogNamespace, pt as PresenceSelectionPoint, q as Project, qn as createRelease, qr as ClientOptions, qt as FavoriteStatusResponse, r as ErrorAuthState, ri as logout, rn as DocumentDeletedEvent, rr as unpublishDocument, rt as ProjectionValuePending, s as getAuthState, si as AuthStateType, sn as DocumentPublishedEvent, sr as ResolveQueryResult, st as DisconnectEvent, t as AuthState, ti as startOAuthAuthorization, tn as ActionErrorEvent, tr as scheduleRelease, tt as PreviewQueryResult, u as getIsInDashboardState, ui as ApplicationBase, un as DocumentUnpublishedEvent, ur as InstanceContext, ut as PresenceLocation, v as SanityProject, vi as ApplicationsOptions, vn as resolvePermissions, vr as createDocumentHandle, vt as UserPresence, w as stringifyPath, wi as applications, wn as patchOperations, wt as SanityUser, x as joinPaths, xi as DeletedResult, xn as PermissionDeniedReason, xr as CommentsOptions, xt as Membership, y as getIndexForKey, yi as ApplicationsResponse, yn as subscribeDocumentEvents, yr as createDocumentTypeHandle, yt as GetUserOptions, zi as StateSource, zn as PublishReleaseAction, zr as Comment, zt as InstallationActiveConfig } from "./authStore-7dZCfKUq.js";
3
3
  export { type AccessResourceType, type Action, type ActionErrorEvent, type ActionsResult, type Application, type ApplicationAccess, type ApplicationBase, type ApplicationDeployment, type ApplicationInclude, type ApplicationInterface, type ApplicationInterfacePlacementMetadata, type ApplicationStudioConfig, type ApplicationVisibility, type ApplicationWorkspace, type ApplicationsOptions, type ApplicationsResponse, type ApplyDocumentActionsOptions, type ArchiveReleaseAction, type AuthConfig, type AuthProvider, type AuthState, AuthStateType, type AuthStoreState, CORE_SDK_VERSION, type CanvasResource, type ClientOptions, type ClientStoreState as ClientState, type Comment, type CommentLocalState, type CommentMessage, type CommentReaction, type CommentStatus, type CommentTextSelection, type CommentTextSelectionItem, type CommentThread, type CommentsOptions, type CreateCommentOptions, type CreateDocumentAction, type CreateReleaseAction, type CurrentUser, type DatasetHandle, type DatasetResource, type DeleteApplicationInput, type DeleteDocumentAction, type DeleteReleaseAction, type DeletedResult, type DiscardDocumentAction, type DisconnectEvent, type DocumentAction, type DocumentCreatedEvent, type DocumentDeletedEvent, type DocumentDiscardedEvent, type DocumentEditedEvent, type DocumentEvent, type DocumentHandle, type DocumentOptions, type DocumentPermissionsResult, type DocumentPresence, type DocumentPresenceOptions, type DocumentPublishedEvent, type DocumentRemotePatchesEvent, type DocumentResource, type DocumentSet, type DocumentTransactionSubmissionResult, type DocumentTypeHandle, type DocumentUnpublishedEvent, type EditDocumentAction, type EditDocumentOptions, type EditReleaseAction, type ErrorAuthState, type FavoriteDocumentContext, type FavoriteStatusResponse, type GetUserOptions, type GetUsersOptions, type Installation, type InstallationAccess, type InstallationActiveConfig, type InstallationBase, type InstallationInclude, type InstallationsOptions, type InstallationsResponse, type InstanceContext, type JsonMatch, type LogContext, type LogLevel, type LogNamespace, type LoggedInAuthState, type LoggedOutAuthState, type Logger, type LoggerConfig, type LoggingInAuthState, type MediaLibraryResource, type Membership, type OAuthTokens, type OrgVerificationResult, type Organization, type OrganizationBase, type OrganizationMember, type OrganizationOptions, type Organizations, type OrganizationsOptions, type PermissionDeniedReason, type PerspectiveHandle, type PresenceLocation, type PresencePerspectiveOptions, type PresenceSelection, type PresenceSelectionPoint, type PreviewMedia, type PreviewQueryResult, type PreviewValue, type ProcessMutationsOptions, type Project, type ProjectBase, type ProjectHandle, type ProjectMember, type ProjectMemberRole, type ProjectMetadata, type ProjectOptions, type ProjectionValuePending, type ProjectsOptions, type PublishDocumentAction, type PublishReleaseAction, type QueryOptions, type ReleaseAction, type ReleaseDocument, type ReleaseHandle, type ReleasePerspective, type ReleaseState, type RemoveCommentOptions, type ReplyToCommentOptions, type ReportPresenceOptions, type ResolveCommentsOptions, type ResolveDocument, type ResolveProjectionResult, type ResolveQueryResult, type ResolveUserOptions, type ResolveUsersOptions, type Role, type RollCallEvent, type SanityConfig, type SanityDocument, type SanityInstance, SanityProject, type SanityUser, type SanityUserResponse, type ScheduleReleaseAction, type Selector, type SetCommentStatusOptions, type SetFavoriteInput, type StateEvent, type StateSource, type StudioConfig, type TokenSource, type TransactionAcceptedEvent, type TransactionRevertedEvent, type TransportEvent, type UnarchiveReleaseAction, type UnpublishDocumentAction, type UnscheduleReleaseAction, type UpdateApplicationInput, type UpdateCommentOptions, type UserPresence, type UserProfile, type UsersGroupState, type UsersStoreState, application, applications, applyDocumentActions, archiveRelease, checkPermissions, configureLogging, createComment, createDatasetHandle, createDocument, createDocumentHandle, createDocumentTypeHandle, createProjectHandle, createRelease, createSanityInstance, datasets, defineProjection, deleteApplication, deleteDocument, deleteRelease, discardDocument, editDocument, editRelease, favorites, getActiveReleasesState, getAllReleasesState, getAuthState, getClient, getClientState, getCommentThreadsState, getCommentsState, getCorsErrorProjectId, getCurrentUserState, getDashboardOrganizationId, getDocumentPresence, getDocumentState, getDocumentSyncStatus, getIndexForKey, getIsInDashboardState, getLoginUrlState, getOAuthTokensState, getPathDepth, getPermissionsState, getPerspectiveState, getPresence, getProjectionState, getQueryState, getReleaseDocumentId, getTokenState, getUserState, getUsersState, handleAuthCallback, handleOAuthCallback, installation, installations, isCanvasResource, isDatasetResource, isImportError, isMediaLibraryResource, joinPaths, jsonMatch, loadMoreUsers, logout, observeOrganizationVerificationState, organization, organizations, patchOperations, processMutations, project, projects, publishDocument, publishRelease, refreshOAuthTokens, removeComment, replyToComment, reportPresence, resolveCommentThreads, resolveComments, resolveDocument, resolvePermissions, resolveProjection, resolveQuery, resolveUser, resolveUsers, revokeOAuthTokens, scheduleRelease, setAuthToken, setCommentStatus, setFavorite, slicePath, startOAuthAuthorization, stringifyPath, subscribeDocumentEvents, unarchiveRelease, unpublishDocument, unscheduleRelease, updateApplication, updateComment };