@sanity/sdk-react 2.8.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 (87) hide show
  1. package/README.md +125 -63
  2. package/dist/index.d.ts +381 -571
  3. package/dist/index.js +435 -366
  4. package/dist/index.js.map +1 -1
  5. package/package.json +7 -9
  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 +8 -26
  13. package/src/components/auth/LoginError.tsx +5 -5
  14. package/src/config/handles.ts +53 -0
  15. package/src/context/ComlinkTokenRefresh.test.tsx +27 -10
  16. package/src/context/DefaultResourceContext.ts +10 -0
  17. package/src/context/PerspectiveContext.ts +12 -0
  18. package/src/context/ResourceProvider.test.tsx +99 -19
  19. package/src/context/ResourceProvider.tsx +103 -37
  20. package/src/context/ResourcesContext.tsx +7 -0
  21. package/src/context/SDKStudioContext.test.tsx +33 -28
  22. package/src/context/SDKStudioContext.ts +6 -0
  23. package/src/context/renderSanityApp.test.tsx +49 -151
  24. package/src/context/renderSanityApp.tsx +8 -12
  25. package/src/hooks/agent/agentActions.test.tsx +1 -1
  26. package/src/hooks/agent/agentActions.ts +56 -19
  27. package/src/hooks/auth/useDashboardOrganizationId.test.tsx +8 -2
  28. package/src/hooks/auth/useVerifyOrgProjects.test.tsx +32 -8
  29. package/src/hooks/client/useClient.test.tsx +4 -1
  30. package/src/hooks/client/useClient.ts +0 -1
  31. package/src/hooks/context/useDefaultResource.test.tsx +25 -0
  32. package/src/hooks/context/useDefaultResource.ts +30 -0
  33. package/src/hooks/context/useSanityInstance.test.tsx +2 -140
  34. package/src/hooks/context/useSanityInstance.ts +9 -53
  35. package/src/hooks/dashboard/useDispatchIntent.test.ts +24 -15
  36. package/src/hooks/dashboard/useDispatchIntent.ts +7 -7
  37. package/src/hooks/dashboard/useManageFavorite.test.tsx +34 -94
  38. package/src/hooks/dashboard/useManageFavorite.ts +16 -10
  39. package/src/hooks/dashboard/useNavigateToStudioDocument.test.ts +7 -5
  40. package/src/hooks/dashboard/useNavigateToStudioDocument.ts +6 -2
  41. package/src/hooks/dashboard/useRecordDocumentHistoryEvent.test.ts +2 -0
  42. package/src/hooks/dashboard/useRecordDocumentHistoryEvent.ts +2 -1
  43. package/src/hooks/dashboard/utils/useResourceIdFromDocumentHandle.test.ts +17 -38
  44. package/src/hooks/dashboard/utils/useResourceIdFromDocumentHandle.ts +12 -19
  45. package/src/hooks/datasets/useDatasets.test.ts +8 -22
  46. package/src/hooks/datasets/useDatasets.ts +8 -16
  47. package/src/hooks/document/useApplyDocumentActions.test.ts +98 -52
  48. package/src/hooks/document/useApplyDocumentActions.ts +35 -37
  49. package/src/hooks/document/useDocument.test.tsx +8 -37
  50. package/src/hooks/document/useDocument.ts +78 -129
  51. package/src/hooks/document/useDocumentEvent.test.tsx +7 -19
  52. package/src/hooks/document/useDocumentEvent.ts +21 -19
  53. package/src/hooks/document/useDocumentPermissions.test.tsx +75 -84
  54. package/src/hooks/document/useDocumentPermissions.ts +41 -28
  55. package/src/hooks/document/useDocumentSyncStatus.test.ts +13 -3
  56. package/src/hooks/document/useDocumentSyncStatus.ts +19 -14
  57. package/src/hooks/document/useEditDocument.test.tsx +28 -70
  58. package/src/hooks/document/useEditDocument.ts +29 -149
  59. package/src/hooks/documents/useDocuments.test.tsx +44 -64
  60. package/src/hooks/documents/useDocuments.ts +19 -25
  61. package/src/hooks/helpers/createCallbackHook.test.tsx +19 -13
  62. package/src/hooks/helpers/createStateSourceHook.test.tsx +10 -10
  63. package/src/hooks/helpers/createStateSourceHook.tsx +2 -4
  64. package/src/hooks/helpers/useNormalizedResourceOptions.test.ts +65 -0
  65. package/src/hooks/helpers/useNormalizedResourceOptions.ts +127 -0
  66. package/src/hooks/paginatedDocuments/usePaginatedDocuments.test.tsx +27 -34
  67. package/src/hooks/paginatedDocuments/usePaginatedDocuments.ts +19 -20
  68. package/src/hooks/presence/usePresence.test.tsx +71 -9
  69. package/src/hooks/presence/usePresence.ts +28 -3
  70. package/src/hooks/preview/useDocumentPreview.test.tsx +85 -193
  71. package/src/hooks/preview/useDocumentPreview.tsx +42 -62
  72. package/src/hooks/projection/useDocumentProjection.test.tsx +9 -37
  73. package/src/hooks/projection/useDocumentProjection.ts +9 -82
  74. package/src/hooks/projects/useProject.test.ts +1 -2
  75. package/src/hooks/projects/useProject.ts +7 -8
  76. package/src/hooks/query/useQuery.test.tsx +5 -6
  77. package/src/hooks/query/useQuery.ts +12 -91
  78. package/src/hooks/releases/useActiveReleases.test.tsx +2 -2
  79. package/src/hooks/releases/useActiveReleases.ts +25 -13
  80. package/src/hooks/releases/usePerspective.test.tsx +9 -17
  81. package/src/hooks/releases/usePerspective.ts +29 -18
  82. package/src/hooks/users/useUser.test.tsx +9 -3
  83. package/src/hooks/users/useUser.ts +1 -1
  84. package/src/hooks/users/useUsers.test.tsx +5 -2
  85. package/src/hooks/users/useUsers.ts +1 -1
  86. package/src/context/SourcesContext.tsx +0 -7
  87. 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,40 +279,39 @@ 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(23), {
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(), {
308
- config: t1
309
- } = useSanityInstance(), {
310
- projectId
311
- } = t1, [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);
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);
312
300
  let t2;
