@sanity/sdk 3.4.0-rc.0 → 3.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/_exports/_internal.d.ts +3 -3
- package/dist/_exports/_internal.js +5 -5
- package/dist/_exports/agent.d.ts +1 -1
- package/dist/_exports/agent.js +1 -1
- package/dist/_exports/comlink.d.ts +1 -1
- package/dist/_exports/dashboard.d.ts +2 -2
- package/dist/_exports/dashboard.js +2 -2
- package/dist/{applications-903KQTrD.d.ts → applications-Bb-0Kgkc.d.ts} +6 -20
- package/dist/applications-Bb-0Kgkc.d.ts.map +1 -0
- package/dist/{clientStore-QDrJNTM4.js → clientStore-CD-USpIU.js} +11 -15
- package/dist/clientStore-CD-USpIU.js.map +1 -0
- package/dist/{createSanityInstance--Lrldto8.d.ts → createSanityInstance-BQIqyGLX.d.ts} +3 -6
- package/dist/createSanityInstance-BQIqyGLX.d.ts.map +1 -0
- package/dist/index.d.ts +2 -2
- package/dist/index.js +204 -211
- package/dist/index.js.map +1 -1
- package/dist/{topicStore-BJ54_X6H.js → topicStore-CPhGph6z.js} +53 -13
- package/dist/topicStore-CPhGph6z.js.map +1 -0
- package/dist/{topicStore-VQILEI1R.d.ts → topicStore-fPK2CfqH.d.ts} +91 -4
- package/dist/topicStore-fPK2CfqH.d.ts.map +1 -0
- package/dist/{version-CYqZgJX1.js → version-C7m7OAy9.js} +3 -3
- package/dist/{version-CYqZgJX1.js.map → version-C7m7OAy9.js.map} +1 -1
- package/package.json +6 -6
- package/src/_exports/dashboard.ts +6 -0
- package/src/auth/authStore.test.ts +0 -18
- package/src/auth/authStore.ts +1 -4
- package/src/auth/handleAuthCallback.test.ts +0 -33
- package/src/auth/handleAuthCallback.ts +1 -11
- package/src/auth/logout.test.ts +1 -9
- package/src/auth/logout.ts +1 -18
- package/src/auth/oauth/oauthActions.test.ts +1 -178
- package/src/auth/oauth/oauthActions.ts +46 -111
- package/src/auth/oauth/oauthAuth.test.ts +0 -23
- package/src/auth/oauth/oauthAuth.ts +8 -18
- package/src/config/authConfig.ts +2 -5
- package/src/dashboard/messageBus/bus.test.ts +118 -0
- package/src/dashboard/messageBus/bus.ts +81 -7
- package/src/dashboard/messageBus/topics.test.ts +20 -0
- package/src/dashboard/messageBus/topics.ts +74 -0
- package/src/document/documentConstants.ts +5 -2
- package/src/document/documentStore.test.ts +194 -0
- package/src/document/documentStore.ts +79 -39
- package/src/document/reducers.ts +2 -2
- package/dist/applications-903KQTrD.d.ts.map +0 -1
- package/dist/clientStore-QDrJNTM4.js.map +0 -1
- package/dist/createSanityInstance--Lrldto8.d.ts.map +0 -1
- package/dist/topicStore-BJ54_X6H.js.map +0 -1
- package/dist/topicStore-VQILEI1R.d.ts.map +0 -1
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
|
|
2
|
-
import { $ as Project, $n as createRelease, $r as ClientOptions, $t as FavoriteStatusResponse, A as stringifyPath, An as patchOperations, At as SanityUser, B as getPerspectiveState, Bn as DocumentAction, Br as createComment, Bt as OrganizationMember, C as SanityDocument, Ci as getTokenState, Cn as resolveDocument, Cr as createDatasetHandle, Ct as TransportEvent, D as joinPaths, Di as AccessResourceType, Dn as PermissionDeniedReason, Dr as CommentsOptions, Dt as Membership, E as getPathDepth, Ei as AuthStateType, En as DocumentPermissionsResult, Er as createProjectHandle, Et as GetUsersOptions, F as getUsersState, Fn as CreateDocumentAction, Fr as CreateCommentOptions, Ft as Organizations, Gn as PublishReleaseAction, Gr as Comment, Gt as InstallationActiveConfig, H as getActiveReleasesState, Hn as EditDocumentOptions, Hr as replyToComment, Ht as organization, I as loadMoreUsers, In as CreateReleaseAction, Ir as RemoveCommentOptions, It as OrganizationsOptions, J as resolveQuery, Jn as UnarchiveReleaseAction, Jr as CommentReaction, Jt as InstallationsOptions, K as getQueryState, Kn as ReleaseAction, Kr as CommentLocalState, Kt as InstallationBase, L as resolveUser, Ln as DeleteDocumentAction, Lr as ReplyToCommentOptions, Lt as organizations, M as isImportError, Mn as JsonMatch, Mt as UserProfile, N as getCorsErrorProjectId, Nn as Action, Nr as resolveCommentThreads, Nt as UsersGroupState, O as jsonMatch, Oi as checkPermissions, On as DocumentSet, Or as ResolveCommentsOptions, Ot as ResolveUserOptions, P as getUserState, Pn as ArchiveReleaseAction, Pr as resolveComments, Pt as UsersStoreState, Q as getProjectionState, Qn as createDocument, Qr as CommentThread, Qt as FavoriteDocumentContext, R as resolveUsers, Ri as Selector, Rn as DeleteReleaseAction, Rr as SetCommentStatusOptions, Rt as Organization, S as Role, Si as getLoginUrlState, Sn as getPermissionsState, St as StateEvent, T as getIndexForKey, Ti as OAuthTokens, Tn as subscribeDocumentEvents, Tr as createDocumentTypeHandle, Tt as GetUserOptions, U as getAllReleasesState, Un as EditReleaseAction, Ur as setCommentStatus, Ut as Installation, V as ReleaseState, Vn as EditDocumentAction, Vr as removeComment, Vt as OrganizationOptions, W as QueryOptions, Wn as PublishDocumentAction, Wr as updateComment, Wt as InstallationAccess, X as projects, Xn as UnscheduleReleaseAction, Xr as CommentTextSelection, Xt as installation, Y as ProjectsOptions, Yn as UnpublishDocumentAction, Yr as CommentStatus, Yt as InstallationsResponse, Z as resolveProjection, Zn as archiveRelease, Zr as CommentTextSelectionItem, Zt as installations, _ as applications, _i as LoggingInAuthState, _n as TransactionAcceptedEvent, _r as LogContext, _t as PresencePerspectiveOptions, a as ApplicationInclude, ai as refreshOAuthTokens, an as ApplyDocumentActionsOptions, ar as publishDocument, at as project, b as CurrentUser, bi as getDashboardOrganizationId, bn as getDocumentState, br as Logger, bt as ReportPresenceOptions, c as ApplicationStudioConfig, ci as logout, cn as DocumentCreatedEvent, cr as unarchiveRelease, ct as PreviewValue, d as ApplicationsOptions, di as OrgVerificationResult, dn as DocumentEditedEvent, dr as ResolveDocument, dt as getPresence, ei as ClientStoreState, en as SetFavoriteInput, er as deleteDocument, et as ProjectBase, f as ApplicationsResponse, fi as AuthState, fn as DocumentEvent, fr as ResolveProjectionResult, ft as reportPresence, g as application, gi as LoggedOutAuthState, gn as DocumentUnpublishedEvent, gr as InstanceContext, gt as PresenceLocation, h as UpdateApplicationInput, hi as LoggedInAuthState, hn as DocumentTransactionSubmissionResult, hr as configureLogging, ht as DocumentPresenceOptions, i as ApplicationDeployment, ii as handleOAuthCallback, in as ActionsResult, ir as editRelease, it as ProjectOptions, j as CORE_SDK_VERSION, jn as processMutations, jr as getCommentsState, jt as SanityUserResponse, k as slicePath, kn as ProcessMutationsOptions, kr as getCommentThreadsState, kt as ResolveUsersOptions, l as ApplicationVisibility, li as handleAuthCallback, ln as DocumentDeletedEvent, lr as unpublishDocument, lt as ProjectionValuePending, m as DeletedResult, mi as ErrorAuthState, mn as DocumentRemotePatchesEvent, mr as datasets, mt as DocumentPresence, n as ApplicationAccess, ni as getClientState, nn as setFavorite, nr as discardDocument, nt as ProjectMemberRole, o as ApplicationInterface, oi as revokeOAuthTokens, on as applyDocumentActions, or as publishRelease, ot as PreviewMedia, p as DeleteApplicationInput, pi as AuthStoreState, pn as DocumentPublishedEvent, pr as ResolveQueryResult, pt as DisconnectEvent, qn as ScheduleReleaseAction, qr as CommentMessage, qt as InstallationInclude, r as ApplicationBase, ri as getOAuthTokensState, rn as getReleaseDocumentId, rr as editDocument, rt as ProjectMetadata, s as ApplicationInterfacePlacementMetadata, si as startOAuthAuthorization, sn as ActionErrorEvent, sr as scheduleRelease, st as PreviewQueryResult, t as Application, ti as getClient, tn as favorites, tr as deleteRelease, tt as ProjectMember, u as ApplicationWorkspace, ui as observeOrganizationVerificationState, un as DocumentDiscardedEvent, ur as unscheduleRelease, ut as getDocumentPresence, v as deleteApplication, vi as getAuthState, vn as TransactionRevertedEvent, vr as LogLevel, vt as PresenceSelection, w as SanityProject, wi as setAuthToken, wn as resolvePermissions, wr as createDocumentHandle, wt as UserPresence, x as ReleaseDocument, xi as getIsInDashboardState, xn as getDocumentSyncStatus, xr as LoggerConfig, xt as RollCallEvent, y as updateApplication, yi as getCurrentUserState, yn as DocumentOptions, yr as LogNamespace, yt as PresenceSelectionPoint, z as defineProjection, zi as StateSource, zn as DiscardDocumentAction, zr as UpdateCommentOptions, zt as OrganizationBase } from "./applications-
|
|
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 createRelease, $r as ClientOptions, $t as FavoriteStatusResponse, A as stringifyPath, An as patchOperations, At as SanityUser, B as getPerspectiveState, Bn as DocumentAction, Br as createComment, Bt as OrganizationMember, C as SanityDocument, Ci as getTokenState, Cn as resolveDocument, Cr as createDatasetHandle, Ct as TransportEvent, D as joinPaths, Di as AccessResourceType, Dn as PermissionDeniedReason, Dr as CommentsOptions, Dt as Membership, E as getPathDepth, Ei as AuthStateType, En as DocumentPermissionsResult, Er as createProjectHandle, Et as GetUsersOptions, F as getUsersState, Fn as CreateDocumentAction, Fr as CreateCommentOptions, Ft as Organizations, Gn as PublishReleaseAction, Gr as Comment, Gt as InstallationActiveConfig, H as getActiveReleasesState, Hn as EditDocumentOptions, Hr as replyToComment, Ht as organization, I as loadMoreUsers, In as CreateReleaseAction, Ir as RemoveCommentOptions, It as OrganizationsOptions, J as resolveQuery, Jn as UnarchiveReleaseAction, Jr as CommentReaction, Jt as InstallationsOptions, K as getQueryState, Kn as ReleaseAction, Kr as CommentLocalState, Kt as InstallationBase, L as resolveUser, Ln as DeleteDocumentAction, Lr as ReplyToCommentOptions, Lt as organizations, M as isImportError, Mn as JsonMatch, Mt as UserProfile, N as getCorsErrorProjectId, Nn as Action, Nr as resolveCommentThreads, Nt as UsersGroupState, O as jsonMatch, Oi as checkPermissions, On as DocumentSet, Or as ResolveCommentsOptions, Ot as ResolveUserOptions, P as getUserState, Pn as ArchiveReleaseAction, Pr as resolveComments, Pt as UsersStoreState, Q as getProjectionState, Qn as createDocument, Qr as CommentThread, Qt as FavoriteDocumentContext, R as resolveUsers, Ri as Selector, Rn as DeleteReleaseAction, Rr as SetCommentStatusOptions, Rt as Organization, S as Role, Si as getLoginUrlState, Sn as getPermissionsState, St as StateEvent, T as getIndexForKey, Ti as OAuthTokens, Tn as subscribeDocumentEvents, Tr as createDocumentTypeHandle, Tt as GetUserOptions, U as getAllReleasesState, Un as EditReleaseAction, Ur as setCommentStatus, Ut as Installation, V as ReleaseState, Vn as EditDocumentAction, Vr as removeComment, Vt as OrganizationOptions, W as QueryOptions, Wn as PublishDocumentAction, Wr as updateComment, Wt as InstallationAccess, X as projects, Xn as UnscheduleReleaseAction, Xr as CommentTextSelection, Xt as installation, Y as ProjectsOptions, Yn as UnpublishDocumentAction, Yr as CommentStatus, Yt as InstallationsResponse, Z as resolveProjection, Zn as archiveRelease, Zr as CommentTextSelectionItem, Zt as installations, _ as applications, _i as LoggingInAuthState, _n as TransactionAcceptedEvent, _r as LogContext, _t as PresencePerspectiveOptions, a as ApplicationInclude, ai as refreshOAuthTokens, an as ApplyDocumentActionsOptions, ar as publishDocument, at as project, b as CurrentUser, bi as getDashboardOrganizationId, bn as getDocumentState, br as Logger, bt as ReportPresenceOptions, c as ApplicationStudioConfig, ci as logout, cn as DocumentCreatedEvent, cr as unarchiveRelease, ct as PreviewValue, d as ApplicationsOptions, di as OrgVerificationResult, dn as DocumentEditedEvent, dr as ResolveDocument, dt as getPresence, ei as ClientStoreState, en as SetFavoriteInput, er as deleteDocument, et as ProjectBase, f as ApplicationsResponse, fi as AuthState, fn as DocumentEvent, fr as ResolveProjectionResult, ft as reportPresence, g as application, gi as LoggedOutAuthState, gn as DocumentUnpublishedEvent, gr as InstanceContext, gt as PresenceLocation, h as UpdateApplicationInput, hi as LoggedInAuthState, hn as DocumentTransactionSubmissionResult, hr as configureLogging, ht as DocumentPresenceOptions, i as ApplicationDeployment, ii as handleOAuthCallback, in as ActionsResult, ir as editRelease, it as ProjectOptions, j as CORE_SDK_VERSION, jn as processMutations, jr as getCommentsState, jt as SanityUserResponse, k as slicePath, kn as ProcessMutationsOptions, kr as getCommentThreadsState, kt as ResolveUsersOptions, l as ApplicationVisibility, li as handleAuthCallback, ln as DocumentDeletedEvent, lr as unpublishDocument, lt as ProjectionValuePending, m as DeletedResult, mi as ErrorAuthState, mn as DocumentRemotePatchesEvent, mr as datasets, mt as DocumentPresence, n as ApplicationAccess, ni as getClientState, nn as setFavorite, nr as discardDocument, nt as ProjectMemberRole, o as ApplicationInterface, oi as revokeOAuthTokens, on as applyDocumentActions, or as publishRelease, ot as PreviewMedia, p as DeleteApplicationInput, pi as AuthStoreState, pn as DocumentPublishedEvent, pr as ResolveQueryResult, pt as DisconnectEvent, qn as ScheduleReleaseAction, qr as CommentMessage, qt as InstallationInclude, r as ApplicationBase, ri as getOAuthTokensState, rn as getReleaseDocumentId, rr as editDocument, rt as ProjectMetadata, s as ApplicationInterfacePlacementMetadata, si as startOAuthAuthorization, sn as ActionErrorEvent, sr as scheduleRelease, st as PreviewQueryResult, t as Application, ti as getClient, tn as favorites, tr as deleteRelease, tt as ProjectMember, u as ApplicationWorkspace, ui as observeOrganizationVerificationState, un as DocumentDiscardedEvent, ur as unscheduleRelease, ut as getDocumentPresence, v as deleteApplication, vi as getAuthState, vn as TransactionRevertedEvent, vr as LogLevel, vt as PresenceSelection, w as SanityProject, wi as setAuthToken, wn as resolvePermissions, wr as createDocumentHandle, wt as UserPresence, x as ReleaseDocument, xi as getIsInDashboardState, xn as getDocumentSyncStatus, xr as LoggerConfig, xt as RollCallEvent, y as updateApplication, yi as getCurrentUserState, yn as DocumentOptions, yr as LogNamespace, yt as PresenceSelectionPoint, z as defineProjection, zi as StateSource, zn as DiscardDocumentAction, zr as UpdateCommentOptions, zt as OrganizationBase } from "./applications-Bb-0Kgkc.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 };
|
package/dist/index.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import { D as getAuthLogger, E as REQUEST_TAG_PREFIX, O as configureLogging$1, S as AuthStateType, T as DEFAULT_BASE, b as getTokenFromLocation, c as getDashboardOrganizationId, d as getTokenState, f as setAuthToken, h as getCleanedUrl, i as authStore, k as createLogger, l as getIsInDashboardState, m as getAuthCode, n as getClient, o as getAuthState, p as createLoggedInAuthState, r as getClientState, s as getCurrentUserState, u as getLoginUrlState, w as DEFAULT_API_VERSION, y as getDefaultLocation } from "./clientStore-
|
|
1
|
+
import { D as getAuthLogger, E as REQUEST_TAG_PREFIX, O as configureLogging$1, S as AuthStateType, T as DEFAULT_BASE, b as getTokenFromLocation, c as getDashboardOrganizationId, d as getTokenState, f as setAuthToken, h as getCleanedUrl, i as authStore, k as createLogger, l as getIsInDashboardState, m as getAuthCode, n as getClient, o as getAuthState, p as createLoggedInAuthState, r as getClientState, s as getCurrentUserState, u as getLoginUrlState, w as DEFAULT_API_VERSION, y as getDefaultLocation } from "./clientStore-CD-USpIU.js";
|
|
2
2
|
import { c as isReleasePerspective, d as isMediaLibraryResource, i as bindActionGlobally, l as isCanvasResource, n as bindActionByResource, o as defineStore, r as bindActionByResourceAndPerspective, t as createStateSourceAction, u as isDatasetResource } from "./createStateSourceAction-DdAhEfnZ.js";
|
|
3
|
-
import { A as clearPendingTransaction, B as assertDatasetResource, C as getCommentsState, D as toCommentsKeyParts, E as resolveComments, F as rollbackCommentUpdate, G as defineMutation, H as provisionAddonDataset, I as setCommentCreateError, K as randomId, L as setPendingTransaction, M as receiveComment, N as removeCommentById, O as addComment, P as restoreComments, R as normalizeComment, T as resolveCommentThreads, U as COMMENTS_API_VERSION, V as getAddonDatasetState, W as defineFetcher, _ as updateLastLoadMoreRequest, a as resolveQuery, b as commentsStore, c as getAllReleasesState, d as getUsersKey, f as initializeRequest, g as setUsersError, h as setUsersData, j as getCommentsKey, k as applyCommentUpdate, l as addSubscription, m as removeSubscription, o as getPerspectiveState, p as parseUsersKey, q as randomUuid, r as getQueryState, s as getActiveReleasesState, t as CORE_SDK_VERSION, u as cancelRequest, v as PROJECT_API_VERSION, x as getCommentThreadsState, y as USERS_STATE_CLEAR_DELAY, z as toCommentFieldPath } from "./version-
|
|
3
|
+
import { A as clearPendingTransaction, B as assertDatasetResource, C as getCommentsState, D as toCommentsKeyParts, E as resolveComments, F as rollbackCommentUpdate, G as defineMutation, H as provisionAddonDataset, I as setCommentCreateError, K as randomId, L as setPendingTransaction, M as receiveComment, N as removeCommentById, O as addComment, P as restoreComments, R as normalizeComment, T as resolveCommentThreads, U as COMMENTS_API_VERSION, V as getAddonDatasetState, W as defineFetcher, _ as updateLastLoadMoreRequest, a as resolveQuery, b as commentsStore, c as getAllReleasesState, d as getUsersKey, f as initializeRequest, g as setUsersError, h as setUsersData, j as getCommentsKey, k as applyCommentUpdate, l as addSubscription, m as removeSubscription, o as getPerspectiveState, p as parseUsersKey, q as randomUuid, r as getQueryState, s as getActiveReleasesState, t as CORE_SDK_VERSION, u as cancelRequest, v as PROJECT_API_VERSION, x as getCommentThreadsState, y as USERS_STATE_CLEAR_DELAY, z as toCommentFieldPath } from "./version-C7m7OAy9.js";
|
|
4
4
|
import { r as omitProperty, t as isDeepEqual } from "./object-CxXlSVg7.js";
|
|
5
5
|
import { n as setCleanupTimeout } from "./setCleanupTimeout-BiM6q1KF.js";
|
|
6
6
|
import { t as _defineProperty } from "./defineProperty-Bho9Ngsi.js";
|
|
7
7
|
import { t as getNodeState } from "./getNodeState-B4nG0sjm.js";
|
|
8
|
-
import { ClientError, CorsOriginError } from "@sanity/client";
|
|
8
|
+
import { ClientError, CorsOriginError, ServerError } from "@sanity/client";
|
|
9
9
|
import { EMPTY, NEVER, Observable, Subject, Subscription, auditTime, catchError, combineLatest, concat, concatMap, debounceTime, defer, distinctUntilChanged, filter, first, firstValueFrom, from, fromEvent, groupBy, map, merge, mergeMap, of, pairwise, partition, race, retry, share, shareReplay, skip, startWith, switchMap, take, takeUntil, tap, throttle, throwError, timer, withLatestFrom } from "rxjs";
|
|
10
10
|
import { isKeySegment, isKeyedObject } from "@sanity/types";
|
|
11
11
|
import { DocumentId, getDraftId, getPublishedId, getVersionId, isDraftId, isPublishedId, isVersionId } from "@sanity/id-utils";
|
|
@@ -303,6 +303,101 @@ function observeOrganizationVerificationState(instance, projectIds) {
|
|
|
303
303
|
}), distinctUntilChanged((prev, curr) => prev.error === curr.error));
|
|
304
304
|
}
|
|
305
305
|
/**
|
|
306
|
+
* @public
|
|
307
|
+
*/
|
|
308
|
+
const handleAuthCallback = bindActionGlobally(authStore, async ({ state, instance }, locationHref = getDefaultLocation()) => {
|
|
309
|
+
let logger = getAuthLogger(instance), { providedToken, callbackUrl, clientFactory, apiHost, storageArea, storageKey } = state.get().options;
|
|
310
|
+
if (providedToken) return logger.debug("Skipping auth callback - token already provided"), !1;
|
|
311
|
+
let { authState } = state.get();
|
|
312
|
+
if (authState.type === "logging-in" && authState.isExchangingToken) return logger.debug("Skipping auth callback - token exchange already in progress"), !1;
|
|
313
|
+
let cleanedUrl = getCleanedUrl(locationHref), tokenFromUrl = getTokenFromLocation(locationHref);
|
|
314
|
+
if (tokenFromUrl) return logger.info("Auth token found in URL, logging in"), state.set("setTokenFromUrl", { authState: createLoggedInAuthState(tokenFromUrl, null) }), cleanedUrl;
|
|
315
|
+
let authCode = getAuthCode(callbackUrl, locationHref);
|
|
316
|
+
if (!authCode) return logger.debug("No auth code found in callback URL"), !1;
|
|
317
|
+
let parsedUrl = new URL(locationHref), dashboardContext = {};
|
|
318
|
+
try {
|
|
319
|
+
let contextParam = parsedUrl.searchParams.get("_context");
|
|
320
|
+
if (contextParam) {
|
|
321
|
+
let parsedContext = JSON.parse(contextParam);
|
|
322
|
+
parsedContext && typeof parsedContext == "object" && (delete parsedContext.sid, dashboardContext = parsedContext, logger.debug("Dashboard context parsed from callback URL", { hasDashboardContext: !0 }));
|
|
323
|
+
}
|
|
324
|
+
} catch (err) {
|
|
325
|
+
logger.warn("Failed to parse dashboard context from callback URL", { error: err });
|
|
326
|
+
}
|
|
327
|
+
logger.info("Exchanging auth code for token"), state.set("exchangeSessionForToken", {
|
|
328
|
+
authState: {
|
|
329
|
+
type: "logging-in",
|
|
330
|
+
isExchangingToken: !0
|
|
331
|
+
},
|
|
332
|
+
dashboardContext
|
|
333
|
+
});
|
|
334
|
+
try {
|
|
335
|
+
let client = clientFactory({
|
|
336
|
+
apiVersion: DEFAULT_API_VERSION,
|
|
337
|
+
requestTagPrefix: REQUEST_TAG_PREFIX,
|
|
338
|
+
useProjectHostname: !1,
|
|
339
|
+
useCdn: !1,
|
|
340
|
+
...apiHost && { apiHost }
|
|
341
|
+
});
|
|
342
|
+
logger.debug("Fetching token from auth endpoint");
|
|
343
|
+
let { token } = await client.request({
|
|
344
|
+
method: "GET",
|
|
345
|
+
url: "/auth/fetch",
|
|
346
|
+
query: { sid: authCode },
|
|
347
|
+
tag: "fetch-token"
|
|
348
|
+
});
|
|
349
|
+
return logger.info("Auth token obtained successfully, user logged in"), storageArea?.setItem(storageKey, JSON.stringify({ token })), state.set("setToken", { authState: createLoggedInAuthState(token, null) }), cleanedUrl;
|
|
350
|
+
} catch (error) {
|
|
351
|
+
return logger.error("Failed to exchange auth code for token", { error }), state.set("exchangeSessionForTokenError", { authState: {
|
|
352
|
+
type: "error",
|
|
353
|
+
error
|
|
354
|
+
} }), cleanedUrl;
|
|
355
|
+
}
|
|
356
|
+
}), logout = bindActionGlobally(authStore, async ({ state, instance }) => {
|
|
357
|
+
let logger = getAuthLogger(instance), { clientFactory, apiHost, providedToken, storageArea, storageKey } = state.get().options;
|
|
358
|
+
if (providedToken) {
|
|
359
|
+
logger.debug("Skipping logout - token is statically provided");
|
|
360
|
+
return;
|
|
361
|
+
}
|
|
362
|
+
let { authState } = state.get();
|
|
363
|
+
if (authState.type === "logged-out" && authState.isDestroyingSession) {
|
|
364
|
+
logger.debug("Skipping logout - already in progress");
|
|
365
|
+
return;
|
|
366
|
+
}
|
|
367
|
+
let token = authState.type === "logged-in" && authState.token;
|
|
368
|
+
try {
|
|
369
|
+
if (token) {
|
|
370
|
+
logger.info("Logging out user"), state.set("loggingOut", { authState: {
|
|
371
|
+
type: "logged-out",
|
|
372
|
+
isDestroyingSession: !0
|
|
373
|
+
} });
|
|
374
|
+
let client = clientFactory({
|
|
375
|
+
token,
|
|
376
|
+
requestTagPrefix: REQUEST_TAG_PREFIX,
|
|
377
|
+
apiVersion: DEFAULT_API_VERSION,
|
|
378
|
+
...apiHost && { apiHost },
|
|
379
|
+
useProjectHostname: !1,
|
|
380
|
+
useCdn: !1
|
|
381
|
+
});
|
|
382
|
+
logger.debug("Calling logout endpoint"), await client.request({
|
|
383
|
+
url: "/auth/logout",
|
|
384
|
+
method: "POST",
|
|
385
|
+
tag: "logout"
|
|
386
|
+
});
|
|
387
|
+
} else logger.debug("No token to logout - already logged out");
|
|
388
|
+
} catch (error) {
|
|
389
|
+
throw logger.error("Logout request failed", { error }), error;
|
|
390
|
+
} finally {
|
|
391
|
+
logger.info("User logged out, clearing stored tokens"), state.set("logoutSuccess", {
|
|
392
|
+
authState: {
|
|
393
|
+
type: "logged-out",
|
|
394
|
+
isDestroyingSession: !1
|
|
395
|
+
},
|
|
396
|
+
oauthTokens: void 0
|
|
397
|
+
}), storageArea?.removeItem(storageKey), storageArea?.removeItem(`${storageKey}_last_refresh`);
|
|
398
|
+
}
|
|
399
|
+
});
|
|
400
|
+
/**
|
|
306
401
|
* Encodes a byte array as a base64url string (RFC 4648 §5) with no padding,
|
|
307
402
|
* as required for PKCE `code_verifier`/`code_challenge` values.
|
|
308
403
|
*
|
|
@@ -345,35 +440,12 @@ async function generateCodeChallenge(codeVerifier) {
|
|
|
345
440
|
return base64UrlEncode(new Uint8Array(digest));
|
|
346
441
|
}
|
|
347
442
|
/** sessionStorage key for the PKCE `code_verifier`. */
|
|
348
|
-
const OAUTH_VERIFIER_KEY = "__sanity_oauth_verifier", OAUTH_STATE_KEY = "__sanity_oauth_state"
|
|
349
|
-
"code",
|
|
350
|
-
"state",
|
|
351
|
-
"error",
|
|
352
|
-
"error_description"
|
|
353
|
-
];
|
|
354
|
-
/** Strips the OAuth callback params from a URL. */
|
|
355
|
-
function stripOAuthParams(href) {
|
|
356
|
-
let url = new URL(href, DEFAULT_BASE);
|
|
357
|
-
for (let param of OAUTH_CALLBACK_PARAMS) url.searchParams.delete(param);
|
|
358
|
-
return url.toString();
|
|
359
|
-
}
|
|
360
|
-
/** Whether `href` is the registered redirect URI (origin + pathname; query and hash ignored). */
|
|
361
|
-
function isCallbackRoute(href, redirectUri) {
|
|
362
|
-
let current = new URL(href, DEFAULT_BASE), redirect = new URL(redirectUri, DEFAULT_BASE);
|
|
363
|
-
return current.origin === redirect.origin && current.pathname === redirect.pathname;
|
|
364
|
-
}
|
|
443
|
+
const OAUTH_VERIFIER_KEY = "__sanity_oauth_verifier", OAUTH_STATE_KEY = "__sanity_oauth_state";
|
|
365
444
|
/** Builds the RFC 8707 resource indicator for an organisation. */
|
|
366
445
|
function getResourceIndicator(organizationId) {
|
|
367
446
|
return `urn:io.sanity:organization:${organizationId}`;
|
|
368
447
|
}
|
|
369
448
|
/**
|
|
370
|
-
* Appends the RFC 8707 `resource` indicator to `params` when an organisation
|
|
371
|
-
* id is configured. Without one, the request is left unscoped.
|
|
372
|
-
*/
|
|
373
|
-
function appendResourceIndicator(params, oauth) {
|
|
374
|
-
oauth.organizationId && params.append("resource", getResourceIndicator(oauth.organizationId));
|
|
375
|
-
}
|
|
376
|
-
/**
|
|
377
449
|
* Serialises tokens for storage, converting `expiresAt` to an ISO string.
|
|
378
450
|
*
|
|
379
451
|
* @internal
|
|
@@ -406,16 +478,6 @@ function createOAuthClient(options) {
|
|
|
406
478
|
...options.apiHost && { apiHost: options.apiHost }
|
|
407
479
|
});
|
|
408
480
|
}
|
|
409
|
-
/** POSTs form-encoded params to the OAuth token endpoint. */
|
|
410
|
-
function postTokenRequest(client, params, tag) {
|
|
411
|
-
return client.request({
|
|
412
|
-
method: "POST",
|
|
413
|
-
url: "/auth/oauth/token",
|
|
414
|
-
headers: { "content-type": "application/x-www-form-urlencoded" },
|
|
415
|
-
body: params.toString(),
|
|
416
|
-
tag
|
|
417
|
-
});
|
|
418
|
-
}
|
|
419
481
|
/** Converts a token endpoint response to the {@link OAuthTokens} shape. */
|
|
420
482
|
function toOAuthTokens(response) {
|
|
421
483
|
return {
|
|
@@ -436,26 +498,37 @@ function toOAuthTokens(response) {
|
|
|
436
498
|
const startOAuthAuthorization = bindActionGlobally(authStore, async ({ state, instance }) => {
|
|
437
499
|
let logger = getAuthLogger(instance), options = getOAuthOptions(state.get()), codeVerifier = generateCodeVerifier(), oauthState = generateState(), codeChallenge = await generateCodeChallenge(codeVerifier), session = typeof sessionStorage < "u" ? sessionStorage : void 0;
|
|
438
500
|
session?.setItem(OAUTH_VERIFIER_KEY, codeVerifier), session?.setItem(OAUTH_STATE_KEY, oauthState);
|
|
439
|
-
let currentHref = getDefaultLocation();
|
|
440
|
-
if (currentHref !== "http://localhost") {
|
|
441
|
-
let returnTo = isCallbackRoute(currentHref, options.oauth.redirectUri) ? stripOAuthParams(currentHref) : currentHref;
|
|
442
|
-
session?.setItem(OAUTH_RETURN_TO_KEY, returnTo);
|
|
443
|
-
}
|
|
444
501
|
let authorizeUrl = new URL("/v1/auth/oauth/authorize", options.apiHost ?? "https://api.sanity.io");
|
|
445
|
-
authorizeUrl.searchParams.set("response_type", "code"), authorizeUrl.searchParams.set("client_id", options.oauth.clientId), authorizeUrl.searchParams.set("redirect_uri", options.oauth.redirectUri), authorizeUrl.searchParams.set("state", oauthState), authorizeUrl.searchParams.set("code_challenge", codeChallenge), authorizeUrl.searchParams.set("code_challenge_method", "S256"),
|
|
502
|
+
authorizeUrl.searchParams.set("response_type", "code"), authorizeUrl.searchParams.set("client_id", options.oauth.clientId), authorizeUrl.searchParams.set("redirect_uri", options.oauth.redirectUri), authorizeUrl.searchParams.set("state", oauthState), authorizeUrl.searchParams.set("code_challenge", codeChallenge), authorizeUrl.searchParams.set("code_challenge_method", "S256"), authorizeUrl.searchParams.append("resource", getResourceIndicator(options.oauth.organizationId)), logger.info("Starting OAuth authorization"), typeof window < "u" && typeof window.location?.assign == "function" && window.location.assign(authorizeUrl.toString());
|
|
446
503
|
}), handleOAuthCallback = bindActionGlobally(authStore, async ({ state, instance }, locationHref = getDefaultLocation()) => {
|
|
447
504
|
let logger = getAuthLogger(instance), options = getOAuthOptions(state.get()), { authState } = state.get();
|
|
448
505
|
if (authState.type === "logging-in" && authState.isExchangingToken) return logger.debug("Skipping OAuth callback - token exchange already in progress"), !1;
|
|
449
|
-
let callbackUrl = new URL(locationHref, DEFAULT_BASE), code = callbackUrl.searchParams.get("code"), returnedState = callbackUrl.searchParams.get("state"), error = callbackUrl.searchParams.get("error"), errorDescription = callbackUrl.searchParams.get("error_description"), session = typeof sessionStorage < "u" ? sessionStorage : void 0,
|
|
506
|
+
let callbackUrl = new URL(locationHref, DEFAULT_BASE), code = callbackUrl.searchParams.get("code"), returnedState = callbackUrl.searchParams.get("state"), error = callbackUrl.searchParams.get("error"), errorDescription = callbackUrl.searchParams.get("error_description"), session = typeof sessionStorage < "u" ? sessionStorage : void 0, cleanedUrlObj = new URL(locationHref, DEFAULT_BASE);
|
|
507
|
+
for (let param of [
|
|
508
|
+
"code",
|
|
509
|
+
"state",
|
|
510
|
+
"error",
|
|
511
|
+
"error_description"
|
|
512
|
+
]) cleanedUrlObj.searchParams.delete(param);
|
|
513
|
+
let cleanedUrl = cleanedUrlObj.toString();
|
|
514
|
+
if (error) return logger.warn("OAuth callback returned an error", {
|
|
515
|
+
error,
|
|
516
|
+
errorDescription
|
|
517
|
+
}), clearOAuthArtifacts(session), state.set("oauthCallbackError", { authState: {
|
|
450
518
|
type: "error",
|
|
451
|
-
error: Error(
|
|
452
|
-
} }), cleanedUrl
|
|
453
|
-
if (error) return rejectCallback("oauthCallbackError", errorDescription ? `${error}: ${errorDescription}` : error);
|
|
519
|
+
error: Error(errorDescription ? `${error}: ${errorDescription}` : error)
|
|
520
|
+
} }), cleanedUrl;
|
|
454
521
|
if (!code) return logger.debug("No OAuth code found in callback URL"), !1;
|
|
455
522
|
let storedState = session?.getItem("__sanity_oauth_state") ?? null;
|
|
456
|
-
if (!returnedState || !storedState || returnedState !== storedState) return
|
|
523
|
+
if (!returnedState || !storedState || returnedState !== storedState) return logger.error("OAuth state mismatch — rejecting callback"), clearOAuthArtifacts(session), state.set("oauthStateMismatch", { authState: {
|
|
524
|
+
type: "error",
|
|
525
|
+
error: /* @__PURE__ */ Error("OAuth state mismatch")
|
|
526
|
+
} }), cleanedUrl;
|
|
457
527
|
let codeVerifier = session?.getItem("__sanity_oauth_verifier") ?? null;
|
|
458
|
-
if (!codeVerifier) return
|
|
528
|
+
if (!codeVerifier) return logger.error("OAuth code verifier missing — cannot exchange code"), clearOAuthArtifacts(session), state.set("oauthVerifierMissing", { authState: {
|
|
529
|
+
type: "error",
|
|
530
|
+
error: /* @__PURE__ */ Error("OAuth code verifier missing")
|
|
531
|
+
} }), cleanedUrl;
|
|
459
532
|
logger.info("Exchanging OAuth code for tokens"), state.set("oauthExchange", { authState: {
|
|
460
533
|
type: "logging-in",
|
|
461
534
|
isExchangingToken: !0
|
|
@@ -466,16 +539,19 @@ const startOAuthAuthorization = bindActionGlobally(authStore, async ({ state, in
|
|
|
466
539
|
code,
|
|
467
540
|
code_verifier: codeVerifier,
|
|
468
541
|
redirect_uri: options.oauth.redirectUri,
|
|
469
|
-
client_id: options.oauth.clientId
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
542
|
+
client_id: options.oauth.clientId,
|
|
543
|
+
resource: getResourceIndicator(options.oauth.organizationId)
|
|
544
|
+
}), tokens = toOAuthTokens(await client.request({
|
|
545
|
+
method: "POST",
|
|
546
|
+
url: "/auth/oauth/token",
|
|
547
|
+
headers: { "content-type": "application/x-www-form-urlencoded" },
|
|
548
|
+
body: params.toString(),
|
|
549
|
+
tag: "oauth.token"
|
|
550
|
+
}));
|
|
551
|
+
return options.storageArea?.setItem(options.storageKey, serializeTokens(tokens)), clearOAuthArtifacts(session), logger.info("OAuth tokens obtained, user logged in"), state.set("oauthLoggedIn", {
|
|
476
552
|
authState: createLoggedInAuthState(tokens.accessToken, null),
|
|
477
553
|
oauthTokens: tokens
|
|
478
|
-
}),
|
|
554
|
+
}), cleanedUrl;
|
|
479
555
|
} catch (exchangeError) {
|
|
480
556
|
return logger.error("Failed to exchange OAuth code for tokens", { error: exchangeError }), clearOAuthArtifacts(session), state.set("oauthExchangeError", { authState: {
|
|
481
557
|
type: "error",
|
|
@@ -518,10 +594,15 @@ async function doRefreshOAuthTokens({ state, instance }) {
|
|
|
518
594
|
let client = createOAuthClient(options), params = new URLSearchParams({
|
|
519
595
|
grant_type: "refresh_token",
|
|
520
596
|
refresh_token: current.refreshToken,
|
|
521
|
-
client_id: options.oauth.clientId
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
597
|
+
client_id: options.oauth.clientId,
|
|
598
|
+
resource: getResourceIndicator(options.oauth.organizationId)
|
|
599
|
+
}), tokens = toOAuthTokens(await client.request({
|
|
600
|
+
method: "POST",
|
|
601
|
+
url: "/auth/oauth/token",
|
|
602
|
+
headers: { "content-type": "application/x-www-form-urlencoded" },
|
|
603
|
+
body: params.toString(),
|
|
604
|
+
tag: "oauth.refresh"
|
|
605
|
+
}));
|
|
525
606
|
return tokens.refreshToken ||= current.refreshToken, options.storageArea?.setItem(options.storageKey, serializeTokens(tokens)), logger.info("OAuth tokens refreshed"), state.set("oauthRefreshed", {
|
|
526
607
|
authState: createLoggedInAuthState(tokens.accessToken, null),
|
|
527
608
|
oauthTokens: tokens
|
|
@@ -572,129 +653,8 @@ const revokeOAuthTokens = bindActionGlobally(authStore, async ({ state, instance
|
|
|
572
653
|
}), getOAuthTokensState = bindActionGlobally(authStore, createStateSourceAction(({ state }) => state.oauthTokens ?? null));
|
|
573
654
|
/** Removes the transient PKCE artifacts from session storage. */
|
|
574
655
|
function clearOAuthArtifacts(session) {
|
|
575
|
-
session?.removeItem(OAUTH_VERIFIER_KEY), session?.removeItem(OAUTH_STATE_KEY)
|
|
576
|
-
}
|
|
577
|
-
/**
|
|
578
|
-
* Reads the stashed pre-authorize location, only honouring it when it shares
|
|
579
|
-
* the registered redirect URI's origin so a tampered value cannot redirect
|
|
580
|
-
* off-site. (`origin` includes the scheme, so non-http(s) URLs are rejected.)
|
|
581
|
-
*/
|
|
582
|
-
function getSameOriginReturnTo(session, redirectUri) {
|
|
583
|
-
let returnTo = session?.getItem("__sanity_oauth_return_to") ?? null;
|
|
584
|
-
if (!returnTo) return null;
|
|
585
|
-
try {
|
|
586
|
-
return new URL(returnTo).origin === new URL(redirectUri).origin ? returnTo : null;
|
|
587
|
-
} catch {
|
|
588
|
-
return null;
|
|
589
|
-
}
|
|
656
|
+
session?.removeItem(OAUTH_VERIFIER_KEY), session?.removeItem(OAUTH_STATE_KEY);
|
|
590
657
|
}
|
|
591
|
-
/**
|
|
592
|
-
* Handles the auth redirect callback. In OAuth mode this delegates to
|
|
593
|
-
* {@link handleOAuthCallback}; otherwise it exchanges the legacy `sid` for a
|
|
594
|
-
* long-lived token.
|
|
595
|
-
*
|
|
596
|
-
* @public
|
|
597
|
-
*/
|
|
598
|
-
const handleAuthCallback = bindActionGlobally(authStore, async ({ state, instance }, locationHref = getDefaultLocation()) => {
|
|
599
|
-
let logger = getAuthLogger(instance), { providedToken, callbackUrl, clientFactory, apiHost, storageArea, storageKey, oauth } = state.get().options;
|
|
600
|
-
if (providedToken) return logger.debug("Skipping auth callback - token already provided"), !1;
|
|
601
|
-
if (oauth) return logger.debug("OAuth mode - delegating to handleOAuthCallback"), handleOAuthCallback(instance, locationHref);
|
|
602
|
-
let { authState } = state.get();
|
|
603
|
-
if (authState.type === "logging-in" && authState.isExchangingToken) return logger.debug("Skipping auth callback - token exchange already in progress"), !1;
|
|
604
|
-
let cleanedUrl = getCleanedUrl(locationHref), tokenFromUrl = getTokenFromLocation(locationHref);
|
|
605
|
-
if (tokenFromUrl) return logger.info("Auth token found in URL, logging in"), state.set("setTokenFromUrl", { authState: createLoggedInAuthState(tokenFromUrl, null) }), cleanedUrl;
|
|
606
|
-
let authCode = getAuthCode(callbackUrl, locationHref);
|
|
607
|
-
if (!authCode) return logger.debug("No auth code found in callback URL"), !1;
|
|
608
|
-
let parsedUrl = new URL(locationHref), dashboardContext = {};
|
|
609
|
-
try {
|
|
610
|
-
let contextParam = parsedUrl.searchParams.get("_context");
|
|
611
|
-
if (contextParam) {
|
|
612
|
-
let parsedContext = JSON.parse(contextParam);
|
|
613
|
-
parsedContext && typeof parsedContext == "object" && (delete parsedContext.sid, dashboardContext = parsedContext, logger.debug("Dashboard context parsed from callback URL", { hasDashboardContext: !0 }));
|
|
614
|
-
}
|
|
615
|
-
} catch (err) {
|
|
616
|
-
logger.warn("Failed to parse dashboard context from callback URL", { error: err });
|
|
617
|
-
}
|
|
618
|
-
logger.info("Exchanging auth code for token"), state.set("exchangeSessionForToken", {
|
|
619
|
-
authState: {
|
|
620
|
-
type: "logging-in",
|
|
621
|
-
isExchangingToken: !0
|
|
622
|
-
},
|
|
623
|
-
dashboardContext
|
|
624
|
-
});
|
|
625
|
-
try {
|
|
626
|
-
let client = clientFactory({
|
|
627
|
-
apiVersion: DEFAULT_API_VERSION,
|
|
628
|
-
requestTagPrefix: REQUEST_TAG_PREFIX,
|
|
629
|
-
useProjectHostname: !1,
|
|
630
|
-
useCdn: !1,
|
|
631
|
-
...apiHost && { apiHost }
|
|
632
|
-
});
|
|
633
|
-
logger.debug("Fetching token from auth endpoint");
|
|
634
|
-
let { token } = await client.request({
|
|
635
|
-
method: "GET",
|
|
636
|
-
url: "/auth/fetch",
|
|
637
|
-
query: { sid: authCode },
|
|
638
|
-
tag: "fetch-token"
|
|
639
|
-
});
|
|
640
|
-
return logger.info("Auth token obtained successfully, user logged in"), storageArea?.setItem(storageKey, JSON.stringify({ token })), state.set("setToken", { authState: createLoggedInAuthState(token, null) }), cleanedUrl;
|
|
641
|
-
} catch (error) {
|
|
642
|
-
return logger.error("Failed to exchange auth code for token", { error }), state.set("exchangeSessionForTokenError", { authState: {
|
|
643
|
-
type: "error",
|
|
644
|
-
error
|
|
645
|
-
} }), cleanedUrl;
|
|
646
|
-
}
|
|
647
|
-
}), logout = bindActionGlobally(authStore, async ({ state, instance }) => {
|
|
648
|
-
let logger = getAuthLogger(instance), { clientFactory, apiHost, providedToken, storageArea, storageKey, oauth } = state.get().options;
|
|
649
|
-
if (providedToken) {
|
|
650
|
-
logger.debug("Skipping logout - token is statically provided");
|
|
651
|
-
return;
|
|
652
|
-
}
|
|
653
|
-
let { authState } = state.get();
|
|
654
|
-
if (authState.type === "logged-out" && authState.isDestroyingSession) {
|
|
655
|
-
logger.debug("Skipping logout - already in progress");
|
|
656
|
-
return;
|
|
657
|
-
}
|
|
658
|
-
if (oauth) {
|
|
659
|
-
logger.debug("OAuth mode - revoking tokens instead of calling /auth/logout"), state.set("loggingOut", { authState: {
|
|
660
|
-
type: "logged-out",
|
|
661
|
-
isDestroyingSession: !0
|
|
662
|
-
} }), await revokeOAuthTokens(instance);
|
|
663
|
-
return;
|
|
664
|
-
}
|
|
665
|
-
let token = authState.type === "logged-in" && authState.token;
|
|
666
|
-
try {
|
|
667
|
-
if (token) {
|
|
668
|
-
logger.info("Logging out user"), state.set("loggingOut", { authState: {
|
|
669
|
-
type: "logged-out",
|
|
670
|
-
isDestroyingSession: !0
|
|
671
|
-
} });
|
|
672
|
-
let client = clientFactory({
|
|
673
|
-
token,
|
|
674
|
-
requestTagPrefix: REQUEST_TAG_PREFIX,
|
|
675
|
-
apiVersion: DEFAULT_API_VERSION,
|
|
676
|
-
...apiHost && { apiHost },
|
|
677
|
-
useProjectHostname: !1,
|
|
678
|
-
useCdn: !1
|
|
679
|
-
});
|
|
680
|
-
logger.debug("Calling logout endpoint"), await client.request({
|
|
681
|
-
url: "/auth/logout",
|
|
682
|
-
method: "POST",
|
|
683
|
-
tag: "logout"
|
|
684
|
-
});
|
|
685
|
-
} else logger.debug("No token to logout - already logged out");
|
|
686
|
-
} catch (error) {
|
|
687
|
-
throw logger.error("Logout request failed", { error }), error;
|
|
688
|
-
} finally {
|
|
689
|
-
logger.info("User logged out, clearing stored tokens"), state.set("logoutSuccess", {
|
|
690
|
-
authState: {
|
|
691
|
-
type: "logged-out",
|
|
692
|
-
isDestroyingSession: !1
|
|
693
|
-
},
|
|
694
|
-
oauthTokens: void 0
|
|
695
|
-
}), storageArea?.removeItem(storageKey), storageArea?.removeItem(`${storageKey}_last_refresh`);
|
|
696
|
-
}
|
|
697
|
-
});
|
|
698
658
|
function weaken(node) {
|
|
699
659
|
return Array.isArray(node) ? node.map(weaken) : node && typeof node == "object" ? "_ref" in node ? {
|
|
700
660
|
...node,
|
|
@@ -3149,7 +3109,7 @@ function getDocumentIdsFromHandleLikes(handles) {
|
|
|
3149
3109
|
return handles.flatMap((handle) => {
|
|
3150
3110
|
if ("type" in handle && isReleaseAction(handle)) return [getReleaseDocumentId(handle.releaseId)];
|
|
3151
3111
|
let idsForDocument = [];
|
|
3152
|
-
return handle.documentId ? handle.liveEdit ? [handle.documentId] : (isReleasePerspective(handle.perspective) && idsForDocument.push(getVersionId(DocumentId(handle.documentId), handle.perspective.releaseName)), idsForDocument.push(
|
|
3112
|
+
return handle.documentId ? handle.liveEdit ? [handle.documentId] : (isReleasePerspective(handle.perspective) && idsForDocument.push(getVersionId(DocumentId(handle.documentId), handle.perspective.releaseName)), idsForDocument.push(getDraftId(DocumentId(handle.documentId))), idsForDocument.push(getPublishedId(DocumentId(handle.documentId))), idsForDocument) : [];
|
|
3153
3113
|
});
|
|
3154
3114
|
}
|
|
3155
3115
|
const actionMap = {
|
|
@@ -3354,19 +3314,32 @@ const documentStore = defineStore({
|
|
|
3354
3314
|
function getDocumentState(...args) {
|
|
3355
3315
|
return _getDocumentState(...args);
|
|
3356
3316
|
}
|
|
3317
|
+
function throwDocumentError(documentStates, documentIds) {
|
|
3318
|
+
for (let documentId of documentIds) {
|
|
3319
|
+
let documentError = documentStates[documentId]?.error;
|
|
3320
|
+
if (documentError) throw documentError;
|
|
3321
|
+
}
|
|
3322
|
+
}
|
|
3323
|
+
/** Version wins over draft, and draft over published. Undefined until every read has arrived. */
|
|
3324
|
+
function selectLocalDocument(documentStates, documentIds) {
|
|
3325
|
+
throwDocumentError(documentStates, documentIds);
|
|
3326
|
+
let selected = null;
|
|
3327
|
+
for (let documentId of documentIds) {
|
|
3328
|
+
let local = documentStates[documentId]?.local;
|
|
3329
|
+
if (local === void 0) return;
|
|
3330
|
+
selected === null && (selected = local);
|
|
3331
|
+
}
|
|
3332
|
+
return selected;
|
|
3333
|
+
}
|
|
3334
|
+
function hasEveryDocumentArrived(documentStates, documentIds) {
|
|
3335
|
+
return throwDocumentError(documentStates, documentIds), documentIds.every((documentId) => documentStates[documentId] !== void 0);
|
|
3336
|
+
}
|
|
3357
3337
|
const _getDocumentState = bindActionByResource(documentStore, createStateSourceAction({
|
|
3358
3338
|
selector: ({ state: { error, documentStates } }, options) => {
|
|
3359
|
-
let {
|
|
3339
|
+
let { path } = options;
|
|
3360
3340
|
if (error) throw error;
|
|
3361
|
-
let document;
|
|
3362
|
-
if (
|
|
3363
|
-
else {
|
|
3364
|
-
let version;
|
|
3365
|
-
if (isReleasePerspective(perspective) && (version = documentStates[getVersionId(documentId, perspective.releaseName)]?.local, version === void 0)) return;
|
|
3366
|
-
let draft = documentStates[getDraftId(documentId)]?.local, published = documentStates[getPublishedId(documentId)]?.local;
|
|
3367
|
-
if (draft === void 0 || published === void 0) return;
|
|
3368
|
-
document = version ?? draft ?? published;
|
|
3369
|
-
}
|
|
3341
|
+
let document = selectLocalDocument(documentStates, getDocumentIdsFromHandleLikes([options]));
|
|
3342
|
+
if (document === void 0) return;
|
|
3370
3343
|
if (!path) return document;
|
|
3371
3344
|
let result = jsonMatch$1(document, path).next();
|
|
3372
3345
|
if (result.done) return;
|
|
@@ -3384,17 +3357,8 @@ const _resolveDocument = bindActionByResource(documentStore, ({ instance }, docH
|
|
|
3384
3357
|
path: void 0
|
|
3385
3358
|
}).observable.pipe(filter((i) => i !== void 0)))), getDocumentSyncStatus = bindActionByResource(documentStore, createStateSourceAction({
|
|
3386
3359
|
selector: ({ state: { error, documentStates: documents, outgoing, applied, queued } }, doc) => {
|
|
3387
|
-
let documentId = DocumentId(typeof doc == "string" ? doc : doc.documentId);
|
|
3388
3360
|
if (error) throw error;
|
|
3389
|
-
if (doc
|
|
3390
|
-
if (documents[documentId] === void 0) return;
|
|
3391
|
-
} else {
|
|
3392
|
-
let version = isReleasePerspective(doc.perspective) ? documents[getVersionId(documentId, doc.perspective.releaseName)] : void 0;
|
|
3393
|
-
if (isReleasePerspective(doc.perspective) && version === void 0) return;
|
|
3394
|
-
let draft = documents[getDraftId(documentId)], published = documents[getPublishedId(documentId)];
|
|
3395
|
-
if (draft === void 0 || published === void 0) return;
|
|
3396
|
-
}
|
|
3397
|
-
return !queued.length && !applied.length && !outgoing;
|
|
3361
|
+
if (hasEveryDocumentArrived(documents, getDocumentIdsFromHandleLikes([doc]))) return !queued.length && !applied.length && !outgoing;
|
|
3398
3362
|
},
|
|
3399
3363
|
onSubscribe: (context, doc) => manageSubscriberIds(context, [doc])
|
|
3400
3364
|
})), getPermissionsState = bindActionByResource(documentStore, createStateSourceAction({
|
|
@@ -3405,9 +3369,22 @@ const _resolveDocument = bindActionByResource(documentStore, ({ instance }, docH
|
|
|
3405
3369
|
})), resolvePermissions = bindActionByResource(documentStore, ({ instance }, options) => firstValueFrom(getPermissionsState(instance, options).observable.pipe(filter((i) => i !== void 0)))), subscribeDocumentEvents = bindActionByResource(documentStore, ({ state }, options) => {
|
|
3406
3370
|
let { events } = state.get(), subscription = events.subscribe(options.eventHandler);
|
|
3407
3371
|
return () => subscription.unsubscribe();
|
|
3408
|
-
})
|
|
3372
|
+
});
|
|
3373
|
+
function failTransactionOnUnreadableDocument({ queued, documentStates }) {
|
|
3374
|
+
let transaction = queued.at(0);
|
|
3375
|
+
if (!transaction) return;
|
|
3376
|
+
let unreadableId = getDocumentIdsFromHandleLikes(transaction.actions).find((id) => documentStates[id]?.error);
|
|
3377
|
+
if (unreadableId === void 0) return;
|
|
3378
|
+
let error = documentStates[unreadableId]?.error, actionError = new ActionError({
|
|
3379
|
+
message: error instanceof Error ? error.message : String(error),
|
|
3380
|
+
documentId: unreadableId,
|
|
3381
|
+
transactionId: transaction.transactionId
|
|
3382
|
+
});
|
|
3383
|
+
throw actionError.cause = error, actionError;
|
|
3384
|
+
}
|
|
3385
|
+
const subscribeToQueuedAndApplyNextTransaction = ({ state }) => {
|
|
3409
3386
|
let { events } = state.get();
|
|
3410
|
-
return state.observable.pipe(map(applyFirstQueuedTransaction), distinctUntilChanged(), tap((next) => state.set("applyFirstQueuedTransaction", next)), catchError((error, caught) => {
|
|
3387
|
+
return state.observable.pipe(tap(failTransactionOnUnreadableDocument), map(applyFirstQueuedTransaction), distinctUntilChanged(), tap((next) => state.set("applyFirstQueuedTransaction", next)), catchError((error, caught) => {
|
|
3411
3388
|
if (error instanceof ActionError) return state.set("removeQueuedTransaction", (prev) => removeQueuedTransaction(prev, error.transactionId)), events.next({
|
|
3412
3389
|
type: "error",
|
|
3413
3390
|
message: error.message,
|
|
@@ -3479,11 +3456,27 @@ const _resolveDocument = bindActionByResource(documentStore, ({ instance }, docH
|
|
|
3479
3456
|
return aIsDraft && bIsDraft ? a.id.localeCompare(b.id, "en-US") : aIsDraft ? -1 : bIsDraft ? 1 : a.id.localeCompare(b.id, "en-US");
|
|
3480
3457
|
});
|
|
3481
3458
|
return of(...changes);
|
|
3482
|
-
}), groupBy((i) => i.id), mergeMap((group) => group.pipe(switchMap((e) => e.add ? listen(context, e.id).pipe(retry({
|
|
3483
|
-
|
|
3484
|
-
|
|
3485
|
-
|
|
3486
|
-
|
|
3459
|
+
}), groupBy((i) => i.id), mergeMap((group) => group.pipe(switchMap((e) => e.add ? listen(context, e.id).pipe(retry({
|
|
3460
|
+
count: 5,
|
|
3461
|
+
resetOnSuccess: !0,
|
|
3462
|
+
delay: (error, retryCount) => {
|
|
3463
|
+
if (!(error instanceof OutOfSyncError || error instanceof ServerError || error instanceof ClientError && (error.statusCode === 408 || error.statusCode === 429))) return throwError(() => error);
|
|
3464
|
+
let backoff = Math.min(500 * 2 ** (retryCount - 1), 1e4);
|
|
3465
|
+
return timer(backoff);
|
|
3466
|
+
}
|
|
3467
|
+
}), catchError((error) => (state.set("setDocumentError", (prev) => {
|
|
3468
|
+
let documentState = prev.documentStates[e.id];
|
|
3469
|
+
return documentState ? {
|
|
3470
|
+
...prev,
|
|
3471
|
+
documentStates: {
|
|
3472
|
+
...prev.documentStates,
|
|
3473
|
+
[e.id]: {
|
|
3474
|
+
...documentState,
|
|
3475
|
+
error
|
|
3476
|
+
}
|
|
3477
|
+
}
|
|
3478
|
+
} : prev;
|
|
3479
|
+
}), EMPTY)), tap((remote) => state.set("applyRemoteDocument", (prev) => applyRemoteDocument(prev, remote, events)))) : EMPTY)))).subscribe({ error: (error) => state.set("setError", { error }) });
|
|
3487
3480
|
}, subscribeToClientAndFetchDatasetAcl = ({ instance, state, key: { resource } }) => {
|
|
3488
3481
|
let clientOptions = {
|
|
3489
3482
|
apiVersion: API_VERSION$4,
|