@sanity/sdk-react 2.7.0 → 3.0.0-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (88) hide show
  1. package/README.md +125 -63
  2. package/dist/index.d.ts +381 -571
  3. package/dist/index.js +450 -366
  4. package/dist/index.js.map +1 -1
  5. package/package.json +6 -8
  6. package/src/_exports/index.ts +4 -0
  7. package/src/_exports/sdk-react.ts +16 -0
  8. package/src/components/SDKProvider.test.tsx +23 -58
  9. package/src/components/SDKProvider.tsx +38 -30
  10. package/src/components/SanityApp.test.tsx +12 -68
  11. package/src/components/SanityApp.tsx +88 -65
  12. package/src/components/auth/AuthBoundary.test.tsx +11 -26
  13. package/src/components/auth/LoginError.test.tsx +5 -0
  14. package/src/components/auth/LoginError.tsx +23 -2
  15. package/src/config/handles.ts +53 -0
  16. package/src/context/ComlinkTokenRefresh.test.tsx +27 -10
  17. package/src/context/DefaultResourceContext.ts +10 -0
  18. package/src/context/PerspectiveContext.ts +12 -0
  19. package/src/context/ResourceProvider.test.tsx +99 -19
  20. package/src/context/ResourceProvider.tsx +103 -37
  21. package/src/context/ResourcesContext.tsx +7 -0
  22. package/src/context/SDKStudioContext.test.tsx +33 -28
  23. package/src/context/SDKStudioContext.ts +6 -0
  24. package/src/context/renderSanityApp.test.tsx +49 -151
  25. package/src/context/renderSanityApp.tsx +8 -12
  26. package/src/hooks/agent/agentActions.test.tsx +1 -1
  27. package/src/hooks/agent/agentActions.ts +56 -19
  28. package/src/hooks/auth/useDashboardOrganizationId.test.tsx +8 -2
  29. package/src/hooks/auth/useVerifyOrgProjects.test.tsx +32 -8
  30. package/src/hooks/client/useClient.test.tsx +4 -1
  31. package/src/hooks/client/useClient.ts +0 -1
  32. package/src/hooks/context/useDefaultResource.test.tsx +25 -0
  33. package/src/hooks/context/useDefaultResource.ts +30 -0
  34. package/src/hooks/context/useSanityInstance.test.tsx +2 -140
  35. package/src/hooks/context/useSanityInstance.ts +9 -53
  36. package/src/hooks/dashboard/useDispatchIntent.test.ts +24 -15
  37. package/src/hooks/dashboard/useDispatchIntent.ts +7 -7
  38. package/src/hooks/dashboard/useManageFavorite.test.tsx +34 -94
  39. package/src/hooks/dashboard/useManageFavorite.ts +16 -10
  40. package/src/hooks/dashboard/useNavigateToStudioDocument.test.ts +7 -5
  41. package/src/hooks/dashboard/useNavigateToStudioDocument.ts +6 -2
  42. package/src/hooks/dashboard/useRecordDocumentHistoryEvent.test.ts +2 -0
  43. package/src/hooks/dashboard/useRecordDocumentHistoryEvent.ts +2 -1
  44. package/src/hooks/dashboard/utils/useResourceIdFromDocumentHandle.test.ts +17 -38
  45. package/src/hooks/dashboard/utils/useResourceIdFromDocumentHandle.ts +12 -19
  46. package/src/hooks/datasets/useDatasets.test.ts +8 -22
  47. package/src/hooks/datasets/useDatasets.ts +8 -16
  48. package/src/hooks/document/useApplyDocumentActions.test.ts +98 -52
  49. package/src/hooks/document/useApplyDocumentActions.ts +35 -37
  50. package/src/hooks/document/useDocument.test.tsx +8 -37
  51. package/src/hooks/document/useDocument.ts +78 -129
  52. package/src/hooks/document/useDocumentEvent.test.tsx +7 -19
  53. package/src/hooks/document/useDocumentEvent.ts +21 -19
  54. package/src/hooks/document/useDocumentPermissions.test.tsx +75 -84
  55. package/src/hooks/document/useDocumentPermissions.ts +41 -28
  56. package/src/hooks/document/useDocumentSyncStatus.test.ts +13 -3
  57. package/src/hooks/document/useDocumentSyncStatus.ts +19 -14
  58. package/src/hooks/document/useEditDocument.test.tsx +28 -70
  59. package/src/hooks/document/useEditDocument.ts +29 -149
  60. package/src/hooks/documents/useDocuments.test.tsx +44 -64
  61. package/src/hooks/documents/useDocuments.ts +19 -25
  62. package/src/hooks/helpers/createCallbackHook.test.tsx +19 -13
  63. package/src/hooks/helpers/createStateSourceHook.test.tsx +10 -10
  64. package/src/hooks/helpers/createStateSourceHook.tsx +2 -4
  65. package/src/hooks/helpers/useNormalizedResourceOptions.test.ts +65 -0
  66. package/src/hooks/helpers/useNormalizedResourceOptions.ts +127 -0
  67. package/src/hooks/paginatedDocuments/usePaginatedDocuments.test.tsx +27 -34
  68. package/src/hooks/paginatedDocuments/usePaginatedDocuments.ts +19 -20
  69. package/src/hooks/presence/usePresence.test.tsx +71 -9
  70. package/src/hooks/presence/usePresence.ts +28 -3
  71. package/src/hooks/preview/useDocumentPreview.test.tsx +85 -193
  72. package/src/hooks/preview/useDocumentPreview.tsx +42 -62
  73. package/src/hooks/projection/useDocumentProjection.test.tsx +9 -37
  74. package/src/hooks/projection/useDocumentProjection.ts +9 -82
  75. package/src/hooks/projects/useProject.test.ts +1 -2
  76. package/src/hooks/projects/useProject.ts +7 -8
  77. package/src/hooks/query/useQuery.test.tsx +5 -6
  78. package/src/hooks/query/useQuery.ts +12 -91
  79. package/src/hooks/releases/useActiveReleases.test.tsx +2 -2
  80. package/src/hooks/releases/useActiveReleases.ts +25 -13
  81. package/src/hooks/releases/usePerspective.test.tsx +9 -17
  82. package/src/hooks/releases/usePerspective.ts +29 -18
  83. package/src/hooks/users/useUser.test.tsx +9 -3
  84. package/src/hooks/users/useUser.ts +1 -1
  85. package/src/hooks/users/useUsers.test.tsx +5 -2
  86. package/src/hooks/users/useUsers.ts +1 -1
  87. package/src/context/SourcesContext.tsx +0 -7
  88. package/src/hooks/helpers/useNormalizedSourceOptions.ts +0 -85
package/dist/index.js CHANGED
@@ -1,40 +1,29 @@
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, isProjectUserNotFoundClientError, getClientErrorApiDescription, getClientErrorApiBody, getCorsErrorProjectId, createSanityInstance, agentGenerate, agentTransform, agentTranslate, agentPrompt, agentPatch, getTokenState, getCurrentUserState, getDashboardOrganizationId, getClientState, getOrCreateController, getOrCreateChannel, releaseChannel, isDatasetSource, isMediaLibrarySource, isCanvasSource, getFavoritesState, resolveFavoritesState, resolveDatasets, getDatasetsState, applyDocumentActions, resolveDocument, getDocumentState, subscribeDocumentEvents, getPermissionsState, getDocumentSyncStatus, editDocument, getQueryKey, parseQueryKey, getQueryState, resolveQuery, createGroqSearchFilter, getPresence, getPreviewState, resolvePreview, getProjectionState, resolveProjection, 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, 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";
5
5
  export * from "@sanity/sdk";
6
6
  import { createContext, useContext, useSyncExternalStore, useRef, useEffect, useState, Suspense, StrictMode, useCallback, useMemo, useInsertionEffect, useTransition } from "react";
7
7
  import { ErrorBoundary } from "react-error-boundary";
8
8
  import { SDK_CHANNEL_NAME, SDK_NODE_NAME } from "@sanity/message-protocol";
9
- import { firstValueFrom, filter, identity, Observable, startWith, distinctUntilChanged, switchMap, EMPTY } from "rxjs";
9
+ import { firstValueFrom, filter, Observable, startWith, distinctUntilChanged, switchMap, EMPTY } from "rxjs";
10
10
  import { createRoot } from "react-dom/client";
11
11
  import { pick } from "lodash-es";