313
- $[0] === Symbol.for("react.memo_cache_sentinel") ? (t2 = {
301
+ $[2] === Symbol.for("react.memo_cache_sentinel") ? (t2 = {
314
302
  name: SDK_NODE_NAME,
315
303
  connectTo: SDK_CHANNEL_NAME
316
- }, $[0] = t2) : t2 = $[0];
304
+ }, $[2] = t2) : t2 = $[2];
317
305
  const {
318
306
  fetch
319
307
  } = useWindowConnection(t2);
320
308
  let t3;
321
- $[1] !== logout2 || $[2] !== resetErrorBoundary ? (t3 = async () => {
309
+ $[3] !== logout2 || $[4] !== resetErrorBoundary ? (t3 = async () => {
322
310
  await logout2(), resetErrorBoundary();
323
- }, $[1] = logout2, $[2] = resetErrorBoundary, $[3] = t3) : t3 = $[3];
311
+ }, $[3] = logout2, $[4] = resetErrorBoundary, $[5] = t3) : t3 = $[5];
324
312
  const handleRetry = t3;
325
313
  let t4;
326
- $[4] !== authState.type || $[5] !== error || $[6] !== fetch || $[7] !== handleRetry || $[8] !== projectId ? (t4 = () => {
314
+ $[6] !== authState.type || $[7] !== error || $[8] !== fetch || $[9] !== handleRetry || $[10] !== projectId ? (t4 = () => {
327
315
  if (error instanceof ClientError) {
328
316
  if (error.statusCode === 401)
329
317
  if (isProjectUserNotFoundClientError(error)) {
@@ -340,17 +328,17 @@ function LoginError(t0) {
340
328
  }
341
329
  }
342
330
  authState.type !== AuthStateType.ERROR && error instanceof ConfigurationError && (setAuthErrorMessage(error.message), setShowRetryCta(!0));
343
- }, $[4] = authState.type, $[5] = error, $[6] = fetch, $[7] = handleRetry, $[8] = projectId, $[9] = t4) : t4 = $[9];
331
+ }, $[6] = authState.type, $[7] = error, $[8] = fetch, $[9] = handleRetry, $[10] = projectId, $[11] = t4) : t4 = $[11];
344
332
  let t5;
345
- $[10] !== authState || $[11] !== error || $[12] !== fetch || $[13] !== handleRetry || $[14] !== projectId ? (t5 = [authState, handleRetry, error, fetch, projectId], $[10] = authState, $[11] = error, $[12] = fetch, $[13] = handleRetry, $[14] = projectId, $[15] = t5) : t5 = $[15], useEffect(t4, 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);
346
334
  const t6 = error instanceof AuthError ? "Authentication Error" : "Configuration Error";
347
335
  let t7;
348
- $[16] !== handleRetry || $[17] !== showRetryCta ? (t7 = showRetryCta ? {
336
+ $[18] !== handleRetry || $[19] !== showRetryCta ? (t7 = showRetryCta ? {
349
337
  text: "Retry",
350
338
  onClick: handleRetry
351
- } : void 0, $[16] = handleRetry, $[17] = showRetryCta, $[18] = t7) : t7 = $[18];
339
+ } : void 0, $[18] = handleRetry, $[19] = showRetryCta, $[20] = t7) : t7 = $[20];
352
340
  let t8;
353
- return $[19] !== authErrorMessage || $[20] !== t6 || $[21] !== t7 ? (t8 = /* @__PURE__ */ jsx(Error$1, { heading: t6, description: authErrorMessage, cta: t7 }), $[19] = authErrorMessage, $[20] = t6, $[21] = t7, $[22] = t8) : t8 = $[22], 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;
354
342
  }
355
343
  if (isInIframe() && !document.querySelector("[data-sanity-core]")) {
356
344
  const parsedUrl = new URL(window.location.href), mode = new URLSearchParams(parsedUrl.hash.slice(1)).get("mode"), script = document.createElement("script");
@@ -412,132 +400,269 @@ function AuthSwitch(t0) {
412
400
  }
413
401
  const SDKStudioContext = createContext(null);
414
402
  SDKStudioContext.displayName = "SDKStudioContext";
415
- 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." });
416
404
  function ResourceProvider(t0) {
417
- const $ = c(16);
418
- let children, config, fallback;
405
+ const $ = c(19);
406
+ let children, fallback, resource, rest;
419
407
  $[0] !== t0 ? ({
420
408
  children,
421
409
  fallback,
422
- ...config
423
- } = t0, $[0] = t0, $[1] = children, $[2] = config, $[3] = fallback) : (children = $[1], config = $[2], fallback = $[3]);
424
- 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;
425
439
  let t1, t2;
426
- $[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;
427
441
  const instance = t1, disposal = useRef(null);
428
442
  let t3, t4;
429
- $[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), () => {
430
444
  disposal.current = {
431
445
  instance,
432
446
  timeoutId: setTimeout(() => {
433
447
  instance.isDisposed() || instance.dispose();
434
448
  }, 0)
435
449
  };
436
- }), 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);
437
451
  const t5 = fallback ?? DEFAULT_FALLBACK;
438
452
  let t6;
439
- $[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];
440
454
  let t7;
441
- 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];
442
481
  }
443
- const SourcesContext = createContext({});
444
482
  function SDKProvider(t0) {
445
- const $ = c(19);
446
- let children, config, fallback, props;
483
+ const $ = c(22);
484
+ let children, config, fallback, props, t1;
447
485
  $[0] !== t0 ? ({
448
486
  children,
449
487
  config,
488
+ resources: t1,
450
489
  fallback,
451
490
  ...props
452
- } = t0, $[0] = t0, $[1] = children, $[2] = config, $[3] = fallback, $[4] = props) : (children = $[1], config = $[2], fallback = $[3], props = $[4]);
453
- let t1;
454
- $[5] !== config ? (t1 = Array.isArray(config) ? config : [config], $[5] = config, $[6] = t1) : t1 = $[6];
455
- let configs, t2;
456
- $[7] !== t1 ? (configs = t1.slice().reverse(), t2 = configs.map(_temp$5).filter(_temp2$1), $[7] = t1, $[8] = configs, $[9] = t2) : (configs = $[8], t2 = $[9]);
457
- 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;
458
495
  let t3, t4;
459
- $[10] !== props.sources ? (t4 = props.sources ?? {}, $[10] = props.sources, $[11] = t4) : t4 = $[11], t3 = t4;
460
- const sourcesValue = t3;
496
+ $[8] !== resources ? (t4 = collectProjectIds(resources), $[8] = resources, $[9] = t4) : t4 = $[9], t3 = t4;
497
+ const projectIds = t3;
461
498
  let t5;
462
- if ($[12] !== children || $[13] !== configs || $[14] !== fallback || $[15] !== projectIds || $[16] !== props || $[17] !== sourcesValue) {
463
- 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) });
464
- t5 = createNestedProviders(0), $[12] = children, $[13] = configs, $[14] = fallback, $[15] = projectIds, $[16] = props, $[17] = sourcesValue, $[18] = t5;
465
- } else
466
- t5 = $[18];
467
- return t5;
468
- }
469
- function _temp2$1(id) {
470
- return !!id;
471
- }
472
- function _temp$5(c2) {
473
- 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;
474
507
  }
