@sanity/sdk-react 3.0.0-rc.0 → 3.0.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 (160) hide show
  1. package/README.md +103 -155
  2. package/dist/index.d.ts +1564 -682
  3. package/dist/index.js +1118 -612
  4. package/dist/index.js.map +1 -1
  5. package/package.json +51 -54
  6. package/src/_exports/index.ts +2 -4
  7. package/src/_exports/sdk-react.ts +26 -17
  8. package/src/components/SDKProvider.test.tsx +173 -32
  9. package/src/components/SDKProvider.tsx +87 -28
  10. package/src/components/SanityApp.test.tsx +68 -12
  11. package/src/components/SanityApp.tsx +94 -87
  12. package/src/components/auth/AuthBoundary.recovery.test.tsx +86 -0
  13. package/src/components/auth/AuthBoundary.test.tsx +26 -8
  14. package/src/components/auth/AuthBoundary.tsx +28 -6
  15. package/src/components/auth/DashboardAccessRequest.tsx +37 -0
  16. package/src/components/auth/LoginError.test.tsx +191 -5
  17. package/src/components/auth/LoginError.tsx +103 -59
  18. package/src/components/errors/ChunkLoadError.test.tsx +59 -0
  19. package/src/components/errors/ChunkLoadError.tsx +56 -0
  20. package/src/components/errors/CorsErrorComponent.tsx +2 -2
  21. package/src/components/errors/chunkReloadStorage.ts +57 -0
  22. package/src/config/handles.ts +29 -27
  23. package/src/constants.ts +5 -0
  24. package/src/context/ComlinkTokenRefresh.test.tsx +10 -27
  25. package/src/context/DefaultResourceContext.ts +3 -3
  26. package/src/context/OrganizationResourcesProvider.test.tsx +189 -0
  27. package/src/context/OrganizationResourcesProvider.tsx +111 -0
  28. package/src/context/PerspectiveContext.ts +3 -3
  29. package/src/context/ProjectContext.ts +15 -0
  30. package/src/context/ResourceProvider.test.tsx +72 -90
  31. package/src/context/ResourceProvider.tsx +59 -93
  32. package/src/context/SDKStudioContext.test.tsx +28 -33
  33. package/src/context/SanityInstanceProvider.test.tsx +100 -0
  34. package/src/context/SanityInstanceProvider.tsx +71 -0
  35. package/src/context/WorkbenchTokenRefresh.test.tsx +106 -0
  36. package/src/context/WorkbenchTokenRefresh.tsx +61 -0
  37. package/src/context/renderSanityApp.test.tsx +151 -49
  38. package/src/context/renderSanityApp.tsx +12 -8
  39. package/src/context/workbenchToken.ts +63 -0
  40. package/src/hooks/access/useCheckPermissions.test-d.ts +15 -0
  41. package/src/hooks/access/useCheckPermissions.test.tsx +53 -0
  42. package/src/hooks/access/useCheckPermissions.ts +24 -0
  43. package/src/hooks/agent/agentActions.test.tsx +1 -1
  44. package/src/hooks/agent/agentActions.ts +51 -71
  45. package/src/hooks/applications/useApplication.test-d.ts +30 -0
  46. package/src/hooks/applications/useApplication.ts +22 -0
  47. package/src/hooks/applications/useApplications.test-d.ts +31 -0
  48. package/src/hooks/applications/useApplications.ts +25 -0
  49. package/src/hooks/applications/useCreateUserApplication.test-d.ts +14 -0
  50. package/src/hooks/applications/useCreateUserApplication.ts +11 -0
  51. package/src/hooks/applications/useDeleteApplication.test-d.ts +12 -0
  52. package/src/hooks/applications/useDeleteApplication.ts +11 -0
  53. package/src/hooks/applications/useDeleteUserApplication.test-d.ts +14 -0
  54. package/src/hooks/applications/useDeleteUserApplication.ts +11 -0
  55. package/src/hooks/applications/useUpdateApplication.test-d.ts +12 -0
  56. package/src/hooks/applications/useUpdateApplication.ts +11 -0
  57. package/src/hooks/applications/useUpdateUserApplication.test-d.ts +14 -0
  58. package/src/hooks/applications/useUpdateUserApplication.ts +11 -0
  59. package/src/hooks/applications/useUserApplication.test-d.ts +11 -0
  60. package/src/hooks/applications/useUserApplication.ts +14 -0
  61. package/src/hooks/applications/useUserApplications.test-d.ts +11 -0
  62. package/src/hooks/applications/useUserApplications.ts +14 -0
  63. package/src/hooks/auth/useDashboardOrganizationId.test.tsx +2 -8
  64. package/src/hooks/auth/useVerifyOrgProjects.test.tsx +8 -32
  65. package/src/hooks/auth/useVerifyOrgProjects.tsx +13 -6
  66. package/src/hooks/client/useClient.test.tsx +1 -4
  67. package/src/hooks/client/useClient.ts +1 -0
  68. package/src/hooks/context/useResource.test.tsx +32 -0
  69. package/src/hooks/context/useResource.ts +24 -0
  70. package/src/hooks/context/useSanityInstance.test.tsx +72 -3
  71. package/src/hooks/context/useSanityInstance.ts +30 -8
  72. package/src/hooks/dashboard/useManageFavorite.test.tsx +110 -46
  73. package/src/hooks/dashboard/useManageFavorite.ts +10 -16
  74. package/src/hooks/dashboard/useNavigateToStudioDocument.test.ts +5 -7
  75. package/src/hooks/dashboard/useNavigateToStudioDocument.ts +2 -6
  76. package/src/hooks/dashboard/useRecordDocumentHistoryEvent.test.ts +0 -2
  77. package/src/hooks/dashboard/useRecordDocumentHistoryEvent.ts +1 -2
  78. package/src/hooks/dashboard/useWindowTitle.test.ts +244 -0
  79. package/src/hooks/dashboard/useWindowTitle.ts +114 -0
  80. package/src/hooks/datasets/useDatasets.test.tsx +116 -0
  81. package/src/hooks/datasets/useDatasets.ts +33 -13
  82. package/src/hooks/document/useApplyDocumentActions.test.tsx +48 -0
  83. package/src/hooks/document/useApplyDocumentActions.ts +66 -48
  84. package/src/hooks/document/useCreateDocument.test.tsx +83 -0
  85. package/src/hooks/document/useCreateDocument.ts +117 -0
  86. package/src/hooks/document/useDocument.test.tsx +37 -8
  87. package/src/hooks/document/useDocument.ts +131 -66
  88. package/src/hooks/document/useDocumentEvent.test.tsx +16 -4
  89. package/src/hooks/document/useDocumentEvent.ts +16 -10
  90. package/src/hooks/document/useDocumentPermissions.test.tsx +8 -7
  91. package/src/hooks/document/useDocumentPermissions.ts +71 -39
  92. package/src/hooks/document/useDocumentSyncStatus.test.ts +1 -0
  93. package/src/hooks/document/useDocumentSyncStatus.ts +13 -9
  94. package/src/hooks/document/useEditDocument.test.tsx +21 -14
  95. package/src/hooks/document/useEditDocument.ts +163 -17
  96. package/src/hooks/documents/useDocuments.test.tsx +64 -44
  97. package/src/hooks/documents/useDocuments.ts +36 -20
  98. package/src/hooks/helpers/createCallbackHook.test.tsx +13 -19
  99. package/src/hooks/helpers/createFetcherHook.test.tsx +180 -0
  100. package/src/hooks/helpers/createFetcherHook.ts +69 -0
  101. package/src/hooks/helpers/createMutationHook.test.tsx +125 -0
  102. package/src/hooks/helpers/createMutationHook.tsx +93 -0
  103. package/src/hooks/helpers/createStateSourceHook.test.tsx +10 -10
  104. package/src/hooks/helpers/createStateSourceHook.tsx +2 -1
  105. package/src/hooks/{document/useApplyDocumentActions.test.ts → helpers/useApplyActions.test.tsx} +92 -53
  106. package/src/hooks/helpers/useApplyActions.ts +68 -0
  107. package/src/hooks/helpers/useNormalizedResourceOptions.test.tsx +253 -0
  108. package/src/hooks/helpers/useNormalizedResourceOptions.ts +92 -50
  109. package/src/hooks/helpers/useResolvedProjectId.test.tsx +59 -0
  110. package/src/hooks/helpers/useResolvedProjectId.ts +35 -0
  111. package/src/hooks/helpers/useTrackHookUsage.ts +37 -0
  112. package/src/hooks/installations/useInstallation.test-d.ts +19 -0
  113. package/src/hooks/installations/useInstallation.ts +22 -0
  114. package/src/hooks/installations/useInstallations.test-d.ts +26 -0
  115. package/src/hooks/installations/useInstallations.ts +25 -0
  116. package/src/hooks/organizations/useOrganization.test-d.ts +60 -0
  117. package/src/hooks/organizations/useOrganization.test.ts +63 -0
  118. package/src/hooks/organizations/useOrganization.ts +34 -0
  119. package/src/hooks/organizations/useOrganizations.test-d.ts +68 -0
  120. package/src/hooks/organizations/useOrganizations.test.ts +63 -0
  121. package/src/hooks/organizations/useOrganizations.ts +39 -0
  122. package/src/hooks/paginatedDocuments/usePaginatedDocuments.test.tsx +34 -27
  123. package/src/hooks/paginatedDocuments/usePaginatedDocuments.ts +40 -22
  124. package/src/hooks/presence/usePresence.test.tsx +0 -15
  125. package/src/hooks/presence/usePresence.ts +9 -20
  126. package/src/hooks/preview/useDocumentPreview.test.tsx +0 -1
  127. package/src/hooks/preview/useDocumentPreview.tsx +10 -8
  128. package/src/hooks/projection/useDocumentProjection.test.tsx +78 -9
  129. package/src/hooks/projection/useDocumentProjection.ts +81 -2
  130. package/src/hooks/projects/useProject.test-d.ts +56 -0
  131. package/src/hooks/projects/useProject.test.tsx +120 -0
  132. package/src/hooks/projects/useProject.ts +42 -43
  133. package/src/hooks/projects/useProjects.test-d.ts +60 -0
  134. package/src/hooks/projects/useProjects.test.ts +45 -98
  135. package/src/hooks/projects/useProjects.ts +19 -26
  136. package/src/hooks/query/useQuery.test.tsx +6 -5
  137. package/src/hooks/query/useQuery.ts +91 -9
  138. package/src/hooks/releases/useActiveReleases.test.tsx +13 -7
  139. package/src/hooks/releases/useActiveReleases.ts +28 -24
  140. package/src/hooks/releases/useAllReleases.test.tsx +93 -0
  141. package/src/hooks/releases/useAllReleases.ts +62 -0
  142. package/src/hooks/releases/useApplyReleaseActions.test.tsx +66 -0
  143. package/src/hooks/releases/useApplyReleaseActions.ts +82 -0
  144. package/src/hooks/releases/usePerspective.test.tsx +18 -10
  145. package/src/hooks/releases/usePerspective.ts +13 -17
  146. package/src/hooks/users/useUser.test.tsx +3 -9
  147. package/src/hooks/users/useUser.ts +2 -0
  148. package/src/hooks/users/useUsers.test.tsx +103 -7
  149. package/src/hooks/users/useUsers.ts +37 -3
  150. package/src/utils/resolveOrgResources.test.ts +111 -0
  151. package/src/utils/resolveOrgResources.ts +69 -0
  152. package/src/hooks/context/useDefaultResource.test.tsx +0 -25
  153. package/src/hooks/context/useDefaultResource.ts +0 -30
  154. package/src/hooks/dashboard/useDispatchIntent.test.ts +0 -254
  155. package/src/hooks/dashboard/useDispatchIntent.ts +0 -157
  156. package/src/hooks/dashboard/utils/useResourceIdFromDocumentHandle.test.ts +0 -107
  157. package/src/hooks/dashboard/utils/useResourceIdFromDocumentHandle.ts +0 -39
  158. package/src/hooks/datasets/useDatasets.test.ts +0 -66
  159. package/src/hooks/helpers/useNormalizedResourceOptions.test.ts +0 -65
  160. package/src/hooks/projects/useProject.test.ts +0 -79
package/dist/index.js CHANGED
@@ -1,15 +1,21 @@
1
1
  import { jsx, jsxs, Fragment } from "react/jsx-runtime";
2
- import { c } from "react/compiler-runtime";
2
+ import { c } from "react-compiler-runtime";
3
3
  import { ClientError, CorsOriginError } from "@sanity/client";
4
- import { getAuthState, getNodeState, getIsInDashboardState, isStudioConfig, setAuthToken, AuthStateType, getLoginUrlState, observeOrganizationVerificationState, handleAuthCallback, logout, isDatasetResource, isProjectUserNotFoundClientError, getClientErrorApiDescription, getClientErrorApiBody, getCorsErrorProjectId, createSanityInstance, DEFAULT_RESOURCE_NAME, agentGenerate, agentTransform, agentTranslate, agentPrompt, agentPatch, getTokenState, getCurrentUserState, getDashboardOrganizationId, getClientState, getOrCreateController, getOrCreateChannel, releaseChannel, isMediaLibraryResource, isCanvasResource, getFavoritesState, resolveFavoritesState, resolveDatasets, getDatasetsState, applyDocumentActions, resolveDocument, getDocumentState, subscribeDocumentEvents, getPermissionsState, getDocumentSyncStatus, editDocument, getQueryKey, parseQueryKey, getQueryState, resolveQuery, createGroqSearchFilter, getPresence, getProjectionState, resolveProjection, transformProjectionToPreview, PREVIEW_PROJECTION, resolveProject, getProjectState, resolveProjects, getProjectsState, getActiveReleasesState, getPerspectiveState, getUsersKey, parseUsersKey, getUsersState, resolveUsers, loadMoreUsers } from "@sanity/sdk";
4
+ import { getAuthState, getNodeState, getIsInDashboardState, isStudioConfig, setAuthToken, AuthStateType, getLoginUrlState, observeOrganizationVerificationState, handleAuthCallback, logout, isProjectUserNotFoundClientError, getClientErrorApiDescription, getClientErrorApiBody, isImportError, getCorsErrorProjectId, getDashboardOrganizationId, getClientState, isDatasetResource, createSanityInstance, checkPermissions, agentGenerate, agentPatch, agentPrompt, agentTransform, agentTranslate, application, applications, createUserApplication, deleteApplication, deleteUserApplication, updateApplication, updateUserApplication, userApplication, userApplications, getTokenState, getCurrentUserState, getOrCreateController, getOrCreateChannel, releaseChannel, getFavoritesState, resolveFavoritesState, resolveDatasets, getDatasetsState, applyDocumentActions, createDocument, resolveDocument, getDocumentState, subscribeDocumentEvents, getPermissionsState, getDocumentSyncStatus, editDocument, getQueryKey, parseQueryKey, getQueryState, resolveQuery, createGroqSearchFilter, installation, installations, organization, organizations, isMediaLibraryResource, getPresence, getProjectionState, resolveProjection, PREVIEW_PROJECTION, transformProjectionToPreview, project, projects, getActiveReleasesState, getAllReleasesState, getPerspectiveState, getUsersKey, parseUsersKey, getUsersState, resolveUsers, loadMoreUsers } from "@sanity/sdk";
5
5
  export * from "@sanity/sdk";
6
- import { createContext, useContext, useSyncExternalStore, useRef, useEffect, useState, Suspense, StrictMode, useCallback, useMemo, useInsertionEffect, useTransition } from "react";
7
- import { ErrorBoundary } from "react-error-boundary";
6
+ import { createContext, useContext, useSyncExternalStore, useRef, useEffect, useState, Suspense, use, StrictMode, useCallback, useMemo, useInsertionEffect, useTransition } from "react";
7
+ import { getErrorMessage, ErrorBoundary } from "react-error-boundary";
8
8
  import { SDK_CHANNEL_NAME, SDK_NODE_NAME } from "@sanity/message-protocol";
9
- import { firstValueFrom, filter, Observable, startWith, distinctUntilChanged, switchMap, EMPTY } from "rxjs";
9
+ import { firstValueFrom, filter, from, of, identity, Observable, startWith, distinctUntilChanged, switchMap as switchMap$1, EMPTY } from "rxjs";
10
+ import { switchMap, catchError } from "rxjs/operators";
11
+ import { initTelemetry, isDeepEqual, trackHookMounted, pickProperties } from "@sanity/sdk/_internal";
10
12
  import { createRoot } from "react-dom/client";
11
- import { pick } from "lodash-es";
12
- const SanityInstanceContext = createContext(null), useSanityInstance = () => {
13
+ const SanityInstanceContext = createContext(null), warnedCallers = /* @__PURE__ */ new Set(), useSanityInstance = (config) => {
14
+ if (config !== void 0) {
15
+ const caller = new Error().stack?.split(`
16
+ `)[2]?.trim() ?? "unknown";
17
+ warnedCallers.has(caller) || (warnedCallers.add(caller), console.warn("[useSanityInstance] Passing a config argument is deprecated and has no effect. SDK apps use a single instance for all resources, so the config argument is no longer needed. Call useSanityInstance() without arguments instead, or useResource() to get your currently active resource."));
18
+ }
13
19
  const instance = useContext(SanityInstanceContext);
14
20
  if (!instance)
15
21
  throw new Error("SanityInstance context not found. Please ensure that your component is wrapped in a ResourceProvider or a SanityApp component.");
@@ -48,14 +54,14 @@ function useWindowConnection(t0) {
48
54
  node
49
55
  } = useNodeState(t1);
50
56
  let t2;
51
- $[3] === Symbol.for("react.memo_cache_sentinel") ? (t2 = [], $[3] = t2) : t2 = $[3];
57
+ $[3] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t2 = [], $[3] = t2) : t2 = $[3];
52
58
  const messageUnsubscribers = useRef(t2), instance = useSanityInstance();
53
59
  let t3;
54
60
  $[4] !== node || $[5] !== onMessage ? (t3 = () => (onMessage && Object.entries(onMessage).forEach((t42) => {
55
61
  const [type, handler] = t42, messageUnsubscribe = node.on(type, handler);
56
62
  messageUnsubscribe && messageUnsubscribers.current.push(messageUnsubscribe);
57
63
  }), () => {
58
- messageUnsubscribers.current.forEach(_temp$6), messageUnsubscribers.current = [];
64
+ messageUnsubscribers.current.forEach(_temp$9), messageUnsubscribers.current = [];
59
65
  }), $[4] = node, $[5] = onMessage, $[6] = t3) : t3 = $[6];
60
66
  let t4;
61
67
  $[7] !== instance || $[8] !== name || $[9] !== node || $[10] !== onMessage ? (t4 = [instance, name, onMessage, node], $[7] = instance, $[8] = name, $[9] = node, $[10] = onMessage, $[11] = t4) : t4 = $[11], useEffect(t3, t4);
@@ -73,7 +79,7 @@ function useWindowConnection(t0) {
73
79
  fetch
74
80
  }, $[16] = fetch, $[17] = sendMessage, $[18] = t7) : t7 = $[18], t7;
75
81
  }