12
- const SanityInstanceContext = createContext(null), useSanityInstance = (config) => {
13
- const $ = c(3), instance = useContext(SanityInstanceContext);
12
+ const SanityInstanceContext = createContext(null), useSanityInstance = () => {
13
+ const instance = useContext(SanityInstanceContext);
14
14
  if (!instance)
15
- throw new Error(`SanityInstance context not found. ${config ? `Requested config: ${JSON.stringify(config, null, 2)}. ` : ""}Please ensure that your component is wrapped in a ResourceProvider or a SanityApp component.`);
16
- if (!config)
17
- return instance;
18
- let t0;
19
- $[0] !== config || $[1] !== instance ? (t0 = instance.match(config), $[0] = config, $[1] = instance, $[2] = t0) : t0 = $[2];
20
- const match = t0;
21
- if (!match)
22
- throw new Error(`Could not find a matching Sanity instance for the requested configuration: ${JSON.stringify(config, null, 2)}.
23
- Please ensure there is a ResourceProvider component with a matching configuration in the component hierarchy.`);
24
- return match;
15
+ throw new Error("SanityInstance context not found. Please ensure that your component is wrapped in a ResourceProvider or a SanityApp component.");
16
+ return instance;
25
17
  };
26
18
  function createStateSourceHook(options) {
27
- const getState = typeof options == "function" ? options : options.getState, getConfig = "getConfig" in options ? options.getConfig : void 0, suspense = "shouldSuspend" in options && "suspender" in options ? options : void 0;
19
+ const getState = typeof options == "function" ? options : options.getState, suspense = "shouldSuspend" in options && "suspender" in options ? options : void 0;
28
20
  function useHook(...t0) {
29
- const $ = c(5), params = t0;
30
- let t1;
31
- $[0] !== params ? (t1 = getConfig?.(...params), $[0] = params, $[1] = t1) : t1 = $[1];
32
- const instance = useSanityInstance(t1);
21
+ const $ = c(3), params = t0, instance = useSanityInstance();
33
22
  if (suspense?.suspender && suspense?.shouldSuspend?.(instance, ...params))
34
23
  throw suspense.suspender(instance, ...params);
35
- let t2;
36
- $[2] !== instance || $[3] !== params ? (t2 = getState(instance, ...params), $[2] = instance, $[3] = params, $[4] = t2) : t2 = $[4];
37
- const state = t2;
24
+ let t1;
25
+ $[0] !== instance || $[1] !== params ? (t1 = getState(instance, ...params), $[0] = instance, $[1] = params, $[2] = t1) : t1 = $[2];
26
+ const state = t1;
38
27
  return useSyncExternalStore(state.subscribe, state.getCurrent);
39
28
  }
40
29
  return useHook;
@@ -66,7 +55,7 @@ function useWindowConnection(t0) {
66
55
  const [type, handler] = t42, messageUnsubscribe = node.on(type, handler);
67
56
  messageUnsubscribe && messageUnsubscribers.current.push(messageUnsubscribe);
68
57
  }), () => {
69
- messageUnsubscribers.current.forEach(_temp$8), messageUnsubscribers.current = [];
58
+ messageUnsubscribers.current.forEach(_temp$6), messageUnsubscribers.current = [];
70
59
  }), $[4] = node, $[5] = onMessage, $[6] = t3) : t3 = $[6];
71
60
  let t4;
72
61
  $[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);
@@ -84,7 +73,7 @@ function useWindowConnection(t0) {
84
73
  fetch
85
74
  }, $[16] = fetch, $[17] = sendMessage, $[18] = t7) : t7 = $[18], t7;
86
75
  }