475
508
  const REDIRECT_URL = "https://sanity.io/welcome";
476
- function deriveConfigFromWorkspace(workspace) {
509
+ function deriveFromWorkspace(workspace) {
477
510
  return {
478
- projectId: workspace.projectId,
479
- dataset: workspace.dataset,
480
- studio: {
481
- auth: workspace.auth.token ? {
482
- token: workspace.auth.token
483
- } : 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
+ }
484
525
  }
485
526
  };
486
527
  }
487
528
  function SanityApp(t0) {
488
- const $ = c(18);
489
- let children, configProp, fallback, props;
529
+ const $ = c(21);
530
+ let children, configProp, fallback, props, resourcesProp;
490
531
  $[0] !== t0 ? ({
491
532
  children,
492
533
  fallback,
493
534
  config: configProp,
535
+ resources: resourcesProp,
494
536
  ...props
495
- } = 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]);
496
538
  const studioWorkspace = useContext(SDKStudioContext);
497
539
  let t1;
498
540
  bb0: {
499
- if (configProp) {
500
- t1 = configProp;
541
+ if (studioWorkspace && !configProp && !resourcesProp) {
542
+ let t22;
543
+ $[6] !== studioWorkspace ? (t22 = deriveFromWorkspace(studioWorkspace), $[6] = studioWorkspace, $[7] = t22) : t22 = $[7], t1 = t22;
501
544
  break bb0;
502
545
  }
503
- if (studioWorkspace) {
504
- let t23;
505
- $[5] !== studioWorkspace ? (t23 = deriveConfigFromWorkspace(studioWorkspace), $[5] = studioWorkspace, $[6] = t23) : t23 = $[6], t1 = t23;
506
- break bb0;
546
+ t1 = null;
547
+ }
548
+ const derived = t1;
549
+ let t2;
550
+ bb1: {
551
+ if (configProp) {
552
+ t2 = configProp;
553
+ break bb1;
507
554
  }
508
- let t22;
509
- $[7] === Symbol.for("react.memo_cache_sentinel") ? (t22 = [], $[7] = t22) : t22 = $[7], t1 = t22;
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;
510
561
  }
511
- const resolvedConfig = t1;
512
- let t2, t3;
513
- $[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 = () => {
514
579
  let timeout;
515
- const primaryConfig = Array.isArray(resolvedConfig) ? resolvedConfig[0] : resolvedConfig, shouldRedirectWithoutConfig = configProp === void 0 && !studioWorkspace && !primaryConfig;
516
- return !isInIframe() && !isLocalUrl(window) && (shouldRedirectWithoutConfig || primaryConfig && !isStudioConfig(primaryConfig)) && (timeout = setTimeout(_temp$4, 1e3)), () => clearTimeout(timeout);
517
- }, t3 = [configProp, resolvedConfig, studioWorkspace], $[8] = configProp, $[9] = resolvedConfig, $[10] = studioWorkspace, $[11] = t2, $[12] = t3) : (t2 = $[11], t3 = $[12]), useEffect(t2, t3);
518
- let t4;
519
- 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;
520
585
  }
521
- function _temp$4() {
586
+ function _temp$3() {
522
587
  console.warn("Redirecting to core", REDIRECT_URL), window.location.replace(REDIRECT_URL);
523
588
  }
524
- function renderSanityApp(rootElement, namedSources, options, children) {
589
+ function renderSanityApp(rootElement, namedResources, options, children) {
525
590
  if (!rootElement)
526
591
  throw new Error("Missing root element to mount application into");
527
592
  const {
528
593
  reactStrictMode = !1
529
- } = options, root = createRoot(rootElement), config = Object.values(namedSources);
530
- 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);
531
653
  }
532
- const useAgentGenerate = createCallbackHook(agentGenerate), useAgentTransform = createCallbackHook(agentTransform), useAgentTranslate = createCallbackHook(agentTranslate);
533
654
  function promptAdapter(instance, options) {
534
655
  return firstValueFrom(agentPrompt(instance, options));
535
656
  }
536
- const useAgentPrompt = createCallbackHook(promptAdapter);
657
+ function useAgentPrompt() {
658
+ return useAgentCallback(promptAdapter);
659
+ }
537
660
  function patchAdapter(instance, options) {
538
661
  return firstValueFrom(agentPatch(instance, options));
539
662
  }
540
- const useAgentPatch = createCallbackHook(patchAdapter);
663
+ function useAgentPatch() {
664
+ return useAgentCallback(patchAdapter);
665
+ }
541
666
  function useAgentResourceContext(options) {
542
667
  const $ = c(9), {
543
668
  projectId,
@@ -599,8 +724,7 @@ const useClient = createStateSourceHook({
599
724
  if (!options || typeof options != "object")
600
725
  throw new Error('useClient() requires a configuration object with at least an "apiVersion" property. Example: useClient({ apiVersion: "2024-11-12" })');
601
726
  return getClientState(instance, options);
602
- },
603
- getConfig: (options) => options
727
+ }
604
728
  });
605
729
  function useFrameConnection(options) {
606
730
  const $ = c(12), {
@@ -626,7 +750,7 @@ function useFrameConnection(options) {
626
750
  const [type, handler] = t22, unsubscribe = channel.on(type, handler);
627
751
  messageUnsubscribers.push(unsubscribe);
628
752
  }), () => {
629
- 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;
630
754
  };
631
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);
632
756
  let t2;
@@ -648,9 +772,12 @@ function useFrameConnection(options) {
648
772
  sendMessage
649
773
  }, $[11] = t4) : t4 = $[11], t4;
650
774
  }