76
- function _temp$6(unsubscribe) {
82
+ function _temp$9(unsubscribe) {
77
83
  return unsubscribe();
78
84
  }
79
85
  const DEFAULT_RESPONSE_TIMEOUT = 1e4;
@@ -82,12 +88,12 @@ function DashboardTokenRefresh(t0) {
82
88
  children
83
89
  } = t0, instance = useSanityInstance(), isTokenRefreshInProgress = useRef(!1), timeoutRef = useRef(null), processed401ErrorRef = useRef(null), authState = useAuthState();
84
90
  let t1;
85
- $[0] === Symbol.for("react.memo_cache_sentinel") ? (t1 = () => {
91
+ $[0] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t1 = () => {
86
92
  timeoutRef.current && (clearTimeout(timeoutRef.current), timeoutRef.current = null);
87
93
  }, $[0] = t1) : t1 = $[0];
88
94
  const clearRefreshTimeout = t1;
89
95
  let t2;
90
- $[1] === Symbol.for("react.memo_cache_sentinel") ? (t2 = {
96
+ $[1] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t2 = {
91
97
  name: SDK_NODE_NAME,
92
98
  connectTo: SDK_CHANNEL_NAME
93
99
  }, $[1] = t2) : t2 = $[1];
@@ -103,7 +109,7 @@ function DashboardTokenRefresh(t0) {
103
109
  if (clearRefreshTimeout(), res.token) {
104
110
  setAuthToken(instance, res.token);
105
111
  const errorContainer = document.getElementById("__sanityError");
106
- errorContainer && Array.from(errorContainer.getElementsByTagName("div")).some(_temp$5) && errorContainer.remove();
112
+ errorContainer && Array.from(errorContainer.getElementsByTagName("div")).some(_temp$8) && errorContainer.remove();
107
113
  }
108
114
  isTokenRefreshInProgress.current = !1;
109
115
  } catch {
@@ -113,7 +119,7 @@ function DashboardTokenRefresh(t0) {
113
119
  }, $[2] = instance, $[3] = windowConnection, $[4] = t3) : t3 = $[4];
114
120
  const requestNewToken = t3;
115
121
  let t4, t5;
116
- $[5] === Symbol.for("react.memo_cache_sentinel") ? (t4 = () => () => {
122
+ $[5] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t4 = () => () => {
117
123
  clearRefreshTimeout();
118
124
  }, t5 = [clearRefreshTimeout], $[5] = t4, $[6] = t5) : (t4 = $[5], t5 = $[6]), useEffect(t4, t5);
119
125
  let t6;
@@ -124,26 +130,72 @@ function DashboardTokenRefresh(t0) {
124
130
  let t7;
125
131
  return $[11] !== authState || $[12] !== requestNewToken ? (t7 = [authState, requestNewToken], $[11] = authState, $[12] = requestNewToken, $[13] = t7) : t7 = $[13], useEffect(t6, t7), children;
126
132
  }
127
- function _temp$5(div) {
133
+ function _temp$8(div) {
128
134
  return div.textContent?.includes("Uncaught error: Unauthorized - A valid session is required for this endpoint");
129
135
  }
130
136
  const ComlinkTokenRefreshProvider = (t0) => {
131
137
  const $ = c(2), {
132
138
  children
133
- } = t0, instance = useSanityInstance();
134
- let t1;
135
- t1 = getIsInDashboardState(instance).getCurrent();
136
- const isInDashboard = t1, isStudio = isStudioConfig(instance.config);
139
+ } = t0, instance = useSanityInstance(), isInDashboard = getIsInDashboardState(instance).getCurrent(), isStudio = isStudioConfig(instance.config);
137
140
  if (isInDashboard && !isStudio) {
138
- let t2;
139
- return $[0] !== children ? (t2 = /* @__PURE__ */ jsx(DashboardTokenRefresh, { children }), $[0] = children, $[1] = t2) : t2 = $[1], t2;
141
+ let t1;
142
+ return $[0] !== children ? (t1 = /* @__PURE__ */ jsx(DashboardTokenRefresh, { children }), $[0] = children, $[1] = t1) : t1 = $[1], t1;
143
+ }
144
+ return children;
145
+ }, OS_BUS_KEY = /* @__PURE__ */ Symbol.for("sanity.os.bus");
146
+ function isWorkbenchEnvironment() {
147
+ return typeof globalThis == "object" && OS_BUS_KEY in globalThis;
148
+ }
149
+ function observeWorkbenchToken() {
150
+ if (isWorkbenchEnvironment())
151
+ return from(import("@sanity/workbench")).pipe(
152
+ switchMap(({
153
+ os
154
+ }) => os.subscribe("auth.token")),
155
+ // Any failure (importing the host bundle, or the subscription) means "no OS token".
156
+ catchError(() => of(null))
157
+ );
158
+ }
159
+ function refreshWorkbenchToken() {
160
+ isWorkbenchEnvironment() && import("@sanity/workbench").then(({
161
+ os
162
+ }) => os.emit("auth.token.refresh", void 0), () => {
163
+ });
164
+ }
165
+ function WorkbenchTokenRefresh(t0) {
166
+ const $ = c(8), {
167
+ children
168
+ } = t0, instance = useSanityInstance(), authState = useAuthState(), processed401ErrorRef = useRef(null);
169
+ let t1, t2;
170
+ $[0] !== instance ? (t1 = () => {
171
+ const token$ = observeWorkbenchToken();
172
+ if (!token$)
173
+ return;
174
+ const subscription = token$.subscribe((token) => setAuthToken(instance, token));
175
+ return () => subscription.unsubscribe();
176
+ }, t2 = [instance], $[0] = instance, $[1] = t1, $[2] = t2) : (t1 = $[1], t2 = $[2]), useEffect(t1, t2);
177
+ let t3;
178
+ $[3] !== authState.error || $[4] !== authState.type ? (t3 = () => {
179
+ const has401Error = authState.type === AuthStateType.ERROR && authState.error?.statusCode === 401;
180
+ has401Error && processed401ErrorRef.current !== authState.error ? (processed401ErrorRef.current = authState.error, refreshWorkbenchToken()) : has401Error || (processed401ErrorRef.current = null);
181
+ }, $[3] = authState.error, $[4] = authState.type, $[5] = t3) : t3 = $[5];
182
+ let t4;
183
+ return $[6] !== authState ? (t4 = [authState], $[6] = authState, $[7] = t4) : t4 = $[7], useEffect(t3, t4), children;
184
+ }
185
+ const WorkbenchTokenRefreshProvider = (t0) => {
186
+ const $ = c(2), {
187
+ children
188
+ } = t0;
189
+ if (isWorkbenchEnvironment()) {
190
+ let t1;
191
+ return $[0] !== children ? (t1 = /* @__PURE__ */ jsx(WorkbenchTokenRefresh, { children }), $[0] = children, $[1] = t1) : t1 = $[1], t1;
140
192
  }
141
193
  return children;
142
194
  };
143
195
  function useLoginUrl() {
144
196
  const $ = c(2), instance = useSanityInstance();
145
- let t0, t1;
146
- $[0] !== instance ? (t1 = getLoginUrlState(instance), $[0] = instance, $[1] = t1) : t1 = $[1], t0 = t1;
197
+ let t0;
198
+ $[0] !== instance ? (t0 = getLoginUrlState(instance), $[0] = instance, $[1] = t0) : t0 = $[1];
147
199
  const {
148
200
  subscribe,
149
201
  getCurrent
@@ -151,20 +203,41 @@ function useLoginUrl() {
151
203
  return useSyncExternalStore(subscribe, getCurrent);
152
204
  }
153
205
  function useVerifyOrgProjects(t0, projectIds) {
154
- const $ = c(6), disabled = t0 === void 0 ? !1 : t0, instance = useSanityInstance(), [error, setError] = useState(null);
206
+ const $ = c(5), disabled = t0 === void 0 ? !1 : t0, instance = useSanityInstance(), [error, setError] = useState(null), isInactive = disabled || !projectIds || projectIds.length === 0, [prevInactive, setPrevInactive] = useState(isInactive);
207
+ prevInactive !== isInactive && (setPrevInactive(isInactive), isInactive && setError(null));
155
208
  let t1, t2;
156
- return $[0] !== disabled || $[1] !== error || $[2] !== instance || $[3] !== projectIds ? (t1 = () => {
157
- if (disabled || !projectIds || projectIds.length === 0) {
158
- error !== null && setError(null);
209
+ return $[0] !== instance || $[1] !== isInactive || $[2] !== projectIds ? (t1 = () => {
210
+ if (isInactive)
159
211
  return;
160
- }
161
212
  const subscription = observeOrganizationVerificationState(instance, projectIds).subscribe((result) => {
162
213
  setError(result.error);
163
214
  });
164
215
  return () => {
165
216
  subscription.unsubscribe();
166
217
  };
167
- }, t2 = [instance, disabled, error, projectIds], $[0] = disabled, $[1] = error, $[2] = instance, $[3] = projectIds, $[4] = t1, $[5] = t2) : (t1 = $[4], t2 = $[5]), useEffect(t1, t2), error;
218
+ }, t2 = [instance, isInactive, projectIds], $[0] = instance, $[1] = isInactive, $[2] = projectIds, $[3] = t1, $[4] = t2) : (t1 = $[3], t2 = $[4]), useEffect(t1, t2), error;
219
+ }
220
+ const CHUNK_RELOAD_STORAGE_KEY = "__sanity_sdk_chunk_reload_attempted";
221
+ function readChunkReloadFlag() {
222
+ try {
223
+ return typeof window > "u" || typeof window.sessionStorage > "u" ? !1 : window.sessionStorage.getItem(CHUNK_RELOAD_STORAGE_KEY) !== null;
224
+ } catch {
225
+ return !1;
226
+ }
227
+ }
228
+ function setChunkReloadFlag() {
229
+ try {
230
+ if (typeof window > "u" || typeof window.sessionStorage > "u") return;
231
+ window.sessionStorage.setItem(CHUNK_RELOAD_STORAGE_KEY, "1");
232
+ } catch {
233
+ }
234
+ }
235
+ function clearChunkReloadFlag() {
236
+ try {
237
+ if (typeof window > "u" || typeof window.sessionStorage > "u") return;
238
+ window.sessionStorage.removeItem(CHUNK_RELOAD_STORAGE_KEY);
239
+ } catch {
240
+ }
168
241
  }
169
242
  const FONT_SANS_SERIF = "-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Helvetica, Arial, system-ui, sans-serif", FONT_MONOSPACE = "-apple-system-ui-monospace, 'SF Mono', Menlo, Monaco, Consolas, monospace", styles = {
170
243
  container: {
@@ -221,23 +294,45 @@ function Error$1(t0) {
221
294
  t4
222
295
  ] }), $[8] = t1, $[9] = t2, $[10] = t3, $[11] = t4, $[12] = t5) : t5 = $[12], t5;
223
296
  }
297
+ function reload() {
298
+ try {
299
+ window.location.reload();
300
+ } catch {
301
+ }
302
+ }
303
+ function ChunkLoadError(_props) {
304
+ const $ = c(4);
305
+ let t0;
306
+ $[0] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t0 = readChunkReloadFlag(), $[0] = t0) : t0 = $[0];
307
+ const alreadyAttempted = t0;
308
+ let t1, t2;
309
+ if ($[1] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t1 = () => {
310
+ alreadyAttempted || (setChunkReloadFlag(), reload());
311
+ }, t2 = [alreadyAttempted], $[1] = t1, $[2] = t2) : (t1 = $[1], t2 = $[2]), useEffect(t1, t2), !alreadyAttempted)
312
+ return null;
313
+ let t3;
314
+ return $[3] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t3 = /* @__PURE__ */ jsx(Error$1, { heading: "A new version is available", description: "The page tried to load an asset that no longer exists. Reload to continue with the latest version.", cta: {
315
+ text: "Reload page",
316
+ onClick: _temp$7
317
+ } }), $[3] = t3) : t3 = $[3], t3;
318
+ }
319
+ function _temp$7() {
320
+ clearChunkReloadFlag(), reload();
321
+ }
224
322
  function CorsErrorComponent(t0) {
225
323
  const $ = c(6), {
226
324
  projectId,
227
325
  error
228
326
  } = t0, origin = window.location.origin;
229
327
  let t1;
230
- const t2 = `https://sanity.io/manage/project/${projectId}/api`;
231
- let t3;
232
- if ($[0] !== t2) {
233
- const url = new URL(t2);
234
- url.searchParams.set("cors", "add"), url.searchParams.set("origin", origin), url.searchParams.set("credentials", "include"), t3 = url.toString(), $[0] = t2, $[1] = t3;
328
+ if ($[0] !== projectId) {
329
+ const url = new URL(`https://sanity.io/manage/project/${projectId}/api`);
330
+ url.searchParams.set("cors", "add"), url.searchParams.set("origin", origin), url.searchParams.set("credentials", "include"), t1 = url.toString(), $[0] = projectId, $[1] = t1;
235
331
  } else
236
- t3 = $[1];
237
- t1 = t3;
332
+ t1 = $[1];
238
333
  const corsUrl = t1;
239
- let t4;
240
- return $[2] !== corsUrl || $[3] !== error?.message || $[4] !== projectId ? (t4 = /* @__PURE__ */ jsx(Error$1, { heading: "Before you continue\u2026", ...projectId ? {
334
+ let t2;
335
+ return $[2] !== corsUrl || $[3] !== error || $[4] !== projectId ? (t2 = /* @__PURE__ */ jsx(Error$1, { heading: "Before you continue\u2026", ...projectId ? {
241
336
  description: "To access your content, you need to <strong>add the following URL as a CORS origin</strong> to your Sanity project.",
242
337
  code: origin,
243
338
  cta: {
@@ -245,8 +340,8 @@ function CorsErrorComponent(t0) {
245
340
  href: corsUrl
246
341
  }
247
342
  } : {
248
- description: error?.message
249
- } }), $[2] = corsUrl, $[3] = error?.message, $[4] = projectId, $[5] = t4) : t4 = $[5], t4;
343
+ description: getErrorMessage(error)
344
+ } }), $[2] = corsUrl, $[3] = error, $[4] = projectId, $[5] = t2) : t2 = $[5], t2;
250
345
  }
251
346
  function isInIframe() {
252
347
  return typeof window < "u" && window.self !== window.top;
@@ -279,88 +374,124 @@ function LoginCallback() {
279
374
  let t0, t1;
280
375
  return $[0] !== handleAuthCallback2 ? (t0 = () => {
281
376
  const url = new URL(location.href);
282
- handleAuthCallback2(url.toString()).then(_temp$4);
377
+ handleAuthCallback2(url.toString()).then(_temp$6);
283
378
  }, t1 = [handleAuthCallback2], $[0] = handleAuthCallback2, $[1] = t0, $[2] = t1) : (t0 = $[1], t1 = $[2]), useEffect(t0, t1), null;
284
379
  }
285
- function _temp$4(replacementLocation) {
380
+ function _temp$6(replacementLocation) {
286
381
  replacementLocation && history.replaceState(null, "", replacementLocation);
287
382
  }
288
- const ResourceContext = createContext(void 0), useLogOut = createCallbackHook(logout);
383
+ const useLogOut = createCallbackHook(logout);
384
+ function DashboardAccessRequest(t0) {
385
+ const $ = c(5), {
386
+ projectId
387
+ } = t0;
388
+ let t1;
389
+ $[0] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t1 = {
390
+ name: SDK_NODE_NAME,
391
+ connectTo: SDK_CHANNEL_NAME
392
+ }, $[0] = t1) : t1 = $[0];
393
+ const {
394
+ fetch
395
+ } = useWindowConnection(t1);
396
+ let t2, t3;
397
+ return $[1] !== fetch || $[2] !== projectId ? (t2 = () => {
398
+ fetch("dashboard/v1/auth/access/request", {
399
+ resourceType: "project",
400
+ resourceId: projectId
401
+ });
402
+ }, t3 = [fetch, projectId], $[1] = fetch, $[2] = projectId, $[3] = t2, $[4] = t3) : (t2 = $[3], t3 = $[4]), useEffect(t2, t3), null;
403
+ }
289
404
  function LoginError(t0) {
290
- const $ = c(25), {
405
+ const $ = c(30), {
291
406
  error,
292
407
  resetErrorBoundary
293
408
  } = t0;
294
409
  if (!(error instanceof AuthError || error instanceof ConfigurationError || error instanceof ClientError))
295
410
  throw error;
296
- const logout2 = useLogOut(), authState = useAuthState(), resource = useContext(ResourceContext);
297
- let t1;
298
- $[0] !== resource ? (t1 = resource && isDatasetResource(resource) ? resource.projectId : void 0, $[0] = resource, $[1] = t1) : t1 = $[1];
299
- const projectId = t1, [authErrorMessage, setAuthErrorMessage] = useState("Please try again or contact support if the problem persists."), [showRetryCta, setShowRetryCta] = useState(!0);
411
+ const logout2 = useLogOut(), authState = useAuthState(), instance = useSanityInstance(), {
412
+ config: t1
413
+ } = instance, {
414
+ projectId
415
+ } = t1, clientError = error instanceof ClientError ? error : error instanceof AuthError && error.cause instanceof ClientError ? error.cause : null;
300
416
  let t2;
301
- $[2] === Symbol.for("react.memo_cache_sentinel") ? (t2 = {
302
- name: SDK_NODE_NAME,
303
- connectTo: SDK_CHANNEL_NAME
304
- }, $[2] = t2) : t2 = $[2];
305
- const {
306
- fetch
307
- } = useWindowConnection(t2);
417
+ $[0] !== instance ? (t2 = getIsInDashboardState(instance).getCurrent(), $[0] = instance, $[1] = t2) : t2 = $[1];
418
+ const isInDashboard = t2;
308
419
  let t3;
309
- $[3] !== logout2 || $[4] !== resetErrorBoundary ? (t3 = async () => {
310
- await logout2(), resetErrorBoundary();
311
- }, $[3] = logout2, $[4] = resetErrorBoundary, $[5] = t3) : t3 = $[5];
312
- const handleRetry = t3;
420
+ $[2] !== clientError ? (t3 = !!clientError && clientError.statusCode === 401 && isProjectUserNotFoundClientError(clientError), $[2] = clientError, $[3] = t3) : t3 = $[3];
421
+ const isProjectUserNotFound = t3, dashboardAccessProjectId = isProjectUserNotFound && projectId && isInDashboard ? projectId : null;
313
422
  let t4;
314
- $[6] !== authState.type || $[7] !== error || $[8] !== fetch || $[9] !== handleRetry || $[10] !== projectId ? (t4 = () => {
315
- if (error instanceof ClientError) {
316
- if (error.statusCode === 401)
317
- if (isProjectUserNotFoundClientError(error)) {
318
- const description = getClientErrorApiDescription(error);
319
- description && setAuthErrorMessage(description), setShowRetryCta(!1), fetch("dashboard/v1/auth/access/request", {
320
- resourceType: "project",
321
- resourceId: projectId
322
- });
323
- } else
324
- setShowRetryCta(!0), handleRetry();
325
- else if (error.statusCode === 404) {
326
- const errorMessage = getClientErrorApiBody(error)?.message || "";
327
- errorMessage.startsWith("Session with sid") && errorMessage.endsWith("not found") ? setAuthErrorMessage("The session ID is invalid or expired.") : setAuthErrorMessage("The login link is invalid or expired. Please try again."), setShowRetryCta(!0);
328
- }
423
+ $[4] !== logout2 || $[5] !== resetErrorBoundary ? (t4 = async () => {
424
+ await logout2(), resetErrorBoundary();
425
+ }, $[4] = logout2, $[5] = resetErrorBoundary, $[6] = t4) : t4 = $[6];
426
+ const handleRetry = t4;
427
+ let message = "Please try again or contact support if the problem persists.", retry = !0;
428
+ if (clientError) {
429
+ if (clientError.statusCode === 401)
430
+ if (isProjectUserNotFound) {
431
+ let t52;
432
+ $[7] !== clientError ? (t52 = getClientErrorApiDescription(clientError), $[7] = clientError, $[8] = t52) : t52 = $[8];
433
+ const description = t52;
434
+ description && (message = description), retry = !1;
435
+ } else
436
+ isInDashboard || (message = "Signing you out and returning to login...", retry = !0);
437
+ else if (clientError.statusCode === 404) {
438
+ const errorMessage = getClientErrorApiBody(clientError)?.message || "";
439
+ message = errorMessage.startsWith("Session with sid") && errorMessage.endsWith("not found") ? "The session ID is invalid or expired." : "The login link is invalid or expired. Please try again.", retry = !0;
329
440
  }
330
- authState.type !== AuthStateType.ERROR && error instanceof ConfigurationError && (setAuthErrorMessage(error.message), setShowRetryCta(!0));
331
- }, $[6] = authState.type, $[7] = error, $[8] = fetch, $[9] = handleRetry, $[10] = projectId, $[11] = t4) : t4 = $[11];
441
+ }
442
+ authState.type !== AuthStateType.ERROR && error instanceof ConfigurationError && (message = error.message, retry = !0);
332
443
  let t5;
333
- $[12] !== authState || $[13] !== error || $[14] !== fetch || $[15] !== handleRetry || $[16] !== projectId ? (t5 = [authState, handleRetry, error, fetch, projectId], $[12] = authState, $[13] = error, $[14] = fetch, $[15] = handleRetry, $[16] = projectId, $[17] = t5) : t5 = $[17], useEffect(t4, t5);
334
- const t6 = error instanceof AuthError ? "Authentication Error" : "Configuration Error";
335
- let t7;
336
- $[18] !== handleRetry || $[19] !== showRetryCta ? (t7 = showRetryCta ? {
444
+ $[9] !== message || $[10] !== retry ? (t5 = {
445
+ authErrorMessage: message,
446
+ showRetryCta: retry
447
+ }, $[9] = message, $[10] = retry, $[11] = t5) : t5 = $[11];
448
+ const {
449
+ authErrorMessage,
450
+ showRetryCta
451
+ } = t5, hasAutoLoggedOutRef = useRef(!1);
452
+ let t6, t7;
453
+ $[12] !== clientError || $[13] !== handleRetry || $[14] !== isInDashboard || $[15] !== isProjectUserNotFound ? (t6 = () => {
454
+ clientError && clientError.statusCode === 401 && !isProjectUserNotFound && !isInDashboard && !hasAutoLoggedOutRef.current && (hasAutoLoggedOutRef.current = !0, handleRetry());
455
+ }, t7 = [clientError, handleRetry, isInDashboard, isProjectUserNotFound], $[12] = clientError, $[13] = handleRetry, $[14] = isInDashboard, $[15] = isProjectUserNotFound, $[16] = t6, $[17] = t7) : (t6 = $[16], t7 = $[17]), useEffect(t6, t7);
456
+ let t8;
457
+ $[18] !== dashboardAccessProjectId ? (t8 = dashboardAccessProjectId && /* @__PURE__ */ jsx(Suspense, { fallback: null, children: /* @__PURE__ */ jsx(DashboardAccessRequest, { projectId: dashboardAccessProjectId }) }), $[18] = dashboardAccessProjectId, $[19] = t8) : t8 = $[19];
458
+ const t9 = error instanceof ConfigurationError ? "Configuration Error" : "Authentication Error";
459
+ let t10;
460
+ $[20] !== handleRetry || $[21] !== showRetryCta ? (t10 = showRetryCta ? {
337
461
  text: "Retry",
338
462
  onClick: handleRetry
339
- } : void 0, $[18] = handleRetry, $[19] = showRetryCta, $[20] = t7) : t7 = $[20];
340
- let t8;
341
- return $[21] !== authErrorMessage || $[22] !== t6 || $[23] !== t7 ? (t8 = /* @__PURE__ */ jsx(Error$1, { heading: t6, description: authErrorMessage, cta: t7 }), $[21] = authErrorMessage, $[22] = t6, $[23] = t7, $[24] = t8) : t8 = $[24], t8;
463
+ } : void 0, $[20] = handleRetry, $[21] = showRetryCta, $[22] = t10) : t10 = $[22];
464
+ let t11;
465
+ $[23] !== authErrorMessage || $[24] !== t10 || $[25] !== t9 ? (t11 = /* @__PURE__ */ jsx(Error$1, { heading: t9, description: authErrorMessage, cta: t10 }), $[23] = authErrorMessage, $[24] = t10, $[25] = t9, $[26] = t11) : t11 = $[26];
466
+ let t12;
467
+ return $[27] !== t11 || $[28] !== t8 ? (t12 = /* @__PURE__ */ jsxs(Fragment, { children: [
468
+ t8,
469
+ t11
470
+ ] }), $[27] = t11, $[28] = t8, $[29] = t12) : t12 = $[29], t12;
342
471
  }
343
472
  if (isInIframe() && !document.querySelector("[data-sanity-core]")) {
344
473
  const parsedUrl = new URL(window.location.href), mode = new URLSearchParams(parsedUrl.hash.slice(1)).get("mode"), script = document.createElement("script");
345
474
  script.src = mode === "core-ui--staging" ? "https://core.sanity-cdn.work/bridge.js" : "https://core.sanity-cdn.com/bridge.js", script.type = "module", script.async = !0, document.head.appendChild(script);
346
475
  }
347
476
  function AuthBoundary(t0) {
348
- const $ = c(10);
477
+ const $ = c(13);
349
478
  let props, t1;
350
479
  $[0] !== t0 ? ({
351
480
  LoginErrorComponent: t1,
352
481
  ...props
353
482
  } = t0, $[0] = t0, $[1] = props, $[2] = t1) : (props = $[1], t1 = $[2]);
354
- const LoginErrorComponent = t1 === void 0 ? LoginError : t1;
355
- let t2, t3;
356
- $[3] !== LoginErrorComponent ? (t3 = function(fallbackProps) {
357
- return fallbackProps.error instanceof CorsOriginError ? /* @__PURE__ */ jsx(CorsErrorComponent, { ...fallbackProps, projectId: getCorsErrorProjectId(fallbackProps.error) }) : /* @__PURE__ */ jsx(LoginErrorComponent, { ...fallbackProps });
358
- }, $[3] = LoginErrorComponent, $[4] = t3) : t3 = $[4], t2 = t3;
483
+ const LoginErrorComponent = t1 === void 0 ? LoginError : t1, authState = useAuthState(), sessionResetKey = authState.type === AuthStateType.LOGGED_IN ? authState.token : authState.type;
484
+ let t2;
485
+ $[3] !== LoginErrorComponent ? (t2 = function(fallbackProps) {
486
+ return isImportError(fallbackProps.error) ? /* @__PURE__ */ jsx(ChunkLoadError, { ...fallbackProps }) : fallbackProps.error instanceof CorsOriginError ? /* @__PURE__ */ jsx(CorsErrorComponent, { ...fallbackProps, projectId: getCorsErrorProjectId(fallbackProps.error) }) : /* @__PURE__ */ jsx(LoginErrorComponent, { ...fallbackProps });
487
+ }, $[3] = LoginErrorComponent, $[4] = t2) : t2 = $[4];
359
488
  const FallbackComponent = t2;
489
+ let t3;
490
+ $[5] !== sessionResetKey ? (t3 = [sessionResetKey], $[5] = sessionResetKey, $[6] = t3) : t3 = $[6];
360
491
  let t4;
361
- $[5] !== props ? (t4 = /* @__PURE__ */ jsx(AuthSwitch, { ...props }), $[5] = props, $[6] = t4) : t4 = $[6];
492
+ $[7] !== props ? (t4 = /* @__PURE__ */ jsx(AuthSwitch, { ...props }), $[7] = props, $[8] = t4) : t4 = $[8];
362
493
  let t5;
363
- return $[7] !== FallbackComponent || $[8] !== t4 ? (t5 = /* @__PURE__ */ jsx(ComlinkTokenRefreshProvider, { children: /* @__PURE__ */ jsx(ErrorBoundary, { FallbackComponent, children: t4 }) }), $[7] = FallbackComponent, $[8] = t4, $[9] = t5) : t5 = $[9], t5;
494
+ return $[9] !== FallbackComponent || $[10] !== t3 || $[11] !== t4 ? (t5 = /* @__PURE__ */ jsx(ComlinkTokenRefreshProvider, { children: /* @__PURE__ */ jsx(WorkbenchTokenRefreshProvider, { children: /* @__PURE__ */ jsx(ErrorBoundary, { FallbackComponent, resetKeys: t3, children: t4 }) }) }), $[9] = FallbackComponent, $[10] = t3, $[11] = t4, $[12] = t5) : t5 = $[12], t5;
364
495
  }
365
496
  function AuthSwitch(t0) {
366
497
  const $ = c(16);
@@ -378,7 +509,7 @@ function AuthSwitch(t0) {
378
509
  const isStudio = t3, disableVerifyOrg = !verifyOrganization || isStudio || authState.type !== AuthStateType.LOGGED_IN, orgError = useVerifyOrgProjects(disableVerifyOrg, projectIds), isLoggedOut = authState.type === AuthStateType.LOGGED_OUT && !authState.isDestroyingSession, loginUrl = useLoginUrl();
379
510
  let t4, t5;
380
511
  if ($[8] !== isLoggedOut || $[9] !== isStudio || $[10] !== loginUrl ? (t4 = () => {
381
- isLoggedOut && !isInIframe() && !isStudio && (window.location.href = loginUrl);
512
+ isLoggedOut && !isInIframe() && !isStudio && !isWorkbenchEnvironment() && (window.location.href = loginUrl);
382
513
  }, t5 = [isLoggedOut, loginUrl, isStudio], $[8] = isLoggedOut, $[9] = isStudio, $[10] = loginUrl, $[11] = t4, $[12] = t5) : (t4 = $[11], t5 = $[12]), useEffect(t4, t5), verifyOrganization && orgError)
383
514
  throw new ConfigurationError({
384
515
  message: orgError
@@ -400,268 +531,466 @@ function AuthSwitch(t0) {
400
531
  }
401
532
  const SDKStudioContext = createContext(null);
402
533
  SDKStudioContext.displayName = "SDKStudioContext";
403
- const PerspectiveContext = createContext(void 0), DEFAULT_FALLBACK = /* @__PURE__ */ jsx(Fragment, { children: "Warning: No fallback provided. Please supply a fallback prop to ensure proper Suspense handling." });
404
- function ResourceProvider(t0) {
405
- const $ = c(19);
406
- let children, fallback, resource, rest;
407
- $[0] !== t0 ? ({
408
- children,
409
- fallback,
410
- resource,
411
- ...rest
412
- } = t0, $[0] = t0, $[1] = children, $[2] = fallback, $[3] = resource, $[4] = rest) : (children = $[1], fallback = $[2], resource = $[3], rest = $[4]);
413
- const parent = useContext(SanityInstanceContext), {
414
- perspective,
415
- auth,
416
- studio
417
- } = rest;
418
- let t1, t2;
419
- $[5] !== auth || $[6] !== perspective || $[7] !== studio ? (t2 = {
420
- perspective,
421
- auth,
422
- studio
423
- }, $[5] = auth, $[6] = perspective, $[7] = studio, $[8] = t2) : t2 = $[8], t1 = t2;
424
- const config = t1;
425
- if (parent) {
534
+ const DEFAULT_RESOURCE_NAME = "default";
535
+ function useDashboardOrganizationId() {
536
+ const $ = c(2), instance = useSanityInstance();
537
+ let t0;
538
+ $[0] !== instance ? (t0 = getDashboardOrganizationId(instance), $[0] = instance, $[1] = t0) : t0 = $[1];
539
+ const {
540
+ subscribe,
541
+ getCurrent
542
+ } = t0;
543
+ return useSyncExternalStore(subscribe, getCurrent);
544
+ }
545
+ const API_VERSION = "v2026-07-09";
546
+ function getFirstResourceId(result) {
547
+ if (result.status === "fulfilled")
548
+ return result.value.data?.[0]?.id;
549
+ }
550
+ async function resolveOrgResources(instance, organizationId) {
551
+ const client = await firstValueFrom(getClientState(instance, {
552
+ apiVersion: API_VERSION,
553
+ scope: "global"
554
+ }).observable), [mediaLibrariesResult, canvasesResult] = await Promise.allSettled([client.request({
555
+ uri: "/media-libraries",
556
+ query: {
557
+ organizationId
558
+ },
559
+ tag: "org-resources.media-libraries"
560
+ }), client.request({
561
+ uri: "/canvases",
562
+ query: {
563
+ organizationId
564
+ },
565
+ tag: "org-resources.canvases"
566
+ })]), mediaLibraryId = getFirstResourceId(mediaLibrariesResult), canvasId = getFirstResourceId(canvasesResult);
567
+ return {
568
+ mediaLibrary: mediaLibraryId ? {
569
+ mediaLibraryId
570
+ } : void 0,
571
+ canvas: canvasId ? {
572
+ canvasId
573
+ } : void 0
574
+ };
575
+ }
576
+ const ResourcesContext = createContext({}), DEFAULT_MEDIA_LIBRARY_RESOURCE_NAME = "media-library", DEFAULT_CANVAS_RESOURCE_NAME = "canvas", inferredResourceCache = /* @__PURE__ */ new WeakMap();
577
+ function getOrgResourcePromises(instance, organizationId) {
578
+ let promises = inferredResourceCache.get(instance);
579
+ if (!promises) {
580
+ const basePromise = resolveOrgResources(instance, organizationId).then((result) => result, (error) => (console.warn("[sanity/sdk] Failed to infer org resources:", error), {
581
+ mediaLibrary: void 0,
582
+ canvas: void 0
583
+ }));
584
+ promises = /* @__PURE__ */ new Map([[DEFAULT_MEDIA_LIBRARY_RESOURCE_NAME, basePromise.then((r) => r.mediaLibrary)], [DEFAULT_CANVAS_RESOURCE_NAME, basePromise.then((r) => r.canvas)]]), inferredResourceCache.set(instance, promises);
585
+ }
586
+ return promises;
587
+ }
588
+ function InferredResourcesProvider(t0) {
589
+ const $ = c(9), {
590
+ instance,
591
+ orgId,
592
+ explicitResources,
593
+ children
594
+ } = t0, promises = getOrgResourcePromises(instance, orgId), ml = use(promises.get(DEFAULT_MEDIA_LIBRARY_RESOURCE_NAME)), canvas = use(promises.get(DEFAULT_CANVAS_RESOURCE_NAME));
595
+ let inferred;
596
+ $[0] !== canvas || $[1] !== ml ? (inferred = {}, ml !== void 0 && (inferred[DEFAULT_MEDIA_LIBRARY_RESOURCE_NAME] = ml), canvas !== void 0 && (inferred[DEFAULT_CANVAS_RESOURCE_NAME] = canvas), $[0] = canvas, $[1] = ml, $[2] = inferred) : inferred = $[2];
597
+ let t1;
598
+ $[3] !== explicitResources || $[4] !== inferred ? (t1 = {
599
+ ...inferred,
600
+ ...explicitResources
601
+ }, $[3] = explicitResources, $[4] = inferred, $[5] = t1) : t1 = $[5];
602
+ const resources = t1;
603
+ let t2;
604
+ return $[6] !== children || $[7] !== resources ? (t2 = /* @__PURE__ */ jsx(ResourcesContext.Provider, { value: resources, children }), $[6] = children, $[7] = resources, $[8] = t2) : t2 = $[8], t2;
605
+ }
606
+ function OrganizationResourcesProvider(t0) {
607
+ const $ = c(10), {
608
+ resources: t1,
609
+ inferMediaLibraryAndCanvas,
610
+ children
611
+ } = t0;
612
+ let t2;
613
+ $[0] !== t1 ? (t2 = t1 === void 0 ? {} : t1, $[0] = t1, $[1] = t2) : t2 = $[1];
614
+ const explicitResources = t2, instance = useSanityInstance(), orgId = useDashboardOrganizationId();
615
+ if (!inferMediaLibraryAndCanvas || !orgId) {
426
616
  let t32;
427
- return $[9] !== children || $[10] !== fallback || $[11] !== perspective || $[12] !== resource ? (t32 = /* @__PURE__ */ jsx(NestedResourceProvider, { resource, perspective, fallback, children }), $[9] = children, $[10] = fallback, $[11] = perspective, $[12] = resource, $[13] = t32) : t32 = $[13], t32;
617
+ return $[2] !== children || $[3] !== explicitResources ? (t32 = /* @__PURE__ */ jsx(ResourcesContext.Provider, { value: explicitResources, children }), $[2] = children, $[3] = explicitResources, $[4] = t32) : t32 = $[4], t32;
428
618
  }
429
619
  let t3;
430
- return $[14] !== children || $[15] !== config || $[16] !== fallback || $[17] !== resource ? (t3 = /* @__PURE__ */ jsx(RootResourceProvider, { config, resource, fallback, children }), $[14] = children, $[15] = config, $[16] = fallback, $[17] = resource, $[18] = t3) : t3 = $[18], t3;
620
+ return $[5] !== children || $[6] !== explicitResources || $[7] !== instance || $[8] !== orgId ? (t3 = /* @__PURE__ */ jsx(InferredResourcesProvider, { instance, orgId, explicitResources, children }), $[5] = children, $[6] = explicitResources, $[7] = instance, $[8] = orgId, $[9] = t3) : t3 = $[9], t3;
431
621
  }
432
- function RootResourceProvider(t0) {
433
- const $ = c(17), {
434
- children,
622
+ const ResourceContext = createContext(void 0), PerspectiveContext = createContext(void 0), ProjectContext = createContext(void 0);
623
+ function SanityInstanceProvider(t0) {
624
+ const $ = c(6), {
625
+ instance,
435
626
  fallback,
436
- config,
437
- resource
627
+ children
438
628
  } = t0;
439
- let t1, t2;
440
- $[0] !== config ? (t2 = createSanityInstance(config), $[0] = config, $[1] = t2) : t2 = $[1], t1 = t2;
441
- const instance = t1, disposal = useRef(null);
442
- let t3, t4;
443
- $[2] !== instance ? (t3 = () => (disposal.current !== null && instance === disposal.current.instance && (clearTimeout(disposal.current.timeoutId), disposal.current = null), () => {
444
- disposal.current = {
445
- instance,
446
- timeoutId: setTimeout(() => {
447
- instance.isDisposed() || instance.dispose();
448
- }, 0)
449
- };
450
- }), t4 = [instance], $[2] = instance, $[3] = t3, $[4] = t4) : (t3 = $[3], t4 = $[4]), useEffect(t3, t4);
451
- const t5 = fallback ?? DEFAULT_FALLBACK;
452
- let t6;
453
- $[5] !== children || $[6] !== t5 ? (t6 = /* @__PURE__ */ jsx(Suspense, { fallback: t5, children }), $[5] = children, $[6] = t5, $[7] = t6) : t6 = $[7];
454
- let t7;
455
- $[8] !== config.perspective || $[9] !== t6 ? (t7 = /* @__PURE__ */ jsx(PerspectiveContext.Provider, { value: config.perspective, children: t6 }), $[8] = config.perspective, $[9] = t6, $[10] = t7) : t7 = $[10];
456
- let t8;
457
- $[11] !== resource || $[12] !== t7 ? (t8 = /* @__PURE__ */ jsx(ResourceContext.Provider, { value: resource, children: t7 }), $[11] = resource, $[12] = t7, $[13] = t8) : t8 = $[13];
458
- let t9;
459
- return $[14] !== instance || $[15] !== t8 ? (t9 = /* @__PURE__ */ jsx(SanityInstanceContext.Provider, { value: instance, children: t8 }), $[14] = instance, $[15] = t8, $[16] = t9) : t9 = $[16], t9;
629
+ let t1;
630
+ $[0] !== children || $[1] !== fallback ? (t1 = /* @__PURE__ */ jsx(Suspense, { fallback, children }), $[0] = children, $[1] = fallback, $[2] = t1) : t1 = $[2];
631
+ let t2;
632
+ return $[3] !== instance || $[4] !== t1 ? (t2 = /* @__PURE__ */ jsx(SanityInstanceContext.Provider, { value: instance, children: t1 }), $[3] = instance, $[4] = t1, $[5] = t2) : t2 = $[5], t2;
460
633
  }
461
- function NestedResourceProvider(t0) {
462
- const $ = c(9), {
634
+ const DEFAULT_FALLBACK = /* @__PURE__ */ jsx(Fragment, { children: "Warning: No fallback provided. Please supply a fallback prop to ensure proper Suspense handling." });
635
+ function ResourceProvider(t0) {
636
+ const $ = c(35);
637
+ let children, config, fallback, resource;
638
+ $[0] !== t0 ? ({
463
639
  children,
464
640
  fallback,
465
641
  resource,
642
+ ...config
643
+ } = t0, $[0] = t0, $[1] = children, $[2] = config, $[3] = fallback, $[4] = resource) : (children = $[1], config = $[2], fallback = $[3], resource = $[4]);
644
+ const parentPerspective = useContext(PerspectiveContext), parentResource = useContext(ResourceContext), parentInstance = useContext(SanityInstanceContext), parentProjectId = useContext(ProjectContext), {
645
+ projectId,
646
+ dataset,
466
647
  perspective
467
- } = t0, parentResource = useContext(ResourceContext), parentPerspective = useContext(PerspectiveContext), resolvedResource = resource ?? parentResource, resolvedPerspective = perspective ?? parentPerspective, t1 = fallback ?? DEFAULT_FALLBACK;
648
+ } = config;
649
+ let t1;
650
+ $[5] !== config || $[6] !== parentInstance ? (t1 = () => parentInstance ?? createSanityInstance(config), $[5] = config, $[6] = parentInstance, $[7] = t1) : t1 = $[7];
651
+ const [instance] = useState(t1);
468
652
  let t2;
469
- $[0] !== children || $[1] !== t1 ? (t2 = /* @__PURE__ */ jsx(Suspense, { fallback: t1, children }), $[0] = children, $[1] = t1, $[2] = t2) : t2 = $[2];
653
+ bb0: {
654
+ if (projectId && dataset) {
655
+ let t32;
656
+ $[8] !== dataset || $[9] !== projectId ? (t32 = {
657
+ projectId,
658
+ dataset
659
+ }, $[8] = dataset, $[9] = projectId, $[10] = t32) : t32 = $[10], t2 = t32;
660
+ break bb0;
661
+ }
662
+ if (dataset && parentProjectId) {
663
+ let t32;
664
+ $[11] !== dataset || $[12] !== parentProjectId ? (t32 = {
665
+ projectId: parentProjectId,
666
+ dataset
667
+ }, $[11] = dataset, $[12] = parentProjectId, $[13] = t32) : t32 = $[13], t2 = t32;
668
+ break bb0;
669
+ }
670
+ t2 = void 0;
671
+ }
672
+ const configResource = t2;
470
673
  let t3;
471
- $[3] !== resolvedPerspective || $[4] !== t2 ? (t3 = /* @__PURE__ */ jsx(PerspectiveContext.Provider, { value: resolvedPerspective, children: t2 }), $[3] = resolvedPerspective, $[4] = t2, $[5] = t3) : t3 = $[5];
674
+ bb1: {
675
+ if (resource) {
676
+ t3 = resource;
677
+ break bb1;
678
+ }
679
+ if (configResource) {
680
+ t3 = configResource;
681
+ break bb1;
682
+ }
683
+ if (projectId) {
684
+ t3 = void 0;
685
+ break bb1;
686
+ }
687
+ t3 = parentResource;
688
+ }
689
+ const effectiveResource = t3;
472
690
  let t4;
473
- return $[6] !== resolvedResource || $[7] !== t3 ? (t4 = /* @__PURE__ */ jsx(ResourceContext.Provider, { value: resolvedResource, children: t3 }), $[6] = resolvedResource, $[7] = t3, $[8] = t4) : t4 = $[8], t4;
691
+ bb2: {
692
+ if (effectiveResource && isDatasetResource(effectiveResource)) {
693
+ t4 = effectiveResource.projectId;
694
+ break bb2;
695
+ }
696
+ t4 = projectId ?? parentProjectId;
697
+ }
698
+ const effectiveProjectId = t4;
699
+ let t5, t6;
700
+ $[14] !== effectiveResource || $[15] !== instance ? (t5 = () => {
701
+ effectiveResource && isDatasetResource(effectiveResource) && initTelemetry(instance, effectiveResource.projectId);
702
+ }, t6 = [instance, effectiveResource], $[14] = effectiveResource, $[15] = instance, $[16] = t5, $[17] = t6) : (t5 = $[16], t6 = $[17]), useEffect(t5, t6);
703
+ const disposal = useRef(null);
704
+ let t7, t8;
705
+ $[18] !== instance || $[19] !== parentInstance ? (t7 = () => (disposal.current !== null && instance === disposal.current.instance && (clearTimeout(disposal.current.timeoutId), disposal.current = null), () => {
706
+ disposal.current = {
707
+ instance,
708
+ timeoutId: setTimeout(() => {
709
+ !instance.isDisposed() && instance !== parentInstance && instance.dispose();
710
+ }, 0)
711
+ };
712
+ }), t8 = [instance, parentInstance], $[18] = instance, $[19] = parentInstance, $[20] = t7, $[21] = t8) : (t7 = $[20], t8 = $[21]), useEffect(t7, t8);
713
+ const t9 = fallback ?? DEFAULT_FALLBACK, t10 = perspective ?? parentPerspective;
714
+ let t11;
715
+ $[22] !== children || $[23] !== t10 ? (t11 = /* @__PURE__ */ jsx(PerspectiveContext.Provider, { value: t10, children }), $[22] = children, $[23] = t10, $[24] = t11) : t11 = $[24];
716
+ let t12;
717
+ $[25] !== effectiveProjectId || $[26] !== t11 ? (t12 = /* @__PURE__ */ jsx(ProjectContext.Provider, { value: effectiveProjectId, children: t11 }), $[25] = effectiveProjectId, $[26] = t11, $[27] = t12) : t12 = $[27];
718
+ let t13;
719
+ $[28] !== effectiveResource || $[29] !== t12 ? (t13 = /* @__PURE__ */ jsx(ResourceContext.Provider, { value: effectiveResource, children: t12 }), $[28] = effectiveResource, $[29] = t12, $[30] = t13) : t13 = $[30];
720
+ let t14;
721
+ return $[31] !== instance || $[32] !== t13 || $[33] !== t9 ? (t14 = /* @__PURE__ */ jsx(SanityInstanceProvider, { instance, fallback: t9, children: t13 }), $[31] = instance, $[32] = t13, $[33] = t9, $[34] = t14) : t14 = $[34], t14;
474
722
  }
475
- const ResourcesContext = createContext({});
476
- function collectProjectIds(resources) {
477
- const ids = /* @__PURE__ */ new Set();
478
- for (const res of Object.values(resources))
479
- isDatasetResource(res) && ids.add(res.projectId);
480
- return [...ids];
723
+ function ResetChunkReloadFlagOnMount() {
724
+ const $ = c(1);
725
+ let t0;
726
+ return $[0] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t0 = [], $[0] = t0) : t0 = $[0], useEffect(_temp$5, t0), null;
727
+ }
728
+ function _temp$5() {
729
+ clearChunkReloadFlag();
481
730
  }
482
731
  function SDKProvider(t0) {
483
- const $ = c(22);
484
- let children, config, fallback, props, t1;
732
+ const $ = c(36);
733
+ let children, config, fallback, inferMediaLibraryAndCanvas, props;
485
734
  $[0] !== t0 ? ({
486
735
  children,
487
736
  config,
488
- resources: t1,
489
737
  fallback,
738
+ inferMediaLibraryAndCanvas,
490
739
  ...props
491
- } = t0, $[0] = t0, $[1] = children, $[2] = config, $[3] = fallback, $[4] = props, $[5] = t1) : (children = $[1], config = $[2], fallback = $[3], props = $[4], t1 = $[5]);
740
+ } = t0, $[0] = t0, $[1] = children, $[2] = config, $[3] = fallback, $[4] = inferMediaLibraryAndCanvas, $[5] = props) : (children = $[1], config = $[2], fallback = $[3], inferMediaLibraryAndCanvas = $[4], props = $[5]);
741
+ const defaultConfig = Array.isArray(config) ? config[0] : config, defaultProjectId = defaultConfig?.projectId, defaultDataset = defaultConfig?.dataset;
742
+ let t1;
743
+ bb0: {
744
+ let t22;
745
+ $[6] !== props.resources ? (t22 = props.resources ?? {}, $[6] = props.resources, $[7] = t22) : t22 = $[7];
746
+ const explicit = t22;
747
+ if (defaultProjectId && defaultDataset && !Object.hasOwn(explicit, DEFAULT_RESOURCE_NAME)) {
748
+ let t32;
749
+ $[8] !== defaultDataset || $[9] !== defaultProjectId ? (t32 = {
750
+ projectId: defaultProjectId,
751
+ dataset: defaultDataset
752
+ }, $[8] = defaultDataset, $[9] = defaultProjectId, $[10] = t32) : t32 = $[10];
753
+ let t42;
754
+ $[11] !== explicit || $[12] !== t32 ? (t42 = {
755
+ [DEFAULT_RESOURCE_NAME]: t32,
756
+ ...explicit
757
+ }, $[11] = explicit, $[12] = t32, $[13] = t42) : t42 = $[13], t1 = t42;
758
+ break bb0;
759
+ }
760
+ t1 = explicit;
761
+ }
762
+ const resourcesValue = t1;
492
763
  let t2;
493
- $[6] !== t1 ? (t2 = t1 === void 0 ? {} : t1, $[6] = t1, $[7] = t2) : t2 = $[7];
494
- const resources = t2;
495
- let t3, t4;
496
- $[8] !== resources ? (t4 = collectProjectIds(resources), $[8] = resources, $[9] = t4) : t4 = $[9], t3 = t4;
497
- const projectIds = t3;
764
+ if ($[14] !== config || $[15] !== resourcesValue) {
765
+ let t32;
766
+ $[17] !== resourcesValue ? (t32 = Object.values(resourcesValue).filter(isDatasetResource).map(_temp2$1), $[17] = resourcesValue, $[18] = t32) : t32 = $[18];
767
+ let t42;
768
+ $[19] !== config || $[20] !== t32 ? (t42 = new Set([...t32, ...(Array.isArray(config) ? config : [config]).map(_temp3$1)].filter(_temp4)), $[19] = config, $[20] = t32, $[21] = t42) : t42 = $[21], t2 = Array.from(t42), $[14] = config, $[15] = resourcesValue, $[16] = t2;
769
+ } else
770
+ t2 = $[16];
771
+ const projectIds = t2;
772
+ let t3;
773
+ $[22] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t3 = /* @__PURE__ */ jsx(ResetChunkReloadFlagOnMount, {}), $[22] = t3) : t3 = $[22];
774
+ const t4 = resourcesValue[DEFAULT_RESOURCE_NAME];
498
775
  let t5;
499
- t5 = resources[DEFAULT_RESOURCE_NAME];
500
- const rootResource = t5;
776
+ $[23] !== children || $[24] !== inferMediaLibraryAndCanvas || $[25] !== resourcesValue ? (t5 = /* @__PURE__ */ jsx(OrganizationResourcesProvider, { resources: resourcesValue, inferMediaLibraryAndCanvas, children }), $[23] = children, $[24] = inferMediaLibraryAndCanvas, $[25] = resourcesValue, $[26] = t5) : t5 = $[26];
501
777
  let t6;
502
- $[10] !== children || $[11] !== resources ? (t6 = /* @__PURE__ */ jsx(ResourcesContext.Provider, { value: resources, children }), $[10] = children, $[11] = resources, $[12] = t6) : t6 = $[12];
778
+ $[27] !== projectIds || $[28] !== props || $[29] !== t5 ? (t6 = /* @__PURE__ */ jsx(AuthBoundary, { ...props, projectIds, children: t5 }), $[27] = projectIds, $[28] = props, $[29] = t5, $[30] = t6) : t6 = $[30];
503
779
  let t7;
504
- $[13] !== projectIds || $[14] !== props || $[15] !== t6 ? (t7 = /* @__PURE__ */ jsx(AuthBoundary, { ...props, projectIds, children: t6 }), $[13] = projectIds, $[14] = props, $[15] = t6, $[16] = t7) : t7 = $[16];
505
- let t8;
506
- return $[17] !== config || $[18] !== fallback || $[19] !== rootResource || $[20] !== t7 ? (t8 = /* @__PURE__ */ jsx(ResourceProvider, { ...config, resource: rootResource, fallback, children: t7 }), $[17] = config, $[18] = fallback, $[19] = rootResource, $[20] = t7, $[21] = t8) : t8 = $[21], t8;
780
+ return $[31] !== defaultConfig || $[32] !== fallback || $[33] !== t4 || $[34] !== t6 ? (t7 = /* @__PURE__ */ jsxs(ErrorBoundary, { FallbackComponent: ChunkAwareFallback, children: [
781
+ t3,
782
+ /* @__PURE__ */ jsx(ResourceProvider, { ...defaultConfig, resource: t4, fallback, children: t6 })
783
+ ] }), $[31] = defaultConfig, $[32] = fallback, $[33] = t4, $[34] = t6, $[35] = t7) : t7 = $[35], t7;
784
+ }
785
+ function _temp4(id) {
786
+ return !!id;
787
+ }
788
+ function _temp3$1(configObj) {
789
+ return configObj.projectId;
790
+ }
791
+ function _temp2$1(resource) {
792
+ return resource.projectId;
793
+ }
794
+ function ChunkAwareFallback(fallbackProps) {
795
+ const $ = c(2);
796
+ if (isImportError(fallbackProps.error)) {
797
+ let t0;
798
+ return $[0] !== fallbackProps ? (t0 = /* @__PURE__ */ jsx(ChunkLoadError, { ...fallbackProps }), $[0] = fallbackProps, $[1] = t0) : t0 = $[1], t0;
799
+ }
800
+ throw fallbackProps.error;
507
801
  }
508
802
  const REDIRECT_URL = "https://sanity.io/welcome";
509
- function deriveFromWorkspace(workspace) {
803
+ function deriveConfigFromWorkspace(workspace) {
510
804
  return {
511
- config: {
512
- studio: {
513
- authenticated: workspace.authenticated,
514
- auth: workspace.auth.token ? {
515
- token: workspace.auth.token
516
- } : void 0,
517
- projectId: workspace.projectId
518
- }
519
- },
520
- resources: {
521
- [DEFAULT_RESOURCE_NAME]: {
522
- projectId: workspace.projectId,
523
- dataset: workspace.dataset
524
- }
805
+ projectId: workspace.projectId,
806
+ dataset: workspace.dataset,
807
+ studio: {
808
+ authenticated: workspace.authenticated,
809
+ auth: workspace.auth.token ? {
810
+ token: workspace.auth.token
811
+ } : void 0
525
812
  }
526
813
  };
527
814
  }
528
815
  function SanityApp(t0) {
529
- const $ = c(21);
530
- let children, configProp, fallback, props, resourcesProp;
816
+ const $ = c(18);
817
+ let children, configProp, fallback, props;
531
818
  $[0] !== t0 ? ({
532
819
  children,
533
820
  fallback,
534
821
  config: configProp,
535
- resources: resourcesProp,
536
822
  ...props
537
- } = t0, $[0] = t0, $[1] = children, $[2] = configProp, $[3] = fallback, $[4] = props, $[5] = resourcesProp) : (children = $[1], configProp = $[2], fallback = $[3], props = $[4], resourcesProp = $[5]);
823
+ } = t0, $[0] = t0, $[1] = children, $[2] = configProp, $[3] = fallback, $[4] = props) : (children = $[1], configProp = $[2], fallback = $[3], props = $[4]);
538
824
  const studioWorkspace = useContext(SDKStudioContext);
539
825
  let t1;
540
826
  bb0: {
541
- if (studioWorkspace && !configProp && !resourcesProp) {
542
- let t22;
543
- $[6] !== studioWorkspace ? (t22 = deriveFromWorkspace(studioWorkspace), $[6] = studioWorkspace, $[7] = t22) : t22 = $[7], t1 = t22;
544
- break bb0;
545
- }
546
- t1 = null;
547
- }
548
- const derived = t1;
549
- let t2;
550
- bb1: {
551
827
  if (configProp) {
552
- t2 = configProp;
553
- break bb1;
554
- }
555
- if (derived) {
556
- t2 = derived.config;
557
- break bb1;
558
- }
559
- let t32;
560
- $[8] === Symbol.for("react.memo_cache_sentinel") ? (t32 = {}, $[8] = t32) : t32 = $[8], t2 = t32;
561
- }
562
- const resolvedConfig = t2;
563
- let t3;
564
- bb2: {
565
- if (resourcesProp) {
566
- t3 = resourcesProp;
567
- break bb2;
828
+ t1 = configProp;
829
+ break bb0;
568
830
  }
569
- if (derived) {
570
- t3 = derived.resources;
571
- break bb2;
831
+ if (studioWorkspace) {
832
+ let t23;
833
+ $[5] !== studioWorkspace ? (t23 = deriveConfigFromWorkspace(studioWorkspace), $[5] = studioWorkspace, $[6] = t23) : t23 = $[6], t1 = t23;
834
+ break bb0;
572
835
  }
573
- let t42;
574
- $[9] === Symbol.for("react.memo_cache_sentinel") ? (t42 = {}, $[9] = t42) : t42 = $[9], t3 = t42;
836
+ let t22;
837
+ $[7] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t22 = [], $[7] = t22) : t22 = $[7], t1 = t22;
575
838
  }
576
- const resolvedResources = t3;
577
- let t4, t5;
578
- $[10] !== configProp || $[11] !== resolvedConfig || $[12] !== studioWorkspace ? (t4 = () => {
839
+ const resolvedConfig = t1;
840
+ let t2, t3;
841
+ $[8] !== configProp || $[9] !== resolvedConfig || $[10] !== studioWorkspace ? (t2 = () => {
579
842
  let timeout;
580
- const shouldRedirectWithoutConfig = configProp === void 0 && !studioWorkspace && !resolvedConfig;
581
- return !isInIframe() && !isLocalUrl(window) && (shouldRedirectWithoutConfig || resolvedConfig && !isStudioConfig(resolvedConfig)) && (timeout = setTimeout(_temp$3, 1e3)), () => clearTimeout(timeout);
582
- }, t5 = [configProp, resolvedConfig, studioWorkspace], $[10] = configProp, $[11] = resolvedConfig, $[12] = studioWorkspace, $[13] = t4, $[14] = t5) : (t4 = $[13], t5 = $[14]), useEffect(t4, t5);
583
- let t6;
584
- return $[15] !== children || $[16] !== fallback || $[17] !== props || $[18] !== resolvedConfig || $[19] !== resolvedResources ? (t6 = /* @__PURE__ */ jsx(SDKProvider, { ...props, fallback, config: resolvedConfig, resources: resolvedResources, children }), $[15] = children, $[16] = fallback, $[17] = props, $[18] = resolvedConfig, $[19] = resolvedResources, $[20] = t6) : t6 = $[20], t6;
843
+ const primaryConfig = Array.isArray(resolvedConfig) ? resolvedConfig[0] : resolvedConfig, shouldRedirectWithoutConfig = configProp === void 0 && !studioWorkspace && !primaryConfig;
844
+ return !isInIframe() && !isLocalUrl(window) && (shouldRedirectWithoutConfig || primaryConfig && !isStudioConfig(primaryConfig)) && (timeout = setTimeout(_temp$4, 1e3)), () => clearTimeout(timeout);
845
+ }, t3 = [configProp, resolvedConfig, studioWorkspace], $[8] = configProp, $[9] = resolvedConfig, $[10] = studioWorkspace, $[11] = t2, $[12] = t3) : (t2 = $[11], t3 = $[12]), useEffect(t2, t3);
846
+ let t4;
847
+ return $[13] !== children || $[14] !== fallback || $[15] !== props || $[16] !== resolvedConfig ? (t4 = /* @__PURE__ */ jsx(SDKProvider, { ...props, fallback, config: resolvedConfig, children }), $[13] = children, $[14] = fallback, $[15] = props, $[16] = resolvedConfig, $[17] = t4) : t4 = $[17], t4;
585
848
  }
586
- function _temp$3() {
849
+ function _temp$4() {
587
850
  console.warn("Redirecting to core", REDIRECT_URL), window.location.replace(REDIRECT_URL);
588
851
  }
589
- function renderSanityApp(rootElement, namedResources, options, children) {
852
+ function renderSanityApp(rootElement, namedSources, options, children) {
590
853
  if (!rootElement)
591
854
  throw new Error("Missing root element to mount application into");
592
855
  const {
593
856
  reactStrictMode = !1
594
- } = options, root = createRoot(rootElement);
595
- return root.render(reactStrictMode ? /* @__PURE__ */ jsx(StrictMode, { children: /* @__PURE__ */ jsx(SanityApp, { resources: namedResources, fallback: /* @__PURE__ */ jsx("div", { children: "Loading..." }), children }) }) : /* @__PURE__ */ jsx(SanityApp, { resources: namedResources, fallback: /* @__PURE__ */ jsx("div", { children: "Loading..." }), children })), () => root.unmount();
857
+ } = options, root = createRoot(rootElement), config = Object.values(namedSources);
858
+ return root.render(reactStrictMode ? /* @__PURE__ */ jsx(StrictMode, { children: /* @__PURE__ */ jsx(SanityApp, { config, fallback: /* @__PURE__ */ jsx("div", { children: "Loading..." }), children }) }) : /* @__PURE__ */ jsx(SanityApp, { config, fallback: /* @__PURE__ */ jsx("div", { children: "Loading..." }), children })), () => root.unmount();
859
+ }
860
+ function createFetcherHook(fetcher) {
861
+ return function(...params) {
862
+ const instance = useSanityInstance(), source = fetcher.getState(instance, ...params);
863
+ if (source.getCurrent().status === "pending")
864
+ throw fetcher.resolveState(instance, ...params);
865
+ const previous = useRef(null), snapshot = useSyncExternalStore(source.subscribe, () => {
866
+ const next = source.getCurrent(), prev = previous.current;
867
+ return prev && isDeepEqual(prev, next) ? prev : (previous.current = next, next);
868
+ });
869
+ if (snapshot.status !== "success")
870
+ throw snapshot.status === "error" ? snapshot.error : fetcher.resolveState(instance, ...params);
871
+ return {
872
+ data: snapshot.data,
873
+ isFetching: snapshot.isFetching,
874
+ error: snapshot.error,
875
+ refetch: () => fetcher.refetch(instance, ...params)
876
+ };
877
+ };
596
878
  }
879
+ const useCheckPermissions = createFetcherHook(checkPermissions);
597
880
  function normalizeResourceOptions(options, resources, contextResource, contextPerspective) {
598
881
  const {
599
882
  resourceName,
883
+ sourceName,
884
+ source,
885
+ projectId,
886
+ dataset,
600
887
  ...rest
601
- } = options;
602
- if (resourceName && Object.hasOwn(options, "resource"))
603
- throw new Error(`Resource name ${JSON.stringify(resourceName)} and resource ${JSON.stringify(options.resource)} cannot be used together.`);
604
- let resolvedResource = options.resource;
605
- if (!resolvedResource && resourceName) {
606
- if (!Object.hasOwn(resources, resourceName))
607
- throw new Error(`There's no resource named ${JSON.stringify(resourceName)} in context. Register it via the resources prop on <SanityApp>.`);
608
- resolvedResource = resources[resourceName];
888
+ } = options, effectiveResourceName = resourceName ?? sourceName, effectiveResource = options.resource ?? source;
889
+ if (effectiveResourceName && effectiveResource)
890
+ throw new Error(`Resource name ${JSON.stringify(effectiveResourceName)} and resource ${JSON.stringify(effectiveResource)} cannot be used together.`);
891
+ let resolvedResource;
892
+ if (effectiveResource)
893
+ resolvedResource = effectiveResource;
894
+ else if (effectiveResourceName) {
895
+ if (!Object.hasOwn(resources, effectiveResourceName))
896
+ throw new Error(`There's no resource named ${JSON.stringify(effectiveResourceName)} in context. Please use <ResourceProvider>.`);
897
+ resolvedResource = resources[effectiveResourceName];
609
898
  }
610
- if (resolvedResource || (resolvedResource = contextResource), resolvedResource === void 0)
611
- throw new Error("A resource is required. Provide `resource`, `resourceName`, or ensure a default resource is available from context (e.g. via <ResourceProvider> or <SanityApp>).");
899
+ !resolvedResource && projectId && dataset && (resolvedResource = {
900
+ projectId,
901
+ dataset
902
+ }), resolvedResource || (resolvedResource = contextResource);
612
903
  const resolvedPerspective = Object.hasOwn(options, "perspective") ? options.perspective : contextPerspective;
613
904
  return {
614
905
  ...rest,
615
- resource: resolvedResource,
906
+ ...resolvedResource !== void 0 && {
907
+ resource: resolvedResource
908
+ },
616
909
  ...resolvedPerspective !== void 0 && {
617
910
  perspective: resolvedPerspective
618
911
  }
619
912
  };
620
913
  }
621
- function useNormalizedResourceOptions(options) {
622
- const $ = c(5), resources = useContext(ResourcesContext), contextResource = useContext(ResourceContext), contextPerspective = useContext(PerspectiveContext);
914
+ function useEffectiveContextResource() {
915
+ const $ = c(5), contextResource = useContext(ResourceContext), instance = useContext(SanityInstanceContext);
623
916
  let t0;
624
- return $[0] !== contextPerspective || $[1] !== contextResource || $[2] !== options || $[3] !== resources ? (t0 = normalizeResourceOptions(options, resources, contextResource, contextPerspective), $[0] = contextPerspective, $[1] = contextResource, $[2] = options, $[3] = resources, $[4] = t0) : t0 = $[4], t0;
917
+ $[0] !== instance?.config ? (t0 = instance?.config ?? {}, $[0] = instance?.config, $[1] = t0) : t0 = $[1];
918
+ const {
919
+ projectId,
920
+ dataset
921
+ } = t0;
922
+ let t1;
923
+ bb0: {
924
+ if (contextResource) {
925
+ t1 = contextResource;
926
+ break bb0;
927
+ }
928
+ if (projectId && dataset) {
929
+ let t2;
930
+ $[2] !== dataset || $[3] !== projectId ? (t2 = {
931
+ projectId,
932
+ dataset
933
+ }, $[2] = dataset, $[3] = projectId, $[4] = t2) : t2 = $[4], t1 = t2;
934
+ break bb0;
935
+ }
936
+ t1 = void 0;
937
+ }
938
+ return t1;
625
939
  }
626
- function useAgentCallback(action) {
627
- const $ = c(5), instance = useSanityInstance(), resources = useContext(ResourcesContext), contextResource = useContext(ResourceContext);
940
+ function useNormalizedResourceOptions(options) {
941
+ const $ = c(5), resources = useContext(ResourcesContext), effectiveContextResource = useEffectiveContextResource(), contextPerspective = useContext(PerspectiveContext);
628
942
  let t0;
629
- return $[0] !== action || $[1] !== contextResource || $[2] !== instance || $[3] !== resources ? (t0 = (options) => {
630
- const {
631
- resource
632
- } = normalizeResourceOptions({
633
- resource: options.resource,
634
- resourceName: options.resourceName
635
- }, resources, contextResource), {
636
- resourceName: _,
637
- ...rest
638
- } = options;
639
- return action(instance, {
640
- ...rest,
641
- resource
642
- });
643
- }, $[0] = action, $[1] = contextResource, $[2] = instance, $[3] = resources, $[4] = t0) : t0 = $[4], t0;
644
- }
645
- function useAgentGenerate() {
646
- return useAgentCallback(agentGenerate);
647
- }
648
- function useAgentTransform() {
649
- return useAgentCallback(agentTransform);
943
+ return $[0] !== contextPerspective || $[1] !== effectiveContextResource || $[2] !== options || $[3] !== resources ? (t0 = normalizeResourceOptions(options, resources, effectiveContextResource, contextPerspective), $[0] = contextPerspective, $[1] = effectiveContextResource, $[2] = options, $[3] = resources, $[4] = t0) : t0 = $[4], t0;
650
944
  }
651
- function useAgentTranslate() {
652
- return useAgentCallback(agentTranslate);
945
+ function useAgentGenerate(resourceHandle) {
946
+ const $ = c(5), instance = useSanityInstance();
947
+ let t0;
948
+ $[0] !== resourceHandle ? (t0 = resourceHandle ?? {}, $[0] = resourceHandle, $[1] = t0) : t0 = $[1];
949
+ const {
950
+ resource
951
+ } = useNormalizedResourceOptions(t0);
952
+ let t1;
953
+ return $[2] !== instance || $[3] !== resource ? (t1 = (options) => agentGenerate(instance, options, resource), $[2] = instance, $[3] = resource, $[4] = t1) : t1 = $[4], t1;
653
954
  }
654
- function promptAdapter(instance, options) {
655
- return firstValueFrom(agentPrompt(instance, options));
955
+ function useAgentTransform(resourceHandle) {
956
+ const $ = c(5), instance = useSanityInstance();
957
+ let t0;
958
+ $[0] !== resourceHandle ? (t0 = resourceHandle ?? {}, $[0] = resourceHandle, $[1] = t0) : t0 = $[1];
959
+ const {
960
+ resource
961
+ } = useNormalizedResourceOptions(t0);
962
+ let t1;
963
+ return $[2] !== instance || $[3] !== resource ? (t1 = (options) => agentTransform(instance, options, resource), $[2] = instance, $[3] = resource, $[4] = t1) : t1 = $[4], t1;
656
964
  }
657
- function useAgentPrompt() {
658
- return useAgentCallback(promptAdapter);
965
+ function useAgentTranslate(resourceHandle) {
966
+ const $ = c(5), instance = useSanityInstance();
967
+ let t0;
968
+ $[0] !== resourceHandle ? (t0 = resourceHandle ?? {}, $[0] = resourceHandle, $[1] = t0) : t0 = $[1];
969
+ const {
970
+ resource
971
+ } = useNormalizedResourceOptions(t0);
972
+ let t1;
973
+ return $[2] !== instance || $[3] !== resource ? (t1 = (options) => agentTranslate(instance, options, resource), $[2] = instance, $[3] = resource, $[4] = t1) : t1 = $[4], t1;
659
974
  }
660
- function patchAdapter(instance, options) {
661
- return firstValueFrom(agentPatch(instance, options));
975
+ function useAgentPrompt(resourceHandle) {
976
+ const $ = c(5), instance = useSanityInstance();
977
+ let t0;
978
+ $[0] !== resourceHandle ? (t0 = resourceHandle ?? {}, $[0] = resourceHandle, $[1] = t0) : t0 = $[1];
979
+ const {
980
+ resource
981
+ } = useNormalizedResourceOptions(t0);
982
+ let t1;
983
+ return $[2] !== instance || $[3] !== resource ? (t1 = (options) => firstValueFrom(agentPrompt(instance, options, resource)), $[2] = instance, $[3] = resource, $[4] = t1) : t1 = $[4], t1;
662
984
  }
663
- function useAgentPatch() {
664
- return useAgentCallback(patchAdapter);
985
+ function useAgentPatch(resourceHandle) {
986
+ const $ = c(5), instance = useSanityInstance();
987
+ let t0;
988
+ $[0] !== resourceHandle ? (t0 = resourceHandle ?? {}, $[0] = resourceHandle, $[1] = t0) : t0 = $[1];
989
+ const {
990
+ resource
991
+ } = useNormalizedResourceOptions(t0);
992
+ let t1;
993
+ return $[2] !== instance || $[3] !== resource ? (t1 = (options) => firstValueFrom(agentPatch(instance, options, resource)), $[2] = instance, $[3] = resource, $[4] = t1) : t1 = $[4], t1;
665
994
  }
666
995
  function useAgentResourceContext(options) {
667
996
  const $ = c(9), {
@@ -670,7 +999,7 @@ function useAgentResourceContext(options) {
670
999
  documentId
671
1000
  } = options;
672
1001
  let t0;
673
- $[0] === Symbol.for("react.memo_cache_sentinel") ? (t0 = {
1002
+ $[0] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t0 = {
674
1003
  name: SDK_NODE_NAME,
675
1004
  connectTo: SDK_CHANNEL_NAME
676
1005
  }, $[0] = t0) : t0 = $[0];
@@ -708,23 +1037,52 @@ function useAgentResourceContext(options) {
708
1037
  updateContext();
709
1038
  }, t3 = [updateContext], $[6] = updateContext, $[7] = t2, $[8] = t3) : (t2 = $[7], t3 = $[8]), useEffect(t2, t3);
710
1039
  }
711
- const useAuthToken = createStateSourceHook(getTokenState), useCurrentUser = createStateSourceHook(getCurrentUserState);
712
- function useDashboardOrganizationId() {
713
- const $ = c(2), instance = useSanityInstance();
714
- let t0, t1;
715
- $[0] !== instance ? (t1 = getDashboardOrganizationId(instance), $[0] = instance, $[1] = t1) : t1 = $[1], t0 = t1;
716
- const {
717
- subscribe,
718
- getCurrent
719
- } = t0;
720
- return useSyncExternalStore(subscribe, getCurrent);
1040
+ const useApplication = createFetcherHook(application), useApplications = createFetcherHook(applications);
1041
+ function createMutationHook(mutation) {
1042
+ const idle = {
1043
+ status: "idle",
1044
+ data: void 0,
1045
+ error: void 0
1046
+ };
1047
+ return function() {
1048
+ const instance = useSanityInstance(), [state, setState] = useState(idle), callId = useRef(0), mutate = useCallback((input) => {
1049
+ const id = ++callId.current;
1050
+ return setState((prev) => ({
1051
+ status: "pending",
1052
+ data: prev.data,
1053
+ error: void 0
1054
+ })), mutation(instance, input).then(({
1055
+ data
1056
+ }) => (id === callId.current && setState({
1057
+ status: "success",
1058
+ data,
1059
+ error: void 0
1060
+ }), data), (error) => {
1061
+ throw id === callId.current && setState((prev) => ({
1062
+ status: "error",
1063
+ data: prev.data,
1064
+ error
1065
+ })), error;
1066
+ });
1067
+ }, [instance]), reset = useCallback(() => {
1068
+ callId.current++, setState(idle);
1069
+ }, []);
1070
+ return {
1071
+ mutate,
1072
+ isPending: state.status === "pending",
1073
+ error: state.error,
1074
+ data: state.data,
1075
+ reset
1076
+ };
1077
+ };
721
1078
  }
722
- const useClient = createStateSourceHook({
1079
+ const useCreateUserApplication = createMutationHook(createUserApplication), useDeleteApplication = createMutationHook(deleteApplication), useDeleteUserApplication = createMutationHook(deleteUserApplication), useUpdateApplication = createMutationHook(updateApplication), useUpdateUserApplication = createMutationHook(updateUserApplication), useUserApplication = createFetcherHook(userApplication), useUserApplications = createFetcherHook(userApplications), useAuthToken = createStateSourceHook(getTokenState), useCurrentUser = createStateSourceHook(getCurrentUserState), useClient = createStateSourceHook({
723
1080
  getState: (instance, options) => {
724
1081
  if (!options || typeof options != "object")
725
1082
  throw new Error('useClient() requires a configuration object with at least an "apiVersion" property. Example: useClient({ apiVersion: "2024-11-12" })');
726
1083
  return getClientState(instance, options);
727
- }
1084
+ },
1085
+ getConfig: (options) => options
728
1086
  });
729
1087
  function useFrameConnection(options) {
730
1088
  const $ = c(12), {
@@ -750,11 +1108,11 @@ function useFrameConnection(options) {
750
1108
  const [type, handler] = t22, unsubscribe = channel.on(type, handler);
751
1109
  messageUnsubscribers.push(unsubscribe);
752
1110
  }), () => {
753
- messageUnsubscribers.forEach(_temp$2), releaseChannel(instance, name), channelRef.current = null, controllerRef.current = null;
1111
+ messageUnsubscribers.forEach(_temp$3), releaseChannel(instance, name), channelRef.current = null, controllerRef.current = null;
754
1112
  };
755
1113
  }, t1 = [targetOrigin, name, connectTo, heartbeat, onMessage, instance, onStatus], $[0] = connectTo, $[1] = heartbeat, $[2] = instance, $[3] = name, $[4] = onMessage, $[5] = onStatus, $[6] = targetOrigin, $[7] = t0, $[8] = t1) : (t0 = $[7], t1 = $[8]), useEffect(t0, t1);
756
1114
  let t2;
757
- $[9] === Symbol.for("react.memo_cache_sentinel") ? (t2 = (frameWindow) => {
1115
+ $[9] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t2 = (frameWindow) => {
758
1116
  const removeTarget = controllerRef.current?.addTarget(frameWindow);
759
1117
  return () => {
760
1118
  removeTarget?.();
@@ -762,21 +1120,21 @@ function useFrameConnection(options) {
762
1120
  }, $[9] = t2) : t2 = $[9];
763
1121
  const connect = t2;
764
1122
  let t3;
765
- $[10] === Symbol.for("react.memo_cache_sentinel") ? (t3 = (type_0, data) => {
1123
+ $[10] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t3 = (type_0, data) => {
766
1124
  channelRef.current?.post(type_0, data);
767
1125
  }, $[10] = t3) : t3 = $[10];
768
1126
  const sendMessage = t3;
769
1127
  let t4;
770
- return $[11] === Symbol.for("react.memo_cache_sentinel") ? (t4 = {
1128
+ return $[11] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t4 = {
771
1129
  connect,
772
1130
  sendMessage
773
1131
  }, $[11] = t4) : t4 = $[11], t4;
774
1132
  }
775
- function _temp$2(unsub) {
1133
+ function _temp$3(unsub) {
776
1134
  return unsub();
777
1135
  }
778
1136
  function useResource() {
779
- return useContext(ResourceContext);
1137
+ return useEffectiveContextResource();
780
1138
  }
781
1139
  function useDashboardNavigate(navigateFn) {
782
1140
  const $ = c(2);
@@ -791,72 +1149,11 @@ function useDashboardNavigate(navigateFn) {
791
1149
  }
792
1150
  }, $[0] = navigateFn, $[1] = t0) : t0 = $[1], useWindowConnection(t0);
793
1151
  }
794
- function useResourceIdFromDocumentHandle(documentHandle) {
795
- const $ = c(3), options = useNormalizedResourceOptions(documentHandle), {
796
- resource
797
- } = options;
798
- let resourceId = "", resourceType;
799
- resource && (isDatasetResource(resource) ? (resourceId = `${resource.projectId}.${resource.dataset}`, resourceType = void 0) : isMediaLibraryResource(resource) ? (resourceId = resource.mediaLibraryId, resourceType = "media-library") : isCanvasResource(resource) && (resourceId = resource.canvasId, resourceType = "canvas"));
800
- let t0;
801
- return $[0] !== resourceId || $[1] !== resourceType ? (t0 = {
802
- id: resourceId,
803
- type: resourceType
804
- }, $[0] = resourceId, $[1] = resourceType, $[2] = t0) : t0 = $[2], t0;
805
- }
806
- function useDispatchIntent(params) {
807
- const {
808
- action,
809
- intentId,
810
- documentHandle,
811
- parameters
812
- } = params, {
813
- sendMessage
814
- } = useWindowConnection({
815
- name: SDK_NODE_NAME,
816
- connectTo: SDK_CHANNEL_NAME
817
- }), resource = useResourceIdFromDocumentHandle(documentHandle);
818
- return {
819
- dispatchIntent: useCallback(() => {
820
- try {
821
- if (!action && !intentId)
822
- throw new Error("useDispatchIntent: Either `action` or `intentId` must be provided.");
823
- if (action && intentId && console.warn("useDispatchIntent: Both `action` and `intentId` were provided. Using `intentId` and ignoring `action`."), !resource.id)
824
- throw new Error("useDispatchIntent: Unable to determine resource. Either `resource`, `resourceName`, or both `projectId` and `dataset` must be provided in documentHandle.");
825
- const message = {
826
- type: "dashboard/v1/events/intents/dispatch-intent",
827
- data: {
828
- ...action && !intentId ? {
829
- action
830
- } : {},
831
- ...intentId ? {
832
- intentId
833
- } : {},
834
- document: {
835
- id: documentHandle.documentId,
836
- type: documentHandle.documentType
837
- },
838
- resource: {
839
- id: resource.id,
840
- ...resource.type ? {
841
- type: resource.type
842
- } : {}
843
- },
844
- ...parameters && Object.keys(parameters).length > 0 ? {
845
- parameters
846
- } : {}
847
- }
848
- };
849
- sendMessage(message.type, message.data);
850
- } catch (error) {
851
- throw console.error("Failed to dispatch intent:", error), error;
852
- }
853
- }, [action, intentId, documentHandle, parameters, sendMessage, resource.id, resource.type])
854
- };
855
- }
856
1152
  function useManageFavorite({
857
1153
  documentId,
858
1154
  documentType,
859
- resource: paramResource,
1155
+ projectId: paramProjectId,
1156
+ dataset: paramDataset,
860
1157
  resourceId: paramResourceId,
861
1158
  resourceType,
862
1159
  schemaName
@@ -866,22 +1163,21 @@ function useManageFavorite({
866
1163
  } = useWindowConnection({
867
1164
  name: SDK_NODE_NAME,
868
1165
  connectTo: SDK_CHANNEL_NAME
869
- }), instance = useSanityInstance(), contextResource = useContext(ResourceContext), resource = paramResource ?? contextResource, datasetResource = resource && isDatasetResource(resource) ? resource : void 0, projectId = datasetResource?.projectId, dataset = datasetResource?.dataset;
1166
+ }), instance = useSanityInstance(), {
1167
+ config
1168
+ } = instance, instanceProjectId = config?.projectId, instanceDataset = config?.dataset, projectId = paramProjectId ?? instanceProjectId, dataset = paramDataset ?? instanceDataset;
870
1169
  if (resourceType === "studio" && (!projectId || !dataset))
871
1170
  throw new Error("projectId and dataset are required for studio resources");
872
1171
  const resourceId = resourceType === "studio" && !paramResourceId ? `${projectId}.${dataset}` : paramResourceId;
873
1172
  if (!resourceId)
874
1173
  throw new Error("resourceId is required for media-library and canvas resources");
875
- if (!resource)
876
- throw new Error("resource is required");
877
1174
  const context = useMemo(() => ({
878
1175
  documentId,
879
1176
  documentType,
880
- resource,
881
1177
  resourceId,
882
1178
  resourceType,
883
1179
  schemaName
884
- }), [documentId, documentType, resource, resourceId, resourceType, schemaName]), favoriteState = getFavoritesState(instance, context), isFavorited = useSyncExternalStore(favoriteState.subscribe, favoriteState.getCurrent)?.isFavorited ?? !1, handleFavoriteAction = useCallback(async (action) => {
1180
+ }), [documentId, documentType, resourceId, resourceType, schemaName]), favoriteState = getFavoritesState(instance, context), isFavorited = useSyncExternalStore(favoriteState.subscribe, favoriteState.getCurrent)?.isFavorited ?? !1, handleFavoriteAction = useCallback(async (action) => {
885
1181
  if (!(!fetch || !documentId || !documentType || !resourceType))
886
1182
  try {
887
1183
  const payload = {
@@ -912,10 +1208,10 @@ function useManageFavorite({
912
1208
  function useStudioWorkspacesByProjectIdDataset() {
913
1209
  const $ = c(8);
914
1210
  let t0;
915
- $[0] === Symbol.for("react.memo_cache_sentinel") ? (t0 = {}, $[0] = t0) : t0 = $[0];
1211
+ $[0] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t0 = {}, $[0] = t0) : t0 = $[0];
916
1212
  const [workspacesByProjectIdAndDataset, setWorkspacesByProjectIdAndDataset] = useState(t0), [error, setError] = useState(null);
917
1213
  let t1;
918
- $[1] === Symbol.for("react.memo_cache_sentinel") ? (t1 = {
1214
+ $[1] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t1 = {
919
1215
  name: SDK_NODE_NAME,
920
1216
  connectTo: SDK_CHANNEL_NAME
921
1217
  }, $[1] = t1) : t1 = $[1];
@@ -965,7 +1261,7 @@ function useNavigateToStudioDocument(documentHandle, preferredStudioUrl) {
965
1261
  workspacesByProjectIdAndDataset
966
1262
  } = useStudioWorkspacesByProjectIdDataset();
967
1263
  let t0;
968
- $[0] === Symbol.for("react.memo_cache_sentinel") ? (t0 = {
1264
+ $[0] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t0 = {
969
1265
  name: SDK_NODE_NAME,
970
1266
  connectTo: SDK_CHANNEL_NAME
971
1267
  }, $[0] = t0) : t0 = $[0];
@@ -975,8 +1271,9 @@ function useNavigateToStudioDocument(documentHandle, preferredStudioUrl) {
975
1271
  let t1;
976
1272
  $[1] !== documentHandle || $[2] !== preferredStudioUrl || $[3] !== sendMessage || $[4] !== workspacesByProjectIdAndDataset ? (t1 = () => {
977
1273
  const {
978
- resource
979
- } = documentHandle, datasetResource = resource && isDatasetResource(resource) ? resource : void 0, projectId = datasetResource?.projectId, dataset = datasetResource?.dataset;
1274
+ projectId,
1275
+ dataset
1276
+ } = documentHandle;
980
1277
  if (!projectId || !dataset) {
981
1278
  console.warn("Project ID and dataset are required to navigate to a studio document");
982
1279
  return;
@@ -1017,7 +1314,7 @@ function useRecordDocumentHistoryEvent(t0) {
1017
1314
  schemaName
1018
1315
  } = t0;
1019
1316
  let t1;
1020
- $[0] === Symbol.for("react.memo_cache_sentinel") ? (t1 = {
1317
+ $[0] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t1 = {
1021
1318
  name: SDK_NODE_NAME,
1022
1319
  connectTo: SDK_CHANNEL_NAME
1023
1320
  }, $[0] = t1) : t1 = $[0];
@@ -1056,30 +1353,110 @@ function useRecordDocumentHistoryEvent(t0) {
1056
1353
  recordEvent
1057
1354
  }, $[8] = recordEvent, $[9] = t3) : t3 = $[9], t3;
1058
1355
  }
1059
- const useDatasets = createStateSourceHook({
1356
+ function resolveAppTitle(resource) {
1357
+ return resource.manifest?.title || resource.activeDeployment?.manifest?.title || resource.title;
1358
+ }
1359
+ function useWindowTitle(viewTitle) {
1360
+ const [appTitle, setAppTitle] = useState(null), {
1361
+ fetch
1362
+ } = useWindowConnection({
1363
+ name: SDK_NODE_NAME,
1364
+ connectTo: SDK_CHANNEL_NAME
1365
+ });
1366
+ useEffect(() => {
1367
+ if (!fetch) return;
1368
+ const controller = new AbortController();
1369
+ async function fetchAppTitle(signal) {
1370
+ try {
1371
+ const data = await fetch("dashboard/v1/context", void 0, {
1372
+ signal
1373
+ }), title = resolveAppTitle(data.context.resource) || document.title;
1374
+ title && setAppTitle(title);
1375
+ } catch (err) {
1376
+ if (err instanceof Error && err.name === "AbortError") return;
1377
+ console.error("Failed to fetch app title from dashboard context:", err);
1378
+ }
1379
+ }
1380
+ return fetchAppTitle(controller.signal), () => {
1381
+ controller.abort();
1382
+ };
1383
+ }, [fetch]), useEffect(() => {
1384
+ if (!appTitle) return;
1385
+ const previous = document.title;
1386
+ return document.title = viewTitle ? `${viewTitle} | ${appTitle}` : appTitle, () => {
1387
+ document.title = previous;
1388
+ };
1389
+ }, [viewTitle, appTitle]);
1390
+ }
1391
+ function useResolvedProjectId(options) {
1392
+ const $ = c(6);
1393
+ let t0;
1394
+ $[0] !== options ? (t0 = options ?? {}, $[0] = options, $[1] = t0) : t0 = $[1];
1395
+ const {
1396
+ resource
1397
+ } = useNormalizedResourceOptions(t0), contextProjectId = useContext(ProjectContext);
1398
+ let t1;
1399
+ return $[2] !== contextProjectId || $[3] !== options?.projectId || $[4] !== resource ? (t1 = options?.projectId ?? contextProjectId ?? (resource && isDatasetResource(resource) ? resource.projectId : void 0), $[2] = contextProjectId, $[3] = options?.projectId, $[4] = resource, $[5] = t1) : t1 = $[5], t1;
1400
+ }
1401
+ const useDatasetsBase = createStateSourceHook({
1060
1402
  getState: getDatasetsState,
1061
- shouldSuspend: (instance, options) => getDatasetsState(instance, options).getCurrent() === void 0,
1403
+ shouldSuspend: (instance, projectHandle) => (
1404
+ // remove `undefined` since we're suspending when that is the case
1405
+ getDatasetsState(instance, projectHandle).getCurrent() === void 0
1406
+ ),
1062
1407
  suspender: resolveDatasets
1063
- }), useApplyDocumentActions = () => {
1064
- const $ = c(4), instance = useSanityInstance(), resources = useContext(ResourcesContext), contextResource = useContext(ResourceContext);
1408
+ }), useDatasets = (options) => {
1409
+ const $ = c(3), projectId = useResolvedProjectId(options);
1410
+ let t0;
1411
+ return $[0] !== options || $[1] !== projectId ? (t0 = projectId ? {
1412
+ ...options,
1413
+ projectId
1414
+ } : options, $[0] = options, $[1] = projectId, $[2] = t0) : t0 = $[2], useDatasetsBase(t0);
1415
+ };
1416
+ function useApplyActions() {
1417
+ const $ = c(4), instance = useSanityInstance(), resources = useContext(ResourcesContext), effectiveContextResource = useEffectiveContextResource();
1065
1418
  let t0;
1066
- return $[0] !== contextResource || $[1] !== instance || $[2] !== resources ? (t0 = (actionOrActions, options) => {
1067
- const actions = Array.isArray(actionOrActions) ? actionOrActions : [actionOrActions], optionsResource = options ? normalizeResourceOptions(options, resources, contextResource).resource : void 0, normalizedActions = actions.map((action) => normalizeResourceOptions(action, resources, contextResource));
1419
+ return $[0] !== effectiveContextResource || $[1] !== instance || $[2] !== resources ? (t0 = (actionOrActions, options) => {
1420
+ const actions = Array.isArray(actionOrActions) ? actionOrActions : [actionOrActions], optionsResource = options ? normalizeResourceOptions(options, resources, effectiveContextResource).resource : void 0, normalizedActions = actions.map((action) => normalizeResourceOptions(action, resources, effectiveContextResource));
1068
1421
  let resource;
1069
- for (const action_0 of normalizedActions)
1070
- if (resource || (resource = action_0.resource), action_0.resource !== resource)
1071
- throw new Error(`Mismatched resources found in actions. All actions must belong to the same resource. Found "${JSON.stringify(action_0.resource)}" but expected "${JSON.stringify(resource)}".`);
1072
- if (optionsResource && resource && optionsResource !== resource)
1422
+ for (const action_0 of normalizedActions) {
1423
+ const actionResource = action_0.resource;
1424
+ if (!resource && actionResource && (resource = actionResource), !isDeepEqual(actionResource, resource))
1425
+ throw new Error(`Mismatched resources found in actions. All actions must belong to the same resource. Found "${JSON.stringify(actionResource)}" but expected "${JSON.stringify(resource)}".`);
1426
+ }
1427
+ if (optionsResource && resource && !isDeepEqual(optionsResource, resource))
1073
1428
  throw new Error(`Mismatched resources found in actions. Found top-level resource "${JSON.stringify(optionsResource)}" but expected resource from action handles "${JSON.stringify(resource)}".`);
1074
- const effectiveResource = resource ?? optionsResource;
1429
+ const effectiveResource = resource ?? optionsResource ?? effectiveContextResource;
1075
1430
  if (!effectiveResource)
1076
1431
  throw new Error("No resource found. Provide a resource via the action handle or context.");
1077
1432
  return applyDocumentActions(instance, {
1078
- actions,
1433
+ actions: normalizedActions,
1079
1434
  resource: effectiveResource
1080
1435
  });
1081
- }, $[0] = contextResource, $[1] = instance, $[2] = resources, $[3] = t0) : t0 = $[3], t0;
1082
- }, useDocumentValue = createStateSourceHook({
1436
+ }, $[0] = effectiveContextResource, $[1] = instance, $[2] = resources, $[3] = t0) : t0 = $[3], t0;
1437
+ }
1438
+ const useApplyDocumentActions = () => useApplyActions();
1439
+ function useTrackHookUsage(hookName) {
1440
+ const instance = useSanityInstance(), tracked = useRef(null);
1441
+ tracked.current === null && (tracked.current = !0, trackHookMounted(instance, hookName));
1442
+ }
1443
+ function trackHookUsage(instance, hookName) {
1444
+ trackHookMounted(instance, hookName);
1445
+ }
1446
+ function useCreateDocument(options) {
1447
+ const $ = c(3), instance = useSanityInstance();
1448
+ trackHookUsage(instance, "useCreateDocument");
1449
+ const apply = useApplyDocumentActions();
1450
+ let t0;
1451
+ return $[0] !== apply || $[1] !== options ? (t0 = async (initialValue, overrides) => {
1452
+ const documentId = overrides?.documentId ?? options.documentId ?? crypto.randomUUID(), handle = {
1453
+ ...options,
1454
+ documentId
1455
+ };
1456
+ return await apply(createDocument(handle, initialValue)), handle;
1457
+ }, $[0] = apply, $[1] = options, $[2] = t0) : t0 = $[2], t0;
1458
+ }
1459
+ const useDocumentValue = createStateSourceHook({
1083
1460
  // Pass options directly to getDocumentState
1084
1461
  getState: (instance, options) => getDocumentState(instance, options),
1085
1462
  // Pass options directly to getDocumentState for checking current value
@@ -1088,7 +1465,8 @@ const useDatasets = createStateSourceHook({
1088
1465
  ...options
1089
1466
  }) => getDocumentState(instance, options).getCurrent() === void 0,
1090
1467
  // Extract handle part for resolveDocument
1091
- suspender: (instance, options) => resolveDocument(instance, options)
1468
+ suspender: (instance, options) => resolveDocument(instance, options),
1469
+ getConfig: identity
1092
1470
  }), wrapHookWithData = (useValue) => {
1093
1471
  function useHook(...params) {
1094
1472
  return {
@@ -1097,11 +1475,14 @@ const useDatasets = createStateSourceHook({
1097
1475
  }
1098
1476
  return useHook;
1099
1477
  }, useDocument = wrapHookWithData((options) => {
1478
+ useTrackHookUsage("useDocument");
1100
1479
  const normalizedOptions = useNormalizedResourceOptions(options);
1101
1480
  return useDocumentValue(normalizedOptions);
1102
1481
  });
1103
1482
  function useDocumentEvent(options) {
1104
- const $ = c(10), normalizedOptions = useNormalizedResourceOptions(options);
1483
+ const $ = c(10);
1484
+ useTrackHookUsage("useDocumentEvent");
1485
+ const normalizedOptions = useNormalizedResourceOptions(options);
1105
1486
  let datasetHandle, onEvent;
1106
1487
  $[0] !== normalizedOptions ? ({
1107
1488
  onEvent,
@@ -1113,7 +1494,7 @@ function useDocumentEvent(options) {
1113
1494
  ref.current = onEvent;
1114
1495
  }, $[3] = onEvent, $[4] = t0) : t0 = $[4], useInsertionEffect(t0);
1115
1496
  let t1;
1116
- $[5] === Symbol.for("react.memo_cache_sentinel") ? (t1 = (documentEvent) => ref.current(documentEvent), $[5] = t1) : t1 = $[5];
1497
+ $[5] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t1 = (documentEvent) => ref.current(documentEvent), $[5] = t1) : t1 = $[5];
1117
1498
  const stableHandler = t1, instance = useSanityInstance();
1118
1499
  let t2, t3;
1119
1500
  $[6] !== datasetHandle.resource || $[7] !== instance ? (t2 = () => subscribeDocumentEvents(instance, {
@@ -1121,31 +1502,67 @@ function useDocumentEvent(options) {
1121
1502
  resource: datasetHandle.resource
1122
1503
  }), t3 = [instance, datasetHandle.resource, stableHandler], $[6] = datasetHandle.resource, $[7] = instance, $[8] = t2, $[9] = t3) : (t2 = $[8], t3 = $[9]), useEffect(t2, t3);
1123
1504
  }
1505
+ const noopSubscribe = () => () => {
1506
+ }, returnUndefined = () => {
1507
+ };
1124
1508
  function useDocumentPermissions(actionOrActions) {
1125
- const instance = useSanityInstance(), contextResource = useContext(ResourceContext), resources = useContext(ResourcesContext), normalizedActions = useMemo(() => Array.isArray(actionOrActions) ? actionOrActions.map((action) => normalizeResourceOptions(action, resources, contextResource)) : [normalizeResourceOptions(actionOrActions, resources, contextResource)], [actionOrActions, resources, contextResource]);
1126
- let resource;
1127
- for (const action_0 of normalizedActions)
1128
- if (action_0.resource && (resource || (resource = action_0.resource), action_0.resource !== resource))
1129
- throw new Error(`Mismatched resources found in actions. All actions must belong to the same resource. Found "${JSON.stringify(action_0.resource)}" but expected "${JSON.stringify(resource)}".`);
1130
- const effectiveResource = resource ?? contextResource;
1131
- if (!effectiveResource)
1132
- throw new Error("No resource found. Provide a resource via the action handle or wrap with a resource context.");
1133
- const permissionsOptions = useMemo(() => ({
1509
+ const $ = c(13), instance = useSanityInstance();
1510
+ trackHookUsage(instance, "useDocumentPermissions");
1511
+ const effectiveContextResource = useEffectiveContextResource(), resources = useContext(ResourcesContext);
1512
+ let t0;
1513
+ if ($[0] !== actionOrActions || $[1] !== effectiveContextResource || $[2] !== resources) {
1514
+ bb0: {
1515
+ const normalized = Array.isArray(actionOrActions) ? actionOrActions.map((action) => normalizeResourceOptions(action, resources, effectiveContextResource)) : [normalizeResourceOptions(actionOrActions, resources, effectiveContextResource)];
1516
+ let resource;
1517
+ for (const action_0 of normalized)
1518
+ if (action_0.resource && (resource || (resource = action_0.resource), !isDeepEqual(action_0.resource, resource))) {
1519
+ t0 = {
1520
+ actions: normalized,
1521
+ resource,
1522
+ error: new Error(`Mismatched resources found in actions. All actions must belong to the same resource. Found "${JSON.stringify(action_0.resource)}" but expected "${JSON.stringify(resource)}".`)
1523
+ };
1524
+ break bb0;
1525
+ }
1526
+ let t12;
1527
+ $[4] !== normalized || $[5] !== resource ? (t12 = {
1528
+ actions: normalized,
1529
+ resource,
1530
+ error: void 0
1531
+ }, $[4] = normalized, $[5] = resource, $[6] = t12) : t12 = $[6], t0 = t12;
1532
+ }
1533
+ $[0] = actionOrActions, $[1] = effectiveContextResource, $[2] = resources, $[3] = t0;
1534
+ } else
1535
+ t0 = $[3];
1536
+ const {
1537
+ actions: normalizedActions,
1538
+ resource: actionResource,
1539
+ error: validationError
1540
+ } = t0, effectiveResource = actionResource ?? effectiveContextResource;
1541
+ let t1;
1542
+ $[7] !== effectiveResource || $[8] !== normalizedActions ? (t1 = effectiveResource ? {
1134
1543
  resource: effectiveResource,
1135
1544
  actions: normalizedActions
1136
- }), [effectiveResource, normalizedActions]);
1137
- if (!useCallback(() => getPermissionsState(instance, permissionsOptions).getCurrent() !== void 0, [permissionsOptions, instance])())
1138
- throw firstValueFrom(getPermissionsState(instance, permissionsOptions).observable.pipe(filter((result) => result !== void 0)));
1139
- const {
1140
- subscribe,
1141
- getCurrent
1142
- } = useMemo(() => getPermissionsState(instance, permissionsOptions), [permissionsOptions, instance]);
1143
- return useSyncExternalStore(subscribe, getCurrent);
1545
+ } : void 0, $[7] = effectiveResource, $[8] = normalizedActions, $[9] = t1) : t1 = $[9];
1546
+ const permissionsOptions = t1;
1547
+ let t2;
1548
+ $[10] !== instance || $[11] !== permissionsOptions ? (t2 = permissionsOptions ? getPermissionsState(instance, permissionsOptions) : void 0, $[10] = instance, $[11] = permissionsOptions, $[12] = t2) : t2 = $[12];
1549
+ const stateSource = t2, isDocumentReady = () => stateSource !== void 0 && stateSource.getCurrent() !== void 0, result = useSyncExternalStore(stateSource?.subscribe ?? noopSubscribe, stateSource?.getCurrent ?? returnUndefined);
1550
+ if (validationError)
1551
+ throw validationError;
1552
+ if (!effectiveResource)
1553
+ throw new Error("No resource found. Provide a resource via the action handle or wrap with a resource context.");
1554
+ if (!isDocumentReady())
1555
+ throw firstValueFrom(stateSource.observable.pipe(filter(_temp$2)));
1556
+ return result;
1557
+ }
1558
+ function _temp$2(permissions) {
1559
+ return permissions !== void 0;
1144
1560
  }
1145
1561
  const useDocumentSyncStatusValue = createStateSourceHook({
1146
1562
  getState: getDocumentSyncStatus,
1147
1563
  shouldSuspend: (instance, doc) => getDocumentSyncStatus(instance, doc).getCurrent() === void 0,
1148
- suspender: (instance, doc) => resolveDocument(instance, doc)
1564
+ suspender: (instance, doc) => resolveDocument(instance, doc),
1565
+ getConfig: identity
1149
1566
  }), useDocumentSyncStatus = (options) => {
1150
1567
  const normalizedOptions = useNormalizedResourceOptions(options);
1151
1568
  return useDocumentSyncStatusValue(normalizedOptions);
@@ -1157,7 +1574,9 @@ function useEditDocument(t0) {
1157
1574
  path,
1158
1575
  ...doc
1159
1576
  } = t0, $[0] = t0, $[1] = doc, $[2] = path) : (doc = $[1], path = $[2]);
1160
- const instance = useSanityInstance(), normalizedDoc = useNormalizedResourceOptions(doc), apply = useApplyDocumentActions();
1577
+ const instance = useSanityInstance();
1578
+ trackHookUsage(instance, "useEditDocument");
1579
+ const normalizedDoc = useNormalizedResourceOptions(doc), apply = useApplyDocumentActions();
1161
1580
  if (getDocumentState(instance, normalizedDoc).getCurrent() === void 0)
1162
1581
  throw resolveDocument(instance, normalizedDoc);
1163
1582
  let t1;
@@ -1197,7 +1616,9 @@ function _temp$1(key) {
1197
1616
  return !ignoredKeys.includes(key);
1198
1617
  }
1199
1618
  function useQuery(options) {
1200
- const instance = useSanityInstance(), normalized = useNormalizedResourceOptions(options), [isPending, startTransition] = useTransition(), queryKey = getQueryKey(normalized), [deferredQueryKey, setDeferredQueryKey] = useState(queryKey), ref = useRef(new AbortController());
1619
+ const instance = useSanityInstance();
1620
+ trackHookUsage(instance, "useQuery");
1621
+ const normalized = useNormalizedResourceOptions(options), [isPending, startTransition] = useTransition(), queryKey = getQueryKey(normalized), [deferredQueryKey, setDeferredQueryKey] = useState(queryKey), ref = useRef(new AbortController());
1201
1622
  useEffect(() => {
1202
1623
  queryKey !== deferredQueryKey && startTransition(() => {
1203
1624
  ref && !ref.current.signal.aborted && (ref.current.abort(), ref.current = new AbortController()), setDeferredQueryKey(queryKey);
@@ -1224,16 +1645,28 @@ function useQuery(options) {
1224
1645
  }), [data, isPending]);
1225
1646
  }
1226
1647
  const DEFAULT_BATCH_SIZE = 25;
1227
- function useDocuments({
1228
- batchSize = DEFAULT_BATCH_SIZE,
1229
- params,
1230
- search,
1231
- filter: filter2,
1232
- orderings,
1233
- documentType,
1234
- ...rawOptions
1235
- }) {
1236
- const options = useNormalizedResourceOptions(rawOptions), [limit, setLimit] = useState(batchSize), documentTypes = useMemo(() => (Array.isArray(documentType) ? documentType : [documentType]).filter((i) => typeof i == "string"), [documentType]), key = JSON.stringify({
1648
+ function useDocuments(t0) {
1649
+ const $ = c(50);
1650
+ let documentType, filter2, orderings, params, rawOptions, search, t1;
1651
+ $[0] !== t0 ? ({
1652
+ batchSize: t1,
1653
+ params,
1654
+ search,
1655
+ filter: filter2,
1656
+ orderings,
1657
+ documentType,
1658
+ ...rawOptions
1659
+ } = t0, $[0] = t0, $[1] = documentType, $[2] = filter2, $[3] = orderings, $[4] = params, $[5] = rawOptions, $[6] = search, $[7] = t1) : (documentType = $[1], filter2 = $[2], orderings = $[3], params = $[4], rawOptions = $[5], search = $[6], t1 = $[7]);
1660
+ const batchSize = t1 === void 0 ? DEFAULT_BATCH_SIZE : t1;
1661
+ useTrackHookUsage("useDocuments");
1662
+ const options = useNormalizedResourceOptions(rawOptions), [limit, setLimit] = useState(batchSize);
1663
+ let t2;
1664
+ $[8] !== documentType ? (t2 = Array.isArray(documentType) ? documentType : [documentType], $[8] = documentType, $[9] = t2) : t2 = $[9];
1665
+ let t3;
1666
+ $[10] !== t2 ? (t3 = t2.filter(_temp), $[10] = t2, $[11] = t3) : t3 = $[11];
1667
+ const documentTypes = t3;
1668
+ let t4;
1669
+ $[12] !== batchSize || $[13] !== documentTypes || $[14] !== filter2 || $[15] !== options || $[16] !== orderings || $[17] !== params || $[18] !== search ? (t4 = JSON.stringify({
1237
1670
  filter: filter2,
1238
1671
  search,
1239
1672
  params,
@@ -1241,129 +1674,125 @@ function useDocuments({
1241
1674
  batchSize,
1242
1675
  types: documentTypes,
1243
1676
  ...options
1244
- });
1245
- useEffect(() => {
1246
- setLimit(batchSize);
1247
- }, [key, batchSize]);
1248
- const filterClause = useMemo(() => {
1249
- const conditions = [], trimmedSearch = search?.trim();
1677
+ }), $[12] = batchSize, $[13] = documentTypes, $[14] = filter2, $[15] = options, $[16] = orderings, $[17] = params, $[18] = search, $[19] = t4) : t4 = $[19];
1678
+ const key = t4, [prevKey, setPrevKey] = useState(key);
1679
+ prevKey !== key && (setPrevKey(key), setLimit(batchSize));
1680
+ let conditions;
1681
+ if ($[20] !== documentTypes?.length || $[21] !== filter2 || $[22] !== search) {
1682
+ conditions = [];
1683
+ const trimmedSearch = search?.trim();
1250
1684
  if (trimmedSearch) {
1251
1685
  const searchFilter = createGroqSearchFilter(trimmedSearch);
1252
1686
  searchFilter && conditions.push(searchFilter);
1253
1687
  }
1254
- return documentTypes?.length && conditions.push("(_type in $__types)"), filter2 && conditions.push(`(${filter2})`), conditions.length ? `[${conditions.join(" && ")}]` : "";
1255
- }, [filter2, search, documentTypes]), orderClause = orderings ? `| order(${orderings.map((ordering) => [ordering.field, ordering.direction.toLowerCase()].map((str) => str.trim()).filter(Boolean).join(" ")).join(",")})` : "", dataQuery = `*${filterClause}${orderClause}[0...${limit}]{"documentId":_id,"documentType":_type,...$__handle}`, countQuery = `count(*${filterClause})`, {
1256
- data: {
1257
- count,
1258
- data
1259
- },
1260
- isPending
1261
- } = useQuery({
1688
+ documentTypes?.length && conditions.push("(_type in $__types)"), filter2 && conditions.push(`(${filter2})`), $[20] = documentTypes?.length, $[21] = filter2, $[22] = search, $[23] = conditions;
1689
+ } else
1690
+ conditions = $[23];
1691
+ const filterClause = conditions.length ? `[${conditions.join(" && ")}]` : "";
1692
+ let t5;
1693
+ $[24] !== orderings ? (t5 = orderings ? `| order(${orderings.map(_temp3).join(",")})` : "", $[24] = orderings, $[25] = t5) : t5 = $[25];
1694
+ const dataQuery = `*${filterClause}${t5}[0...${limit}]{"documentId":_id,"documentType":_type,...$__handle}`, t6 = `{"count":${`count(*${filterClause})`},"data":${dataQuery}}`;
1695
+ let t7;
1696
+ $[26] !== options.resource ? (t7 = options.resource && isDatasetResource(options.resource) ? pickProperties(options.resource, ["projectId", "dataset"]) : {}, $[26] = options.resource, $[27] = t7) : t7 = $[27];
1697
+ let t8;
1698
+ $[28] !== options ? (t8 = pickProperties(options, ["perspective", "resource"]), $[28] = options, $[29] = t8) : t8 = $[29];
1699
+ let t9;
1700
+ $[30] !== t7 || $[31] !== t8 ? (t9 = {
1701
+ ...t7,
1702
+ ...t8
1703
+ }, $[30] = t7, $[31] = t8, $[32] = t9) : t9 = $[32];
1704
+ let t10;
1705
+ $[33] !== documentTypes || $[34] !== params || $[35] !== t9 ? (t10 = {
1706
+ ...params,
1707
+ __handle: t9,
1708
+ __types: documentTypes
1709
+ }, $[33] = documentTypes, $[34] = params, $[35] = t9, $[36] = t10) : t10 = $[36];
1710
+ let t11;
1711
+ $[37] !== options || $[38] !== t10 || $[39] !== t6 ? (t11 = {
1262
1712
  ...options,
1263
- query: `{"count":${countQuery},"data":${dataQuery}}`,
1264
- params: {
1265
- ...params,
1266
- // these are passed back to the user as part of each document handle
1267
- __handle: pick(options, ["resource", "perspective"]),
1268
- __types: documentTypes
1269
- }
1270
- }), hasMore = data.length < count, loadMore = useCallback(() => {
1713
+ query: t6,
1714
+ params: t10
1715
+ }, $[37] = options, $[38] = t10, $[39] = t6, $[40] = t11) : t11 = $[40];
1716
+ const {
1717
+ data: t12,
1718
+ isPending
1719
+ } = useQuery(t11), {
1720
+ count,
1721
+ data
1722
+ } = t12, hasMore = data.length < count;
1723
+ let t13;
1724
+ $[41] !== batchSize || $[42] !== count ? (t13 = () => {
1271
1725
  setLimit((prev) => Math.min(prev + batchSize, count));
1272
- }, [count, batchSize]);
1273
- return useMemo(() => ({
1726
+ }, $[41] = batchSize, $[42] = count, $[43] = t13) : t13 = $[43];
1727
+ const loadMore = t13;
1728
+ let t14;
1729
+ return $[44] !== count || $[45] !== data || $[46] !== hasMore || $[47] !== isPending || $[48] !== loadMore ? (t14 = {
1274
1730
  data,
1275
1731
  hasMore,
1276
1732
  count,
1277
1733
  isPending,
1278
1734
  loadMore
1279
- }), [count, data, hasMore, isPending, loadMore]);
1735
+ }, $[44] = count, $[45] = data, $[46] = hasMore, $[47] = isPending, $[48] = loadMore, $[49] = t14) : t14 = $[49], t14;
1280
1736
  }
1281
- function usePaginatedDocuments(t0) {
1282
- const $ = c(58);
1283
- let documentType, orderings, rawOptions, search, t1, t2, t3;
1284
- $[0] !== t0 ? ({
1285
- documentType,
1286
- filter: t1,
1287
- pageSize: t2,
1288
- params: t3,
1289
- orderings,
1290
- search,
1291
- ...rawOptions
1292
- } = t0, $[0] = t0, $[1] = documentType, $[2] = orderings, $[3] = rawOptions, $[4] = search, $[5] = t1, $[6] = t2, $[7] = t3) : (documentType = $[1], orderings = $[2], rawOptions = $[3], search = $[4], t1 = $[5], t2 = $[6], t3 = $[7]);
1293
- const filter2 = t1 === void 0 ? "" : t1, pageSize = t2 === void 0 ? 25 : t2;
1294
- let t4;
1295
- $[8] !== t3 ? (t4 = t3 === void 0 ? {} : t3, $[8] = t3, $[9] = t4) : t4 = $[9];
1296
- const params = t4, options = useNormalizedResourceOptions(rawOptions), [pageIndex, setPageIndex] = useState(0);
1297
- let t5;
1298
- $[10] !== filter2 || $[11] !== options || $[12] !== orderings || $[13] !== pageSize || $[14] !== params || $[15] !== search ? (t5 = JSON.stringify({
1737
+ function _temp3(ordering) {
1738
+ return [ordering.field, ordering.direction.toLowerCase()].map(_temp2).filter(Boolean).join(" ");
1739
+ }
1740
+ function _temp2(str) {
1741
+ return str.trim();
1742
+ }
1743
+ function _temp(i) {
1744
+ return typeof i == "string";
1745
+ }
1746
+ const useInstallation = createFetcherHook(installation), useInstallations = createFetcherHook(installations), useOrganization = createFetcherHook(organization), useOrganizations = createFetcherHook(organizations);
1747
+ function usePaginatedDocuments({
1748
+ documentType,
1749
+ filter: filter2 = "",
1750
+ pageSize = 25,
1751
+ params = {},
1752
+ orderings,
1753
+ search,
1754
+ ...rawOptions
1755
+ }) {
1756
+ useTrackHookUsage("usePaginatedDocuments");
1757
+ const options = useNormalizedResourceOptions(rawOptions), [pageIndex, setPageIndex] = useState(0), key = JSON.stringify({
1299
1758
  filter: filter2,
1300
1759
  search,
1301
1760
  params,
1302
1761
  orderings,
1303
1762
  pageSize,
1304
1763
  ...options
1305
- }), $[10] = filter2, $[11] = options, $[12] = orderings, $[13] = pageSize, $[14] = params, $[15] = search, $[16] = t5) : t5 = $[16];
1306
- const key = t5;
1307
- let t6;
1308
- $[17] === Symbol.for("react.memo_cache_sentinel") ? (t6 = () => {
1309
- setPageIndex(0);
1310
- }, $[17] = t6) : t6 = $[17];
1311
- let t7;
1312
- $[18] !== key ? (t7 = [key], $[18] = key, $[19] = t7) : t7 = $[19], useEffect(t6, t7);
1313
- const startIndex = pageIndex * pageSize, endIndex = (pageIndex + 1) * pageSize;
1314
- let t8;
1315
- $[20] !== documentType ? (t8 = Array.isArray(documentType) ? documentType : [documentType], $[20] = documentType, $[21] = t8) : t8 = $[21];
1316
- let t9;
1317
- $[22] !== t8 ? (t9 = t8.filter(_temp), $[22] = t8, $[23] = t9) : t9 = $[23];
1318
- const documentTypes = t9;
1319
- let t10;
1320
- const conditions = [], trimmedSearch = search?.trim();
1321
- if (trimmedSearch) {
1322
- const searchFilter = createGroqSearchFilter(trimmedSearch);
1323
- searchFilter && conditions.push(searchFilter);
1324
- }
1325
- documentTypes?.length && conditions.push("(_type in $__types)"), filter2 && conditions.push(`(${filter2})`), t10 = conditions.length ? `[${conditions.join(" && ")}]` : "";
1326
- const filterClause = t10, orderClause = orderings ? `| order(${orderings.map(_temp3).join(",")})` : "", dataQuery = `*${filterClause}${orderClause}[${startIndex}...${endIndex}]{"documentId":_id,"documentType":_type,...$__handle}`, countQuery = `count(*${filterClause})`, t11 = `{"data":${dataQuery},"count":${countQuery}}`;
1327
- let t12;
1328
- $[24] !== options ? (t12 = pick(options, ["resource", "perspective"]), $[24] = options, $[25] = t12) : t12 = $[25];
1329
- let t13;
1330
- $[26] !== documentTypes || $[27] !== params || $[28] !== t12 ? (t13 = {
1331
- ...params,
1332
- __types: documentTypes,
1333
- __handle: t12
1334
- }, $[26] = documentTypes, $[27] = params, $[28] = t12, $[29] = t13) : t13 = $[29];
1335
- let t14;
1336
- $[30] !== options || $[31] !== t11 || $[32] !== t13 ? (t14 = {
1337
- ...options,
1338
- query: t11,
1339
- params: t13
1340
- }, $[30] = options, $[31] = t11, $[32] = t13, $[33] = t14) : t14 = $[33];
1341
- const {
1342
- data: t15,
1764
+ }), [prevKey, setPrevKey] = useState(key);
1765
+ prevKey !== key && (setPrevKey(key), setPageIndex(0));
1766
+ const startIndex = pageIndex * pageSize, endIndex = (pageIndex + 1) * pageSize, documentTypes = (Array.isArray(documentType) ? documentType : [documentType]).filter((i) => typeof i == "string"), filterClause = useMemo(() => {
1767
+ const conditions = [], trimmedSearch = search?.trim();
1768
+ if (trimmedSearch) {
1769
+ const searchFilter = createGroqSearchFilter(trimmedSearch);
1770
+ searchFilter && conditions.push(searchFilter);
1771
+ }
1772
+ return documentTypes?.length && conditions.push("(_type in $__types)"), filter2 && conditions.push(`(${filter2})`), conditions.length ? `[${conditions.join(" && ")}]` : "";
1773
+ }, [filter2, search, documentTypes?.length]), orderClause = orderings ? `| order(${orderings.map((ordering) => [ordering.field, ordering.direction.toLowerCase()].map((str) => str.trim()).filter(Boolean).join(" ")).join(",")})` : "", dataQuery = `*${filterClause}${orderClause}[${startIndex}...${endIndex}]{"documentId":_id,"documentType":_type,...$__handle}`, countQuery = `count(*${filterClause})`, {
1774
+ data: {
1775
+ data,
1776
+ count
1777
+ },
1343
1778
  isPending
1344
- } = useQuery(t14), {
1345
- data,
1346
- count
1347
- } = t15, totalPages = Math.ceil(count / pageSize), currentPage = pageIndex + 1;
1348
- let t16;
1349
- $[34] === Symbol.for("react.memo_cache_sentinel") ? (t16 = () => setPageIndex(0), $[34] = t16) : t16 = $[34];
1350
- const firstPage = t16;
1351
- let t17;
1352
- $[35] === Symbol.for("react.memo_cache_sentinel") ? (t17 = () => setPageIndex(_temp4), $[35] = t17) : t17 = $[35];
1353
- const previousPage = t17;
1354
- let t18;
1355
- $[36] !== totalPages ? (t18 = () => setPageIndex((prev_0) => Math.min(prev_0 + 1, totalPages - 1)), $[36] = totalPages, $[37] = t18) : t18 = $[37];
1356
- const nextPage = t18;
1357
- let t19;
1358
- $[38] !== totalPages ? (t19 = () => setPageIndex(totalPages - 1), $[38] = totalPages, $[39] = t19) : t19 = $[39];
1359
- const lastPage = t19;
1360
- let t20;
1361
- $[40] !== totalPages ? (t20 = (pageNumber) => {
1779
+ } = useQuery({
1780
+ ...options,
1781
+ query: `{"data":${dataQuery},"count":${countQuery}}`,
1782
+ params: {
1783
+ ...params,
1784
+ __types: documentTypes,
1785
+ __handle: {
1786
+ // keep projectId/dataset for backward compat until v4; resource is added
1787
+ // intentionally so that hook consumers can resolve the correct resource
1788
+ ...options.resource && isDatasetResource(options.resource) ? pickProperties(options.resource, ["projectId", "dataset"]) : {},
1789
+ ...pickProperties(options, ["perspective", "resource"])
1790
+ }
1791
+ }
1792
+ }), totalPages = Math.ceil(count / pageSize), currentPage = pageIndex + 1, firstPage = useCallback(() => setPageIndex(0), []), previousPage = useCallback(() => setPageIndex((prev) => Math.max(prev - 1, 0)), []), nextPage = useCallback(() => setPageIndex((prev_0) => Math.min(prev_0 + 1, totalPages - 1)), [totalPages]), lastPage = useCallback(() => setPageIndex(totalPages - 1), [totalPages]), goToPage = useCallback((pageNumber) => {
1362
1793
  pageNumber < 1 || pageNumber > totalPages || setPageIndex(pageNumber - 1);
1363
- }, $[40] = totalPages, $[41] = t20) : t20 = $[41];
1364
- const goToPage = t20, hasFirstPage = pageIndex > 0, hasPreviousPage = pageIndex > 0, hasNextPage = pageIndex < totalPages - 1, hasLastPage = pageIndex < totalPages - 1;
1365
- let t21;
1366
- return $[42] !== count || $[43] !== currentPage || $[44] !== data || $[45] !== endIndex || $[46] !== goToPage || $[47] !== hasFirstPage || $[48] !== hasLastPage || $[49] !== hasNextPage || $[50] !== hasPreviousPage || $[51] !== isPending || $[52] !== lastPage || $[53] !== nextPage || $[54] !== pageSize || $[55] !== startIndex || $[56] !== totalPages ? (t21 = {
1794
+ }, [totalPages]), hasFirstPage = pageIndex > 0, hasPreviousPage = pageIndex > 0, hasNextPage = pageIndex < totalPages - 1, hasLastPage = pageIndex < totalPages - 1;
1795
+ return {
1367
1796
  data,
1368
1797
  isPending,
1369
1798
  pageSize,
@@ -1381,78 +1810,77 @@ function usePaginatedDocuments(t0) {
1381
1810
  lastPage,
1382
1811
  hasLastPage,
1383
1812
  goToPage
1384
- }, $[42] = count, $[43] = currentPage, $[44] = data, $[45] = endIndex, $[46] = goToPage, $[47] = hasFirstPage, $[48] = hasLastPage, $[49] = hasNextPage, $[50] = hasPreviousPage, $[51] = isPending, $[52] = lastPage, $[53] = nextPage, $[54] = pageSize, $[55] = startIndex, $[56] = totalPages, $[57] = t21) : t21 = $[57], t21;
1385
- }
1386
- function _temp4(prev) {
1387
- return Math.max(prev - 1, 0);
1388
- }
1389
- function _temp3(ordering) {
1390
- return [ordering.field, ordering.direction.toLowerCase()].map(_temp2).filter(Boolean).join(" ");
1391
- }
1392
- function _temp2(str) {
1393
- return str.trim();
1394
- }
1395
- function _temp(i) {
1396
- return typeof i == "string";
1813
+ };
1397
1814
  }
1398
1815
  function usePresence(t0) {
1399
1816
  const $ = c(14);
1400
1817
  let t1;
1401
1818
  $[0] !== t0 ? (t1 = t0 === void 0 ? {} : t0, $[0] = t0, $[1] = t1) : t1 = $[1];
1402
- const normalizedOptions = useNormalizedResourceOptions(t1), sanityInstance = useSanityInstance();
1403
- if (normalizedOptions.resource) {
1404
- if (isMediaLibraryResource(normalizedOptions.resource))
1405
- throw new Error("usePresence() does not support media library resources. Presence tracking requires a dataset resource. Either remove the resourceName parameter or use a dataset resource instead.");
1406
- if (isCanvasResource(normalizedOptions.resource))
1407
- throw new Error("usePresence() does not support canvas resources. Presence tracking requires a dataset resource. Either remove the resourceName parameter or use a dataset resource instead.");
1408
- }
1409
- let t2, t3;
1410
- $[2] !== normalizedOptions || $[3] !== sanityInstance ? (t3 = getPresence(sanityInstance, normalizedOptions), $[2] = normalizedOptions, $[3] = sanityInstance, $[4] = t3) : t3 = $[4], t2 = t3;
1819
+ const normalizedOptions = useNormalizedResourceOptions(t1);
1820
+ if (normalizedOptions.resource && isMediaLibraryResource(normalizedOptions.resource))
1821
+ throw new Error("usePresence() does not support media library resources. Presence tracking requires a canvas or dataset resource.");
1822
+ const sanityInstance = useSanityInstance();
1823
+ trackHookUsage(sanityInstance, "usePresence");
1824
+ let t2;
1825
+ $[2] !== normalizedOptions || $[3] !== sanityInstance ? (t2 = getPresence(sanityInstance, normalizedOptions), $[2] = normalizedOptions, $[3] = sanityInstance, $[4] = t2) : t2 = $[4];
1411
1826
  const source = t2;
1412
- let t4;
1413
- $[5] !== source ? (t4 = (callback) => source.subscribe(callback), $[5] = source, $[6] = t4) : t4 = $[6];
1414
- const subscribe = t4;
1415
- let t5, t6;
1416
- $[7] !== source ? (t5 = () => source.getCurrent(), t6 = () => source.getCurrent(), $[7] = source, $[8] = t5, $[9] = t6) : (t5 = $[8], t6 = $[9]);
1417
- const locations = useSyncExternalStore(subscribe, t5, t6);
1827
+ let t3;
1828
+ $[5] !== source ? (t3 = (callback) => source.subscribe(callback), $[5] = source, $[6] = t3) : t3 = $[6];
1829
+ const subscribe = t3;
1830
+ let t4, t5;
1831
+ $[7] !== source ? (t4 = () => source.getCurrent(), t5 = () => source.getCurrent(), $[7] = source, $[8] = t4, $[9] = t5) : (t4 = $[8], t5 = $[9]);
1832
+ const locations = useSyncExternalStore(subscribe, t4, t5);
1833
+ let t6;
1834
+ $[10] !== locations ? (t6 = locations || [], $[10] = locations, $[11] = t6) : t6 = $[11];
1418
1835
  let t7;
1419
- $[10] !== locations ? (t7 = locations || [], $[10] = locations, $[11] = t7) : t7 = $[11];
1420
- let t8;
1421
- return $[12] !== t7 ? (t8 = {
1422
- locations: t7
1423
- }, $[12] = t7, $[13] = t8) : t8 = $[13], t8;
1424
- }
1425
- function useDocumentProjection({
1426
- ref,
1427
- projection,
1428
- ...docHandle
1429
- }) {
1430
- const instance = useSanityInstance(), normalizedProjection = useMemo(() => projection.trim(), [projection]), normalizedDocHandle = useNormalizedResourceOptions(docHandle), stateSource = useMemo(() => getProjectionState(instance, {
1836
+ return $[12] !== t6 ? (t7 = {
1837
+ locations: t6
1838
+ }, $[12] = t6, $[13] = t7) : t7 = $[13], t7;
1839
+ }
1840
+ function useDocumentProjection(t0) {
1841
+ const $ = c(13);
1842
+ let docHandle, projection, ref;
1843
+ $[0] !== t0 ? ({
1844
+ ref,
1845
+ projection,
1846
+ ...docHandle
1847
+ } = t0, $[0] = t0, $[1] = docHandle, $[2] = projection, $[3] = ref) : (docHandle = $[1], projection = $[2], ref = $[3]);
1848
+ const instance = useSanityInstance();
1849
+ trackHookUsage(instance, "useDocumentProjection");
1850
+ let t1;
1851
+ $[4] !== projection ? (t1 = projection.trim(), $[4] = projection, $[5] = t1) : t1 = $[5];
1852
+ const normalizedProjection = t1, normalizedDocHandle = useNormalizedResourceOptions(docHandle);
1853
+ let t2;
1854
+ $[6] !== instance || $[7] !== normalizedDocHandle || $[8] !== normalizedProjection ? (t2 = getProjectionState(instance, {
1431
1855
  ...normalizedDocHandle,
1432
1856
  projection: normalizedProjection
1433
- }), [instance, normalizedDocHandle, normalizedProjection]);
1857
+ }), $[6] = instance, $[7] = normalizedDocHandle, $[8] = normalizedProjection, $[9] = t2) : t2 = $[9];
1858
+ const stateSource = t2;
1434
1859
  if (stateSource.getCurrent()?.data === null)
1435
1860
  throw resolveProjection(instance, {
1436
1861
  ...normalizedDocHandle,
1437
1862
  projection: normalizedProjection
1438
1863
  });
1439
- const subscribe = useCallback((onStoreChanged) => {
1864
+ let t3;
1865
+ return $[10] !== ref || $[11] !== stateSource ? (t3 = (onStoreChanged) => {
1440
1866
  const subscription = new Observable((observer) => {
1441
1867
  if (typeof IntersectionObserver > "u" || typeof HTMLElement > "u") {
1442
1868
  observer.next(!0);
1443
1869
  return;
1444
1870
  }
1445
- const intersectionObserver = new IntersectionObserver(([entry]) => observer.next(entry.isIntersecting), {
1871
+ const intersectionObserver = new IntersectionObserver((t4) => {
1872
+ const [entry] = t4;
1873
+ return observer.next(entry.isIntersecting);
1874
+ }, {
1446
1875
  rootMargin: "0px",
1447
1876
  threshold: 0
1448
1877
  });
1449
1878
  return ref?.current && ref.current instanceof HTMLElement ? intersectionObserver.observe(ref.current) : observer.next(!0), () => intersectionObserver.disconnect();
1450
- }).pipe(startWith(!1), distinctUntilChanged(), switchMap((isVisible) => isVisible ? new Observable((obs) => stateSource.subscribe(() => obs.next())) : EMPTY)).subscribe({
1879
+ }).pipe(startWith(!1), distinctUntilChanged(), switchMap$1((isVisible) => isVisible ? new Observable((obs) => (obs.next(), stateSource.subscribe(() => obs.next()))) : EMPTY)).subscribe({
1451
1880
  next: onStoreChanged
1452
1881
  });
1453
1882
  return () => subscription.unsubscribe();
1454
- }, [stateSource, ref]);
1455
- return useSyncExternalStore(subscribe, stateSource.getCurrent);
1883
+ }, $[10] = ref, $[11] = stateSource, $[12] = t3) : t3 = $[12], useSyncExternalStore(t3, stateSource.getCurrent);
1456
1884
  }
1457
1885
  function useDocumentPreview(t0) {
1458
1886
  const $ = c(13);
@@ -1461,7 +1889,9 @@ function useDocumentPreview(t0) {
1461
1889
  ref,
1462
1890
  ...docHandle
1463
1891
  } = t0, $[0] = t0, $[1] = docHandle, $[2] = ref) : (docHandle = $[1], ref = $[2]);
1464
- const instance = useSanityInstance(), normalizedDocHandle = useNormalizedResourceOptions(docHandle);
1892
+ const instance = useSanityInstance();
1893
+ trackHookUsage(instance, "useDocumentPreview");
1894
+ const normalizedDocHandle = useNormalizedResourceOptions(docHandle);
1465
1895
  let t1;
1466
1896
  $[3] !== normalizedDocHandle || $[4] !== ref ? (t1 = {
1467
1897
  ...normalizedDocHandle,
@@ -1469,77 +1899,131 @@ function useDocumentPreview(t0) {
1469
1899
  ref
1470
1900
  }, $[3] = normalizedDocHandle, $[4] = ref, $[5] = t1) : t1 = $[5];
1471
1901
  const projectionResult = useDocumentProjection(t1);
1472
- let t2, t3;
1473
- $[6] !== instance || $[7] !== normalizedDocHandle.resource || $[8] !== projectionResult.data ? (t3 = transformProjectionToPreview(instance, normalizedDocHandle.resource, projectionResult.data), $[6] = instance, $[7] = normalizedDocHandle.resource, $[8] = projectionResult.data, $[9] = t3) : t3 = $[9], t2 = t3;
1902
+ let t2;
1903
+ $[6] !== instance || $[7] !== normalizedDocHandle.resource || $[8] !== projectionResult.data ? (t2 = transformProjectionToPreview(instance, projectionResult.data, normalizedDocHandle.resource), $[6] = instance, $[7] = normalizedDocHandle.resource, $[8] = projectionResult.data, $[9] = t2) : t2 = $[9];
1474
1904
  const previewValue = t2;
1475
- let t4;
1476
- return $[10] !== previewValue || $[11] !== projectionResult.isPending ? (t4 = {
1905
+ let t3;
1906
+ return $[10] !== previewValue || $[11] !== projectionResult.isPending ? (t3 = {
1477
1907
  data: previewValue,
1478
1908
  isPending: projectionResult.isPending
1479
- }, $[10] = previewValue, $[11] = projectionResult.isPending, $[12] = t4) : t4 = $[12], t4;
1480
- }
1481
- const useProject = createStateSourceHook({
1482
- // remove `undefined` since we're suspending when that is the case
1483
- getState: getProjectState,
1484
- shouldSuspend: (instance, projectHandle) => getProjectState(instance, projectHandle).getCurrent() === void 0,
1485
- suspender: (instance, projectHandle) => resolveProject(instance, projectHandle)
1486
- }), useProjects = createStateSourceHook({
1487
- getState: getProjectsState,
1488
- shouldSuspend: (instance, options) => getProjectsState(instance, options).getCurrent() === void 0,
1489
- suspender: resolveProjects
1490
- }), useActiveReleasesValue = createStateSourceHook({
1909
+ }, $[10] = previewValue, $[11] = projectionResult.isPending, $[12] = t3) : t3 = $[12], t3;
1910
+ }
1911
+ const useProjectBase = createFetcherHook(project), useProject = (options) => {
1912
+ const projectId = useResolvedProjectId(options);
1913
+ return useProjectBase(projectId ? {
1914
+ ...options,
1915
+ projectId
1916
+ } : options);
1917
+ }, useProjects = createFetcherHook(projects), useActiveReleasesValue = createStateSourceHook({
1491
1918
  getState: getActiveReleasesState,
1492
- shouldSuspend: (instance, options) => getActiveReleasesState(instance, options).getCurrent() === void 0,
1493
- suspender: (instance, options) => firstValueFrom(getActiveReleasesState(instance, options).observable.pipe(filter(Boolean)))
1494
- }), useActiveReleases = (options) => {
1919
+ shouldSuspend: (instance, options) => getActiveReleasesState(instance, options ?? {}).getCurrent() === void 0,
1920
+ suspender: (instance, options) => firstValueFrom(getActiveReleasesState(instance, options ?? {}).observable.pipe(filter(Boolean)))
1921
+ });
1922
+ function useActiveReleases(options) {
1495
1923
  const $ = c(2);
1496
1924
  let t0;
1497
1925
  $[0] !== options ? (t0 = options ?? {}, $[0] = options, $[1] = t0) : t0 = $[1];
1498
1926
  const normalizedOptions = useNormalizedResourceOptions(t0);
1499
1927
  return useActiveReleasesValue(normalizedOptions);
1500
- }, usePerspectiveValue = createStateSourceHook({
1928
+ }
1929
+ const useAllReleasesValue = createStateSourceHook({
1930
+ getState: getAllReleasesState,
1931
+ shouldSuspend: (instance, options) => getAllReleasesState(instance, options ?? {}).getCurrent() === void 0,
1932
+ suspender: (instance, options) => firstValueFrom(getAllReleasesState(instance, options ?? {}).observable.pipe(filter(Boolean)))
1933
+ });
1934
+ function useAllReleases(options) {
1935
+ const $ = c(2);
1936
+ let t0;
1937
+ $[0] !== options ? (t0 = options ?? {}, $[0] = options, $[1] = t0) : t0 = $[1];
1938
+ const normalizedOptions = useNormalizedResourceOptions(t0);
1939
+ return useAllReleasesValue(normalizedOptions);
1940
+ }
1941
+ const useApplyReleaseActions = () => useApplyActions(), usePerspectiveValue = createStateSourceHook({
1501
1942
  getState: getPerspectiveState,
1502
1943
  shouldSuspend: (instance, options) => getPerspectiveState(instance, options).getCurrent() === void 0,
1503
- suspender: (instance, _options) => firstValueFrom(getPerspectiveState(instance, _options).observable.pipe(filter(Boolean)))
1504
- }), usePerspective = (options) => {
1944
+ suspender: (instance, _options) => firstValueFrom(getPerspectiveState(instance, _options ?? {}).observable.pipe(filter(Boolean)))
1945
+ });
1946
+ function usePerspective(perspectiveHandle) {
1505
1947
  const $ = c(2);
1506
1948
  let t0;
1507
- $[0] !== options ? (t0 = options ?? {}, $[0] = options, $[1] = t0) : t0 = $[1];
1949
+ $[0] !== perspectiveHandle ? (t0 = perspectiveHandle ?? {}, $[0] = perspectiveHandle, $[1] = t0) : t0 = $[1];
1508
1950
  const normalizedOptions = useNormalizedResourceOptions(t0);
1509
1951
  return usePerspectiveValue(normalizedOptions);
1510
- };
1952
+ }
1511
1953
  function useUser(options) {
1512
- const instance = useSanityInstance(), [isPending, startTransition] = useTransition(), key = getUsersKey(instance, options), [deferredKey, setDeferredKey] = useState(key), deferred = useMemo(() => parseUsersKey(deferredKey), [deferredKey]), [ref, setRef] = useState(new AbortController());
1513
- useEffect(() => {
1954
+ const $ = c(17), instance = useSanityInstance();
1955
+ trackHookUsage(instance, "useUser");
1956
+ const [isPending, startTransition] = useTransition();
1957
+ let t0;
1958
+ $[0] !== instance || $[1] !== options ? (t0 = getUsersKey(instance, options), $[0] = instance, $[1] = options, $[2] = t0) : t0 = $[2];
1959
+ const key = t0, [deferredKey, setDeferredKey] = useState(key);
1960
+ let t1;
1961
+ $[3] !== deferredKey ? (t1 = parseUsersKey(deferredKey), $[3] = deferredKey, $[4] = t1) : t1 = $[4];
1962
+ const deferred = t1;
1963
+ let t2;
1964
+ $[5] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t2 = new AbortController(), $[5] = t2) : t2 = $[5];
1965
+ const [ref, setRef] = useState(t2);
1966
+ let t3, t4;
1967
+ $[6] !== deferredKey || $[7] !== key || $[8] !== ref ? (t3 = () => {
1514
1968
  key !== deferredKey && startTransition(() => {
1515
1969
  ref.signal.aborted || (ref.abort(), setRef(new AbortController())), setDeferredKey(key);
1516
1970
  });
1517
- }, [deferredKey, key, ref]);
1971
+ }, t4 = [deferredKey, key, ref], $[6] = deferredKey, $[7] = key, $[8] = ref, $[9] = t3, $[10] = t4) : (t3 = $[9], t4 = $[10]), useEffect(t3, t4);
1972
+ const t5 = deferred;
1973
+ let t6;
1974
+ $[11] !== instance || $[12] !== t5 ? (t6 = getUsersState(instance, t5), $[11] = instance, $[12] = t5, $[13] = t6) : t6 = $[13];
1518
1975
  const {
1519
1976
  getCurrent,
1520
1977
  subscribe
1521
- } = useMemo(() => getUsersState(instance, deferred), [instance, deferred]);
1978
+ } = t6;
1522
1979
  if (getCurrent() === void 0)
1523
1980
  throw resolveUsers(instance, {
1524
1981
  ...deferred,
1525
1982
  signal: ref.signal
1526
1983
  });
1527
- return {
1528
- data: useSyncExternalStore(subscribe, getCurrent)?.data[0],
1984
+ const data = useSyncExternalStore(subscribe, getCurrent)?.data[0];
1985
+ let t7;
1986
+ return $[14] !== data || $[15] !== isPending ? (t7 = {
1987
+ data,
1529
1988
  isPending
1530
- };
1989
+ }, $[14] = data, $[15] = isPending, $[16] = t7) : t7 = $[16], t7;
1990
+ }
1991
+ function withResolvedProjectId(options, projectId) {
1992
+ return projectId ? options ? options.resourceType === "organization" || options.organizationId || options.projectId ? options : {
1993
+ ...options,
1994
+ projectId
1995
+ } : {
1996
+ projectId
1997
+ } : options;
1531
1998
  }
1532
1999
  function useUsers(options) {
1533
- const instance = useSanityInstance(), [isPending, startTransition] = useTransition(), key = getUsersKey(instance, options), [deferredKey, setDeferredKey] = useState(key), deferred = useMemo(() => parseUsersKey(deferredKey), [deferredKey]), [ref, setRef] = useState(new AbortController());
1534
- useEffect(() => {
2000
+ const $ = c(25), instance = useSanityInstance();
2001
+ trackHookUsage(instance, "useUsers");
2002
+ const [isPending, startTransition] = useTransition(), resolvedProjectId = useResolvedProjectId(options);
2003
+ let t0;
2004
+ $[0] !== options || $[1] !== resolvedProjectId ? (t0 = withResolvedProjectId(options, resolvedProjectId), $[0] = options, $[1] = resolvedProjectId, $[2] = t0) : t0 = $[2];
2005
+ const effectiveOptions = t0;
2006
+ let t1;
2007
+ $[3] !== effectiveOptions || $[4] !== instance ? (t1 = getUsersKey(instance, effectiveOptions), $[3] = effectiveOptions, $[4] = instance, $[5] = t1) : t1 = $[5];
2008
+ const key = t1, [deferredKey, setDeferredKey] = useState(key);
2009
+ let t2;
2010
+ $[6] !== deferredKey ? (t2 = parseUsersKey(deferredKey), $[6] = deferredKey, $[7] = t2) : t2 = $[7];
2011
+ const deferred = t2;
2012
+ let t3;
2013
+ $[8] === /* @__PURE__ */ Symbol.for("react.memo_cache_sentinel") ? (t3 = new AbortController(), $[8] = t3) : t3 = $[8];
2014
+ const [ref, setRef] = useState(t3);
2015
+ let t4, t5;
2016
+ $[9] !== deferredKey || $[10] !== key || $[11] !== ref ? (t4 = () => {
1535
2017
  key !== deferredKey && startTransition(() => {
1536
2018
  ref.signal.aborted || (ref.abort(), setRef(new AbortController())), setDeferredKey(key);
1537
2019
  });
1538
- }, [deferredKey, key, ref]);
2020
+ }, t5 = [deferredKey, key, ref], $[9] = deferredKey, $[10] = key, $[11] = ref, $[12] = t4, $[13] = t5) : (t4 = $[12], t5 = $[13]), useEffect(t4, t5);
2021
+ let t6;
2022
+ $[14] !== deferred || $[15] !== instance ? (t6 = getUsersState(instance, deferred), $[14] = deferred, $[15] = instance, $[16] = t6) : t6 = $[16];
1539
2023
  const {
1540
2024
  getCurrent,
1541
2025
  subscribe
1542
- } = useMemo(() => getUsersState(instance, deferred), [instance, deferred]);
2026
+ } = t6;
1543
2027
  if (getCurrent() === void 0)
1544
2028
  throw resolveUsers(instance, {
1545
2029
  ...deferred,
@@ -1548,17 +2032,21 @@ function useUsers(options) {
1548
2032
  const {
1549
2033
  data,
1550
2034
  hasMore
1551
- } = useSyncExternalStore(subscribe, getCurrent), loadMore = useCallback(() => {
1552
- loadMoreUsers(instance, options);
1553
- }, [instance, options]);
1554
- return {
2035
+ } = useSyncExternalStore(subscribe, getCurrent);
2036
+ let t7;
2037
+ $[17] !== effectiveOptions || $[18] !== instance ? (t7 = () => {
2038
+ loadMoreUsers(instance, effectiveOptions);
2039
+ }, $[17] = effectiveOptions, $[18] = instance, $[19] = t7) : t7 = $[19];
2040
+ const loadMore = t7;
2041
+ let t8;
2042
+ return $[20] !== data || $[21] !== hasMore || $[22] !== isPending || $[23] !== loadMore ? (t8 = {
1555
2043
  data,
1556
2044
  hasMore,
1557
2045
  isPending,
1558
2046
  loadMore
1559
- };
2047
+ }, $[20] = data, $[21] = hasMore, $[22] = isPending, $[23] = loadMore, $[24] = t8) : t8 = $[24], t8;
1560
2048
  }
1561
- var version = "3.0.0-rc.0";
2049
+ var version = "3.0.0-rc.1";
1562
2050
  function getEnv(key) {
1563
2051
  if (typeof import.meta < "u" && import.meta.env)
1564
2052
  return import.meta.env[key];
@@ -1576,6 +2064,7 @@ export {
1576
2064
  SDKProvider,
1577
2065
  SDKStudioContext,
1578
2066
  SanityApp,
2067
+ SanityInstanceProvider,
1579
2068
  renderSanityApp,
1580
2069
  useActiveReleases,
1581
2070
  useAgentGenerate,
@@ -1584,15 +2073,23 @@ export {
1584
2073
  useAgentResourceContext,
1585
2074
  useAgentTransform,
1586
2075
  useAgentTranslate,
2076
+ useAllReleases,
2077
+ useApplication,
2078
+ useApplications,
1587
2079
  useApplyDocumentActions,
2080
+ useApplyReleaseActions,
1588
2081
  useAuthState,
1589
2082
  useAuthToken,
2083
+ useCheckPermissions,
1590
2084
  useClient,
2085
+ useCreateDocument,
2086
+ useCreateUserApplication,
1591
2087
  useCurrentUser,
1592
2088
  useDashboardNavigate,
1593
2089
  useDashboardOrganizationId,
1594
2090
  useDatasets,
1595
- useDispatchIntent,
2091
+ useDeleteApplication,
2092
+ useDeleteUserApplication,
1596
2093
  useDocument,
1597
2094
  useDocumentEvent,
1598
2095
  useDocumentPermissions,
@@ -1603,10 +2100,14 @@ export {
1603
2100
  useEditDocument,
1604
2101
  useFrameConnection,
1605
2102
  useHandleAuthCallback,
2103
+ useInstallation,
2104
+ useInstallations,
1606
2105
  useLogOut,
1607
2106
  useLoginUrl,
1608
2107
  useManageFavorite,
1609
2108
  useNavigateToStudioDocument,
2109
+ useOrganization,
2110
+ useOrganizations,
1610
2111
  usePaginatedDocuments,
1611
2112
  usePerspective,
1612
2113
  usePresence,
@@ -1617,9 +2118,14 @@ export {
1617
2118
  useResource,
1618
2119
  useSanityInstance,
1619
2120
  useStudioWorkspacesByProjectIdDataset,
2121
+ useUpdateApplication,
2122
+ useUpdateUserApplication,
1620
2123
  useUser,
2124
+ useUserApplication,
2125
+ useUserApplications,
1621
2126
  useUsers,
1622
2127
  useVerifyOrgProjects,
1623
- useWindowConnection
2128
+ useWindowConnection,
2129
+ useWindowTitle
1624
2130
  };
1625
2131
  //# sourceMappingURL=index.js.map