87
- function _temp$8(unsubscribe) {
76
+ function _temp$6(unsubscribe) {
88
77
  return unsubscribe();
89
78
  }
90
79
  const DEFAULT_RESPONSE_TIMEOUT = 1e4;
@@ -114,7 +103,7 @@ function DashboardTokenRefresh(t0) {
114
103
  if (clearRefreshTimeout(), res.token) {
115
104
  setAuthToken(instance, res.token);
116
105
  const errorContainer = document.getElementById("__sanityError");
117
- errorContainer && Array.from(errorContainer.getElementsByTagName("div")).some(_temp$7) && errorContainer.remove();
106
+ errorContainer && Array.from(errorContainer.getElementsByTagName("div")).some(_temp$5) && errorContainer.remove();
118
107
  }
119
108
  isTokenRefreshInProgress.current = !1;
120
109
  } catch {
@@ -135,7 +124,7 @@ function DashboardTokenRefresh(t0) {
135
124
  let t7;
136
125
  return $[11] !== authState || $[12] !== requestNewToken ? (t7 = [authState, requestNewToken], $[11] = authState, $[12] = requestNewToken, $[13] = t7) : t7 = $[13], useEffect(t6, t7), children;
137
126
  }
138
- function _temp$7(div) {
127
+ function _temp$5(div) {
139
128
  return div.textContent?.includes("Uncaught error: Unauthorized - A valid session is required for this endpoint");
140
129
  }
141
130
  const ComlinkTokenRefreshProvider = (t0) => {
@@ -290,33 +279,47 @@ function LoginCallback() {
290
279
  let t0, t1;
291
280
  return $[0] !== handleAuthCallback2 ? (t0 = () => {
292
281
  const url = new URL(location.href);
293
- handleAuthCallback2(url.toString()).then(_temp$6);
282
+ handleAuthCallback2(url.toString()).then(_temp$4);
294
283
  }, t1 = [handleAuthCallback2], $[0] = handleAuthCallback2, $[1] = t0, $[2] = t1) : (t0 = $[1], t1 = $[2]), useEffect(t0, t1), null;
295
284
  }
296
- function _temp$6(replacementLocation) {
285
+ function _temp$4(replacementLocation) {
297
286
  replacementLocation && history.replaceState(null, "", replacementLocation);
298
287
  }
299
- const useLogOut = createCallbackHook(logout);
288
+ const ResourceContext = createContext(void 0), useLogOut = createCallbackHook(logout);
300
289
  function LoginError(t0) {
301
- const $ = c(18), {
290
+ const $ = c(25), {
302
291
  error,
303
292
  resetErrorBoundary
304
293
  } = t0;
305
294
  if (!(error instanceof AuthError || error instanceof ConfigurationError || error instanceof ClientError))
306
295
  throw error;
307
- const logout2 = useLogOut(), authState = useAuthState(), [authErrorMessage, setAuthErrorMessage] = useState("Please try again or contact support if the problem persists."), [showRetryCta, setShowRetryCta] = useState(!0);
296
+ const logout2 = useLogOut(), authState = useAuthState(), resource = useContext(ResourceContext);
308
297
  let t1;
309
- $[0] !== logout2 || $[1] !== resetErrorBoundary ? (t1 = async () => {
310
- await logout2(), resetErrorBoundary();
311
- }, $[0] = logout2, $[1] = resetErrorBoundary, $[2] = t1) : t1 = $[2];
312
- const handleRetry = 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);
313
300
  let t2;
314
- $[3] !== authState.type || $[4] !== error || $[5] !== handleRetry ? (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);
308
+ 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;
313
+ let t4;
314
+ $[6] !== authState.type || $[7] !== error || $[8] !== fetch || $[9] !== handleRetry || $[10] !== projectId ? (t4 = () => {
315
315
  if (error instanceof ClientError) {
316
316
  if (error.statusCode === 401)
317
317
  if (isProjectUserNotFoundClientError(error)) {
318
318
  const description = getClientErrorApiDescription(error);
319
- description && setAuthErrorMessage(description), setShowRetryCta(!1);
319
+ description && setAuthErrorMessage(description), setShowRetryCta(!1), fetch("dashboard/v1/auth/access/request", {
320
+ resourceType: "project",
321
+ resourceId: projectId
322
+ });
320
323
  } else
321
324
  setShowRetryCta(!0), handleRetry();
322
325
  else if (error.statusCode === 404) {
@@ -325,17 +328,17 @@ function LoginError(t0) {
325
328
  }
326
329
  }
327
330
  authState.type !== AuthStateType.ERROR && error instanceof ConfigurationError && (setAuthErrorMessage(error.message), setShowRetryCta(!0));
328
- }, $[3] = authState.type, $[4] = error, $[5] = handleRetry, $[6] = t2) : t2 = $[6];
329
- let t3;
330
- $[7] !== authState || $[8] !== error || $[9] !== handleRetry ? (t3 = [authState, handleRetry, error], $[7] = authState, $[8] = error, $[9] = handleRetry, $[10] = t3) : t3 = $[10], useEffect(t2, t3);
331
- const t4 = error instanceof AuthError ? "Authentication Error" : "Configuration Error";
331
+ }, $[6] = authState.type, $[7] = error, $[8] = fetch, $[9] = handleRetry, $[10] = projectId, $[11] = t4) : t4 = $[11];
332
332
  let t5;
333
- $[11] !== handleRetry || $[12] !== showRetryCta ? (t5 = showRetryCta ? {
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 ? {
334
337
  text: "Retry",
335
338
  onClick: handleRetry
336
- } : void 0, $[11] = handleRetry, $[12] = showRetryCta, $[13] = t5) : t5 = $[13];
337
- let t6;
338
- return $[14] !== authErrorMessage || $[15] !== t4 || $[16] !== t5 ? (t6 = /* @__PURE__ */ jsx(Error$1, { heading: t4, description: authErrorMessage, cta: t5 }), $[14] = authErrorMessage, $[15] = t4, $[16] = t5, $[17] = t6) : t6 = $[17], t6;
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;
339
342
  }
340
343
  if (isInIframe() && !document.querySelector("[data-sanity-core]")) {
341
344
  const parsedUrl = new URL(window.location.href), mode = new URLSearchParams(parsedUrl.hash.slice(1)).get("mode"), script = document.createElement("script");
@@ -397,132 +400,269 @@ function AuthSwitch(t0) {
397
400
  }
398
401
  const SDKStudioContext = createContext(null);
399
402
  SDKStudioContext.displayName = "SDKStudioContext";
400
- const DEFAULT_FALLBACK = /* @__PURE__ */ jsx(Fragment, { children: "Warning: No fallback provided. Please supply a fallback prop to ensure proper Suspense handling." });
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." });
401
404
  function ResourceProvider(t0) {
402
- const $ = c(16);
403
- let children, config, fallback;
405
+ const $ = c(19);
406
+ let children, fallback, resource, rest;
404
407
  $[0] !== t0 ? ({
405
408
  children,
406
409
  fallback,
407
- ...config
408
- } = t0, $[0] = t0, $[1] = children, $[2] = config, $[3] = fallback) : (children = $[1], config = $[2], fallback = $[3]);
409
- const parent = useContext(SanityInstanceContext);
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) {
426
+ 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;
428
+ }
429
+ 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;
431
+ }
432
+ function RootResourceProvider(t0) {
433
+ const $ = c(17), {
434
+ children,
435
+ fallback,
436
+ config,
437
+ resource
438
+ } = t0;
410
439
  let t1, t2;
411
- $[4] !== config || $[5] !== parent ? (t2 = parent ? parent.createChild(config) : createSanityInstance(config), $[4] = config, $[5] = parent, $[6] = t2) : t2 = $[6], t1 = t2;
440
+ $[0] !== config ? (t2 = createSanityInstance(config), $[0] = config, $[1] = t2) : t2 = $[1], t1 = t2;
412
441
  const instance = t1, disposal = useRef(null);
413
442
  let t3, t4;
414
- $[7] !== instance ? (t3 = () => (disposal.current !== null && instance === disposal.current.instance && (clearTimeout(disposal.current.timeoutId), disposal.current = null), () => {
443
+ $[2] !== instance ? (t3 = () => (disposal.current !== null && instance === disposal.current.instance && (clearTimeout(disposal.current.timeoutId), disposal.current = null), () => {
415
444
  disposal.current = {
416
445
  instance,
417
446
  timeoutId: setTimeout(() => {
418
447
  instance.isDisposed() || instance.dispose();
419
448
  }, 0)
420
449
  };
421
- }), t4 = [instance], $[7] = instance, $[8] = t3, $[9] = t4) : (t3 = $[8], t4 = $[9]), useEffect(t3, t4);
450
+ }), t4 = [instance], $[2] = instance, $[3] = t3, $[4] = t4) : (t3 = $[3], t4 = $[4]), useEffect(t3, t4);
422
451
  const t5 = fallback ?? DEFAULT_FALLBACK;
423
452
  let t6;
424
- $[10] !== children || $[11] !== t5 ? (t6 = /* @__PURE__ */ jsx(Suspense, { fallback: t5, children }), $[10] = children, $[11] = t5, $[12] = t6) : t6 = $[12];
453
+ $[5] !== children || $[6] !== t5 ? (t6 = /* @__PURE__ */ jsx(Suspense, { fallback: t5, children }), $[5] = children, $[6] = t5, $[7] = t6) : t6 = $[7];
425
454
  let t7;
426
- return $[13] !== instance || $[14] !== t6 ? (t7 = /* @__PURE__ */ jsx(SanityInstanceContext.Provider, { value: instance, children: t6 }), $[13] = instance, $[14] = t6, $[15] = t7) : t7 = $[15], 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;
460
+ }
461
+ function NestedResourceProvider(t0) {
462
+ const $ = c(9), {
463
+ children,
464
+ fallback,
465
+ resource,
466
+ perspective
467
+ } = t0, parentResource = useContext(ResourceContext), parentPerspective = useContext(PerspectiveContext), resolvedResource = resource ?? parentResource, resolvedPerspective = perspective ?? parentPerspective, t1 = fallback ?? DEFAULT_FALLBACK;
468
+ let t2;
469
+ $[0] !== children || $[1] !== t1 ? (t2 = /* @__PURE__ */ jsx(Suspense, { fallback: t1, children }), $[0] = children, $[1] = t1, $[2] = t2) : t2 = $[2];
470
+ let t3;
471
+ $[3] !== resolvedPerspective || $[4] !== t2 ? (t3 = /* @__PURE__ */ jsx(PerspectiveContext.Provider, { value: resolvedPerspective, children: t2 }), $[3] = resolvedPerspective, $[4] = t2, $[5] = t3) : t3 = $[5];
472
+ 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;
474
+ }
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];
427
481
  }
428
- const SourcesContext = createContext({});
429
482
  function SDKProvider(t0) {
430
- const $ = c(19);
431
- let children, config, fallback, props;
483
+ const $ = c(22);
484
+ let children, config, fallback, props, t1;
432
485
  $[0] !== t0 ? ({
433
486
  children,
434
487
  config,
488
+ resources: t1,
435
489
  fallback,
436
490
  ...props
437
- } = t0, $[0] = t0, $[1] = children, $[2] = config, $[3] = fallback, $[4] = props) : (children = $[1], config = $[2], fallback = $[3], props = $[4]);
438
- let t1;
439
- $[5] !== config ? (t1 = Array.isArray(config) ? config : [config], $[5] = config, $[6] = t1) : t1 = $[6];
440
- let configs, t2;
441
- $[7] !== t1 ? (configs = t1.slice().reverse(), t2 = configs.map(_temp$5).filter(_temp2$1), $[7] = t1, $[8] = configs, $[9] = t2) : (configs = $[8], t2 = $[9]);
442
- const projectIds = t2;
491
+ } = t0, $[0] = t0, $[1] = children, $[2] = config, $[3] = fallback, $[4] = props, $[5] = t1) : (children = $[1], config = $[2], fallback = $[3], props = $[4], t1 = $[5]);
492
+ let t2;
493
+ $[6] !== t1 ? (t2 = t1 === void 0 ? {} : t1, $[6] = t1, $[7] = t2) : t2 = $[7];
494
+ const resources = t2;
443
495
  let t3, t4;
444
- $[10] !== props.sources ? (t4 = props.sources ?? {}, $[10] = props.sources, $[11] = t4) : t4 = $[11], t3 = t4;
445
- const sourcesValue = t3;
496
+ $[8] !== resources ? (t4 = collectProjectIds(resources), $[8] = resources, $[9] = t4) : t4 = $[9], t3 = t4;
497
+ const projectIds = t3;
446
498
  let t5;
447
- if ($[12] !== children || $[13] !== configs || $[14] !== fallback || $[15] !== projectIds || $[16] !== props || $[17] !== sourcesValue) {
448
- const createNestedProviders = (index) => index >= configs.length ? /* @__PURE__ */ jsx(AuthBoundary, { ...props, projectIds, children: /* @__PURE__ */ jsx(SourcesContext.Provider, { value: sourcesValue, children }) }) : /* @__PURE__ */ jsx(ResourceProvider, { ...configs[index], fallback, children: createNestedProviders(index + 1) });
449
- t5 = createNestedProviders(0), $[12] = children, $[13] = configs, $[14] = fallback, $[15] = projectIds, $[16] = props, $[17] = sourcesValue, $[18] = t5;
450
- } else
451
- t5 = $[18];
452
- return t5;
453
- }
454
- function _temp2$1(id) {
455
- return !!id;
456
- }
457
- function _temp$5(c2) {
458
- return c2.projectId;
499
+ t5 = resources[DEFAULT_RESOURCE_NAME];
500
+ const rootResource = t5;
501
+ let t6;
502
+ $[10] !== children || $[11] !== resources ? (t6 = /* @__PURE__ */ jsx(ResourcesContext.Provider, { value: resources, children }), $[10] = children, $[11] = resources, $[12] = t6) : t6 = $[12];
503
+ 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;
459
507
  }
460
508
  const REDIRECT_URL = "https://sanity.io/welcome";
461
- function deriveConfigFromWorkspace(workspace) {
509
+ function deriveFromWorkspace(workspace) {
462
510
  return {
463
- projectId: workspace.projectId,
464
- dataset: workspace.dataset,
465
- studio: {
466
- auth: workspace.auth.token ? {
467
- token: workspace.auth.token
468
- } : void 0
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
+ }
469
525
  }
470
526
  };
471
527
  }
472
528
  function SanityApp(t0) {
473
- const $ = c(18);
474
- let children, configProp, fallback, props;
529
+ const $ = c(21);
530
+ let children, configProp, fallback, props, resourcesProp;
475
531
  $[0] !== t0 ? ({
476
532
  children,
477
533
  fallback,
478
534
  config: configProp,
535
+ resources: resourcesProp,
479
536
  ...props
480
- } = t0, $[0] = t0, $[1] = children, $[2] = configProp, $[3] = fallback, $[4] = props) : (children = $[1], configProp = $[2], fallback = $[3], props = $[4]);
537
+ } = t0, $[0] = t0, $[1] = children, $[2] = configProp, $[3] = fallback, $[4] = props, $[5] = resourcesProp) : (children = $[1], configProp = $[2], fallback = $[3], props = $[4], resourcesProp = $[5]);
481
538
  const studioWorkspace = useContext(SDKStudioContext);
482
539
  let t1;