651
- function _temp$3(unsub) {
775
+ function _temp$2(unsub) {
652
776
  return unsub();
653
777
  }
778
+ function useResource() {
779
+ return useContext(ResourceContext);
780
+ }
654
781
  function useDashboardNavigate(navigateFn) {
655
782
  const $ = c(2);
656
783
  let t0;
@@ -664,33 +791,12 @@ function useDashboardNavigate(navigateFn) {
664
791
  }
665
792
  }, $[0] = navigateFn, $[1] = t0) : t0 = $[1], useWindowConnection(t0);
666
793
  }
667
- function useNormalizedSourceOptions(options) {
668
- const $ = c(6);
669
- let rest, sourceName;
670
- if ($[0] !== options ? ({
671
- sourceName,
672
- ...rest
673
- } = options, $[0] = options, $[1] = rest, $[2] = sourceName) : (rest = $[1], sourceName = $[2]), sourceName && Object.hasOwn(options, "source"))
674
- throw new Error(`Source name ${JSON.stringify(sourceName)} and source ${JSON.stringify(options.source)} cannot be used together.`);
675
- const sources = useContext(SourcesContext);
676
- let resolvedSource;
677
- if (options.source && (resolvedSource = options.source), sourceName && !Object.hasOwn(sources, sourceName))
678
- throw new Error(`There's no source named ${JSON.stringify(sourceName)} in context. Please use <SourceProvider>.`);
679
- sourceName && sources[sourceName] && (resolvedSource = sources[sourceName]);
680
- let t0;
681
- return $[3] !== resolvedSource || $[4] !== rest ? (t0 = {
682
- ...rest,
683
- source: resolvedSource
684
- }, $[3] = resolvedSource, $[4] = rest, $[5] = t0) : t0 = $[5], t0;
685
- }
686
794
  function useResourceIdFromDocumentHandle(documentHandle) {
687
- const $ = c(3), options = useNormalizedSourceOptions(documentHandle), {
688
- projectId,
689
- dataset,
690
- source
795
+ const $ = c(3), options = useNormalizedResourceOptions(documentHandle), {
796
+ resource
691
797
  } = options;
692
798
  let resourceId = "", resourceType;
693
- 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"));
694
800
  let t0;
695
801
  return $[0] !== resourceId || $[1] !== resourceType ? (t0 = {
696
802
  id: resourceId,
@@ -715,7 +821,7 @@ function useDispatchIntent(params) {
715
821
  if (!action && !intentId)
716
822
  throw new Error("useDispatchIntent: Either `action` or `intentId` must be provided.");
717
823
  if (action && intentId && console.warn("useDispatchIntent: Both `action` and `intentId` were provided. Using `intentId` and ignoring `action`."), !resource.id)
718
- 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.");
719
825
  const message = {
720
826
  type: "dashboard/v1/events/intents/dispatch-intent",
721
827
  data: {
@@ -750,8 +856,7 @@ function useDispatchIntent(params) {
750
856
  function useManageFavorite({
751
857
  documentId,
752
858
  documentType,
753
- projectId: paramProjectId,
754
- dataset: paramDataset,
859
+ resource: paramResource,
755
860
  resourceId: paramResourceId,
756
861
  resourceType,
757
862
  schemaName
@@ -761,21 +866,22 @@ function useManageFavorite({
761
866
  } = useWindowConnection({
762
867
  name: SDK_NODE_NAME,
763
868
  connectTo: SDK_CHANNEL_NAME
764
- }), instance = useSanityInstance(), {
765
- config
766
- } = 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;
767
870
  if (resourceType === "studio" && (!projectId || !dataset))
768
871
  throw new Error("projectId and dataset are required for studio resources");
769
872
  const resourceId = resourceType === "studio" && !paramResourceId ? `${projectId}.${dataset}` : paramResourceId;
770
873
  if (!resourceId)
771
874
  throw new Error("resourceId is required for media-library and canvas resources");
875
+ if (!resource)
876
+ throw new Error("resource is required");
772
877
  const context = useMemo(() => ({
773
878
  documentId,
774
879
  documentType,
880
+ resource,
775
881
  resourceId,
776
882
  resourceType,
777
883
  schemaName
778
- }), [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) => {
779
885
  if (!(!fetch || !documentId || !documentType || !resourceType))
780
886
  try {
781
887
  const payload = {
@@ -869,9 +975,8 @@ function useNavigateToStudioDocument(documentHandle, preferredStudioUrl) {
869
975
  let t1;
870
976
  $[1] !== documentHandle || $[2] !== preferredStudioUrl || $[3] !== sendMessage || $[4] !== workspacesByProjectIdAndDataset ? (t1 = () => {
871
977
  const {
872
- projectId,
873
- dataset
874
- } = documentHandle;
978
+ resource
979
+ } = documentHandle, datasetResource = resource && isDatasetResource(resource) ? resource : void 0, projectId = datasetResource?.projectId, dataset = datasetResource?.dataset;
875
980
  if (!projectId || !dataset) {
876
981
  console.warn("Project ID and dataset are required to navigate to a studio document");
877
982
  return;
@@ -953,46 +1058,27 @@ function useRecordDocumentHistoryEvent(t0) {
953
1058
  }
954
1059
  const useDatasets = createStateSourceHook({
955
1060
  getState: getDatasetsState,
956
- shouldSuspend: (instance, projectHandle) => (
957
- // remove `undefined` since we're suspending when that is the case
958
- getDatasetsState(instance, projectHandle).getCurrent() === void 0
959
- ),
960
- suspender: resolveDatasets,
961
- getConfig: identity
1061
+ shouldSuspend: (instance, options) => getDatasetsState(instance, options).getCurrent() === void 0,
1062
+ suspender: resolveDatasets
962
1063
  }), useApplyDocumentActions = () => {
963
- const $ = c(2), instance = useSanityInstance();
1064
+ const $ = c(4), instance = useSanityInstance(), resources = useContext(ResourcesContext), contextResource = useContext(ResourceContext);
964
1065
  let t0;
965
- return $[0] !== instance ? (t0 = (actionOrActions, options) => {
966
- const actions = Array.isArray(actionOrActions) ? actionOrActions : [actionOrActions];
967
- let projectId, dataset;
968
- for (const action of actions)
969
- if (action.projectId) {
970
- if (projectId || (projectId = action.projectId), action.projectId !== projectId)
971
- throw new Error(`Mismatched project IDs found in actions. All actions must belong to the same project. Found "${action.projectId}" but expected "${projectId}".`);
972
- if (action.dataset && (dataset || (dataset = action.dataset), action.dataset !== dataset))
973
- throw new Error(`Mismatched datasets found in actions. All actions must belong to the same dataset. Found "${action.dataset}" but expected "${dataset}".`);
974
- }
975
- if (projectId || dataset) {
976
- const actualInstance = instance.match({
977
- projectId,
978
- dataset
979
- });
980
- if (!actualInstance)
981
- throw new Error(`Could not find a matching Sanity instance for the requested action: ${JSON.stringify({
982
- projectId,
983
- dataset
984
- }, null, 2)}.
985
- Please ensure there is a ResourceProvider component with a matching configuration in the component hierarchy.`);
986
- return applyDocumentActions(actualInstance, {
987
- actions,
988
- ...options
989
- });
990
- }
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.");
991
1077
  return applyDocumentActions(instance, {
992
1078
  actions,
993
- ...options
1079
+ resource: effectiveResource
994
1080
  });
995
- }, $[0] = instance, $[1] = t0) : t0 = $[1], t0;
1081
+ }, $[0] = contextResource, $[1] = instance, $[2] = resources, $[3] = t0) : t0 = $[3], t0;
996
1082
  }, useDocumentValue = createStateSourceHook({
997
1083
  // Pass options directly to getDocumentState
998
1084
  getState: (instance, options) => getDocumentState(instance, options),
@@ -1002,8 +1088,7 @@ const useDatasets = createStateSourceHook({
1002
1088
  ...options
1003
1089
  }) => getDocumentState(instance, options).getCurrent() === void 0,
1004
1090
  // Extract handle part for resolveDocument
1005
- suspender: (instance, options) => resolveDocument(instance, options),
1006
- getConfig: identity
1091
+ suspender: (instance, options) => resolveDocument(instance, options)
1007
1092
  }), wrapHookWithData = (useValue) => {
1008
1093
  function useHook(...params) {
1009
1094
  return {
@@ -1011,14 +1096,17 @@ const useDatasets = createStateSourceHook({
1011
1096
  };
1012
1097
  }
1013
1098
  return useHook;
1014
- }, useDocument = wrapHookWithData(useDocumentValue);
1099
+ }, useDocument = wrapHookWithData((options) => {
1100
+ const normalizedOptions = useNormalizedResourceOptions(options);
1101
+ return useDocumentValue(normalizedOptions);
1102
+ });
1015
1103
  function useDocumentEvent(options) {
1016
- const $ = c(9);
1104
+ const $ = c(10), normalizedOptions = useNormalizedResourceOptions(options);
1017
1105
  let datasetHandle, onEvent;
1018
- $[0] !== options ? ({
1106
+ $[0] !== normalizedOptions ? ({
1019
1107
  onEvent,
1020
1108
  ...datasetHandle
1021
- } = options, $[0] = options, $[1] = datasetHandle, $[2] = onEvent) : (datasetHandle = $[1], onEvent = $[2]);
1109
+ } = normalizedOptions, $[0] = normalizedOptions, $[1] = datasetHandle, $[2] = onEvent) : (datasetHandle = $[1], onEvent = $[2]);
1022
1110
  const ref = useRef(onEvent);
1023
1111
  let t0;
1024
1112
  $[3] !== onEvent ? (t0 = () => {
@@ -1026,58 +1114,42 @@ function useDocumentEvent(options) {
1026
1114
  }, $[3] = onEvent, $[4] = t0) : t0 = $[4], useInsertionEffect(t0);
1027
1115
  let t1;
1028
1116
  $[5] === Symbol.for("react.memo_cache_sentinel") ? (t1 = (documentEvent) => ref.current(documentEvent), $[5] = t1) : t1 = $[5];
1029
- const stableHandler = t1, instance = useSanityInstance(datasetHandle);
1117
+ const stableHandler = t1, instance = useSanityInstance();
1030
1118
  let t2, t3;
1031
- $[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);
1032
1123
  }
1033
1124
  function useDocumentPermissions(actionOrActions) {
1034
- const $ = c(13);
1035
- let t0, t1;
1036
- $[0] !== actionOrActions ? (t1 = Array.isArray(actionOrActions) ? actionOrActions : [actionOrActions], $[0] = actionOrActions, $[1] = t1) : t1 = $[1], t0 = t1;
1037
- const actions = t0;
1038
- let projectId, dataset;
1039
- if ($[2] !== actions || $[3] !== dataset || $[4] !== projectId) {
1040
- for (const action of actions)
1041
- if (action.projectId) {
1042
- if (projectId || (projectId = action.projectId), action.projectId !== projectId)
1043
- throw new Error(`Mismatched project IDs found in actions. All actions must belong to the same project. Found "${action.projectId}" but expected "${projectId}".`);
1044
- if (action.dataset && (dataset || (dataset = action.dataset), action.dataset !== dataset))
1045
- throw new Error(`Mismatched datasets found in actions. All actions must belong to the same dataset. Found "${action.dataset}" but expected "${dataset}".`);
1046
- }
1047
- $[2] = actions, $[3] = dataset, $[4] = projectId, $[5] = projectId, $[6] = dataset;
1048
- } else
1049
- projectId = $[5], dataset = $[6];
1050
- let t2;
1051
- $[7] !== dataset || $[8] !== projectId ? (t2 = {
1052
- projectId,
1053
- dataset
1054
- }, $[7] = dataset, $[8] = projectId, $[9] = t2) : t2 = $[9];
1055
- const instance = useSanityInstance(t2);
1056
- if (getPermissionsState(instance, {
1057
- actions
1058
- }).getCurrent() === void 0)
1059
- throw firstValueFrom(getPermissionsState(instance, {
1060
- actions
1061
- }).observable.pipe(filter(_temp$2)));
1062
- let t3, t4;
1063
- $[10] !== actions || $[11] !== instance ? (t4 = getPermissionsState(instance, {
1064
- actions
1065
- }), $[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)));
1066
1139
  const {
1067
1140
  subscribe,
1068
1141
  getCurrent
1069
- } = t3;
1142
+ } = useMemo(() => getPermissionsState(instance, permissionsOptions), [permissionsOptions, instance]);
1070
1143
  return useSyncExternalStore(subscribe, getCurrent);
1071
1144
  }
1072
- function _temp$2(result) {
1073
- return result !== void 0;
1074
- }
1075
- const useDocumentSyncStatus = createStateSourceHook({
1145
+ const useDocumentSyncStatusValue = createStateSourceHook({
1076
1146
  getState: getDocumentSyncStatus,
1077
1147
  shouldSuspend: (instance, doc) => getDocumentSyncStatus(instance, doc).getCurrent() === void 0,
1078
- suspender: (instance, doc) => resolveDocument(instance, doc),
1079
- getConfig: identity
1080
- }), 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"];
1081
1153
  function useEditDocument(t0) {
1082
1154
  const $ = c(8);
1083
1155
  let doc, path;
@@ -1085,25 +1157,25 @@ function useEditDocument(t0) {
1085
1157
  path,
1086
1158
  ...doc
1087
1159
  } = t0, $[0] = t0, $[1] = doc, $[2] = path) : (doc = $[1], path = $[2]);
1088
- const instance = useSanityInstance(doc), apply = useApplyDocumentActions();
1089
- if (getDocumentState(instance, doc).getCurrent() === void 0)
1090
- 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);
1091
1163
  let t1;
1092
- return $[3] !== apply || $[4] !== doc || $[5] !== instance || $[6] !== path ? (t1 = (updater) => {
1164
+ return $[3] !== apply || $[4] !== instance || $[5] !== normalizedDoc || $[6] !== path ? (t1 = (updater) => {
1093
1165
  const currentPath = path;
1094
1166
  if (currentPath) {
1095
1167
  const currentValue = getDocumentState(instance, {
1096
- ...doc,
1168
+ ...normalizedDoc,
1097
1169
  path
1098
1170
  }).getCurrent(), nextValue = typeof updater == "function" ? updater(currentValue) : updater;
1099
- return apply(editDocument(doc, {
1171
+ return apply(editDocument(normalizedDoc, {
1100
1172
  set: {
1101
1173
  [currentPath]: nextValue
1102
1174
  }
1103
1175
  }));
1104
1176
  }
1105
1177
  const current = getDocumentState(instance, {
1106
- ...doc,
1178
+ ...normalizedDoc,
1107
1179
  path
1108
1180
  }).getCurrent(), nextValue_0 = typeof updater == "function" ? updater(current) : updater;
1109
1181
  if (typeof nextValue_0 != "object" || !nextValue_0)
@@ -1111,21 +1183,21 @@ function useEditDocument(t0) {
1111
1183
  const editActions = Object.keys({
1112
1184
  ...current,
1113
1185
  ...nextValue_0
1114
- }).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, {
1115
1187
  set: {
1116
1188
  [key_1]: nextValue_0[key_1]
1117
1189
  }
1118
- }) : editDocument(doc, {
1190
+ }) : editDocument(normalizedDoc, {
1119
1191
  unset: [key_1]
1120
1192
  }));
1121
1193
  return apply(editActions);
1122
- }, $[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;
1123
1195
  }
1124
1196
  function _temp$1(key) {
1125
1197
  return !ignoredKeys.includes(key);
1126
1198
  }
1127
1199
  function useQuery(options) {
1128
- 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());
1129
1201
  useEffect(() => {
1130
1202
  queryKey !== deferredQueryKey && startTransition(() => {
1131
1203
  ref && !ref.current.signal.aborted && (ref.current.abort(), ref.current = new AbortController()), setDeferredQueryKey(queryKey);
@@ -1159,9 +1231,9 @@ function useDocuments({
1159
1231
  filter: filter2,
1160
1232
  orderings,
1161
1233
  documentType,
1162
- ...options
1234
+ ...rawOptions
1163
1235
  }) {
1164
- 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({
1165
1237
  filter: filter2,
1166
1238
  search,
1167
1239
  params,
@@ -1191,10 +1263,8 @@ function useDocuments({
1191
1263
  query: `{"count":${countQuery},"data":${dataQuery}}`,
1192
1264
  params: {
1193
1265
  ...params,
1194
- __handle: {
1195
- ...pick(instance.config, "projectId", "dataset", "perspective"),
1196
- ...pick(options, "projectId", "dataset", "perspective")
1197
- },
1266
+ // these are passed back to the user as part of each document handle
1267
+ __handle: pick(options, ["resource", "perspective"]),
1198
1268
  __types: documentTypes
1199
1269
  }
1200
1270
  }), hasMore = data.length < count, loadMore = useCallback(() => {
@@ -1209,8 +1279,8 @@ function useDocuments({
1209
1279
  }), [count, data, hasMore, isPending, loadMore]);
1210
1280
  }
1211
1281
  function usePaginatedDocuments(t0) {
1212
- const $ = c(62);
1213
- let documentType, options, orderings, search, t1, t2, t3;
1282
+ const $ = c(58);
1283
+ let documentType, orderings, rawOptions, search, t1, t2, t3;
1214
1284
  $[0] !== t0 ? ({
1215
1285
  documentType,
1216
1286
  filter: t1,
@@ -1218,32 +1288,33 @@ function usePaginatedDocuments(t0) {
1218
1288
  params: t3,
1219
1289
  orderings,
1220
1290
  search,
1221
- ...options
1222
- } = 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]);
1223
1293
  const filter2 = t1 === void 0 ? "" : t1, pageSize = t2 === void 0 ? 25 : t2;
1224
1294
  let t4;
1225
1295
  $[8] !== t3 ? (t4 = t3 === void 0 ? {} : t3, $[8] = t3, $[9] = t4) : t4 = $[9];
1226
- const params = t4, instance = useSanityInstance(options), [pageIndex, setPageIndex] = useState(0);
1296
+ const params = t4, options = useNormalizedResourceOptions(rawOptions), [pageIndex, setPageIndex] = useState(0);
1227
1297
  let t5;
1228
- $[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({
1229
1299
  filter: filter2,
1230
1300
  search,
1231
1301
  params,
1232
1302
  orderings,
1233
- pageSize
1234
- }), $[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];
1235
1306
  const key = t5;
1236
1307
  let t6;
1237
- $[16] === Symbol.for("react.memo_cache_sentinel") ? (t6 = () => {
1308
+ $[17] === Symbol.for("react.memo_cache_sentinel") ? (t6 = () => {
1238
1309
  setPageIndex(0);
1239
- }, $[16] = t6) : t6 = $[16];
1310
+ }, $[17] = t6) : t6 = $[17];
1240
1311
  let t7;
1241
- $[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);
1242
1313
  const startIndex = pageIndex * pageSize, endIndex = (pageIndex + 1) * pageSize;
1243
1314
  let t8;
1244
- $[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];
1245
1316
  let t9;
1246
- $[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];
1247
1318
  const documentTypes = t9;
1248
1319
  let t10;
1249
1320
  const conditions = [], trimmedSearch = search?.trim();
@@ -1254,52 +1325,45 @@ function usePaginatedDocuments(t0) {
1254
1325
  documentTypes?.length && conditions.push("(_type in $__types)"), filter2 && conditions.push(`(${filter2})`), t10 = conditions.length ? `[${conditions.join(" && ")}]` : "";
1255
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}}`;
1256
1327
  let t12;
1257
- $[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];
1258
1329
  let t13;
1259
- $[25] !== options ? (t13 = pick(options, "projectId", "dataset", "perspective"), $[25] = options, $[26] = t13) : t13 = $[26];
1260
- let t14;
1261
- $[27] !== t12 || $[28] !== t13 ? (t14 = {
1262
- ...t12,
1263
- ...t13
1264
- }, $[27] = t12, $[28] = t13, $[29] = t14) : t14 = $[29];
1265
- let t15;
1266
- $[30] !== documentTypes || $[31] !== params || $[32] !== t14 ? (t15 = {
1330
+ $[26] !== documentTypes || $[27] !== params || $[28] !== t12 ? (t13 = {
1267
1331
  ...params,
1268
1332
  __types: documentTypes,
1269
- __handle: t14
1270
- }, $[30] = documentTypes, $[31] = params, $[32] = t14, $[33] = t15) : t15 = $[33];
1271
- let t16;
1272
- $[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 = {
1273
1337
  ...options,
1274
1338
  query: t11,
1275
- params: t15
1276
- }, $[34] = options, $[35] = t11, $[36] = t15, $[37] = t16) : t16 = $[37];
1339
+ params: t13
1340
+ }, $[30] = options, $[31] = t11, $[32] = t13, $[33] = t14) : t14 = $[33];
1277
1341
  const {
1278
- data: t17,
1342
+ data: t15,
1279
1343
  isPending
1280
- } = useQuery(t16), {
1344
+ } = useQuery(t14), {
1281
1345
  data,
1282
1346
  count
1283
- } = 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;
1284
1354
  let t18;
1285
- $[38] === Symbol.for("react.memo_cache_sentinel") ? (t18 = () => setPageIndex(0), $[38] = t18) : t18 = $[38];
1286
- 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;
1287
1357
  let t19;
1288
- $[39] === Symbol.for("react.memo_cache_sentinel") ? (t19 = () => setPageIndex(_temp4), $[39] = t19) : t19 = $[39];
1289
- const previousPage = t19;
1358
+ $[38] !== totalPages ? (t19 = () => setPageIndex(totalPages - 1), $[38] = totalPages, $[39] = t19) : t19 = $[39];
1359
+ const lastPage = t19;
1290
1360
  let t20;
1291
- $[40] !== totalPages ? (t20 = () => setPageIndex((prev_0) => Math.min(prev_0 + 1, totalPages - 1)), $[40] = totalPages, $[41] = t20) : t20 = $[41];
1292
- const nextPage = t20;
1293
- let t21;
1294
- $[42] !== totalPages ? (t21 = () => setPageIndex(totalPages - 1), $[42] = totalPages, $[43] = t21) : t21 = $[43];
1295
- const lastPage = t21;
1296
- let t22;
1297
- $[44] !== totalPages ? (t22 = (pageNumber) => {
1361
+ $[40] !== totalPages ? (t20 = (pageNumber) => {
1298
1362
  pageNumber < 1 || pageNumber > totalPages || setPageIndex(pageNumber - 1);
1299
- }, $[44] = totalPages, $[45] = t22) : t22 = $[45];
1300
- const goToPage = t22, hasFirstPage = pageIndex > 0, hasPreviousPage = pageIndex > 0, hasNextPage = pageIndex < totalPages - 1, hasLastPage = pageIndex < totalPages - 1;
1301
- let t23;
1302
- 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 = {
1303
1367
  data,
1304
1368
  isPending,
1305
1369
  pageSize,
@@ -1317,7 +1381,7 @@ function usePaginatedDocuments(t0) {
1317
1381
  lastPage,
1318
1382
  hasLastPage,
1319
1383
  goToPage
1320
- }, $[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;
1321
1385
  }
1322
1386
  function _temp4(prev) {
1323
1387
  return Math.max(prev - 1, 0);
@@ -1331,70 +1395,39 @@ function _temp2(str) {
1331
1395
  function _temp(i) {
1332
1396
  return typeof i == "string";
1333
1397
  }
1334
- function usePresence() {
1335
- const $ = c(11), sanityInstance = useSanityInstance();
1336
- let t0, t1;
1337
- $[0] !== sanityInstance ? (t1 = getPresence(sanityInstance), $[0] = sanityInstance, $[1] = t1) : t1 = $[1], t0 = t1;
1338
- const source = t0;
1339
- let t2;
1340
- $[2] !== source ? (t2 = (callback) => source.subscribe(callback), $[2] = source, $[3] = t2) : t2 = $[3];
1341
- const subscribe = t2;
1342
- let t3, t4;
1343
- $[4] !== source ? (t3 = () => source.getCurrent(), t4 = () => source.getCurrent(), $[4] = source, $[5] = t3, $[6] = t4) : (t3 = $[5], t4 = $[6]);
1344
- const locations = useSyncExternalStore(subscribe, t3, t4);
1345
- let t5;
1346
- $[7] !== locations ? (t5 = locations || [], $[7] = locations, $[8] = t5) : t5 = $[8];
1347
- let t6;
1348
- return $[9] !== t5 ? (t6 = {
1349
- locations: t5
1350
- }, $[9] = t5, $[10] = t6) : t6 = $[10], t6;
1351
- }
1352
- function useDocumentPreview(t0) {
1353
- const $ = c(13);
1354
- let docHandle, ref;
1355
- $[0] !== t0 ? ({
1356
- ref,
1357
- ...docHandle
1358
- } = t0, $[0] = t0, $[1] = docHandle, $[2] = ref) : (docHandle = $[1], ref = $[2]);
1359
- const instance = useSanityInstance(docHandle);
1398
+ function usePresence(t0) {
1399
+ const $ = c(14);
1360
1400
  let t1;
1361
- $[3] !== docHandle || $[4] !== instance ? (t1 = getPreviewState(instance, docHandle), $[3] = docHandle, $[4] = instance, $[5] = t1) : t1 = $[5];
1362
- const stateSource = t1;
1363
- let t2;
1364
- $[6] !== ref || $[7] !== stateSource ? (t2 = (onStoreChanged) => {
1365
- const subscription = new Observable((observer) => {
1366
- if (typeof IntersectionObserver > "u" || typeof HTMLElement > "u") {
1367
- observer.next(!0);
1368
- return;
1369
- }
1370
- const intersectionObserver = new IntersectionObserver((t32) => {
1371
- const [entry] = t32;
1372
- return observer.next(entry.isIntersecting);
1373
- }, {
1374
- rootMargin: "0px",
1375
- threshold: 0
1376
- });
1377
- return ref?.current && ref.current instanceof HTMLElement ? intersectionObserver.observe(ref.current) : observer.next(!0), () => intersectionObserver.disconnect();
1378
- }).pipe(startWith(!1), distinctUntilChanged(), switchMap((isVisible) => isVisible ? new Observable((obs) => stateSource.subscribe(() => obs.next())) : EMPTY)).subscribe({
1379
- next: onStoreChanged
1380
- });
1381
- return () => subscription.unsubscribe();
1382
- }, $[6] = ref, $[7] = stateSource, $[8] = t2) : t2 = $[8];
1383
- const subscribe = t2;
1384
- let t3;
1385
- return $[9] !== docHandle || $[10] !== instance || $[11] !== stateSource ? (t3 = () => {
1386
- const currentState = stateSource.getCurrent();
1387
- if (currentState.data === null)
1388
- throw resolvePreview(instance, docHandle);
1389
- return currentState;
1390
- }, $[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;
1391
1424
  }
1392
1425
  function useDocumentProjection({
1393
1426
  ref,
1394
1427
  projection,
1395
1428
  ...docHandle
1396
1429
  }) {
1397
- 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, {
1398
1431
  ...normalizedDocHandle,
1399
1432
  projection: normalizedProjection
1400
1433
  }), [instance, normalizedDocHandle, normalizedProjection]);
@@ -1421,27 +1454,62 @@ function useDocumentProjection({
1421
1454
  }, [stateSource, ref]);
1422
1455
  return useSyncExternalStore(subscribe, stateSource.getCurrent);
1423
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
+ }
1424
1481
  const useProject = createStateSourceHook({
1425
1482
  // remove `undefined` since we're suspending when that is the case
1426
1483
  getState: getProjectState,
1427
1484
  shouldSuspend: (instance, projectHandle) => getProjectState(instance, projectHandle).getCurrent() === void 0,
1428
- suspender: resolveProject,
1429
- getConfig: identity
1485
+ suspender: (instance, projectHandle) => resolveProject(instance, projectHandle)
1430
1486
  }), useProjects = createStateSourceHook({
1431
1487
  getState: getProjectsState,
1432
1488
  shouldSuspend: (instance, options) => getProjectsState(instance, options).getCurrent() === void 0,
1433
1489
  suspender: resolveProjects
1434
- }), useActiveReleases = createStateSourceHook({
1490
+ }), useActiveReleasesValue = createStateSourceHook({
1435
1491
  getState: getActiveReleasesState,
1436
- shouldSuspend: (instance) => getActiveReleasesState(instance).getCurrent() === void 0,
1437
- suspender: (instance) => firstValueFrom(getActiveReleasesState(instance).observable.pipe(filter(Boolean)))
1438
- }), 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({
1439
1501
  getState: getPerspectiveState,
1440
1502
  shouldSuspend: (instance, options) => getPerspectiveState(instance, options).getCurrent() === void 0,
1441
- suspender: (instance, _options) => firstValueFrom(getActiveReleasesState(instance).observable.pipe(filter(Boolean)))
1442
- });
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
+ };
1443
1511
  function useUser(options) {
1444
- 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());
1445
1513
  useEffect(() => {
1446
1514
  key !== deferredKey && startTransition(() => {
1447
1515
  ref.signal.aborted || (ref.abort(), setRef(new AbortController())), setDeferredKey(key);
@@ -1462,7 +1530,7 @@ function useUser(options) {
1462
1530
  };
1463
1531
  }
1464
1532
  function useUsers(options) {
1465
- 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());
1466
1534
  useEffect(() => {
1467
1535
  key !== deferredKey && startTransition(() => {
1468
1536
  ref.signal.aborted || (ref.abort(), setRef(new AbortController())), setDeferredKey(key);
@@ -1490,7 +1558,7 @@ function useUsers(options) {
1490
1558
  loadMore
1491
1559
  };
1492
1560
  }
1493
- var version = "2.8.0";
1561
+ var version = "3.0.0-rc.0";
1494
1562
  function getEnv(key) {
1495
1563
  if (typeof import.meta < "u" && import.meta.env)
1496
1564
  return import.meta.env[key];
@@ -1546,6 +1614,7 @@ export {
1546
1614
  useProjects,
1547
1615
  useQuery,
1548
1616
  useRecordDocumentHistoryEvent,
1617
+ useResource,
1549
1618
  useSanityInstance,
1550
1619
  useStudioWorkspacesByProjectIdDataset,
1551
1620
  useUser,