@sanity/sdk-react 0.0.0-alpha.27 → 0.0.0-alpha.29

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,5 +1,1022 @@
1
- import { AuthBoundary, REACT_SDK_VERSION, ResourceProvider, SDKProvider, SanityApp, useApplyDocumentActions, useAuthState, useAuthToken, useClient, useCurrentUser, useDashboardOrganizationId, useDatasets, useDocument, useDocumentEvent, useDocumentPermissions, useDocumentSyncStatus, useDocuments, useEditDocument, useFrameConnection, useHandleAuthCallback, useLogOut, useLoginUrl, useManageFavorite, useNavigateToStudioDocument, usePaginatedDocuments, usePreview, useProject, useProjection, useProjects, useQuery, useRecordDocumentHistoryEvent, useSanityInstance, useStudioWorkspacesByProjectIdDataset, useUsers, useWindowConnection } from "./_chunks-es/index.js";
1
+ import { jsxs, jsx, Fragment } from "react/jsx-runtime";
2
+ import { c } from "react-compiler-runtime";
3
+ import { getAuthState, getLoginUrlState, handleAuthCallback, logout, AuthStateType, createSanityInstance, getTokenState, getCurrentUserState, getDashboardOrganizationId, getClientState, getOrCreateController, getOrCreateChannel, releaseChannel, getOrCreateNode, releaseNode, resolveDatasets, getDatasetsState, applyDocumentActions, resolveDocument, getDocumentState, subscribeDocumentEvents, getPermissionsState, getDocumentSyncStatus, editDocument, getQueryKey, parseQueryKey, getQueryState, resolveQuery, createGroqSearchFilter, getPreviewState, resolvePreview, getProjectionState, resolveProjection, resolveProject, getProjectState, resolveProjects, getProjectsState, getUsersKey, parseUsersKey, getUsersState, resolveUsers, loadMoreUsers } from "@sanity/sdk";
2
4
  export * from "@sanity/sdk";