483
540
  bb0: {
484
- if (configProp) {
485
- t1 = configProp;
541
+ if (studioWorkspace && !configProp && !resourcesProp) {
542
+ let t22;
543
+ $[6] !== studioWorkspace ? (t22 = deriveFromWorkspace(studioWorkspace), $[6] = studioWorkspace, $[7] = t22) : t22 = $[7], t1 = t22;
486
544
  break bb0;
487
545
  }
488
- if (studioWorkspace) {
489
- let t23;
490
- $[5] !== studioWorkspace ? (t23 = deriveConfigFromWorkspace(studioWorkspace), $[5] = studioWorkspace, $[6] = t23) : t23 = $[6], t1 = t23;
491
- break bb0;
546
+ t1 = null;
547
+ }
548
+ const derived = t1;
549
+ let t2;
550
+ bb1: {
551
+ if (configProp) {
552
+ t2 = configProp;
553
+ break bb1;
554
+ }
555
+ if (derived) {
556
+ t2 = derived.config;
557
+ break bb1;
492
558
  }
493
- let t22;
494
- $[7] === Symbol.for("react.memo_cache_sentinel") ? (t22 = [], $[7] = t22) : t22 = $[7], t1 = t22;
559
+ let t32;
560
+ $[8] === Symbol.for("react.memo_cache_sentinel") ? (t32 = {}, $[8] = t32) : t32 = $[8], t2 = t32;
495
561
  }
496
- const resolvedConfig = t1;
497
- let t2, t3;
498
- $[8] !== configProp || $[9] !== resolvedConfig || $[10] !== studioWorkspace ? (t2 = () => {
562
+ const resolvedConfig = t2;
563
+ let t3;
564
+ bb2: {
565
+ if (resourcesProp) {
566
+ t3 = resourcesProp;
567
+ break bb2;
568
+ }
569
+ if (derived) {
570
+ t3 = derived.resources;
571
+ break bb2;
572
+ }
573
+ let t42;
574
+ $[9] === Symbol.for("react.memo_cache_sentinel") ? (t42 = {}, $[9] = t42) : t42 = $[9], t3 = t42;
575
+ }
576
+ const resolvedResources = t3;
577
+ let t4, t5;
578
+ $[10] !== configProp || $[11] !== resolvedConfig || $[12] !== studioWorkspace ? (t4 = () => {
499
579
  let timeout;
500
- const primaryConfig = Array.isArray(resolvedConfig) ? resolvedConfig[0] : resolvedConfig, shouldRedirectWithoutConfig = configProp === void 0 && !studioWorkspace && !primaryConfig;
501
- return !isInIframe() && !isLocalUrl(window) && (shouldRedirectWithoutConfig || primaryConfig && !isStudioConfig(primaryConfig)) && (timeout = setTimeout(_temp$4, 1e3)), () => clearTimeout(timeout);
502
- }, t3 = [configProp, resolvedConfig, studioWorkspace], $[8] = configProp, $[9] = resolvedConfig, $[10] = studioWorkspace, $[11] = t2, $[12] = t3) : (t2 = $[11], t3 = $[12]), useEffect(t2, t3);
503
- let t4;
504
- 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;
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;
505
585
  }
506
- function _temp$4() {
586
+ function _temp$3() {
507
587
  console.warn("Redirecting to core", REDIRECT_URL), window.location.replace(REDIRECT_URL);
508
588
  }
509
- function renderSanityApp(rootElement, namedSources, options, children) {
589
+ function renderSanityApp(rootElement, namedResources, options, children) {
510
590
  if (!rootElement)
511
591
  throw new Error("Missing root element to mount application into");
512
592
  const {
513
593
  reactStrictMode = !1
514
- } = options, root = createRoot(rootElement), config = Object.values(namedSources);
515
- 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();
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();
596
+ }
597
+ function normalizeResourceOptions(options, resources, contextResource, contextPerspective) {
598
+ const {
599
+ resourceName,
600
+ ...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];
609
+ }
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>).");
612
+ const resolvedPerspective = Object.hasOwn(options, "perspective") ? options.perspective : contextPerspective;
613
+ return {
614
+ ...rest,
615
+ resource: resolvedResource,
616
+ ...resolvedPerspective !== void 0 && {
617
+ perspective: resolvedPerspective
618
+ }
619
+ };
620
+ }
621
+ function useNormalizedResourceOptions(options) {
622
+ const $ = c(5), resources = useContext(ResourcesContext), contextResource = useContext(ResourceContext), contextPerspective = useContext(PerspectiveContext);
623
+ 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;
625
+ }
626
+ function useAgentCallback(action) {
627
+ const $ = c(5), instance = useSanityInstance(), resources = useContext(ResourcesContext), contextResource = useContext(ResourceContext);
628
+ 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);
650
+ }
651
+ function useAgentTranslate() {
652
+ return useAgentCallback(agentTranslate);
516
653
  }
517
- const useAgentGenerate = createCallbackHook(agentGenerate), useAgentTransform = createCallbackHook(agentTransform), useAgentTranslate = createCallbackHook(agentTranslate);
518
654
  function promptAdapter(instance, options) {
519
655
  return firstValueFrom(agentPrompt(instance, options));
520
656
  }
521
- const useAgentPrompt = createCallbackHook(promptAdapter);
657
+ function useAgentPrompt() {
658
+ return useAgentCallback(promptAdapter);
659
+ }
522
660
  function patchAdapter(instance, options) {
523
661
  return firstValueFrom(agentPatch(instance, options));
524
662
  }
525
- const useAgentPatch = createCallbackHook(patchAdapter);
663
+ function useAgentPatch() {
664
+ return useAgentCallback(patchAdapter);
665
+ }
526
666
  function useAgentResourceContext(options) {
527
667
  const $ = c(9), {
528
668
  projectId,
@@ -584,8 +724,7 @@ const useClient = createStateSourceHook({
584
724
  if (!options || typeof options != "object")
585
725
  throw new Error('useClient() requires a configuration object with at least an "apiVersion" property. Example: useClient({ apiVersion: "2024-11-12" })');
586
726
  return getClientState(instance, options);
587
- },
588
- getConfig: (options) => options
727
+ }
589
728
  });
590
729
  function useFrameConnection(options) {
591
730
  const $ = c(12), {
@@ -611,7 +750,7 @@ function useFrameConnection(options) {
611
750
  const [type, handler] = t22, unsubscribe = channel.on(type, handler);
612
751
  messageUnsubscribers.push(unsubscribe);
613
752
  }), () => {
614
- messageUnsubscribers.forEach(_temp$3), releaseChannel(instance, name), channelRef.current = null, controllerRef.current = null;
753
+ messageUnsubscribers.forEach(_temp$2), releaseChannel(instance, name), channelRef.current = null, controllerRef.current = null;
615
754
  };
616
755
  }, 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);
617
756
  let t2;
@@ -633,9 +772,12 @@ function useFrameConnection(options) {
633
772
  sendMessage
634
773
  }, $[11] = t4) : t4 = $[11], t4;
635
774
  }
636
- function _temp$3(unsub) {
775
+ function _temp$2(unsub) {
637
776
  return unsub();
638
777
  }
778
+ function useResource() {
779
+ return useContext(ResourceContext);
780
+ }
639
781
  function useDashboardNavigate(navigateFn) {
640
782
  const $ = c(2);
641
783
  let t0;
@@ -649,33 +791,12 @@ function useDashboardNavigate(navigateFn) {
649
791
  }
650
792
  }, $[0] = navigateFn, $[1] = t0) : t0 = $[1], useWindowConnection(t0);
651
793
  }