5
+ import { createContext, useContext, useSyncExternalStore, useEffect, useState, useRef, Suspense, useInsertionEffect, useTransition, useMemo, useCallback } from "react";
6
+ import { ErrorBoundary } from "react-error-boundary";
7
+ import { ClientError } from "@sanity/client";
8
+ import { identity, firstValueFrom, filter, Observable, startWith, distinctUntilChanged, switchMap, EMPTY } from "rxjs";
9
+ import { SDK_CHANNEL_NAME, SDK_NODE_NAME } from "@sanity/message-protocol";
10
+ import { pick } from "lodash-es";
11
+ const SanityInstanceContext = createContext(null), useSanityInstance = (config) => {
12
+ const $ = c(3), instance = useContext(SanityInstanceContext);
13
+ if (!instance)
14
+ 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>.`);
15
+ if (!config)
16
+ return instance;
17
+ let t0;
18
+ $[0] !== config || $[1] !== instance ? (t0 = instance.match(config), $[0] = config, $[1] = instance, $[2] = t0) : t0 = $[2];
19
+ const match = t0;
20
+ if (!match)
21
+ throw new Error(`Could not find a matching Sanity instance for the requested configuration: ${JSON.stringify(config, null, 2)}.
22
+ Please ensure there is a <ResourceProvider> with a matching configuration in the component hierarchy.`);
23
+ return match;
24
+ };
25
+ function createStateSourceHook(options) {
26
+ 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;
27
+ function useHook(...t0) {
28
+ const $ = c(5), params = t0;
29
+ let t1;
30
+ $[0] !== params ? (t1 = getConfig?.(...params), $[0] = params, $[1] = t1) : t1 = $[1];
31
+ const instance = useSanityInstance(t1);
32
+ if (suspense?.suspender && suspense?.shouldSuspend?.(instance, ...params))
33
+ throw suspense.suspender(instance, ...params);
34
+ let t2;
35
+ $[2] !== instance || $[3] !== params ? (t2 = getState(instance, ...params), $[2] = instance, $[3] = params, $[4] = t2) : t2 = $[4];
36
+ const state = t2;
37
+ return useSyncExternalStore(state.subscribe, state.getCurrent);
38
+ }
39
+ return useHook;
40
+ }
41
+ const useAuthState = createStateSourceHook(getAuthState);
42
+ function useLoginUrl() {
43
+ const $ = c(2), instance = useSanityInstance();
44
+ let t0, t1;
45
+ $[0] !== instance ? (t1 = getLoginUrlState(instance), $[0] = instance, $[1] = t1) : t1 = $[1], t0 = t1;
46
+ const {
47
+ subscribe,
48
+ getCurrent
49
+ } = t0;
50
+ return useSyncExternalStore(subscribe, getCurrent);
51
+ }
52
+ function isInIframe() {
53
+ return typeof window < "u" && window.self !== window.top;
54
+ }
55
+ function isLocalUrl(window2) {
56
+ const url = typeof window2 < "u" ? window2.location.href : "";
57
+ return url.startsWith("http://localhost") || url.startsWith("https://localhost") || url.startsWith("http://127.0.0.1") || url.startsWith("https://127.0.0.1");
58
+ }
59
+ class AuthError extends Error {
60
+ constructor(error) {
61
+ typeof error == "object" && error && "message" in error && typeof error.message == "string" ? super(error.message) : super(), this.cause = error;
62
+ }
63
+ }
64
+ function createCallbackHook(callback) {
65
+ function useHook() {
66
+ const $ = c(2), instance = useSanityInstance();
67
+ let t0;
68
+ return $[0] !== instance ? (t0 = (...t1) => callback(instance, ...t1), $[0] = instance, $[1] = t0) : t0 = $[1], t0;
69
+ }
70
+ return useHook;
71
+ }
72
+ const useHandleAuthCallback = createCallbackHook(handleAuthCallback);
73
+ function LoginCallback() {
74
+ const $ = c(3), handleAuthCallback2 = useHandleAuthCallback();
75
+ let t0, t1;
76
+ return $[0] !== handleAuthCallback2 ? (t0 = () => {
77
+ const url = new URL(location.href);
78
+ handleAuthCallback2(url.toString()).then(_temp$7);
79
+ }, t1 = [handleAuthCallback2], $[0] = handleAuthCallback2, $[1] = t0, $[2] = t1) : (t0 = $[1], t1 = $[2]), useEffect(t0, t1), null;
80
+ }
81
+ function _temp$7(replacementLocation) {
82
+ replacementLocation && history.replaceState(null, "", replacementLocation);
83
+ }
84
+ const useLogOut = createCallbackHook(logout);
85
+ function LoginError(t0) {
86
+ const $ = c(18), {
87
+ error,
88
+ resetErrorBoundary
89
+ } = t0;
90
+ if (!(error instanceof AuthError))
91
+ throw error;
92
+ const logout2 = useLogOut(), authState = useAuthState(), [authErrorMessage, setAuthErrorMessage] = useState("Please try again or contact support if the problem persists.");
93
+ let t1;
94
+ $[0] !== logout2 || $[1] !== resetErrorBoundary ? (t1 = async () => {
95
+ await logout2(), resetErrorBoundary();
96
+ }, $[0] = logout2, $[1] = resetErrorBoundary, $[2] = t1) : t1 = $[2];
97
+ const handleRetry = t1;
98
+ let t2;
99
+ $[3] !== authState.error || $[4] !== authState.type || $[5] !== handleRetry ? (t2 = () => {
100
+ if (authState.type === AuthStateType.ERROR && authState.error instanceof ClientError) {
101
+ if (authState.error.statusCode === 401)
102
+ handleRetry();
103
+ else if (authState.error.statusCode === 404) {
104
+ const errorMessage = authState.error.response.body.message || "";
105
+ errorMessage.startsWith("Session with sid") && errorMessage.endsWith("not found") ? setAuthErrorMessage("The session ID is invalid or expired.") : setAuthErrorMessage("The login link is invalid or expired. Please try again.");
106
+ }
107
+ }
108
+ }, $[3] = authState.error, $[4] = authState.type, $[5] = handleRetry, $[6] = t2) : t2 = $[6];
109
+ let t3;
110
+ $[7] !== authState || $[8] !== handleRetry ? (t3 = [authState, handleRetry], $[7] = authState, $[8] = handleRetry, $[9] = t3) : t3 = $[9], useEffect(t2, t3);
111
+ let t4;
112
+ $[10] === Symbol.for("react.memo_cache_sentinel") ? (t4 = /* @__PURE__ */ jsx("h2", { className: "sc-login-error__title", children: "Authentication Error" }), $[10] = t4) : t4 = $[10];
113
+ let t5;
114
+ $[11] !== authErrorMessage ? (t5 = /* @__PURE__ */ jsxs("div", { className: "sc-login-error__content", children: [
115
+ t4,
116
+ /* @__PURE__ */ jsx("p", { className: "sc-login-error__description", children: authErrorMessage })
117
+ ] }), $[11] = authErrorMessage, $[12] = t5) : t5 = $[12];
118
+ let t6;
119
+ $[13] !== handleRetry ? (t6 = /* @__PURE__ */ jsx("button", { className: "sc-login-error__button", onClick: handleRetry, children: "Retry" }), $[13] = handleRetry, $[14] = t6) : t6 = $[14];
120
+ let t7;
121
+ return $[15] !== t5 || $[16] !== t6 ? (t7 = /* @__PURE__ */ jsxs("div", { className: "sc-login-error", children: [
122
+ t5,
123
+ t6
124
+ ] }), $[15] = t5, $[16] = t6, $[17] = t7) : t7 = $[17], t7;
125
+ }
126
+ if (isInIframe() && !document.querySelector("[data-sanity-core]")) {
127
+ const parsedUrl = new URL(window.location.href), mode = new URLSearchParams(parsedUrl.hash.slice(1)).get("mode"), script = document.createElement("script");
128
+ script.src = mode === "core-ui--staging" ? "https://core.sanity-cdn.work/bridge.js" : "https://core.sanity-cdn.com/bridge.js", script.type = "module", script.async = !0, document.head.appendChild(script);
129
+ }
130
+ function AuthBoundary(t0) {
131
+ const $ = c(10);
132
+ let props, t1;
133
+ $[0] !== t0 ? ({
134
+ LoginErrorComponent: t1,
135
+ ...props
136
+ } = t0, $[0] = t0, $[1] = props, $[2] = t1) : (props = $[1], t1 = $[2]);
137
+ const LoginErrorComponent = t1 === void 0 ? LoginError : t1;
138
+ let t2, t3;
139
+ $[3] !== LoginErrorComponent ? (t3 = function(fallbackProps) {
140
+ return /* @__PURE__ */ jsx(LoginErrorComponent, { ...fallbackProps });
141
+ }, $[3] = LoginErrorComponent, $[4] = t3) : t3 = $[4], t2 = t3;
142
+ const FallbackComponent = t2;
143
+ let t4;
144
+ $[5] !== props ? (t4 = /* @__PURE__ */ jsx(AuthSwitch, { ...props }), $[5] = props, $[6] = t4) : t4 = $[6];
145
+ let t5;
146
+ return $[7] !== FallbackComponent || $[8] !== t4 ? (t5 = /* @__PURE__ */ jsx(ErrorBoundary, { FallbackComponent, children: t4 }), $[7] = FallbackComponent, $[8] = t4, $[9] = t5) : t5 = $[9], t5;
147
+ }
148
+ function AuthSwitch(t0) {
149
+ const $ = c(11);
150
+ let children, props, t1;
151
+ $[0] !== t0 ? ({
152
+ CallbackComponent: t1,
153
+ children,
154
+ ...props
155
+ } = t0, $[0] = t0, $[1] = children, $[2] = props, $[3] = t1) : (children = $[1], props = $[2], t1 = $[3]);
156
+ const CallbackComponent = t1 === void 0 ? LoginCallback : t1, authState = useAuthState(), isLoggedOut = authState.type === AuthStateType.LOGGED_OUT && !authState.isDestroyingSession, loginUrl = useLoginUrl();
157
+ let t2, t3;
158
+ switch ($[4] !== isLoggedOut || $[5] !== loginUrl ? (t2 = () => {
159
+ isLoggedOut && !isInIframe() && (window.location.href = loginUrl);
160
+ }, t3 = [isLoggedOut, loginUrl], $[4] = isLoggedOut, $[5] = loginUrl, $[6] = t2, $[7] = t3) : (t2 = $[6], t3 = $[7]), useEffect(t2, t3), authState.type) {
161
+ case AuthStateType.ERROR:
162
+ throw new AuthError(authState.error);
163
+ case AuthStateType.LOGGING_IN: {
164
+ let t4;
165
+ return $[8] !== CallbackComponent || $[9] !== props ? (t4 = /* @__PURE__ */ jsx(CallbackComponent, { ...props }), $[8] = CallbackComponent, $[9] = props, $[10] = t4) : t4 = $[10], t4;
166
+ }
167
+ case AuthStateType.LOGGED_IN:
168
+ return children;
169
+ case AuthStateType.LOGGED_OUT:
170
+ return null;
171
+ default:
172
+ throw new Error(`Invalid auth state: ${authState.type}`);
173
+ }
174
+ }
175
+ const DEFAULT_FALLBACK = /* @__PURE__ */ jsx(Fragment, { children: "Warning: No fallback provided. Please supply a fallback prop to ensure proper Suspense handling." });
176
+ function ResourceProvider(t0) {
177
+ const $ = c(16);
178
+ let children, config, fallback;
179
+ $[0] !== t0 ? ({
180
+ children,
181
+ fallback,
182
+ ...config
183
+ } = t0, $[0] = t0, $[1] = children, $[2] = config, $[3] = fallback) : (children = $[1], config = $[2], fallback = $[3]);
184
+ const parent = useContext(SanityInstanceContext);
185
+ let t1, t2;
186
+ $[4] !== config || $[5] !== parent ? (t2 = parent ? parent.createChild(config) : createSanityInstance(config), $[4] = config, $[5] = parent, $[6] = t2) : t2 = $[6], t1 = t2;
187
+ const instance = t1, disposal = useRef(null);
188
+ let t3, t4;
189
+ $[7] !== instance ? (t3 = () => (disposal.current !== null && instance === disposal.current.instance && (clearTimeout(disposal.current.timeoutId), disposal.current = null), () => {
190
+ disposal.current = {
191
+ instance,
192
+ timeoutId: setTimeout(() => {
193
+ instance.isDisposed() || instance.dispose();
194
+ }, 0)
195
+ };
196
+ }), t4 = [instance], $[7] = instance, $[8] = t3, $[9] = t4) : (t3 = $[8], t4 = $[9]), useEffect(t3, t4);
197
+ const t5 = fallback ?? DEFAULT_FALLBACK;
198
+ let t6;
199
+ $[10] !== children || $[11] !== t5 ? (t6 = /* @__PURE__ */ jsx(Suspense, { fallback: t5, children }), $[10] = children, $[11] = t5, $[12] = t6) : t6 = $[12];
200
+ let t7;
201
+ return $[13] !== instance || $[14] !== t6 ? (t7 = /* @__PURE__ */ jsx(SanityInstanceContext.Provider, { value: instance, children: t6 }), $[13] = instance, $[14] = t6, $[15] = t7) : t7 = $[15], t7;
202
+ }
203
+ function SDKProvider({
204
+ children,
205
+ config,
206
+ fallback,
207
+ ...props
208
+ }) {
209
+ const configs = (Array.isArray(config) ? config : [config]).slice().reverse(), createNestedProviders = (index) => index >= configs.length ? /* @__PURE__ */ jsx(AuthBoundary, { ...props, children }) : /* @__PURE__ */ jsx(ResourceProvider, { ...configs[index], fallback, children: createNestedProviders(index + 1) });
210
+ return createNestedProviders(0);
211
+ }
212
+ const REDIRECT_URL = "https://sanity.io/welcome";
213
+ function SanityApp(t0) {
214
+ const $ = c(15);
215
+ let children, config, fallback, props, sanityConfigs;
216
+ $[0] !== t0 ? ({
217
+ children,
218
+ fallback,
219
+ config,
220
+ sanityConfigs,
221
+ ...props
222
+ } = t0, $[0] = t0, $[1] = children, $[2] = config, $[3] = fallback, $[4] = props, $[5] = sanityConfigs) : (children = $[1], config = $[2], fallback = $[3], props = $[4], sanityConfigs = $[5]);
223
+ let t1;
224
+ $[6] !== config || $[7] !== sanityConfigs ? (t1 = config ?? sanityConfigs ?? [], $[6] = config, $[7] = sanityConfigs, $[8] = t1) : t1 = $[8];
225
+ const configs = t1;
226
+ let t2;
227
+ $[9] === Symbol.for("react.memo_cache_sentinel") ? (t2 = [], $[9] = t2) : t2 = $[9], useEffect(_temp2$2, t2);
228
+ let t3;
229
+ return $[10] !== children || $[11] !== configs || $[12] !== fallback || $[13] !== props ? (t3 = /* @__PURE__ */ jsx(SDKProvider, { ...props, fallback, config: configs, children }), $[10] = children, $[11] = configs, $[12] = fallback, $[13] = props, $[14] = t3) : t3 = $[14], t3;
230
+ }
231
+ function _temp2$2() {
232
+ let timeout;
233
+ return !isInIframe() && !isLocalUrl(window) && (timeout = setTimeout(_temp$6, 1e3)), () => clearTimeout(timeout);
234
+ }
235
+ function _temp$6() {
236
+ console.warn("Redirecting to core", REDIRECT_URL), window.location.replace(REDIRECT_URL);
237
+ }
238
+ const useAuthToken = createStateSourceHook(getTokenState), useCurrentUser = createStateSourceHook(getCurrentUserState);
239
+ function useDashboardOrganizationId() {
240
+ const $ = c(2), instance = useSanityInstance();
241
+ let t0, t1;
242
+ $[0] !== instance ? (t1 = getDashboardOrganizationId(instance), $[0] = instance, $[1] = t1) : t1 = $[1], t0 = t1;
243
+ const {
244
+ subscribe,
245
+ getCurrent
246
+ } = t0;
247
+ return useSyncExternalStore(subscribe, getCurrent);
248
+ }
249
+ const useClient = createStateSourceHook({
250
+ getState: getClientState,
251
+ getConfig: identity
252
+ });
253
+ function useFrameConnection(options) {
254
+ const $ = c(12), {
255
+ onMessage,
256
+ targetOrigin,
257
+ name,
258
+ connectTo,
259
+ heartbeat,
260
+ onStatus
261
+ } = options, instance = useSanityInstance(), controllerRef = useRef(null), channelRef = useRef(null);
262
+ let t0, t1;
263
+ $[0] !== connectTo || $[1] !== heartbeat || $[2] !== instance || $[3] !== name || $[4] !== onMessage || $[5] !== onStatus || $[6] !== targetOrigin ? (t0 = () => {
264
+ const controller = getOrCreateController(instance, targetOrigin), channel = getOrCreateChannel(instance, {
265
+ name,
266
+ connectTo,
267
+ heartbeat
268
+ });
269
+ controllerRef.current = controller, channelRef.current = channel, channel.onStatus((event) => {
270
+ onStatus?.(event.status);
271
+ });
272
+ const messageUnsubscribers = [];
273
+ return onMessage && Object.entries(onMessage).forEach((t22) => {
274
+ const [type, handler] = t22, unsubscribe = channel.on(type, handler);
275
+ messageUnsubscribers.push(unsubscribe);
276
+ }), () => {
277
+ messageUnsubscribers.forEach(_temp$5), releaseChannel(instance, name), channelRef.current = null, controllerRef.current = null;
278
+ };
279
+ }, 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);
280
+ let t2;
281
+ $[9] === Symbol.for("react.memo_cache_sentinel") ? (t2 = (frameWindow) => {
282
+ const removeTarget = controllerRef.current?.addTarget(frameWindow);
283
+ return () => {
284
+ removeTarget?.();
285
+ };
286
+ }, $[9] = t2) : t2 = $[9];
287
+ const connect = t2;
288
+ let t3;
289
+ $[10] === Symbol.for("react.memo_cache_sentinel") ? (t3 = (type_0, data) => {
290
+ channelRef.current?.post(type_0, data);
291
+ }, $[10] = t3) : t3 = $[10];
292
+ const sendMessage = t3;
293
+ let t4;
294
+ return $[11] === Symbol.for("react.memo_cache_sentinel") ? (t4 = {
295
+ connect,
296
+ sendMessage
297
+ }, $[11] = t4) : t4 = $[11], t4;
298
+ }
299
+ function _temp$5(unsub) {
300
+ return unsub();
301
+ }
302
+ function useWindowConnection(t0) {
303
+ const $ = c(11), {
304
+ name,
305
+ connectTo,
306
+ onMessage,
307
+ onStatus
308
+ } = t0, nodeRef = useRef(null);
309
+ let t1;
310
+ $[0] === Symbol.for("react.memo_cache_sentinel") ? (t1 = [], $[0] = t1) : t1 = $[0];
311
+ const messageUnsubscribers = useRef(t1), instance = useSanityInstance();
312
+ let t2, t3;
313
+ $[1] !== connectTo || $[2] !== instance || $[3] !== name || $[4] !== onMessage || $[5] !== onStatus ? (t2 = () => {
314
+ const node = getOrCreateNode(instance, {
315
+ name,
316
+ connectTo
317
+ });
318
+ nodeRef.current = node;
319
+ const statusUnsubscribe = node.onStatus((eventStatus) => {
320
+ onStatus?.(eventStatus);
321
+ });
322
+ return onMessage && Object.entries(onMessage).forEach((t42) => {
323
+ const [type, handler] = t42, messageUnsubscribe = node.on(type, handler);
324
+ messageUnsubscribers.current.push(messageUnsubscribe);
325
+ }), () => {
326
+ statusUnsubscribe(), messageUnsubscribers.current.forEach(_temp$4), messageUnsubscribers.current = [], releaseNode(instance, name), nodeRef.current = null;
327
+ };
328
+ }, t3 = [instance, name, connectTo, onMessage, onStatus], $[1] = connectTo, $[2] = instance, $[3] = name, $[4] = onMessage, $[5] = onStatus, $[6] = t2, $[7] = t3) : (t2 = $[6], t3 = $[7]), useEffect(t2, t3);
329
+ let t4;
330
+ $[8] === Symbol.for("react.memo_cache_sentinel") ? (t4 = (type_0, data) => {
331
+ if (!nodeRef.current)
332
+ throw new Error("Cannot send message before connection is established");
333
+ nodeRef.current.post(type_0, data);
334
+ }, $[8] = t4) : t4 = $[8];
335
+ const sendMessage = t4;
336
+ let t5;
337
+ $[9] === Symbol.for("react.memo_cache_sentinel") ? (t5 = (type_1, data_0, fetchOptions) => nodeRef.current?.fetch(type_1, data_0, fetchOptions ?? {}), $[9] = t5) : t5 = $[9];
338
+ const fetch = t5;
339
+ let t6;
340
+ return $[10] === Symbol.for("react.memo_cache_sentinel") ? (t6 = {
341
+ sendMessage,
342
+ fetch
343
+ }, $[10] = t6) : t6 = $[10], t6;
344
+ }
345
+ function _temp$4(unsubscribe) {
346
+ return unsubscribe();
347
+ }
348
+ function useManageFavorite(t0) {
349
+ const $ = c(23), {
350
+ documentId,
351
+ documentType,
352
+ projectId: paramProjectId,
353
+ dataset: paramDataset,
354
+ resourceId: paramResourceId,
355
+ resourceType,
356
+ schemaName
357
+ } = t0, [isFavorited, setIsFavorited] = useState(!1), [status, setStatus] = useState("idle"), [resourceId, setResourceId] = useState(paramResourceId || "");
358
+ let t1;
359
+ $[0] === Symbol.for("react.memo_cache_sentinel") ? (t1 = {
360
+ name: SDK_NODE_NAME,
361
+ connectTo: SDK_CHANNEL_NAME,
362
+ onStatus: setStatus
363
+ }, $[0] = t1) : t1 = $[0];
364
+ const {
365
+ sendMessage
366
+ } = useWindowConnection(t1), instance = useSanityInstance(), {
367
+ config
368
+ } = instance, instanceProjectId = config?.projectId, instanceDataset = config?.dataset, projectId = paramProjectId ?? instanceProjectId, dataset = paramDataset ?? instanceDataset;
369
+ if (resourceType === "studio" && (!projectId || !dataset))
370
+ throw new Error("projectId and dataset are required for studio resources");
371
+ let t2, t3;
372
+ $[1] !== dataset || $[2] !== paramResourceId || $[3] !== projectId || $[4] !== resourceType ? (t2 = () => {
373
+ if (resourceType === "studio" && !paramResourceId)
374
+ setResourceId(`${projectId}.${dataset}`);
375
+ else if (paramResourceId)
376
+ setResourceId(paramResourceId);
377
+ else
378
+ throw new Error("resourceId is required for media-library and canvas resources");
379
+ }, t3 = [resourceType, paramResourceId, projectId, dataset], $[1] = dataset, $[2] = paramResourceId, $[3] = projectId, $[4] = resourceType, $[5] = t2, $[6] = t3) : (t2 = $[5], t3 = $[6]), useEffect(t2, t3);
380
+ let t4;
381
+ $[7] !== documentId || $[8] !== documentType || $[9] !== resourceId || $[10] !== resourceType || $[11] !== schemaName || $[12] !== sendMessage ? (t4 = (action, setFavoriteState) => {
382
+ if (!(!documentId || !documentType || !resourceType))
383
+ try {
384
+ const message = {
385
+ type: "dashboard/v1/events/favorite/mutate",
386
+ data: {
387
+ eventType: action,
388
+ document: {
389
+ id: documentId,
390
+ type: documentType,
391
+ resource: {
392
+ id: resourceId,
393
+ type: resourceType,
394
+ schemaName
395
+ }
396
+ }
397
+ },
398
+ response: {
399
+ success: !0
400
+ }
401
+ };
402
+ sendMessage(message.type, message.data), setIsFavorited(setFavoriteState);
403
+ } catch (t52) {
404
+ const err = t52, error = err instanceof Error ? err : new Error("Failed to update favorite status");
405
+ throw console.error(`Failed to ${action === "added" ? "favorite" : "unfavorite"} document:`, error), error;
406
+ }
407
+ }, $[7] = documentId, $[8] = documentType, $[9] = resourceId, $[10] = resourceType, $[11] = schemaName, $[12] = sendMessage, $[13] = t4) : t4 = $[13];
408
+ const handleFavoriteAction = t4;
409
+ let t5;
410
+ $[14] !== handleFavoriteAction ? (t5 = () => handleFavoriteAction("added", !0), $[14] = handleFavoriteAction, $[15] = t5) : t5 = $[15];
411
+ const favorite = t5;
412
+ let t6;
413
+ $[16] !== handleFavoriteAction ? (t6 = () => handleFavoriteAction("removed", !1), $[16] = handleFavoriteAction, $[17] = t6) : t6 = $[17];
414
+ const unfavorite = t6, t7 = status === "connected";
415
+ let t8;
416
+ return $[18] !== favorite || $[19] !== isFavorited || $[20] !== t7 || $[21] !== unfavorite ? (t8 = {
417
+ favorite,
418
+ unfavorite,
419
+ isFavorited,
420
+ isConnected: t7
421
+ }, $[18] = favorite, $[19] = isFavorited, $[20] = t7, $[21] = unfavorite, $[22] = t8) : t8 = $[22], t8;
422
+ }
423
+ function useRecordDocumentHistoryEvent(t0) {
424
+ const $ = c(11), {
425
+ documentId,
426
+ documentType,
427
+ resourceType,
428
+ resourceId,
429
+ schemaName
430
+ } = t0, [status, setStatus] = useState("idle");
431
+ let t1;
432
+ $[0] === Symbol.for("react.memo_cache_sentinel") ? (t1 = {
433
+ name: SDK_NODE_NAME,
434
+ connectTo: SDK_CHANNEL_NAME,
435
+ onStatus: setStatus
436
+ }, $[0] = t1) : t1 = $[0];
437
+ const {
438
+ sendMessage
439
+ } = useWindowConnection(t1);
440
+ if (resourceType !== "studio" && !resourceId)
441
+ throw new Error("resourceId is required for media-library and canvas resources");
442
+ let t2;
443
+ $[1] !== documentId || $[2] !== documentType || $[3] !== resourceId || $[4] !== resourceType || $[5] !== schemaName || $[6] !== sendMessage ? (t2 = (eventType) => {
444
+ try {
445
+ const message = {
446
+ type: "dashboard/v1/events/history",
447
+ data: {
448
+ eventType,
449
+ document: {
450
+ id: documentId,
451
+ type: documentType,
452
+ resource: {
453
+ id: resourceId,
454
+ type: resourceType,
455
+ schemaName
456
+ }
457
+ }
458
+ }
459
+ };
460
+ sendMessage(message.type, message.data);
461
+ } catch (t32) {
462
+ const error = t32;
463
+ throw console.error("Failed to record history event:", error), error;
464
+ }
465
+ }, $[1] = documentId, $[2] = documentType, $[3] = resourceId, $[4] = resourceType, $[5] = schemaName, $[6] = sendMessage, $[7] = t2) : t2 = $[7];
466
+ const recordEvent = t2, t3 = status === "connected";
467
+ let t4;
468
+ return $[8] !== recordEvent || $[9] !== t3 ? (t4 = {
469
+ recordEvent,
470
+ isConnected: t3
471
+ }, $[8] = recordEvent, $[9] = t3, $[10] = t4) : t4 = $[10], t4;
472
+ }
473
+ function useStudioWorkspacesByProjectIdDataset() {
474
+ const $ = c(10);
475
+ let t0;
476
+ $[0] === Symbol.for("react.memo_cache_sentinel") ? (t0 = {}, $[0] = t0) : t0 = $[0];
477
+ const [workspacesByProjectIdAndDataset, setWorkspacesByProjectIdAndDataset] = useState(t0), [status, setStatus] = useState("idle"), [error, setError] = useState(null);
478
+ let t1;
479
+ $[1] === Symbol.for("react.memo_cache_sentinel") ? (t1 = {
480
+ name: SDK_NODE_NAME,
481
+ connectTo: SDK_CHANNEL_NAME,
482
+ onStatus: setStatus
483
+ }, $[1] = t1) : t1 = $[1];
484
+ const {
485
+ fetch
486
+ } = useWindowConnection(t1);
487
+ let t2, t3;
488
+ $[2] !== fetch || $[3] !== status ? (t2 = () => {
489
+ if (!fetch || status !== "connected")
490
+ return;
491
+ const fetchWorkspaces = async function(signal) {
492
+ try {
493
+ const data = await fetch("dashboard/v1/bridge/context", void 0, {
494
+ signal
495
+ }), workspaceMap = {}, noProjectIdAndDataset = [];
496
+ data.context.availableResources.forEach((resource) => {
497
+ if (resource.type !== "studio")
498
+ return;
499
+ if (!resource.projectId || !resource.dataset) {
500
+ noProjectIdAndDataset.push(resource);
501
+ return;
502
+ }
503
+ const key = `${resource.projectId}:${resource.dataset}`;
504
+ workspaceMap[key] || (workspaceMap[key] = []), workspaceMap[key].push(resource);
505
+ }), noProjectIdAndDataset.length > 0 && (workspaceMap["NO_PROJECT_ID:NO_DATASET"] = noProjectIdAndDataset), setWorkspacesByProjectIdAndDataset(workspaceMap), setError(null);
506
+ } catch (t42) {
507
+ const err = t42;
508
+ if (err instanceof Error) {
509
+ if (err.name === "AbortError")
510
+ return;
511
+ setError("Failed to fetch workspaces");
512
+ }
513
+ }
514
+ }, controller = new AbortController();
515
+ return fetchWorkspaces(controller.signal), () => {
516
+ controller.abort();
517
+ };
518
+ }, t3 = [fetch, status], $[2] = fetch, $[3] = status, $[4] = t2, $[5] = t3) : (t2 = $[4], t3 = $[5]), useEffect(t2, t3);
519
+ const t4 = status === "connected";
520
+ let t5;
521
+ return $[6] !== error || $[7] !== t4 || $[8] !== workspacesByProjectIdAndDataset ? (t5 = {
522
+ workspacesByProjectIdAndDataset,
523
+ error,
524
+ isConnected: t4
525
+ }, $[6] = error, $[7] = t4, $[8] = workspacesByProjectIdAndDataset, $[9] = t5) : t5 = $[9], t5;
526
+ }
527
+ function useNavigateToStudioDocument(documentHandle, preferredStudioUrl) {
528
+ const $ = c(11), {
529
+ workspacesByProjectIdAndDataset,
530
+ isConnected: workspacesConnected
531
+ } = useStudioWorkspacesByProjectIdDataset(), [status, setStatus] = useState("idle");
532
+ let t0;
533
+ $[0] === Symbol.for("react.memo_cache_sentinel") ? (t0 = {
534
+ name: SDK_NODE_NAME,
535
+ connectTo: SDK_CHANNEL_NAME,
536
+ onStatus: setStatus
537
+ }, $[0] = t0) : t0 = $[0];
538
+ const {
539
+ sendMessage
540
+ } = useWindowConnection(t0);
541
+ let t1;
542
+ $[1] !== documentHandle || $[2] !== preferredStudioUrl || $[3] !== sendMessage || $[4] !== status || $[5] !== workspacesByProjectIdAndDataset || $[6] !== workspacesConnected ? (t1 = () => {
543
+ const {
544
+ projectId,
545
+ dataset
546
+ } = documentHandle;
547
+ if (!workspacesConnected || status !== "connected") {
548
+ console.warn("Not connected to Dashboard");
549
+ return;
550
+ }
551
+ if (!projectId || !dataset) {
552
+ console.warn("Project ID and dataset are required to navigate to a studio document");
553
+ return;
554
+ }
555
+ let workspace;
556
+ if (preferredStudioUrl)
557
+ workspace = [...workspacesByProjectIdAndDataset[`${projectId}:${dataset}`] || [], ...workspacesByProjectIdAndDataset["NO_PROJECT_ID:NO_DATASET"] || []].find((w) => w.url === preferredStudioUrl);
558
+ else {
559
+ const workspaces = workspacesByProjectIdAndDataset[`${projectId}:${dataset}`];
560
+ workspaces?.length > 1 && (console.warn("Multiple workspaces found for document and no preferred studio url", documentHandle), console.warn("Using the first one", workspaces[0])), workspace = workspaces?.[0];
561
+ }
562
+ if (!workspace) {
563
+ console.warn(`No workspace found for document with projectId: ${projectId} and dataset: ${dataset}${preferredStudioUrl ? ` or with preferred studio url: ${preferredStudioUrl}` : ""}`);
564
+ return;
565
+ }
566
+ const message = {
567
+ type: "dashboard/v1/bridge/navigate-to-resource",
568
+ data: {
569
+ resourceId: workspace.id,
570
+ resourceType: "studio",
571
+ path: `/intent/edit/id=${documentHandle.documentId};type=${documentHandle.documentType}`
572
+ }
573
+ };
574
+ sendMessage(message.type, message.data);
575
+ }, $[1] = documentHandle, $[2] = preferredStudioUrl, $[3] = sendMessage, $[4] = status, $[5] = workspacesByProjectIdAndDataset, $[6] = workspacesConnected, $[7] = t1) : t1 = $[7];
576
+ const navigateToStudioDocument = t1, t2 = workspacesConnected && status === "connected";
577
+ let t3;
578
+ return $[8] !== navigateToStudioDocument || $[9] !== t2 ? (t3 = {
579
+ navigateToStudioDocument,
580
+ isConnected: t2
581
+ }, $[8] = navigateToStudioDocument, $[9] = t2, $[10] = t3) : t3 = $[10], t3;
582
+ }
583
+ const useDatasets = createStateSourceHook({
584
+ getState: getDatasetsState,
585
+ shouldSuspend: (instance, projectHandle) => (
586
+ // remove `undefined` since we're suspending when that is the case
587
+ getDatasetsState(instance, projectHandle).getCurrent() === void 0
588
+ ),
589
+ suspender: resolveDatasets,
590
+ getConfig: (projectHandle) => projectHandle
591
+ }), useApplyDocumentActions = createCallbackHook(applyDocumentActions);
592
+ function useDocument(doc, path) {
593
+ return _useDocument(doc, path);
594
+ }
595
+ const _useDocument = createStateSourceHook({
596
+ getState: getDocumentState,
597
+ shouldSuspend: (instance, doc) => getDocumentState(instance, doc).getCurrent() === void 0,
598
+ suspender: resolveDocument,
599
+ getConfig: identity
600
+ });
601
+ function useDocumentEvent(handler, dataset) {
602
+ const $ = c(6), ref = useRef(handler);
603
+ let t0;
604
+ $[0] !== handler ? (t0 = () => {
605
+ ref.current = handler;
606
+ }, $[0] = handler, $[1] = t0) : t0 = $[1], useInsertionEffect(t0);
607
+ let t1;
608
+ $[2] === Symbol.for("react.memo_cache_sentinel") ? (t1 = (documentEvent) => ref.current(documentEvent), $[2] = t1) : t1 = $[2];
609
+ const stableHandler = t1, instance = useSanityInstance(dataset);
610
+ let t2, t3;
611
+ $[3] !== instance ? (t2 = () => subscribeDocumentEvents(instance, stableHandler), t3 = [instance, stableHandler], $[3] = instance, $[4] = t2, $[5] = t3) : (t2 = $[4], t3 = $[5]), useEffect(t2, t3);
612
+ }
613
+ function useDocumentPermissions(actionOrActions) {
614
+ const $ = c(13);
615
+ let t0;
616
+ $[0] !== actionOrActions ? (t0 = Array.isArray(actionOrActions) ? actionOrActions : [actionOrActions], $[0] = actionOrActions, $[1] = t0) : t0 = $[1];
617
+ const actions = t0;
618
+ let projectId, dataset;
619
+ if ($[2] !== actions || $[3] !== dataset || $[4] !== projectId) {
620
+ for (const action of actions)
621
+ if (action.projectId) {
622
+ if (projectId || (projectId = action.projectId), action.projectId !== projectId)
623
+ throw new Error(`Mismatched project IDs found in actions. All actions must belong to the same project. Found "${action.projectId}" but expected "${projectId}".`);
624
+ if (action.dataset && (dataset || (dataset = action.dataset), action.dataset !== dataset))
625
+ throw new Error(`Mismatched datasets found in actions. All actions must belong to the same dataset. Found "${action.dataset}" but expected "${dataset}".`);
626
+ }
627
+ $[2] = actions, $[3] = dataset, $[4] = projectId, $[5] = projectId, $[6] = dataset;
628
+ } else
629
+ projectId = $[5], dataset = $[6];
630
+ let t1;
631
+ $[7] !== dataset || $[8] !== projectId ? (t1 = {
632
+ projectId,
633
+ dataset
634
+ }, $[7] = dataset, $[8] = projectId, $[9] = t1) : t1 = $[9];
635
+ const instance = useSanityInstance(t1);
636
+ if (getPermissionsState(instance, actionOrActions).getCurrent() === void 0)
637
+ throw firstValueFrom(getPermissionsState(instance, actionOrActions).observable.pipe(filter(_temp$3)));
638
+ let t2, t3;
639
+ $[10] !== actionOrActions || $[11] !== instance ? (t3 = getPermissionsState(instance, actionOrActions), $[10] = actionOrActions, $[11] = instance, $[12] = t3) : t3 = $[12], t2 = t3;
640
+ const {
641
+ subscribe,
642
+ getCurrent
643
+ } = t2;
644
+ return useSyncExternalStore(subscribe, getCurrent);
645
+ }
646
+ function _temp$3(result) {
647
+ return result !== void 0;
648
+ }
649
+ const useDocumentSyncStatus = createStateSourceHook(getDocumentSyncStatus), ignoredKeys = ["_id", "_type", "_createdAt", "_updatedAt", "_rev"];
650
+ function useEditDocument(docHandle, path) {
651
+ const $ = c(5), instance = useSanityInstance(docHandle), apply = useApplyDocumentActions();
652
+ if (getDocumentState(instance, docHandle).getCurrent() === void 0)
653
+ throw resolveDocument(instance, docHandle);
654
+ let t0;
655
+ return $[0] !== apply || $[1] !== docHandle || $[2] !== instance || $[3] !== path ? (t0 = (updater) => {
656
+ if (path) {
657
+ const nextValue = typeof updater == "function" ? updater(getDocumentState(instance, docHandle, path).getCurrent()) : updater;
658
+ return apply(editDocument(docHandle, {
659
+ set: {
660
+ [path]: nextValue
661
+ }
662
+ }));
663
+ }
664
+ const current = getDocumentState(instance, docHandle).getCurrent(), nextValue_0 = typeof updater == "function" ? updater(current) : updater;
665
+ if (typeof nextValue_0 != "object" || !nextValue_0)
666
+ throw new Error("No path was provided to `useEditDocument` and the value provided was not a document object.");
667
+ const editActions = Object.keys({
668
+ ...current,
669
+ ...nextValue_0
670
+ }).filter(_temp$2).filter((key_0) => current?.[key_0] !== nextValue_0[key_0]).map((key_1) => key_1 in nextValue_0 ? editDocument(docHandle, {
671
+ set: {
672
+ [key_1]: nextValue_0[key_1]
673
+ }
674
+ }) : editDocument(docHandle, {
675
+ unset: [key_1]
676
+ }));
677
+ return apply(editActions);
678
+ }, $[0] = apply, $[1] = docHandle, $[2] = instance, $[3] = path, $[4] = t0) : t0 = $[4], t0;
679
+ }
680
+ function _temp$2(key) {
681
+ return !ignoredKeys.includes(key);
682
+ }
683
+ function useQuery(query, options) {
684
+ const instance = useSanityInstance(options), [isPending, startTransition] = useTransition(), queryKey = getQueryKey(query, options), [deferredQueryKey, setDeferredQueryKey] = useState(queryKey), deferred = useMemo(() => parseQueryKey(deferredQueryKey), [deferredQueryKey]), ref = useRef(new AbortController());
685
+ useEffect(() => {
686
+ queryKey !== deferredQueryKey && startTransition(() => {
687
+ ref && !ref.current.signal.aborted && (ref.current.abort(), ref.current = new AbortController()), setDeferredQueryKey(queryKey);
688
+ });
689
+ }, [deferredQueryKey, queryKey]);
690
+ const {
691
+ getCurrent,
692
+ subscribe
693
+ } = useMemo(() => getQueryState(instance, deferred.query, deferred.options), [instance, deferred]);
694
+ if (getCurrent() === void 0) {
695
+ const currentSignal = ref.current.signal;
696
+ throw resolveQuery(instance, deferred.query, {
697
+ ...deferred.options,
698
+ signal: currentSignal
699
+ });
700
+ }
701
+ const data = useSyncExternalStore(subscribe, getCurrent);
702
+ return useMemo(() => ({
703
+ data,
704
+ isPending
705
+ }), [data, isPending]);
706
+ }
707
+ const DEFAULT_BATCH_SIZE = 25, DEFAULT_PERSPECTIVE$1 = "drafts";
708
+ function useDocuments(t0) {
709
+ const $ = c(36);
710
+ let filter2, options, orderings, params, search, t1;
711
+ $[0] !== t0 ? ({
712
+ batchSize: t1,
713
+ params,
714
+ search,
715
+ filter: filter2,
716
+ orderings,
717
+ ...options
718
+ } = t0, $[0] = t0, $[1] = filter2, $[2] = options, $[3] = orderings, $[4] = params, $[5] = search, $[6] = t1) : (filter2 = $[1], options = $[2], orderings = $[3], params = $[4], search = $[5], t1 = $[6]);
719
+ const batchSize = t1 === void 0 ? DEFAULT_BATCH_SIZE : t1, instance = useSanityInstance(options), perspective = options.perspective ?? DEFAULT_PERSPECTIVE$1, [limit, setLimit] = useState(batchSize);
720
+ let t2;
721
+ $[7] !== batchSize || $[8] !== filter2 || $[9] !== orderings || $[10] !== params || $[11] !== search ? (t2 = JSON.stringify({
722
+ filter: filter2,
723
+ search,
724
+ params,
725
+ orderings,
726
+ batchSize
727
+ }), $[7] = batchSize, $[8] = filter2, $[9] = orderings, $[10] = params, $[11] = search, $[12] = t2) : t2 = $[12];
728
+ const key = t2;
729
+ let t3;
730
+ $[13] !== batchSize ? (t3 = () => {
731
+ setLimit(batchSize);
732
+ }, $[13] = batchSize, $[14] = t3) : t3 = $[14];
733
+ let t4;
734
+ $[15] !== batchSize || $[16] !== key ? (t4 = [key, batchSize], $[15] = batchSize, $[16] = key, $[17] = t4) : t4 = $[17], useEffect(t3, t4);
735
+ let t5;
736
+ const conditions = [], trimmedSearch = search?.trim();
737
+ if (trimmedSearch) {
738
+ const searchFilter = createGroqSearchFilter(trimmedSearch);
739
+ searchFilter && conditions.push(searchFilter);
740
+ }
741
+ filter2 && conditions.push(`(${filter2})`), t5 = conditions.length ? `[${conditions.join(" && ")}]` : "";
742
+ const filterClause = t5, orderClause = orderings ? `| order(${orderings.map(_temp2$1).join(",")})` : "", dataQuery = `*${filterClause}${orderClause}[0...${limit}]{"documentId":_id,"documentType":_type,...$__dataset}`, countQuery = `count(*${filterClause})`;
743
+ let t6;
744
+ $[18] !== instance.config ? (t6 = pick(instance.config, "projectId", "dataset"), $[18] = instance.config, $[19] = t6) : t6 = $[19];
745
+ let t7;
746
+ $[20] !== params || $[21] !== t6 ? (t7 = {
747
+ ...params,
748
+ __dataset: t6
749
+ }, $[20] = params, $[21] = t6, $[22] = t7) : t7 = $[22];
750
+ let t8;
751
+ $[23] !== options || $[24] !== perspective || $[25] !== t7 ? (t8 = {
752
+ ...options,
753
+ params: t7,
754
+ perspective
755
+ }, $[23] = options, $[24] = perspective, $[25] = t7, $[26] = t8) : t8 = $[26];
756
+ const {
757
+ data: t9,
758
+ isPending
759
+ } = useQuery(`{"count":${countQuery},"data":${dataQuery}}`, t8), {
760
+ count,
761
+ data
762
+ } = t9, hasMore = data.length < count;
763
+ let t10;
764
+ $[27] !== batchSize || $[28] !== count ? (t10 = () => {
765
+ setLimit((prev) => Math.min(prev + batchSize, count));
766
+ }, $[27] = batchSize, $[28] = count, $[29] = t10) : t10 = $[29];
767
+ const loadMore = t10;
768
+ let t11, t12;
769
+ return $[30] !== count || $[31] !== data || $[32] !== hasMore || $[33] !== isPending || $[34] !== loadMore ? (t12 = {
770
+ data,
771
+ hasMore,
772
+ count,
773
+ isPending,
774
+ loadMore
775
+ }, $[30] = count, $[31] = data, $[32] = hasMore, $[33] = isPending, $[34] = loadMore, $[35] = t12) : t12 = $[35], t11 = t12, t11;
776
+ }
777
+ function _temp2$1(ordering) {
778
+ return [ordering.field, ordering.direction.toLowerCase()].map(_temp$1).filter(Boolean).join(" ");
779
+ }
780
+ function _temp$1(str) {
781
+ return str.trim();
782
+ }
783
+ const DEFAULT_PERSPECTIVE = "drafts";
784
+ function usePaginatedDocuments(t0) {
785
+ const $ = c(51);
786
+ let options, orderings, search, t1, t2, t3;
787
+ $[0] !== t0 ? ({
788
+ filter: t1,
789
+ pageSize: t2,
790
+ params: t3,
791
+ orderings,
792
+ search,
793
+ ...options
794
+ } = t0, $[0] = t0, $[1] = options, $[2] = orderings, $[3] = search, $[4] = t1, $[5] = t2, $[6] = t3) : (options = $[1], orderings = $[2], search = $[3], t1 = $[4], t2 = $[5], t3 = $[6]);
795
+ const filter2 = t1 === void 0 ? "" : t1, pageSize = t2 === void 0 ? 25 : t2;
796
+ let t4;
797
+ $[7] !== t3 ? (t4 = t3 === void 0 ? {} : t3, $[7] = t3, $[8] = t4) : t4 = $[8];
798
+ const params = t4, instance = useSanityInstance(options), [pageIndex, setPageIndex] = useState(0);
799
+ let t5;
800
+ $[9] !== filter2 || $[10] !== orderings || $[11] !== pageSize || $[12] !== params || $[13] !== search ? (t5 = JSON.stringify({
801
+ filter: filter2,
802
+ search,
803
+ params,
804
+ orderings,
805
+ pageSize
806
+ }), $[9] = filter2, $[10] = orderings, $[11] = pageSize, $[12] = params, $[13] = search, $[14] = t5) : t5 = $[14];
807
+ const key = t5;
808
+ let t6;
809
+ $[15] === Symbol.for("react.memo_cache_sentinel") ? (t6 = () => {
810
+ setPageIndex(0);
811
+ }, $[15] = t6) : t6 = $[15];
812
+ let t7;
813
+ $[16] !== key ? (t7 = [key], $[16] = key, $[17] = t7) : t7 = $[17], useEffect(t6, t7);
814
+ const startIndex = pageIndex * pageSize, endIndex = (pageIndex + 1) * pageSize, perspective = options.perspective ?? DEFAULT_PERSPECTIVE;
815
+ let t8;
816
+ const conditions = [], trimmedSearch = search?.trim();
817
+ if (trimmedSearch) {
818
+ const searchFilter = createGroqSearchFilter(trimmedSearch);
819
+ searchFilter && conditions.push(searchFilter);
820
+ }
821
+ filter2 && conditions.push(`(${filter2})`), t8 = conditions.length ? `[${conditions.join(" && ")}]` : "";
822
+ const filterClause = t8, orderClause = orderings ? `| order(${orderings.map(_temp2).join(",")})` : "", dataQuery = `*${filterClause}${orderClause}[${startIndex}...${endIndex}]{"documentId":_id,"documentType":_type,...$__dataset}`, countQuery = `count(*${filterClause})`;
823
+ let t9;
824
+ $[18] !== instance.config ? (t9 = pick(instance.config, "projectId", "dataset"), $[18] = instance.config, $[19] = t9) : t9 = $[19];
825
+ let t10;
826
+ $[20] !== params || $[21] !== t9 ? (t10 = {
827
+ ...params,
828
+ __dataset: t9
829
+ }, $[20] = params, $[21] = t9, $[22] = t10) : t10 = $[22];
830
+ let t11;
831
+ $[23] !== options || $[24] !== perspective || $[25] !== t10 ? (t11 = {
832
+ ...options,
833
+ perspective,
834
+ params: t10
835
+ }, $[23] = options, $[24] = perspective, $[25] = t10, $[26] = t11) : t11 = $[26];
836
+ const {
837
+ data: t12,
838
+ isPending
839
+ } = useQuery(`{"data":${dataQuery},"count":${countQuery}}`, t11), {
840
+ data,
841
+ count
842
+ } = t12, totalPages = Math.ceil(count / pageSize), currentPage = pageIndex + 1;
843
+ let t13;
844
+ $[27] === Symbol.for("react.memo_cache_sentinel") ? (t13 = () => setPageIndex(0), $[27] = t13) : t13 = $[27];
845
+ const firstPage = t13;
846
+ let t14;
847
+ $[28] === Symbol.for("react.memo_cache_sentinel") ? (t14 = () => setPageIndex(_temp3), $[28] = t14) : t14 = $[28];
848
+ const previousPage = t14;
849
+ let t15;
850
+ $[29] !== totalPages ? (t15 = () => setPageIndex((prev_0) => Math.min(prev_0 + 1, totalPages - 1)), $[29] = totalPages, $[30] = t15) : t15 = $[30];
851
+ const nextPage = t15;
852
+ let t16;
853
+ $[31] !== totalPages ? (t16 = () => setPageIndex(totalPages - 1), $[31] = totalPages, $[32] = t16) : t16 = $[32];
854
+ const lastPage = t16;
855
+ let t17;
856
+ $[33] !== totalPages ? (t17 = (pageNumber) => {
857
+ pageNumber < 1 || pageNumber > totalPages || setPageIndex(pageNumber - 1);
858
+ }, $[33] = totalPages, $[34] = t17) : t17 = $[34];
859
+ const goToPage = t17, hasFirstPage = pageIndex > 0, hasPreviousPage = pageIndex > 0, hasNextPage = pageIndex < totalPages - 1, hasLastPage = pageIndex < totalPages - 1;
860
+ let t18;
861
+ return $[35] !== count || $[36] !== currentPage || $[37] !== data || $[38] !== endIndex || $[39] !== goToPage || $[40] !== hasFirstPage || $[41] !== hasLastPage || $[42] !== hasNextPage || $[43] !== hasPreviousPage || $[44] !== isPending || $[45] !== lastPage || $[46] !== nextPage || $[47] !== pageSize || $[48] !== startIndex || $[49] !== totalPages ? (t18 = {
862
+ data,
863
+ isPending,
864
+ pageSize,
865
+ currentPage,
866
+ totalPages,
867
+ startIndex,
868
+ endIndex,
869
+ count,
870
+ firstPage,
871
+ hasFirstPage,
872
+ previousPage,
873
+ hasPreviousPage,
874
+ nextPage,
875
+ hasNextPage,
876
+ lastPage,
877
+ hasLastPage,
878
+ goToPage
879
+ }, $[35] = count, $[36] = currentPage, $[37] = data, $[38] = endIndex, $[39] = goToPage, $[40] = hasFirstPage, $[41] = hasLastPage, $[42] = hasNextPage, $[43] = hasPreviousPage, $[44] = isPending, $[45] = lastPage, $[46] = nextPage, $[47] = pageSize, $[48] = startIndex, $[49] = totalPages, $[50] = t18) : t18 = $[50], t18;
880
+ }
881
+ function _temp3(prev) {
882
+ return Math.max(prev - 1, 0);
883
+ }
884
+ function _temp2(ordering) {
885
+ return [ordering.field, ordering.direction.toLowerCase()].map(_temp).filter(Boolean).join(" ");
886
+ }
887
+ function _temp(str) {
888
+ return str.trim();
889
+ }
890
+ function usePreview(t0) {
891
+ const $ = c(13);
892
+ let docHandle, ref;
893
+ $[0] !== t0 ? ({
894
+ ref,
895
+ ...docHandle
896
+ } = t0, $[0] = t0, $[1] = docHandle, $[2] = ref) : (docHandle = $[1], ref = $[2]);
897
+ const instance = useSanityInstance();
898
+ let t1;
899
+ $[3] !== docHandle || $[4] !== instance ? (t1 = getPreviewState(instance, docHandle), $[3] = docHandle, $[4] = instance, $[5] = t1) : t1 = $[5];
900
+ const stateSource = t1;
901
+ let t2;
902
+ $[6] !== ref || $[7] !== stateSource ? (t2 = (onStoreChanged) => {
903
+ const subscription = new Observable((observer) => {
904
+ if (typeof IntersectionObserver > "u" || typeof HTMLElement > "u") {
905
+ observer.next(!0);
906
+ return;
907
+ }
908
+ const intersectionObserver = new IntersectionObserver((t32) => {
909
+ const [entry] = t32;
910
+ return observer.next(entry.isIntersecting);
911
+ }, {
912
+ rootMargin: "0px",
913
+ threshold: 0
914
+ });
915
+ return ref?.current && ref.current instanceof HTMLElement ? intersectionObserver.observe(ref.current) : observer.next(!0), () => intersectionObserver.disconnect();
916
+ }).pipe(startWith(!1), distinctUntilChanged(), switchMap((isVisible) => isVisible ? new Observable((obs) => stateSource.subscribe(() => obs.next())) : EMPTY)).subscribe({
917
+ next: onStoreChanged
918
+ });
919
+ return () => subscription.unsubscribe();
920
+ }, $[6] = ref, $[7] = stateSource, $[8] = t2) : t2 = $[8];
921
+ const subscribe = t2;
922
+ let t3;
923
+ return $[9] !== docHandle || $[10] !== instance || $[11] !== stateSource ? (t3 = () => {
924
+ const currentState = stateSource.getCurrent();
925
+ if (currentState.data === null)
926
+ throw resolvePreview(instance, docHandle);
927
+ return currentState;
928
+ }, $[9] = docHandle, $[10] = instance, $[11] = stateSource, $[12] = t3) : t3 = $[12], useSyncExternalStore(subscribe, t3);
929
+ }
930
+ function useProjection(t0) {
931
+ const $ = c(12);
932
+ let docHandle, projection, ref;
933
+ $[0] !== t0 ? ({
934
+ ref,
935
+ projection,
936
+ ...docHandle
937
+ } = t0, $[0] = t0, $[1] = docHandle, $[2] = projection, $[3] = ref) : (docHandle = $[1], projection = $[2], ref = $[3]);
938
+ const instance = useSanityInstance();
939
+ let stateSource, t1;
940
+ if ($[4] !== docHandle || $[5] !== instance || $[6] !== projection ? (stateSource = getProjectionState(instance, {
941
+ ...docHandle,
942
+ projection
943
+ }), t1 = stateSource.getCurrent(), $[4] = docHandle, $[5] = instance, $[6] = projection, $[7] = stateSource, $[8] = t1) : (stateSource = $[7], t1 = $[8]), t1.data === null)
944
+ throw resolveProjection(instance, {
945
+ ...docHandle,
946
+ projection
947
+ });
948
+ let t2;
949
+ return $[9] !== ref || $[10] !== stateSource ? (t2 = (onStoreChanged) => {
950
+ const subscription = new Observable((observer) => {
951
+ if (typeof IntersectionObserver > "u" || typeof HTMLElement > "u") {
952
+ observer.next(!0);
953
+ return;
954
+ }
955
+ const intersectionObserver = new IntersectionObserver((t3) => {
956
+ const [entry] = t3;
957
+ return observer.next(entry.isIntersecting);
958
+ }, {
959
+ rootMargin: "0px",
960
+ threshold: 0
961
+ });
962
+ return ref?.current && ref.current instanceof HTMLElement ? intersectionObserver.observe(ref.current) : observer.next(!0), () => intersectionObserver.disconnect();
963
+ }).pipe(startWith(!1), distinctUntilChanged(), switchMap((isVisible) => isVisible ? new Observable((obs) => stateSource.subscribe(() => obs.next())) : EMPTY)).subscribe({
964
+ next: onStoreChanged
965
+ });
966
+ return () => subscription.unsubscribe();
967
+ }, $[9] = ref, $[10] = stateSource, $[11] = t2) : t2 = $[11], useSyncExternalStore(t2, stateSource.getCurrent);
968
+ }
969
+ const useProject = createStateSourceHook({
970
+ // remove `undefined` since we're suspending when that is the case
971
+ getState: getProjectState,
972
+ shouldSuspend: (instance, projectHandle) => getProjectState(instance, projectHandle).getCurrent() === void 0,
973
+ suspender: resolveProject,
974
+ getConfig: identity
975
+ }), useProjects = createStateSourceHook({
976
+ // remove `undefined` since we're suspending when that is the case
977
+ getState: getProjectsState,
978
+ shouldSuspend: (instance) => getProjectsState(instance).getCurrent() === void 0,
979
+ suspender: resolveProjects
980
+ });
981
+ function useUsers(options) {
982
+ 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());
983
+ useEffect(() => {
984
+ key !== deferredKey && startTransition(() => {
985
+ ref.signal.aborted || (ref.abort(), setRef(new AbortController())), setDeferredKey(key);
986
+ });
987
+ }, [deferredKey, key, ref]);
988
+ const {
989
+ getCurrent,
990
+ subscribe
991
+ } = useMemo(() => getUsersState(instance, deferred), [instance, deferred]);
992
+ if (getCurrent() === void 0)
993
+ throw resolveUsers(instance, {
994
+ ...deferred,
995
+ signal: ref.signal
996
+ });
997
+ const {
998
+ data,
999
+ hasMore
1000
+ } = useSyncExternalStore(subscribe, getCurrent), loadMore = useCallback(() => {
1001
+ loadMoreUsers(instance, options);
1002
+ }, [instance, options]);
1003
+ return {
1004
+ data,
1005
+ hasMore,
1006
+ isPending,
1007
+ loadMore
1008
+ };
1009
+ }
1010
+ var version = "0.0.0-alpha.29";
1011
+ function getEnv(key) {
1012
+ if (typeof import.meta < "u" && import.meta.env)
1013
+ return import.meta.env[key];
1014
+ if (typeof process < "u" && process.env)
1015
+ return process.env[key];
1016
+ if (typeof window < "u" && window.ENV)
1017
+ return window.ENV?.[key];
1018
+ }
1019
+ const REACT_SDK_VERSION = getEnv("PKG_VERSION") || `${version}-development`;
3
1020
  export {
4
1021
  AuthBoundary,
5
1022
  REACT_SDK_VERSION,