652
- function useNormalizedSourceOptions(options) {
653
- const $ = c(6);
654
- let rest, sourceName;
655
- if ($[0] !== options ? ({
656
- sourceName,
657
- ...rest
658
- } = options, $[0] = options, $[1] = rest, $[2] = sourceName) : (rest = $[1], sourceName = $[2]), sourceName && Object.hasOwn(options, "source"))
659
- throw new Error(`Source name ${JSON.stringify(sourceName)} and source ${JSON.stringify(options.source)} cannot be used together.`);
660
- const sources = useContext(SourcesContext);
661
- let resolvedSource;
662
- if (options.source && (resolvedSource = options.source), sourceName && !Object.hasOwn(sources, sourceName))
663
- throw new Error(`There's no source named ${JSON.stringify(sourceName)} in context. Please use <SourceProvider>.`);
664
- sourceName && sources[sourceName] && (resolvedSource = sources[sourceName]);
665
- let t0;
666
- return $[3] !== resolvedSource || $[4] !== rest ? (t0 = {
667
- ...rest,
668
- source: resolvedSource
669
- }, $[3] = resolvedSource, $[4] = rest, $[5] = t0) : t0 = $[5], t0;
670
- }
671
794
  function useResourceIdFromDocumentHandle(documentHandle) {
672
- const $ = c(3), options = useNormalizedSourceOptions(documentHandle), {
673
- projectId,
674
- dataset,
675
- source
795
+ const $ = c(3), options = useNormalizedResourceOptions(documentHandle), {
796
+ resource
676
797
  } = options;
677
798
  let resourceId = "", resourceType;
678
- projectId && dataset && (resourceId = `${projectId}.${dataset}`), source && (isDatasetSource(source) ? (resourceId = `${source.projectId}.${source.dataset}`, resourceType = void 0) : isMediaLibrarySource(source) ? (resourceId = source.mediaLibraryId, resourceType = "media-library") : isCanvasSource(source) && (resourceId = source.canvasId, resourceType = "canvas"));
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"));
679
800
  let t0;
680
801
  return $[0] !== resourceId || $[1] !== resourceType ? (t0 = {
681
802
  id: resourceId,
@@ -700,7 +821,7 @@ function useDispatchIntent(params) {
700
821
  if (!action && !intentId)
701
822
  throw new Error("useDispatchIntent: Either `action` or `intentId` must be provided.");
702
823
  if (action && intentId && console.warn("useDispatchIntent: Both `action` and `intentId` were provided. Using `intentId` and ignoring `action`."), !resource.id)
703
- throw new Error("useDispatchIntent: Unable to determine resource. Either `source`, `sourceName`, or both `projectId` and `dataset` must be provided in documentHandle.");
824
+ throw new Error("useDispatchIntent: Unable to determine resource. Either `resource`, `resourceName`, or both `projectId` and `dataset` must be provided in documentHandle.");
704
825
  const message = {
705
826
  type: "dashboard/v1/events/intents/dispatch-intent",
706
827
  data: {
@@ -735,8 +856,7 @@ function useDispatchIntent(params) {
735
856
  function useManageFavorite({
736
857
  documentId,
737
858
  documentType,
738
- projectId: paramProjectId,
739
- dataset: paramDataset,
859
+ resource: paramResource,
740
860
  resourceId: paramResourceId,
741
861
  resourceType,
742
862
  schemaName
@@ -746,21 +866,22 @@ function useManageFavorite({
746
866
  } = useWindowConnection({
747
867
  name: SDK_NODE_NAME,
748
868
  connectTo: SDK_CHANNEL_NAME
749
- }), instance = useSanityInstance(), {
750
- config
751
- } = instance, instanceProjectId = config?.projectId, instanceDataset = config?.dataset, projectId = paramProjectId ?? instanceProjectId, dataset = paramDataset ?? instanceDataset;
869
+ }), instance = useSanityInstance(), contextResource = useContext(ResourceContext), resource = paramResource ?? contextResource, datasetResource = resource && isDatasetResource(resource) ? resource : void 0, projectId = datasetResource?.projectId, dataset = datasetResource?.dataset;
752
870
  if (resourceType === "studio" && (!projectId || !dataset))
753
871
  throw new Error("projectId and dataset are required for studio resources");
754
872
  const resourceId = resourceType === "studio" && !paramResourceId ? `${projectId}.${dataset}` : paramResourceId;
755
873
  if (!resourceId)
756
874
  throw new Error("resourceId is required for media-library and canvas resources");
875
+ if (!resource)
876
+ throw new Error("resource is required");
757
877
  const context = useMemo(() => ({
758
878
  documentId,
759
879
  documentType,
880
+ resource,
760
881
  resourceId,
761
882
  resourceType,
762
883
  schemaName
763
- }), [documentId, documentType, resourceId, resourceType, schemaName]), favoriteState = getFavoritesState(instance, context), isFavorited = useSyncExternalStore(favoriteState.subscribe, favoriteState.getCurrent)?.isFavorited ?? !1, handleFavoriteAction = useCallback(async (action) => {
884
+ }), [documentId, documentType, resource, resourceId, resourceType, schemaName]), favoriteState = getFavoritesState(instance, context), isFavorited = useSyncExternalStore(favoriteState.subscribe, favoriteState.getCurrent)?.isFavorited ?? !1, handleFavoriteAction = useCallback(async (action) => {
764
885
  if (!(!fetch || !documentId || !documentType || !resourceType))
765
886
  try {
766
887
  const payload = {
@@ -854,9 +975,8 @@ function useNavigateToStudioDocument(documentHandle, preferredStudioUrl) {
854
975
  let t1;
855
976
  $[1] !== documentHandle || $[2] !== preferredStudioUrl || $[3] !== sendMessage || $[4] !== workspacesByProjectIdAndDataset ? (t1 = () => {
856
977
  const {
857
- projectId,
858
- dataset
859
- } = documentHandle;
978
+ resource
979
+ } = documentHandle, datasetResource = resource && isDatasetResource(resource) ? resource : void 0, projectId = datasetResource?.projectId, dataset = datasetResource?.dataset;
860
980
  if (!projectId || !dataset) {
861
981
  console.warn("Project ID and dataset are required to navigate to a studio document");
862
982
  return;
@@ -938,46 +1058,27 @@ function useRecordDocumentHistoryEvent(t0) {
938
1058
  }
939
1059
  const useDatasets = createStateSourceHook({
940
1060
  getState: getDatasetsState,
941
- shouldSuspend: (instance, projectHandle) => (
942
- // remove `undefined` since we're suspending when that is the case
943
- getDatasetsState(instance, projectHandle).getCurrent() === void 0
944
- ),
945
- suspender: resolveDatasets,
946
- getConfig: identity
1061
+ shouldSuspend: (instance, options) => getDatasetsState(instance, options).getCurrent() === void 0,
1062
+ suspender: resolveDatasets
947
1063
  }), useApplyDocumentActions = () => {
948
- const $ = c(2), instance = useSanityInstance();
1064
+ const $ = c(4), instance = useSanityInstance(), resources = useContext(ResourcesContext), contextResource = useContext(ResourceContext);
949
1065
  let t0;
950
- return $[0] !== instance ? (t0 = (actionOrActions, options) => {
951
- const actions = Array.isArray(actionOrActions) ? actionOrActions : [actionOrActions];
952
- let projectId, dataset;
953
- for (const action of actions)
954
- if (action.projectId) {
955
- if (projectId || (projectId = action.projectId), action.projectId !== projectId)
956
- throw new Error(`Mismatched project IDs found in actions. All actions must belong to the same project. Found "${action.projectId}" but expected "${projectId}".`);
957
- if (action.dataset && (dataset || (dataset = action.dataset), action.dataset !== dataset))
958
- throw new Error(`Mismatched datasets found in actions. All actions must belong to the same dataset. Found "${action.dataset}" but expected "${dataset}".`);
959
- }
960
- if (projectId || dataset) {
961
- const actualInstance = instance.match({
962
- projectId,
963
- dataset
964
- });
965
- if (!actualInstance)
966
- throw new Error(`Could not find a matching Sanity instance for the requested action: ${JSON.stringify({
967
- projectId,
968
- dataset
969
- }, null, 2)}.
970
- Please ensure there is a ResourceProvider component with a matching configuration in the component hierarchy.`);
971
- return applyDocumentActions(actualInstance, {
972
- actions,
973
- ...options
974
- });
975
- }
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));
1068
+ 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)
1073
+ 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;
1075
+ if (!effectiveResource)
1076
+ throw new Error("No resource found. Provide a resource via the action handle or context.");
976
1077
  return applyDocumentActions(instance, {
977
1078
  actions,
978
- ...options
1079
+ resource: effectiveResource
979
1080
  });
980
- }, $[0] = instance, $[1] = t0) : t0 = $[1], t0;
1081
+ }, $[0] = contextResource, $[1] = instance, $[2] = resources, $[3] = t0) : t0 = $[3], t0;
981
1082
  }, useDocumentValue = createStateSourceHook({
982
1083
  // Pass options directly to getDocumentState
983
1084
  getState: (instance, options) => getDocumentState(instance, options),
@@ -987,8 +1088,7 @@ const useDatasets = createStateSourceHook({
987
1088
  ...options
988
1089
  }) => getDocumentState(instance, options).getCurrent() === void 0,
989
1090
  // Extract handle part for resolveDocument
990
- suspender: (instance, options) => resolveDocument(instance, options),
991
- getConfig: identity
1091
+ suspender: (instance, options) => resolveDocument(instance, options)
992
1092
  }), wrapHookWithData = (useValue) => {
993
1093
  function useHook(...params) {
994
1094
  return {
@@ -996,14 +1096,17 @@ const useDatasets = createStateSourceHook({
996
1096
  };
997
1097
  }
998
1098
  return useHook;
999
- }, useDocument = wrapHookWithData(useDocumentValue);
1099
+ }, useDocument = wrapHookWithData((options) => {
1100
+ const normalizedOptions = useNormalizedResourceOptions(options);
1101
+ return useDocumentValue(normalizedOptions);
1102
+ });
1000
1103
  function useDocumentEvent(options) {
1001
- const $ = c(9);
1104
+ const $ = c(10), normalizedOptions = useNormalizedResourceOptions(options);
1002
1105
  let datasetHandle, onEvent;
1003
- $[0] !== options ? ({
1106
+ $[0] !== normalizedOptions ? ({
1004
1107
  onEvent,
1005
1108
  ...datasetHandle
1006
- } = options, $[0] = options, $[1] = datasetHandle, $[2] = onEvent) : (datasetHandle = $[1], onEvent = $[2]);
1109
+ } = normalizedOptions, $[0] = normalizedOptions, $[1] = datasetHandle, $[2] = onEvent) : (datasetHandle = $[1], onEvent = $[2]);
1007
1110
  const ref = useRef(onEvent);
1008
1111
  let t0;
1009
1112
  $[3] !== onEvent ? (t0 = () => {
@@ -1011,58 +1114,42 @@ function useDocumentEvent(options) {
1011
1114
  }, $[3] = onEvent, $[4] = t0) : t0 = $[4], useInsertionEffect(t0);
1012
1115
  let t1;
1013
1116
  $[5] === Symbol.for("react.memo_cache_sentinel") ? (t1 = (documentEvent) => ref.current(documentEvent), $[5] = t1) : t1 = $[5];
1014
- const stableHandler = t1, instance = useSanityInstance(datasetHandle);
1117
+ const stableHandler = t1, instance = useSanityInstance();
1015
1118
  let t2, t3;
1016
- $[6] !== instance ? (t2 = () => subscribeDocumentEvents(instance, stableHandler), t3 = [instance, stableHandler], $[6] = instance, $[7] = t2, $[8] = t3) : (t2 = $[7], t3 = $[8]), useEffect(t2, t3);
1119
+ $[6] !== datasetHandle.resource || $[7] !== instance ? (t2 = () => subscribeDocumentEvents(instance, {
1120
+ eventHandler: stableHandler,
1121
+ resource: datasetHandle.resource
1122
+ }), t3 = [instance, datasetHandle.resource, stableHandler], $[6] = datasetHandle.resource, $[7] = instance, $[8] = t2, $[9] = t3) : (t2 = $[8], t3 = $[9]), useEffect(t2, t3);
1017
1123
  }
1018
1124
  function useDocumentPermissions(actionOrActions) {
1019
- const $ = c(13);
1020
- let t0, t1;
1021
- $[0] !== actionOrActions ? (t1 = Array.isArray(actionOrActions) ? actionOrActions : [actionOrActions], $[0] = actionOrActions, $[1] = t1) : t1 = $[1], t0 = t1;
1022
- const actions = t0;
1023
- let projectId, dataset;
1024
- if ($[2] !== actions || $[3] !== dataset || $[4] !== projectId) {
1025
- for (const action of actions)
1026
- if (action.projectId) {
1027
- if (projectId || (projectId = action.projectId), action.projectId !== projectId)
1028
- throw new Error(`Mismatched project IDs found in actions. All actions must belong to the same project. Found "${action.projectId}" but expected "${projectId}".`);
1029
- if (action.dataset && (dataset || (dataset = action.dataset), action.dataset !== dataset))
1030
- throw new Error(`Mismatched datasets found in actions. All actions must belong to the same dataset. Found "${action.dataset}" but expected "${dataset}".`);
1031
- }
1032
- $[2] = actions, $[3] = dataset, $[4] = projectId, $[5] = projectId, $[6] = dataset;
1033
- } else
1034
- projectId = $[5], dataset = $[6];
1035
- let t2;
1036
- $[7] !== dataset || $[8] !== projectId ? (t2 = {
1037
- projectId,
1038
- dataset
1039
- }, $[7] = dataset, $[8] = projectId, $[9] = t2) : t2 = $[9];
1040
- const instance = useSanityInstance(t2);
1041
- if (getPermissionsState(instance, {
1042
- actions
1043
- }).getCurrent() === void 0)
1044
- throw firstValueFrom(getPermissionsState(instance, {
1045
- actions
1046
- }).observable.pipe(filter(_temp$2)));
1047
- let t3, t4;
1048
- $[10] !== actions || $[11] !== instance ? (t4 = getPermissionsState(instance, {
1049
- actions
1050
- }), $[10] = actions, $[11] = instance, $[12] = t4) : t4 = $[12], t3 = t4;
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(() => ({
1134
+ resource: effectiveResource,
1135
+ 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)));
1051
1139
  const {
1052
1140
  subscribe,
1053
1141
  getCurrent
1054
- } = t3;
1142
+ } = useMemo(() => getPermissionsState(instance, permissionsOptions), [permissionsOptions, instance]);
1055
1143
  return useSyncExternalStore(subscribe, getCurrent);
1056
1144
  }
1057
- function _temp$2(result) {
1058
- return result !== void 0;
1059
- }
1060
- const useDocumentSyncStatus = createStateSourceHook({
1145
+ const useDocumentSyncStatusValue = createStateSourceHook({
1061
1146
  getState: getDocumentSyncStatus,
1062
1147
  shouldSuspend: (instance, doc) => getDocumentSyncStatus(instance, doc).getCurrent() === void 0,
1063
- suspender: (instance, doc) => resolveDocument(instance, doc),
1064
- getConfig: identity
1065
- }), ignoredKeys = ["_id", "_type", "_createdAt", "_updatedAt", "_rev"];
1148
+ suspender: (instance, doc) => resolveDocument(instance, doc)
1149
+ }), useDocumentSyncStatus = (options) => {
1150
+ const normalizedOptions = useNormalizedResourceOptions(options);
1151
+ return useDocumentSyncStatusValue(normalizedOptions);
1152
+ }, ignoredKeys = ["_id", "_type", "_createdAt", "_updatedAt", "_rev"];
1066
1153
  function useEditDocument(t0) {
1067
1154
  const $ = c(8);
1068
1155
  let doc, path;
@@ -1070,25 +1157,25 @@ function useEditDocument(t0) {
1070
1157
  path,
1071
1158
  ...doc
1072
1159
  } = t0, $[0] = t0, $[1] = doc, $[2] = path) : (doc = $[1], path = $[2]);
1073
- const instance = useSanityInstance(doc), apply = useApplyDocumentActions();
1074
- if (getDocumentState(instance, doc).getCurrent() === void 0)
1075
- throw resolveDocument(instance, doc);
1160
+ const instance = useSanityInstance(), normalizedDoc = useNormalizedResourceOptions(doc), apply = useApplyDocumentActions();
1161
+ if (getDocumentState(instance, normalizedDoc).getCurrent() === void 0)
1162
+ throw resolveDocument(instance, normalizedDoc);
1076
1163
  let t1;
1077
- return $[3] !== apply || $[4] !== doc || $[5] !== instance || $[6] !== path ? (t1 = (updater) => {
1164
+ return $[3] !== apply || $[4] !== instance || $[5] !== normalizedDoc || $[6] !== path ? (t1 = (updater) => {
1078
1165
  const currentPath = path;
1079
1166
  if (currentPath) {
1080
1167
  const currentValue = getDocumentState(instance, {
1081
- ...doc,
1168
+ ...normalizedDoc,
1082
1169
  path
1083
1170
  }).getCurrent(), nextValue = typeof updater == "function" ? updater(currentValue) : updater;
1084
- return apply(editDocument(doc, {
1171
+ return apply(editDocument(normalizedDoc, {
1085
1172
  set: {
1086
1173
  [currentPath]: nextValue
1087
1174
  }
1088
1175
  }));
1089
1176
  }
1090
1177
  const current = getDocumentState(instance, {
1091
- ...doc,
1178
+ ...normalizedDoc,
1092
1179
  path
1093
1180
  }).getCurrent(), nextValue_0 = typeof updater == "function" ? updater(current) : updater;
1094
1181
  if (typeof nextValue_0 != "object" || !nextValue_0)
@@ -1096,21 +1183,21 @@ function useEditDocument(t0) {
1096
1183
  const editActions = Object.keys({
1097
1184
  ...current,
1098
1185
  ...nextValue_0
1099
- }).filter(_temp$1).filter((key_0) => current?.[key_0] !== nextValue_0[key_0]).map((key_1) => key_1 in nextValue_0 ? editDocument(doc, {
1186
+ }).filter(_temp$1).filter((key_0) => current?.[key_0] !== nextValue_0[key_0]).map((key_1) => key_1 in nextValue_0 ? editDocument(normalizedDoc, {
1100
1187
  set: {
1101
1188
  [key_1]: nextValue_0[key_1]
1102
1189
  }
1103
- }) : editDocument(doc, {
1190
+ }) : editDocument(normalizedDoc, {
1104
1191
  unset: [key_1]
1105
1192
  }));
1106
1193
  return apply(editActions);
1107
- }, $[3] = apply, $[4] = doc, $[5] = instance, $[6] = path, $[7] = t1) : t1 = $[7], t1;
1194
+ }, $[3] = apply, $[4] = instance, $[5] = normalizedDoc, $[6] = path, $[7] = t1) : t1 = $[7], t1;
1108
1195
  }
1109
1196
  function _temp$1(key) {
1110
1197
  return !ignoredKeys.includes(key);
1111
1198
  }
1112
1199
  function useQuery(options) {
1113
- const instance = useSanityInstance(options), normalized = useNormalizedSourceOptions(options), [isPending, startTransition] = useTransition(), queryKey = getQueryKey(normalized), [deferredQueryKey, setDeferredQueryKey] = useState(queryKey), ref = useRef(new AbortController());
1200
+ const instance = useSanityInstance(), normalized = useNormalizedResourceOptions(options), [isPending, startTransition] = useTransition(), queryKey = getQueryKey(normalized), [deferredQueryKey, setDeferredQueryKey] = useState(queryKey), ref = useRef(new AbortController());
1114
1201
  useEffect(() => {
1115
1202
  queryKey !== deferredQueryKey && startTransition(() => {
1116
1203
  ref && !ref.current.signal.aborted && (ref.current.abort(), ref.current = new AbortController()), setDeferredQueryKey(queryKey);
@@ -1144,9 +1231,9 @@ function useDocuments({
1144
1231
  filter: filter2,
1145
1232
  orderings,
1146
1233
  documentType,
1147
- ...options
1234
+ ...rawOptions
1148
1235
  }) {
1149
- const instance = useSanityInstance(options), [limit, setLimit] = useState(batchSize), documentTypes = useMemo(() => (Array.isArray(documentType) ? documentType : [documentType]).filter((i) => typeof i == "string"), [documentType]), key = JSON.stringify({
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({
1150
1237
  filter: filter2,
1151
1238
  search,
1152
1239
  params,
@@ -1176,10 +1263,8 @@ function useDocuments({
1176
1263
  query: `{"count":${countQuery},"data":${dataQuery}}`,
1177
1264
  params: {
1178
1265
  ...params,
1179
- __handle: {
1180
- ...pick(instance.config, "projectId", "dataset", "perspective"),
1181
- ...pick(options, "projectId", "dataset", "perspective")
1182
- },
1266
+ // these are passed back to the user as part of each document handle
1267
+ __handle: pick(options, ["resource", "perspective"]),
1183
1268
  __types: documentTypes
1184
1269
  }
1185
1270
  }), hasMore = data.length < count, loadMore = useCallback(() => {
@@ -1194,8 +1279,8 @@ function useDocuments({
1194
1279
  }), [count, data, hasMore, isPending, loadMore]);
1195
1280
  }
1196
1281
  function usePaginatedDocuments(t0) {
1197
- const $ = c(62);
1198
- let documentType, options, orderings, search, t1, t2, t3;
1282
+ const $ = c(58);
1283
+ let documentType, orderings, rawOptions, search, t1, t2, t3;
1199
1284
  $[0] !== t0 ? ({
1200
1285
  documentType,
1201
1286
  filter: t1,
@@ -1203,32 +1288,33 @@ function usePaginatedDocuments(t0) {
1203
1288
  params: t3,
1204
1289
  orderings,
1205
1290
  search,
1206
- ...options
1207
- } = t0, $[0] = t0, $[1] = documentType, $[2] = options, $[3] = orderings, $[4] = search, $[5] = t1, $[6] = t2, $[7] = t3) : (documentType = $[1], options = $[2], orderings = $[3], search = $[4], t1 = $[5], t2 = $[6], t3 = $[7]);
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]);
1208
1293
  const filter2 = t1 === void 0 ? "" : t1, pageSize = t2 === void 0 ? 25 : t2;
1209
1294
  let t4;
1210
1295
  $[8] !== t3 ? (t4 = t3 === void 0 ? {} : t3, $[8] = t3, $[9] = t4) : t4 = $[9];
1211
- const params = t4, instance = useSanityInstance(options), [pageIndex, setPageIndex] = useState(0);
1296
+ const params = t4, options = useNormalizedResourceOptions(rawOptions), [pageIndex, setPageIndex] = useState(0);
1212
1297
  let t5;
1213
- $[10] !== filter2 || $[11] !== orderings || $[12] !== pageSize || $[13] !== params || $[14] !== search ? (t5 = JSON.stringify({
1298
+ $[10] !== filter2 || $[11] !== options || $[12] !== orderings || $[13] !== pageSize || $[14] !== params || $[15] !== search ? (t5 = JSON.stringify({
1214
1299
  filter: filter2,
1215
1300
  search,
1216
1301
  params,
1217
1302
  orderings,
1218
- pageSize
1219
- }), $[10] = filter2, $[11] = orderings, $[12] = pageSize, $[13] = params, $[14] = search, $[15] = t5) : t5 = $[15];
1303
+ pageSize,
1304
+ ...options
1305
+ }), $[10] = filter2, $[11] = options, $[12] = orderings, $[13] = pageSize, $[14] = params, $[15] = search, $[16] = t5) : t5 = $[16];
1220
1306
  const key = t5;
1221
1307
  let t6;
1222
- $[16] === Symbol.for("react.memo_cache_sentinel") ? (t6 = () => {
1308
+ $[17] === Symbol.for("react.memo_cache_sentinel") ? (t6 = () => {
1223
1309
  setPageIndex(0);
1224
- }, $[16] = t6) : t6 = $[16];
1310
+ }, $[17] = t6) : t6 = $[17];
1225
1311
  let t7;
1226
- $[17] !== key ? (t7 = [key], $[17] = key, $[18] = t7) : t7 = $[18], useEffect(t6, t7);
1312
+ $[18] !== key ? (t7 = [key], $[18] = key, $[19] = t7) : t7 = $[19], useEffect(t6, t7);
1227
1313
  const startIndex = pageIndex * pageSize, endIndex = (pageIndex + 1) * pageSize;
1228
1314
  let t8;
1229
- $[19] !== documentType ? (t8 = Array.isArray(documentType) ? documentType : [documentType], $[19] = documentType, $[20] = t8) : t8 = $[20];
1315
+ $[20] !== documentType ? (t8 = Array.isArray(documentType) ? documentType : [documentType], $[20] = documentType, $[21] = t8) : t8 = $[21];
1230
1316
  let t9;
1231
- $[21] !== t8 ? (t9 = t8.filter(_temp), $[21] = t8, $[22] = t9) : t9 = $[22];
1317
+ $[22] !== t8 ? (t9 = t8.filter(_temp), $[22] = t8, $[23] = t9) : t9 = $[23];
1232
1318
  const documentTypes = t9;
1233
1319
  let t10;
1234
1320
  const conditions = [], trimmedSearch = search?.trim();
@@ -1239,52 +1325,45 @@ function usePaginatedDocuments(t0) {
1239
1325
  documentTypes?.length && conditions.push("(_type in $__types)"), filter2 && conditions.push(`(${filter2})`), t10 = conditions.length ? `[${conditions.join(" && ")}]` : "";
1240
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}}`;
1241
1327
  let t12;
1242
- $[23] !== instance.config ? (t12 = pick(instance.config, "projectId", "dataset", "perspective"), $[23] = instance.config, $[24] = t12) : t12 = $[24];
1328
+ $[24] !== options ? (t12 = pick(options, ["resource", "perspective"]), $[24] = options, $[25] = t12) : t12 = $[25];
1243
1329
  let t13;
1244
- $[25] !== options ? (t13 = pick(options, "projectId", "dataset", "perspective"), $[25] = options, $[26] = t13) : t13 = $[26];
1245
- let t14;
1246
- $[27] !== t12 || $[28] !== t13 ? (t14 = {
1247
- ...t12,
1248
- ...t13
1249
- }, $[27] = t12, $[28] = t13, $[29] = t14) : t14 = $[29];
1250
- let t15;
1251
- $[30] !== documentTypes || $[31] !== params || $[32] !== t14 ? (t15 = {
1330
+ $[26] !== documentTypes || $[27] !== params || $[28] !== t12 ? (t13 = {
1252
1331
  ...params,
1253
1332
  __types: documentTypes,
1254
- __handle: t14
1255
- }, $[30] = documentTypes, $[31] = params, $[32] = t14, $[33] = t15) : t15 = $[33];
1256
- let t16;
1257
- $[34] !== options || $[35] !== t11 || $[36] !== t15 ? (t16 = {
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 = {
1258
1337
  ...options,
1259
1338
  query: t11,
1260
- params: t15
1261
- }, $[34] = options, $[35] = t11, $[36] = t15, $[37] = t16) : t16 = $[37];
1339
+ params: t13
1340
+ }, $[30] = options, $[31] = t11, $[32] = t13, $[33] = t14) : t14 = $[33];
1262
1341
  const {
1263
- data: t17,
1342
+ data: t15,
1264
1343
  isPending
1265
- } = useQuery(t16), {
1344
+ } = useQuery(t14), {
1266
1345
  data,
1267
1346
  count
1268
- } = t17, totalPages = Math.ceil(count / pageSize), currentPage = pageIndex + 1;
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;
1269
1354
  let t18;
1270
- $[38] === Symbol.for("react.memo_cache_sentinel") ? (t18 = () => setPageIndex(0), $[38] = t18) : t18 = $[38];
1271
- const firstPage = 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;
1272
1357
  let t19;
1273
- $[39] === Symbol.for("react.memo_cache_sentinel") ? (t19 = () => setPageIndex(_temp4), $[39] = t19) : t19 = $[39];
1274
- const previousPage = t19;
1358
+ $[38] !== totalPages ? (t19 = () => setPageIndex(totalPages - 1), $[38] = totalPages, $[39] = t19) : t19 = $[39];
1359
+ const lastPage = t19;
1275
1360
  let t20;
1276
- $[40] !== totalPages ? (t20 = () => setPageIndex((prev_0) => Math.min(prev_0 + 1, totalPages - 1)), $[40] = totalPages, $[41] = t20) : t20 = $[41];
1277
- const nextPage = t20;
1278
- let t21;
1279
- $[42] !== totalPages ? (t21 = () => setPageIndex(totalPages - 1), $[42] = totalPages, $[43] = t21) : t21 = $[43];
1280
- const lastPage = t21;
1281
- let t22;
1282
- $[44] !== totalPages ? (t22 = (pageNumber) => {
1361
+ $[40] !== totalPages ? (t20 = (pageNumber) => {
1283
1362
  pageNumber < 1 || pageNumber > totalPages || setPageIndex(pageNumber - 1);
1284
- }, $[44] = totalPages, $[45] = t22) : t22 = $[45];
1285
- const goToPage = t22, hasFirstPage = pageIndex > 0, hasPreviousPage = pageIndex > 0, hasNextPage = pageIndex < totalPages - 1, hasLastPage = pageIndex < totalPages - 1;
1286
- let t23;
1287
- return $[46] !== count || $[47] !== currentPage || $[48] !== data || $[49] !== endIndex || $[50] !== goToPage || $[51] !== hasFirstPage || $[52] !== hasLastPage || $[53] !== hasNextPage || $[54] !== hasPreviousPage || $[55] !== isPending || $[56] !== lastPage || $[57] !== nextPage || $[58] !== pageSize || $[59] !== startIndex || $[60] !== totalPages ? (t23 = {
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 = {
1288
1367
  data,
1289
1368
  isPending,
1290
1369
  pageSize,
@@ -1302,7 +1381,7 @@ function usePaginatedDocuments(t0) {
1302
1381
  lastPage,
1303
1382
  hasLastPage,
1304
1383
  goToPage
1305
- }, $[46] = count, $[47] = currentPage, $[48] = data, $[49] = endIndex, $[50] = goToPage, $[51] = hasFirstPage, $[52] = hasLastPage, $[53] = hasNextPage, $[54] = hasPreviousPage, $[55] = isPending, $[56] = lastPage, $[57] = nextPage, $[58] = pageSize, $[59] = startIndex, $[60] = totalPages, $[61] = t23) : t23 = $[61], t23;
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;
1306
1385
  }
1307
1386
  function _temp4(prev) {
1308
1387
  return Math.max(prev - 1, 0);
@@ -1316,70 +1395,39 @@ function _temp2(str) {
1316
1395
  function _temp(i) {
1317
1396
  return typeof i == "string";
1318
1397
  }
1319
- function usePresence() {
1320
- const $ = c(11), sanityInstance = useSanityInstance();
1321
- let t0, t1;
1322
- $[0] !== sanityInstance ? (t1 = getPresence(sanityInstance), $[0] = sanityInstance, $[1] = t1) : t1 = $[1], t0 = t1;
1323
- const source = t0;
1324
- let t2;
1325
- $[2] !== source ? (t2 = (callback) => source.subscribe(callback), $[2] = source, $[3] = t2) : t2 = $[3];
1326
- const subscribe = t2;
1327
- let t3, t4;
1328
- $[4] !== source ? (t3 = () => source.getCurrent(), t4 = () => source.getCurrent(), $[4] = source, $[5] = t3, $[6] = t4) : (t3 = $[5], t4 = $[6]);
1329
- const locations = useSyncExternalStore(subscribe, t3, t4);
1330
- let t5;
1331
- $[7] !== locations ? (t5 = locations || [], $[7] = locations, $[8] = t5) : t5 = $[8];
1332
- let t6;
1333
- return $[9] !== t5 ? (t6 = {
1334
- locations: t5
1335
- }, $[9] = t5, $[10] = t6) : t6 = $[10], t6;
1336
- }
1337
- function useDocumentPreview(t0) {
1338
- const $ = c(13);
1339
- let docHandle, ref;
1340
- $[0] !== t0 ? ({
1341
- ref,
1342
- ...docHandle
1343
- } = t0, $[0] = t0, $[1] = docHandle, $[2] = ref) : (docHandle = $[1], ref = $[2]);
1344
- const instance = useSanityInstance(docHandle);
1398
+ function usePresence(t0) {
1399
+ const $ = c(14);
1345
1400
  let t1;
1346
- $[3] !== docHandle || $[4] !== instance ? (t1 = getPreviewState(instance, docHandle), $[3] = docHandle, $[4] = instance, $[5] = t1) : t1 = $[5];
1347
- const stateSource = t1;
1348
- let t2;
1349
- $[6] !== ref || $[7] !== stateSource ? (t2 = (onStoreChanged) => {
1350
- const subscription = new Observable((observer) => {
1351
- if (typeof IntersectionObserver > "u" || typeof HTMLElement > "u") {
1352
- observer.next(!0);
1353
- return;
1354
- }
1355
- const intersectionObserver = new IntersectionObserver((t32) => {
1356
- const [entry] = t32;
1357
- return observer.next(entry.isIntersecting);
1358
- }, {
1359
- rootMargin: "0px",
1360
- threshold: 0
1361
- });
1362
- return ref?.current && ref.current instanceof HTMLElement ? intersectionObserver.observe(ref.current) : observer.next(!0), () => intersectionObserver.disconnect();
1363
- }).pipe(startWith(!1), distinctUntilChanged(), switchMap((isVisible) => isVisible ? new Observable((obs) => stateSource.subscribe(() => obs.next())) : EMPTY)).subscribe({
1364
- next: onStoreChanged
1365
- });
1366
- return () => subscription.unsubscribe();
1367
- }, $[6] = ref, $[7] = stateSource, $[8] = t2) : t2 = $[8];
1368
- const subscribe = t2;
1369
- let t3;
1370
- return $[9] !== docHandle || $[10] !== instance || $[11] !== stateSource ? (t3 = () => {
1371
- const currentState = stateSource.getCurrent();
1372
- if (currentState.data === null)
1373
- throw resolvePreview(instance, docHandle);
1374
- return currentState;
1375
- }, $[9] = docHandle, $[10] = instance, $[11] = stateSource, $[12] = t3) : t3 = $[12], useSyncExternalStore(subscribe, t3);
1401
+ $[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;
1411
+ 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);
1418
+ 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;
1376
1424
  }
1377
1425
  function useDocumentProjection({
1378
1426
  ref,
1379
1427
  projection,
1380
1428
  ...docHandle
1381
1429
  }) {
1382
- const instance = useSanityInstance(docHandle), normalizedProjection = useMemo(() => projection.trim(), [projection]), normalizedDocHandle = useNormalizedSourceOptions(docHandle), stateSource = useMemo(() => getProjectionState(instance, {
1430
+ const instance = useSanityInstance(), normalizedProjection = useMemo(() => projection.trim(), [projection]), normalizedDocHandle = useNormalizedResourceOptions(docHandle), stateSource = useMemo(() => getProjectionState(instance, {
1383
1431
  ...normalizedDocHandle,
1384
1432
  projection: normalizedProjection
1385
1433
  }), [instance, normalizedDocHandle, normalizedProjection]);
@@ -1406,27 +1454,62 @@ function useDocumentProjection({
1406
1454
  }, [stateSource, ref]);
1407
1455
  return useSyncExternalStore(subscribe, stateSource.getCurrent);
1408
1456
  }
1457
+ function useDocumentPreview(t0) {
1458
+ const $ = c(13);
1459
+ let docHandle, ref;
1460
+ $[0] !== t0 ? ({
1461
+ ref,
1462
+ ...docHandle
1463
+ } = t0, $[0] = t0, $[1] = docHandle, $[2] = ref) : (docHandle = $[1], ref = $[2]);
1464
+ const instance = useSanityInstance(), normalizedDocHandle = useNormalizedResourceOptions(docHandle);
1465
+ let t1;
1466
+ $[3] !== normalizedDocHandle || $[4] !== ref ? (t1 = {
1467
+ ...normalizedDocHandle,
1468
+ projection: PREVIEW_PROJECTION,
1469
+ ref
1470
+ }, $[3] = normalizedDocHandle, $[4] = ref, $[5] = t1) : t1 = $[5];
1471
+ 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;
1474
+ const previewValue = t2;
1475
+ let t4;
1476
+ return $[10] !== previewValue || $[11] !== projectionResult.isPending ? (t4 = {
1477
+ data: previewValue,
1478
+ isPending: projectionResult.isPending
1479
+ }, $[10] = previewValue, $[11] = projectionResult.isPending, $[12] = t4) : t4 = $[12], t4;
1480
+ }
1409
1481
  const useProject = createStateSourceHook({
1410
1482
  // remove `undefined` since we're suspending when that is the case
1411
1483
  getState: getProjectState,
1412
1484
  shouldSuspend: (instance, projectHandle) => getProjectState(instance, projectHandle).getCurrent() === void 0,
1413
- suspender: resolveProject,
1414
- getConfig: identity
1485
+ suspender: (instance, projectHandle) => resolveProject(instance, projectHandle)
1415
1486
  }), useProjects = createStateSourceHook({
1416
1487
  getState: getProjectsState,
1417
1488
  shouldSuspend: (instance, options) => getProjectsState(instance, options).getCurrent() === void 0,
1418
1489
  suspender: resolveProjects
1419
- }), useActiveReleases = createStateSourceHook({
1490
+ }), useActiveReleasesValue = createStateSourceHook({
1420
1491
  getState: getActiveReleasesState,
1421
- shouldSuspend: (instance) => getActiveReleasesState(instance).getCurrent() === void 0,
1422
- suspender: (instance) => firstValueFrom(getActiveReleasesState(instance).observable.pipe(filter(Boolean)))
1423
- }), usePerspective = createStateSourceHook({
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) => {
1495
+ const $ = c(2);
1496
+ let t0;
1497
+ $[0] !== options ? (t0 = options ?? {}, $[0] = options, $[1] = t0) : t0 = $[1];
1498
+ const normalizedOptions = useNormalizedResourceOptions(t0);
1499
+ return useActiveReleasesValue(normalizedOptions);
1500
+ }, usePerspectiveValue = createStateSourceHook({
1424
1501
  getState: getPerspectiveState,
1425
1502
  shouldSuspend: (instance, options) => getPerspectiveState(instance, options).getCurrent() === void 0,
1426
- suspender: (instance, _options) => firstValueFrom(getActiveReleasesState(instance).observable.pipe(filter(Boolean)))
1427
- });
1503
+ suspender: (instance, _options) => firstValueFrom(getPerspectiveState(instance, _options).observable.pipe(filter(Boolean)))
1504
+ }), usePerspective = (options) => {
1505
+ const $ = c(2);
1506
+ let t0;
1507
+ $[0] !== options ? (t0 = options ?? {}, $[0] = options, $[1] = t0) : t0 = $[1];
1508
+ const normalizedOptions = useNormalizedResourceOptions(t0);
1509
+ return usePerspectiveValue(normalizedOptions);
1510
+ };
1428
1511
  function useUser(options) {
1429
- const instance = useSanityInstance(options), [isPending, startTransition] = useTransition(), key = getUsersKey(instance, options), [deferredKey, setDeferredKey] = useState(key), deferred = useMemo(() => parseUsersKey(deferredKey), [deferredKey]), [ref, setRef] = useState(new AbortController());
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());
1430
1513
  useEffect(() => {
1431
1514
  key !== deferredKey && startTransition(() => {
1432
1515
  ref.signal.aborted || (ref.abort(), setRef(new AbortController())), setDeferredKey(key);
@@ -1447,7 +1530,7 @@ function useUser(options) {
1447
1530
  };
1448
1531
  }
1449
1532
  function useUsers(options) {
1450
- const instance = useSanityInstance(options), [isPending, startTransition] = useTransition(), key = getUsersKey(instance, options), [deferredKey, setDeferredKey] = useState(key), deferred = useMemo(() => parseUsersKey(deferredKey), [deferredKey]), [ref, setRef] = useState(new AbortController());
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());
1451
1534
  useEffect(() => {
1452
1535
  key !== deferredKey && startTransition(() => {
1453
1536
  ref.signal.aborted || (ref.abort(), setRef(new AbortController())), setDeferredKey(key);
@@ -1475,7 +1558,7 @@ function useUsers(options) {
1475
1558
  loadMore
1476
1559
  };
1477
1560
  }
1478
- var version = "2.7.0";
1561
+ var version = "3.0.0-rc.0";
1479
1562
  function getEnv(key) {
1480
1563
  if (typeof import.meta < "u" && import.meta.env)
1481
1564
  return import.meta.env[key];
@@ -1531,6 +1614,7 @@ export {
1531
1614
  useProjects,
1532
1615
  useQuery,
1533
1616
  useRecordDocumentHistoryEvent,
1617
+ useResource,
1534
1618
  useSanityInstance,
1535
1619
  useStudioWorkspacesByProjectIdDataset,
1536
1620
  useUser,