@sanity/sdk 2.18.0 → 3.0.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/dist/_chunks-dts/createGroqSearchFilter.d.ts +233 -12
  2. package/dist/_chunks-dts/createGroqSearchFilter.d.ts.map +1 -1
  3. package/dist/_chunks-es/_internal.js +1 -0
  4. package/dist/_chunks-es/_internal.js.map +1 -1
  5. package/dist/_chunks-es/createGroqSearchFilter.js +284 -6
  6. package/dist/_chunks-es/createGroqSearchFilter.js.map +1 -1
  7. package/dist/_chunks-es/telemetryManager.js +2 -2
  8. package/dist/_exports/_internal.d.ts +2 -2
  9. package/dist/_exports/_internal.d.ts.map +1 -1
  10. package/dist/_exports/_internal.js +3 -1
  11. package/dist/index.d.ts +599 -185
  12. package/dist/index.d.ts.map +1 -1
  13. package/dist/index.js +492 -337
  14. package/dist/index.js.map +1 -1
  15. package/package.json +7 -7
  16. package/src/_exports/_internal.ts +11 -0
  17. package/src/_exports/index.ts +57 -12
  18. package/src/access/checkPermissions.test.ts +55 -0
  19. package/src/access/checkPermissions.ts +54 -0
  20. package/src/applications/applications.test-d.ts +83 -0
  21. package/src/applications/applications.test.ts +130 -0
  22. package/src/applications/applications.ts +364 -0
  23. package/src/applications/userApplications.test.ts +126 -0
  24. package/src/applications/userApplications.ts +261 -0
  25. package/src/auth/getOrganizationVerificationState.test.ts +7 -7
  26. package/src/auth/getOrganizationVerificationState.ts +4 -4
  27. package/src/document/documentStore.concurrency.test.ts +313 -22
  28. package/src/installations/installations.test-d.ts +68 -0
  29. package/src/installations/installations.test.ts +62 -0
  30. package/src/installations/installations.ts +202 -0
  31. package/src/organization/organization.test-d.ts +18 -84
  32. package/src/organization/organization.test.ts +11 -11
  33. package/src/organization/organization.ts +26 -54
  34. package/src/organizations/organizations.test-d.ts +11 -32
  35. package/src/organizations/organizations.test.ts +8 -8
  36. package/src/organizations/organizations.ts +29 -54
  37. package/src/project/project.test-d.ts +19 -75
  38. package/src/project/project.test.ts +57 -10
  39. package/src/project/project.ts +33 -52
  40. package/src/projects/projects.test-d.ts +15 -21
  41. package/src/projects/projects.test.ts +8 -8
  42. package/src/projects/projects.ts +25 -49
  43. package/src/store/fetcherStore.test-d.ts +121 -0
  44. package/src/store/fetcherStore.test.ts +299 -0
  45. package/src/store/fetcherStore.ts +801 -0
  46. package/src/utils/buildQuery.test.ts +14 -0
  47. package/src/utils/buildQuery.ts +17 -0
  48. package/src/utils/includeShape.ts +36 -0
  49. package/src/utils/setCleanupTimeout.ts +21 -8
  50. package/dist/_chunks-es/version.js +0 -7
  51. package/dist/_chunks-es/version.js.map +0 -1
  52. package/src/utils/defineIntent.test.ts +0 -477
  53. package/src/utils/defineIntent.ts +0 -244
package/dist/index.js CHANGED
@@ -1,22 +1,24 @@
1
- import { switchMap, from, firstValueFrom, EMPTY, asapScheduler, distinctUntilChanged, map as map$1, combineLatest, of, concatMap, withLatestFrom, filter as filter$1, concat, timer, throwError, defer, Observable, first as first$1, Subject, takeUntil, share, partition, merge, shareReplay, tap as tap$1, catchError as catchError$1, startWith as startWith$1, pairwise as pairwise$1, groupBy as groupBy$1, mergeMap as mergeMap$1, retry, throttle, race, skip, NEVER, fromEvent, Subscription, debounceTime } from "rxjs";
2
- import { createLogger, pickProperties, insecureRandomId, getClientState, bindActionGlobally, createStateSourceAction, setCleanupTimeout, omitProperty, defineStore, authStore, getAuthLogger, AuthStateType, getCleanedUrl, getTokenFromLocation, createLoggedInAuthState, getAuthCode, REQUEST_TAG_PREFIX, DEFAULT_API_VERSION, getDefaultLocation, isDeepEqual, configureLogging as configureLogging$1, isReleasePerspective, bindActionByResource, isDatasetResource, isMediaLibraryResource, isCanvasResource, getCurrentUserState, getUsersKey, addSubscription, USERS_STATE_CLEAR_DELAY, removeSubscription, parseUsersKey, getClient, PROJECT_API_VERSION, setUsersError, setUsersData, API_VERSION as API_VERSION$8, getDashboardOrganizationId as getDashboardOrganizationId$1, updateLastLoadMoreRequest, cancelRequest, initializeRequest, getTokenState, getQueryState, resolveQuery, bindActionByResourceAndPerspective, PREVIEW_PROJECTION, transformProjectionToPreview } from "./_chunks-es/createGroqSearchFilter.js";
3
- import { createGroqSearchFilter, getActiveReleasesState, getAllReleasesState, getAuthState, getClientErrorApiBody, getClientErrorApiDescription, getClientErrorApiType, getIsInDashboardState, getLoginUrlState, getPerspectiveState, getQueryKey, isCanvasSource, isDatasetSource, isMediaLibrarySource, isProjectUserNotFoundClientError, isStudioConfig, parseQueryKey, setAuthToken } from "./_chunks-es/createGroqSearchFilter.js";
4
- import { first, switchMap as switchMap$1, groupBy, mergeMap, startWith, pairwise, filter, map, delay, tap, catchError, scan, share as share$1 } from "rxjs/operators";
1
+ import { CorsOriginError } from "@sanity/client";
2
+ import { switchMap, map, from, distinctUntilChanged, combineLatest, of, firstValueFrom, EMPTY, asapScheduler, concatMap, withLatestFrom, filter as filter$1, concat, timer, throwError, defer, Observable, first as first$1, Subject, takeUntil, share, partition, merge, shareReplay, tap as tap$1, catchError as catchError$1, startWith as startWith$1, pairwise as pairwise$1, groupBy as groupBy$1, mergeMap as mergeMap$1, retry, throttle, race, skip, NEVER, fromEvent, Subscription, debounceTime } from "rxjs";
3
+ import { createLogger, pickProperties, insecureRandomId, defineFetcher, getClientState, defineMutation, bindActionGlobally, authStore, createStateSourceAction, getAuthLogger, AuthStateType, getCleanedUrl, getTokenFromLocation, createLoggedInAuthState, getAuthCode, REQUEST_TAG_PREFIX, DEFAULT_API_VERSION, getDefaultLocation, isDeepEqual, defineStore, setCleanupTimeout, configureLogging as configureLogging$1, omitProperty, isReleasePerspective, bindActionByResource, isDatasetResource, isMediaLibraryResource, isCanvasResource, getCurrentUserState, getUsersKey, addSubscription, USERS_STATE_CLEAR_DELAY, removeSubscription, parseUsersKey, getClient, PROJECT_API_VERSION, setUsersError, setUsersData, API_VERSION as API_VERSION$c, getDashboardOrganizationId as getDashboardOrganizationId$1, updateLastLoadMoreRequest, cancelRequest, initializeRequest, getTokenState, getQueryState, resolveQuery, bindActionByResourceAndPerspective, PREVIEW_PROJECTION, transformProjectionToPreview } from "./_chunks-es/createGroqSearchFilter.js";
4
+ import { CORE_SDK_VERSION, createGroqSearchFilter, getActiveReleasesState, getAllReleasesState, getAuthState, getClientErrorApiBody, getClientErrorApiDescription, getClientErrorApiType, getIsInDashboardState, getLoginUrlState, getPerspectiveState, getQueryKey, isCanvasSource, isDatasetSource, isMediaLibrarySource, isProjectUserNotFoundClientError, isStudioConfig, parseQueryKey, setAuthToken } from "./_chunks-es/createGroqSearchFilter.js";
5
5
  import { createController, createNode } from "@sanity/comlink";
6
+ import "zustand/middleware";
7
+ import "zustand/vanilla";
6
8
  import { createSelector } from "reselect";
9
+ import { first, switchMap as switchMap$1, groupBy, mergeMap, startWith, pairwise, filter, map as map$1, delay, tap, catchError, scan, share as share$1 } from "rxjs/operators";
7
10
  import { SanityEncoder } from "@sanity/mutate";
11
+ import { createDocumentLoaderFromClient } from "@sanity/mutate/_unstable_store";
12
+ import { isKeySegment, isKeyedObject } from "@sanity/types";
13
+ import "groq";
8
14
  import { getVersionId, DocumentId, getPublishedId, getDraftId, isDraftId, isVersionId, isPublishedId } from "@sanity/id-utils";
9
15
  import { jsonMatch, stringifyPath, slicePath, getIndexForKey } from "@sanity/json-match";
10
16
  import { getIndexForKey as getIndexForKey2, getPathDepth, joinPaths, jsonMatch as jsonMatch2, slicePath as slicePath2, stringifyPath as stringifyPath2 } from "@sanity/json-match";
11
17
  import { evaluateSync, parse } from "groq-js";
12
18
  import { applyPatches, parsePatch } from "@sanity/diff-match-patch";
13
- import { isKeySegment, isKeyedObject } from "@sanity/types";
14
19
  import { diffValue } from "@sanity/diff-patch";
15
- import { createDocumentLoaderFromClient } from "@sanity/mutate/_unstable_store";
16
20
  import { SDK_CHANNEL_NAME, SDK_NODE_NAME } from "@sanity/message-protocol";
17
21
  import { fromUrl } from "@sanity/bifur-client";
18
- import { CorsOriginError } from "@sanity/client";
19
- import { CORE_SDK_VERSION } from "./_chunks-es/version.js";
20
22
  function createSanityInstance(config = {}) {
21
23
  const instanceId = crypto.randomUUID(), disposeListeners = /* @__PURE__ */ new Map(), disposed = { current: !1 }, instanceContext = {
22
24
  instanceId,
@@ -91,171 +93,237 @@ function createSanityInstance(config = {}) {
91
93
  };
92
94
  return instance;
93
95
  }
94
- const API_VERSION$7 = "vX";
96
+ const API_VERSION$b = "v2025-07-11", checkPermissions = defineFetcher({
97
+ name: "checkPermissions",
98
+ getKey: (_instance, resourceType, resourceId, permissions) => `${resourceType}:${resourceId}:${[...permissions].sort().join(",")}`,
99
+ fetch: (instance) => (resourceType, resourceId, permissions) => getClientState(instance, { apiVersion: API_VERSION$b, scope: "global" }).observable.pipe(
100
+ switchMap(
101
+ (client) => client.observable.request({
102
+ uri: `/access/${resourceType}/${resourceId}/user-permissions/me/check`,
103
+ query: { permissions },
104
+ tag: "access.check"
105
+ }).pipe(map((response) => response.data))
106
+ )
107
+ ),
108
+ tags: (_data, resourceType, resourceId) => [
109
+ { type: "access", id: `${resourceType}:${resourceId}` }
110
+ ]
111
+ }), API_VERSION$a = "vX";
95
112
  function agentGenerate(instance, options, resource) {
96
- return getClientState(instance, { apiVersion: API_VERSION$7, resource }).observable.pipe(
113
+ return getClientState(instance, { apiVersion: API_VERSION$a, resource }).observable.pipe(
97
114
  switchMap((client) => client.observable.agent.action.generate(options))
98
115
  );
99
116
  }
100
117
  function agentTransform(instance, options, resource) {
101
- return getClientState(instance, { apiVersion: API_VERSION$7, resource }).observable.pipe(
118
+ return getClientState(instance, { apiVersion: API_VERSION$a, resource }).observable.pipe(
102
119
  switchMap((client) => client.observable.agent.action.transform(options))
103
120
  );
104
121
  }
105
122
  function agentTranslate(instance, options, resource) {
106
- return getClientState(instance, { apiVersion: API_VERSION$7, resource }).observable.pipe(
123
+ return getClientState(instance, { apiVersion: API_VERSION$a, resource }).observable.pipe(
107
124
  switchMap((client) => client.observable.agent.action.translate(options))
108
125
  );
109
126
  }
110
127
  function agentPrompt(instance, options, resource) {
111
- return getClientState(instance, { apiVersion: API_VERSION$7, resource }).observable.pipe(
128
+ return getClientState(instance, { apiVersion: API_VERSION$a, resource }).observable.pipe(
112
129
  switchMap((client) => from(client.agent.action.prompt(options)))
113
130
  );
114
131
  }
115
132
  function agentPatch(instance, options, resource) {
116
- return getClientState(instance, { apiVersion: API_VERSION$7, resource }).observable.pipe(
133
+ return getClientState(instance, { apiVersion: API_VERSION$a, resource }).observable.pipe(
117
134
  switchMap((client) => from(client.agent.action.patch(options)))
118
135
  );
119
136
  }
137
+ function buildQuery(params) {
138
+ return Object.fromEntries(
139
+ Object.entries(params).filter(([, value]) => value !== void 0).map(([key, value]) => [key, Array.isArray(value) ? value : String(value)])
140
+ );
141
+ }
142
+ const API_VERSION$9 = "vX";
143
+ function serializeInclude$1(include) {
144
+ return include?.length ? [...include].sort().join(",") : void 0;
145
+ }
146
+ const applications = defineFetcher({
147
+ name: "applications",
148
+ getKey: (_instance, options) => [
149
+ options.organizationId,
150
+ options.type ?? "",
151
+ serializeInclude$1(options.include) ?? "",
152
+ options.limit ?? "",
153
+ options.cursor ?? ""
154
+ ].join(":"),
155
+ fetch: (instance) => (options) => getClientState(instance, { apiVersion: API_VERSION$9, scope: "global" }).observable.pipe(
156
+ switchMap(
157
+ (client) => client.observable.request({
158
+ uri: "/applications",
159
+ query: buildQuery({
160
+ organizationId: options.organizationId,
161
+ type: options.type,
162
+ include: serializeInclude$1(options.include),
163
+ limit: options.limit,
164
+ cursor: options.cursor
165
+ }),
166
+ tag: "applications.list"
167
+ })
168
+ )
169
+ ),
170
+ tags: (data) => [
171
+ { type: "application", id: "LIST" },
172
+ ...data.data.map((app) => ({ type: "application", id: app.id }))
173
+ ]
174
+ }), application = defineFetcher({
175
+ name: "application",
176
+ getKey: (_instance, applicationId, options) => `${applicationId}:${serializeInclude$1(options?.include) ?? ""}`,
177
+ fetch: (instance) => (applicationId, options) => getClientState(instance, { apiVersion: API_VERSION$9, scope: "global" }).observable.pipe(
178
+ switchMap(
179
+ (client) => client.observable.request({
180
+ uri: `/applications/${applicationId}`,
181
+ query: buildQuery({ include: serializeInclude$1(options?.include) }),
182
+ tag: "applications.get"
183
+ })
184
+ )
185
+ ),
186
+ tags: (data) => [{ type: "application", id: data.id }]
187
+ }), updateApplication = defineMutation({
188
+ name: "updateApplication",
189
+ mutationFn: (instance) => ({ applicationId, ...body }) => getClientState(instance, { apiVersion: API_VERSION$9, scope: "global" }).observable.pipe(
190
+ switchMap(
191
+ (client) => client.observable.request({
192
+ uri: `/applications/${applicationId}`,
193
+ method: "PATCH",
194
+ body,
195
+ tag: "applications.update"
196
+ })
197
+ )
198
+ ),
199
+ invalidates: (_result, { applicationId }) => [
200
+ { type: "application", id: "LIST" },
201
+ { type: "application", id: applicationId }
202
+ ]
203
+ }), deleteApplication = defineMutation({
204
+ name: "deleteApplication",
205
+ mutationFn: (instance) => ({ applicationId }) => getClientState(instance, { apiVersion: API_VERSION$9, scope: "global" }).observable.pipe(
206
+ switchMap(
207
+ (client) => client.observable.request({
208
+ uri: `/applications/${applicationId}`,
209
+ method: "DELETE",
210
+ tag: "applications.delete"
211
+ })
212
+ )
213
+ ),
214
+ invalidates: (_result, { applicationId }) => [
215
+ { type: "application", id: "LIST" },
216
+ { type: "application", id: applicationId }
217
+ ]
218
+ }), API_VERSION$8 = "v2024-08-01", userApplications = defineFetcher({
219
+ name: "userApplications",
220
+ getKey: (_instance, options) => options.organizationId,
221
+ fetch: (instance) => (options) => getClientState(instance, { apiVersion: API_VERSION$8, scope: "global" }).observable.pipe(
222
+ switchMap(
223
+ (client) => client.observable.request({
224
+ uri: "/user-applications",
225
+ query: buildQuery({ organizationId: options.organizationId }),
226
+ tag: "user-applications.list"
227
+ })
228
+ )
229
+ ),
230
+ tags: (data) => [
231
+ { type: "user-application", id: "LIST" },
232
+ ...data.map((app) => ({ type: "user-application", id: app.id }))
233
+ ]
234
+ }), userApplication = defineFetcher({
235
+ name: "userApplication",
236
+ getKey: (_instance, userApplicationId) => userApplicationId,
237
+ fetch: (instance) => (userApplicationId) => getClientState(instance, { apiVersion: API_VERSION$8, scope: "global" }).observable.pipe(
238
+ switchMap(
239
+ (client) => client.observable.request({
240
+ uri: `/user-applications/${userApplicationId}`,
241
+ tag: "user-applications.get"
242
+ })
243
+ )
244
+ ),
245
+ tags: (data) => [{ type: "user-application", id: data.id }]
246
+ }), createUserApplication = defineMutation({
247
+ name: "createUserApplication",
248
+ mutationFn: (instance) => ({ organizationId, appType, ...body }) => getClientState(instance, { apiVersion: API_VERSION$8, scope: "global" }).observable.pipe(
249
+ switchMap(
250
+ (client) => client.observable.request({
251
+ uri: "/user-applications",
252
+ method: "POST",
253
+ query: buildQuery({ organizationId, appType }),
254
+ body,
255
+ tag: "user-applications.create"
256
+ })
257
+ )
258
+ ),
259
+ invalidates: [{ type: "user-application", id: "LIST" }]
260
+ }), updateUserApplication = defineMutation({
261
+ name: "updateUserApplication",
262
+ mutationFn: (instance) => ({ userApplicationId, ...body }) => getClientState(instance, { apiVersion: API_VERSION$8, scope: "global" }).observable.pipe(
263
+ switchMap(
264
+ (client) => client.observable.request({
265
+ uri: `/user-applications/${userApplicationId}`,
266
+ method: "PATCH",
267
+ body,
268
+ tag: "user-applications.update"
269
+ })
270
+ )
271
+ ),
272
+ invalidates: (_result, { userApplicationId }) => [
273
+ { type: "user-application", id: "LIST" },
274
+ { type: "user-application", id: userApplicationId }
275
+ ]
276
+ }), deleteUserApplication = defineMutation({
277
+ name: "deleteUserApplication",
278
+ mutationFn: (instance) => ({ userApplicationId }) => getClientState(instance, { apiVersion: API_VERSION$8, scope: "global" }).observable.pipe(
279
+ switchMap(
280
+ (client) => client.observable.request({
281
+ uri: `/user-applications/${userApplicationId}`,
282
+ method: "DELETE",
283
+ tag: "user-applications.delete"
284
+ })
285
+ )
286
+ ),
287
+ invalidates: (_result, { userApplicationId }) => [
288
+ { type: "user-application", id: "LIST" },
289
+ { type: "user-application", id: userApplicationId }
290
+ ]
291
+ });
120
292
  function compareProjectOrganization(projectId, projectOrganizationId, currentDashboardOrgId) {
121
293
  return projectOrganizationId !== currentDashboardOrgId ? {
122
294
  error: `Project ${projectId} belongs to Organization ${projectOrganizationId ?? "unknown"}, but the Dashboard has Organization ${currentDashboardOrgId} selected`
123
295
  } : { error: null };
124
296
  }
125
- function createFetcherStore({
126
- name,
127
- fetcher: getObservable,
128
- getKey,
129
- fetchThrottleInternal = 1e3,
130
- stateExpirationDelay = 5e3
131
- }) {
132
- const store = defineStore({
133
- name,
134
- getInitialState: () => ({
135
- stateByParams: {}
136
- }),
137
- initialize: (context) => {
138
- const subscription = subscribeToSubscriptionsAndFetch(context);
139
- return () => subscription.unsubscribe();
140
- }
141
- }), subscribeToSubscriptionsAndFetch = ({
142
- state
143
- }) => state.observable.pipe(
144
- // Map the state to an array of [serialized, entry] pairs.
145
- switchMap$1((s) => {
146
- const entries = Object.entries(s.stateByParams);
147
- return entries.length > 0 ? from(entries) : EMPTY;
148
- }),
149
- // Group by the serialized key.
150
- groupBy(([key]) => key),
151
- mergeMap(
152
- (group$) => group$.pipe(
153
- // Emit an initial value for pairwise comparisons.
154
- startWith([group$.key, void 0]),
155
- pairwise(),
156
- // Trigger only when the subscriptions array grows.
157
- filter(([[, prevEntry], [, currEntry]]) => {
158
- const prevSubs = prevEntry?.subscriptions ?? [];
159
- return (currEntry?.subscriptions ?? []).length > prevSubs.length;
160
- }),
161
- map(([, [, currEntry]]) => currEntry),
162
- // Only trigger if we haven't fetched recently.
163
- filter((entry) => {
164
- const lastFetch = entry?.lastFetchInitiatedAt;
165
- return lastFetch ? Date.now() - new Date(lastFetch).getTime() >= fetchThrottleInternal : !0;
166
- }),
167
- switchMap$1((entry) => entry ? (state.set("setLastFetchInitiatedAt", (prev) => ({
168
- stateByParams: {
169
- ...prev.stateByParams,
170
- [entry.key]: {
171
- ...entry,
172
- ...prev.stateByParams[entry.key],
173
- lastFetchInitiatedAt: (/* @__PURE__ */ new Date()).toISOString()
174
- }
175
- }
176
- })), getObservable(entry.instance)(...entry.params).pipe(
177
- // the `createStateSourceAction` util requires the update
178
- // to
179
- delay(0, asapScheduler),
180
- tap(
181
- (data) => state.set("setData", (prev) => ({
182
- stateByParams: {
183
- ...prev.stateByParams,
184
- [entry.key]: {
185
- ...omitProperty(entry, "error"),
186
- ...prev.stateByParams[entry.key] ? omitProperty(prev.stateByParams[entry.key], "error") : {},
187
- data
188
- }
189
- }
190
- }))
191
- ),
192
- catchError((error) => (state.set("setError", (prev) => ({
193
- stateByParams: {
194
- ...prev.stateByParams,
195
- [entry.key]: {
196
- ...entry,
197
- ...prev.stateByParams[entry.key],
198
- error
199
- }
200
- }
201
- })), EMPTY))
202
- )) : EMPTY)
203
- )
204
- )
205
- ).subscribe({
206
- error: (error) => state.set("setError", { error })
207
- }), getState = bindActionGlobally(
208
- store,
209
- createStateSourceAction({
210
- selector: ({
211
- instance,
212
- state: { stateByParams, error }
213
- }, ...params) => {
214
- if (error) throw error;
215
- const key = getKey(instance, ...params), entry = stateByParams[key];
216
- if (entry?.error) throw entry.error;
217
- return entry?.data;
218
- },
219
- onSubscribe: ({ instance, state }, ...params) => {
220
- const subscriptionId = insecureRandomId(), key = getKey(instance, ...params);
221
- return state.set("addSubscription", (prev) => ({
222
- stateByParams: {
223
- ...prev.stateByParams,
224
- [key]: {
225
- ...prev.stateByParams[key],
226
- instance,
227
- key,
228
- params: prev.stateByParams[key]?.params || params,
229
- subscriptions: [...prev.stateByParams[key]?.subscriptions || [], subscriptionId]
230
- }
231
- }
232
- })), () => {
233
- setCleanupTimeout(() => {
234
- state.set("removeSubscription", (prev) => {
235
- const entry = prev.stateByParams[key];
236
- if (!entry) return prev;
237
- const newSubs = (entry.subscriptions || []).filter((id) => id !== subscriptionId);
238
- return newSubs.length === 0 ? { stateByParams: omitProperty(prev.stateByParams, key) } : {
239
- stateByParams: {
240
- ...prev.stateByParams,
241
- [key]: {
242
- ...entry,
243
- subscriptions: newSubs
244
- }
245
- }
246
- };
247
- });
248
- }, stateExpirationDelay);
249
- };
250
- }
251
- })
252
- ), resolveState = bindActionGlobally(
253
- store,
254
- ({ instance }, ...params) => firstValueFrom(getState(instance, ...params).observable.pipe(first((i) => i !== void 0)))
255
- );
256
- return { getState, resolveState };
297
+ const API_VERSION$7 = "v2025-02-19";
298
+ function normalizeProjectsOptions(options) {
299
+ return {
300
+ organizationId: options?.organizationId,
301
+ includeMembers: options?.includeMembers ?? !1,
302
+ includeFeatures: options?.includeFeatures ?? !0,
303
+ onlyExplicitMembership: options?.onlyExplicitMembership ?? !1
304
+ };
257
305
  }
258
- const API_VERSION$6 = "v2025-02-19";
306
+ function getProjectsCacheKey(_instance, options) {
307
+ const { organizationId, includeMembers, includeFeatures, onlyExplicitMembership } = normalizeProjectsOptions(options);
308
+ return `projects${organizationId ? `:org:${organizationId}` : ""}${includeMembers ? ":members" : ""}${includeFeatures ? ":features" : ""}${onlyExplicitMembership ? ":explicit" : ""}`;
309
+ }
310
+ const projects = defineFetcher({
311
+ name: "projects",
312
+ getKey: getProjectsCacheKey,
313
+ fetch: (instance) => (options) => getClientState(instance, { apiVersion: API_VERSION$7, scope: "global" }).observable.pipe(
314
+ switchMap(
315
+ (client) => client.observable.request({
316
+ uri: "/projects",
317
+ query: buildQuery(normalizeProjectsOptions(options)),
318
+ tag: "projects.list"
319
+ })
320
+ )
321
+ ),
322
+ tags: (data) => [
323
+ { type: "project", id: "LIST" },
324
+ ...data.map((project2) => ({ type: "project", id: project2.id }))
325
+ ]
326
+ }), API_VERSION$6 = "v2025-02-19";
259
327
  function normalizeProjectOptions(options) {
260
328
  return {
261
329
  includeMembers: options?.includeMembers ?? !0,
@@ -272,35 +340,34 @@ function getProjectCacheKey(instance, options) {
272
340
  const projectId = resolveProjectId(instance, options), { includeMembers, includeFeatures } = normalizeProjectOptions(options);
273
341
  return `project:${projectId}${includeMembers ? ":members" : ""}${includeFeatures ? ":features" : ""}`;
274
342
  }
275
- const project = createFetcherStore({
276
- name: "Project",
343
+ const project = defineFetcher({
344
+ name: "project",
277
345
  getKey: getProjectCacheKey,
278
- fetcher: (instance) => (options) => {
279
- const projectId = resolveProjectId(instance, options);
280
- return getClientState(instance, {
281
- apiVersion: API_VERSION$6,
282
- scope: "global"
283
- }).observable.pipe(
284
- switchMap((client) => {
285
- const normalized = normalizeProjectOptions(options), query = Object.fromEntries(
286
- Object.entries(normalized).filter(([, value]) => value !== void 0).map(([key, value]) => [key, String(value)])
287
- );
288
- return client.observable.request({
289
- uri: `/projects/${projectId}`,
290
- query,
291
- tag: "project.get"
292
- });
346
+ fetch: (instance) => (options) => getClientState(instance, { apiVersion: API_VERSION$6, scope: "global" }).observable.pipe(
347
+ switchMap(
348
+ (client) => client.observable.request({
349
+ uri: `/projects/${resolveProjectId(instance, options)}`,
350
+ query: buildQuery(normalizeProjectOptions(options)),
351
+ tag: "projects.get"
293
352
  })
294
- );
353
+ )
354
+ ),
355
+ tags: (data) => [{ type: "project", id: data.id }],
356
+ initialData: (instance, options) => {
357
+ if (normalizeProjectOptions(options).includeMembers) return;
358
+ const snapshot = projects.getState(instance).getCurrent();
359
+ if (snapshot.status !== "success") return;
360
+ const projectId = resolveProjectId(instance, options), match = snapshot.data.find((item) => item.id === projectId);
361
+ return match && { data: match, dataUpdatedAt: snapshot.dataUpdatedAt };
295
362
  }
296
- }), getProjectState = project.getState, resolveProject = project.resolveState, getDashboardOrganizationId = bindActionGlobally(
363
+ }), getDashboardOrganizationId = bindActionGlobally(
297
364
  authStore,
298
365
  createStateSourceAction(({ state: { dashboardContext } }) => dashboardContext?.orgId)
299
366
  );
300
367
  function observeOrganizationVerificationState(instance, projectIds) {
301
368
  const dashboardOrgId$ = getDashboardOrganizationId(instance).observable.pipe(distinctUntilChanged()), projectOrgIdObservables = projectIds.map(
302
- (id) => getProjectState(instance, { projectId: id }).observable.pipe(
303
- map$1((project2) => ({ projectId: id, orgId: project2?.organizationId ?? null })),
369
+ (id) => project.getState(instance, { projectId: id }).observable.pipe(
370
+ map((snapshot) => ({ projectId: id, orgId: snapshot.data?.organizationId ?? null })),
304
371
  // Ensure we only proceed if the orgId is loaded, distinct prevents unnecessary checks
305
372
  distinctUntilChanged((prev, curr) => prev.orgId === curr.orgId)
306
373
  )
@@ -578,6 +645,139 @@ function configureLogging(config) {
578
645
  source: "programmatic"
579
646
  });
580
647
  }
648
+ function createFetcherStore({
649
+ name,
650
+ fetcher: getObservable,
651
+ getKey,
652
+ fetchThrottleInternal = 1e3,
653
+ stateExpirationDelay = 5e3
654
+ }) {
655
+ const store = defineStore({
656
+ name,
657
+ getInitialState: () => ({
658
+ stateByParams: {}
659
+ }),
660
+ initialize: (context) => {
661
+ const subscription = subscribeToSubscriptionsAndFetch(context);
662
+ return () => subscription.unsubscribe();
663
+ }
664
+ }), subscribeToSubscriptionsAndFetch = ({
665
+ state
666
+ }) => state.observable.pipe(
667
+ // Map the state to an array of [serialized, entry] pairs.
668
+ switchMap$1((s) => {
669
+ const entries = Object.entries(s.stateByParams);
670
+ return entries.length > 0 ? from(entries) : EMPTY;
671
+ }),
672
+ // Group by the serialized key.
673
+ groupBy(([key]) => key),
674
+ mergeMap(
675
+ (group$) => group$.pipe(
676
+ // Emit an initial value for pairwise comparisons.
677
+ startWith([group$.key, void 0]),
678
+ pairwise(),
679
+ // Trigger only when the subscriptions array grows.
680
+ filter(([[, prevEntry], [, currEntry]]) => {
681
+ const prevSubs = prevEntry?.subscriptions ?? [];
682
+ return (currEntry?.subscriptions ?? []).length > prevSubs.length;
683
+ }),
684
+ map$1(([, [, currEntry]]) => currEntry),
685
+ // Only trigger if we haven't fetched recently.
686
+ filter((entry) => {
687
+ const lastFetch = entry?.lastFetchInitiatedAt;
688
+ return lastFetch ? Date.now() - new Date(lastFetch).getTime() >= fetchThrottleInternal : !0;
689
+ }),
690
+ switchMap$1((entry) => entry ? (state.set("setLastFetchInitiatedAt", (prev) => ({
691
+ stateByParams: {
692
+ ...prev.stateByParams,
693
+ [entry.key]: {
694
+ ...entry,
695
+ ...prev.stateByParams[entry.key],
696
+ lastFetchInitiatedAt: (/* @__PURE__ */ new Date()).toISOString()
697
+ }
698
+ }
699
+ })), getObservable(entry.instance)(...entry.params).pipe(
700
+ // the `createStateSourceAction` util requires the update
701
+ // to
702
+ delay(0, asapScheduler),
703
+ tap(
704
+ (data) => state.set("setData", (prev) => ({
705
+ stateByParams: {
706
+ ...prev.stateByParams,
707
+ [entry.key]: {
708
+ ...omitProperty(entry, "error"),
709
+ ...prev.stateByParams[entry.key] ? omitProperty(prev.stateByParams[entry.key], "error") : {},
710
+ data
711
+ }
712
+ }
713
+ }))
714
+ ),
715
+ catchError((error) => (state.set("setError", (prev) => ({
716
+ stateByParams: {
717
+ ...prev.stateByParams,
718
+ [entry.key]: {
719
+ ...entry,
720
+ ...prev.stateByParams[entry.key],
721
+ error
722
+ }
723
+ }
724
+ })), EMPTY))
725
+ )) : EMPTY)
726
+ )
727
+ )
728
+ ).subscribe({
729
+ error: (error) => state.set("setError", { error })
730
+ }), getState = bindActionGlobally(
731
+ store,
732
+ createStateSourceAction({
733
+ selector: ({
734
+ instance,
735
+ state: { stateByParams, error }
736
+ }, ...params) => {
737
+ if (error) throw error;
738
+ const key = getKey(instance, ...params), entry = stateByParams[key];
739
+ if (entry?.error) throw entry.error;
740
+ return entry?.data;
741
+ },
742
+ onSubscribe: ({ instance, state }, ...params) => {
743
+ const subscriptionId = insecureRandomId(), key = getKey(instance, ...params);
744
+ return state.set("addSubscription", (prev) => ({
745
+ stateByParams: {
746
+ ...prev.stateByParams,
747
+ [key]: {
748
+ ...prev.stateByParams[key],
749
+ instance,
750
+ key,
751
+ params: prev.stateByParams[key]?.params || params,
752
+ subscriptions: [...prev.stateByParams[key]?.subscriptions || [], subscriptionId]
753
+ }
754
+ }
755
+ })), () => {
756
+ setCleanupTimeout(() => {
757
+ state.set("removeSubscription", (prev) => {
758
+ const entry = prev.stateByParams[key];
759
+ if (!entry) return prev;
760
+ const newSubs = (entry.subscriptions || []).filter((id) => id !== subscriptionId);
761
+ return newSubs.length === 0 ? { stateByParams: omitProperty(prev.stateByParams, key) } : {
762
+ stateByParams: {
763
+ ...prev.stateByParams,
764
+ [key]: {
765
+ ...entry,
766
+ subscriptions: newSubs
767
+ }
768
+ }
769
+ };
770
+ });
771
+ }, stateExpirationDelay);
772
+ };
773
+ }
774
+ })
775
+ ), resolveState = bindActionGlobally(
776
+ store,
777
+ ({ instance }, ...params) => firstValueFrom(getState(instance, ...params).observable.pipe(first((i) => i !== void 0)))
778
+ );
779
+ return { getState, resolveState };
780
+ }
581
781
  const API_VERSION$5 = "v2025-02-19", datasets = createFetcherStore({
582
782
  name: "Datasets",
583
783
  getKey: (instance, options) => {
@@ -1146,17 +1346,17 @@ const listen = ({ state }, documentId) => {
1146
1346
  const { sharedListener, fetchDocument } = state.get();
1147
1347
  return sharedListener.events.pipe(
1148
1348
  concatMap((e) => e.type === "welcome" || e.type === "reset" ? fetchDocument(documentId).pipe(
1149
- map$1((document) => ({ type: "sync", document }))
1349
+ map((document) => ({ type: "sync", document }))
1150
1350
  ) : e.type === "mutation" && e.documentId === documentId ? of(e) : EMPTY),
1151
1351
  sortListenerEvents(),
1152
1352
  withLatestFrom(
1153
1353
  state.observable.pipe(
1154
- map$1((s) => s.documentStates[documentId]),
1354
+ map((s) => s.documentStates[documentId]),
1155
1355
  filter$1(Boolean),
1156
1356
  distinctUntilChanged()
1157
1357
  )
1158
1358
  ),
1159
- map$1(([next, documentState]) => {
1359
+ map(([next, documentState]) => {
1160
1360
  if (next.type === "sync")
1161
1361
  return {
1162
1362
  type: "sync",
@@ -2578,7 +2778,7 @@ function createFetchDocument(instance, resource) {
2578
2778
  resource
2579
2779
  }).observable.pipe(
2580
2780
  switchMap((client) => createDocumentLoaderFromClient(client)(documentId)),
2581
- map$1((result) => {
2781
+ map((result) => {
2582
2782
  if (!result.accessible) {
2583
2783
  if (result.reason === "existence") return null;
2584
2784
  throw new Error(`Document with ID \`${documentId}\` is inaccessible due to permissions.`);
@@ -2697,7 +2897,7 @@ const _resolveDocument = bindActionByResource(
2697
2897
  }) => {
2698
2898
  const { events } = state.get();
2699
2899
  return state.observable.pipe(
2700
- map$1(applyFirstQueuedTransaction),
2900
+ map(applyFirstQueuedTransaction),
2701
2901
  distinctUntilChanged(),
2702
2902
  tap$1((next) => state.set("applyFirstQueuedTransaction", next)),
2703
2903
  catchError$1((error, caught) => {
@@ -2733,10 +2933,10 @@ const _resolveDocument = bindActionByResource(
2733
2933
  ),
2734
2934
  { leading: !1, trailing: !0 }
2735
2935
  ),
2736
- map$1(transitionAppliedTransactionsToOutgoing),
2936
+ map(transitionAppliedTransactionsToOutgoing),
2737
2937
  distinctUntilChanged((a, b) => a.outgoing?.transactionId === b.outgoing?.transactionId),
2738
2938
  tap$1((next) => state.set("transitionAppliedTransactionsToOutgoing", next)),
2739
- map$1((s) => s.outgoing),
2939
+ map((s) => s.outgoing),
2740
2940
  distinctUntilChanged(),
2741
2941
  withLatestFrom(
2742
2942
  getClientState(instance, {
@@ -2750,7 +2950,7 @@ const _resolveDocument = bindActionByResource(
2750
2950
  state.set("revertOutgoingTransaction", revertOutgoingTransaction);
2751
2951
  const message = error instanceof Error ? error.message : "Request failed";
2752
2952
  return events.next({ type: "reverted", message, outgoing, error }), EMPTY;
2753
- }), toResult = map$1((result) => ({
2953
+ }), toResult = map((result) => ({
2754
2954
  result,
2755
2955
  outgoing
2756
2956
  }));
@@ -2777,7 +2977,7 @@ const _resolveDocument = bindActionByResource(
2777
2977
  const { state } = context, { events } = state.get();
2778
2978
  return state.observable.pipe(
2779
2979
  filter$1((s) => !!s.grants),
2780
- map$1((s) => Object.keys(s.documentStates)),
2980
+ map((s) => Object.keys(s.documentStates)),
2781
2981
  distinctUntilChanged((curr, next) => {
2782
2982
  if (curr.length !== next.length) return !1;
2783
2983
  const currSet = new Set(curr);
@@ -2899,16 +3099,16 @@ async function _applyDocumentActions({ state }, {
2899
3099
  actions: normalizedActions,
2900
3100
  ...disableBatching && { disableBatching }
2901
3101
  }, fatalError$ = state.observable.pipe(
2902
- map$1((s) => s.error),
3102
+ map((s) => s.error),
2903
3103
  first$1(Boolean),
2904
- map$1((error) => ({ type: "error", error }))
3104
+ map((error) => ({ type: "error", error }))
2905
3105
  ), transactionError$ = events.pipe(
2906
3106
  filter$1((e) => e.type === "error"),
2907
3107
  first$1((e) => e.transactionId === transactionId)
2908
3108
  ), appliedTransaction$ = state.observable.pipe(
2909
- map$1((s) => s.applied),
3109
+ map((s) => s.applied),
2910
3110
  distinctUntilChanged(),
2911
- map$1((applied) => applied.find((t) => t.transactionId === transactionId)),
3111
+ map((applied) => applied.find((t) => t.transactionId === transactionId)),
2912
3112
  first$1(Boolean)
2913
3113
  ), successfulTransaction$ = events.pipe(
2914
3114
  filter$1((e) => e.type === "accepted"),
@@ -2981,52 +3181,87 @@ const favorites = createFetcherStore({
2981
3181
  payload
2982
3182
  )
2983
3183
  ).pipe(
2984
- map$1((response) => ({ isFavorited: response.isFavorited })),
3184
+ map((response) => ({ isFavorited: response.isFavorited })),
2985
3185
  catchError$1((err) => (console.error("Favorites service connection error", err), of({ isFavorited: !1 })))
2986
3186
  );
2987
3187
  })
2988
3188
  );
2989
3189
  }
2990
- }), getFavoritesState = favorites.getState, resolveFavoritesState = favorites.resolveState, API_VERSION$2 = "v2025-02-19";
3190
+ }), getFavoritesState = favorites.getState, resolveFavoritesState = favorites.resolveState, API_VERSION$2 = "vX";
3191
+ function serializeInclude(include) {
3192
+ return include?.length ? [...include].sort().join(",") : void 0;
3193
+ }
3194
+ const installations = defineFetcher({
3195
+ name: "installations",
3196
+ getKey: (_instance, options) => [
3197
+ options.organizationId,
3198
+ serializeInclude(options.include) ?? "",
3199
+ options.limit ?? "",
3200
+ options.cursor ?? ""
3201
+ ].join(":"),
3202
+ fetch: (instance) => (options) => getClientState(instance, { apiVersion: API_VERSION$2, scope: "global" }).observable.pipe(
3203
+ switchMap(
3204
+ (client) => client.observable.request({
3205
+ uri: "/installations",
3206
+ query: buildQuery({
3207
+ organizationId: options.organizationId,
3208
+ include: serializeInclude(options.include),
3209
+ limit: options.limit,
3210
+ cursor: options.cursor
3211
+ }),
3212
+ tag: "installations.list"
3213
+ })
3214
+ )
3215
+ ),
3216
+ tags: (data) => [
3217
+ { type: "installation", id: "LIST" },
3218
+ ...data.data.map((installation2) => ({ type: "installation", id: installation2.id }))
3219
+ ]
3220
+ }), installation = defineFetcher({
3221
+ name: "installation",
3222
+ getKey: (_instance, installationId, options) => `${installationId}:${serializeInclude(options?.include) ?? ""}`,
3223
+ fetch: (instance) => (installationId, options) => getClientState(instance, { apiVersion: API_VERSION$2, scope: "global" }).observable.pipe(
3224
+ switchMap(
3225
+ (client) => client.observable.request({
3226
+ uri: `/installations/${installationId}`,
3227
+ query: buildQuery({ include: serializeInclude(options?.include) }),
3228
+ tag: "installations.get"
3229
+ })
3230
+ )
3231
+ ),
3232
+ tags: (data) => [{ type: "installation", id: data.id }]
3233
+ }), API_VERSION$1 = "v2025-02-19";
2991
3234
  function resolveOrganizationId(options) {
2992
3235
  const organizationId = options?.organizationId;
2993
3236
  if (!organizationId)
2994
3237
  throw new Error("An organizationId is required to use the organization API.");
2995
3238
  return organizationId;
2996
3239
  }
2997
- function normalizeOrganizationOptions$1(options) {
3240
+ function normalizeOrganizationOptions(options) {
2998
3241
  return {
2999
3242
  includeMembers: options?.includeMembers ?? !1,
3000
3243
  includeFeatures: options?.includeFeatures ?? !1
3001
3244
  };
3002
3245
  }
3003
3246
  function getOrganizationCacheKey(_instance, options) {
3004
- const organizationId = resolveOrganizationId(options), { includeMembers, includeFeatures } = normalizeOrganizationOptions$1(options);
3247
+ const organizationId = resolveOrganizationId(options), { includeMembers, includeFeatures } = normalizeOrganizationOptions(options);
3005
3248
  return `organization:${organizationId}${includeMembers ? ":members" : ""}${includeFeatures ? ":features" : ""}`;
3006
3249
  }
3007
- const organization = createFetcherStore({
3008
- name: "Organization",
3250
+ const organization = defineFetcher({
3251
+ name: "organization",
3009
3252
  getKey: getOrganizationCacheKey,
3010
- fetcher: (instance) => (options) => {
3011
- const organizationId = resolveOrganizationId(options);
3012
- return getClientState(instance, {
3013
- apiVersion: API_VERSION$2,
3014
- scope: "global"
3015
- }).observable.pipe(
3016
- switchMap((client) => {
3017
- const normalized = normalizeOrganizationOptions$1(options), query = Object.fromEntries(
3018
- Object.entries(normalized).filter(([, value]) => value !== void 0).map(([key, value]) => [key, String(value)])
3019
- );
3020
- return client.observable.request({
3021
- uri: `/organizations/${organizationId}`,
3022
- query,
3023
- tag: "organization.get"
3024
- });
3253
+ fetch: (instance) => (options) => getClientState(instance, { apiVersion: API_VERSION$1, scope: "global" }).observable.pipe(
3254
+ switchMap(
3255
+ (client) => client.observable.request({
3256
+ uri: `/organizations/${resolveOrganizationId(options)}`,
3257
+ query: buildQuery(normalizeOrganizationOptions(options)),
3258
+ tag: "organizations.get"
3025
3259
  })
3026
- );
3027
- }
3028
- }), getOrganizationState = organization.getState, resolveOrganization = organization.resolveState, API_VERSION$1 = "v2025-02-19";
3029
- function normalizeOrganizationOptions(options) {
3260
+ )
3261
+ ),
3262
+ tags: (data) => [{ type: "organization", id: data.id }]
3263
+ }), API_VERSION = "v2025-02-19";
3264
+ function normalizeOrganizationsOptions(options) {
3030
3265
  return {
3031
3266
  includeImplicitMemberships: options?.includeImplicitMemberships ?? !1,
3032
3267
  includeMembers: options?.includeMembers ?? !1,
@@ -3034,28 +3269,26 @@ function normalizeOrganizationOptions(options) {
3034
3269
  };
3035
3270
  }
3036
3271
  function getOrganizationsCacheKey(_instance, options) {
3037
- const { includeMembers, includeFeatures, includeImplicitMemberships } = normalizeOrganizationOptions(options);
3272
+ const { includeMembers, includeFeatures, includeImplicitMemberships } = normalizeOrganizationsOptions(options);
3038
3273
  return `organizations${includeMembers ? ":members" : ""}${includeFeatures ? ":features" : ""}${includeImplicitMemberships ? ":implicit" : ""}`;
3039
3274
  }
3040
- const organizations = createFetcherStore({
3041
- name: "Organizations",
3275
+ const organizations = defineFetcher({
3276
+ name: "organizations",
3042
3277
  getKey: getOrganizationsCacheKey,
3043
- fetcher: (instance) => (options) => getClientState(instance, {
3044
- apiVersion: API_VERSION$1,
3045
- scope: "global"
3046
- }).observable.pipe(
3047
- switchMap((client) => {
3048
- const normalized = normalizeOrganizationOptions(options), query = Object.fromEntries(
3049
- Object.entries(normalized).filter(([, value]) => value !== void 0).map(([key, value]) => [key, String(value)])
3050
- );
3051
- return client.observable.request({
3278
+ fetch: (instance) => (options) => getClientState(instance, { apiVersion: API_VERSION, scope: "global" }).observable.pipe(
3279
+ switchMap(
3280
+ (client) => client.observable.request({
3052
3281
  uri: "/organizations",
3053
- query,
3054
- tag: "organizations.get"
3055
- });
3056
- })
3057
- )
3058
- }), getOrganizationsState = organizations.getState, resolveOrganizations = organizations.resolveState, usersStore = defineStore({
3282
+ query: buildQuery(normalizeOrganizationsOptions(options)),
3283
+ tag: "organizations.list"
3284
+ })
3285
+ )
3286
+ ),
3287
+ tags: (data) => [
3288
+ { type: "organization", id: "LIST" },
3289
+ ...data.map((org) => ({ type: "organization", id: org.id }))
3290
+ ]
3291
+ }), usersStore = defineStore({
3059
3292
  name: "UsersStore",
3060
3293
  getInitialState: () => ({ users: {} }),
3061
3294
  initialize: (context) => {
@@ -3063,7 +3296,7 @@ const organizations = createFetcherStore({
3063
3296
  return () => subscription.unsubscribe();
3064
3297
  }
3065
3298
  }), errorHandler = (state) => (error) => state.set("setError", { error }), listenForLoadMoreAndFetch = ({ state, instance }) => state.observable.pipe(
3066
- map$1((s) => new Set(Object.keys(s.users))),
3299
+ map((s) => new Set(Object.keys(s.users))),
3067
3300
  distinctUntilChanged((curr, next) => curr.size !== next.size ? !1 : Array.from(next).every((i) => curr.has(i))),
3068
3301
  startWith$1(/* @__PURE__ */ new Set()),
3069
3302
  pairwise$1(),
@@ -3093,7 +3326,7 @@ const organizations = createFetcherStore({
3093
3326
  uri: `/users/${userId}`,
3094
3327
  tag: "users.get"
3095
3328
  }).pipe(
3096
- map$1((user) => ({
3329
+ map((user) => ({
3097
3330
  data: [{
3098
3331
  sanityUserId: user.sanityUserId,
3099
3332
  profile: {
@@ -3121,14 +3354,14 @@ const organizations = createFetcherStore({
3121
3354
  );
3122
3355
  const scope = userId.startsWith("g") ? "global" : void 0, client = getClient(instance, {
3123
3356
  scope,
3124
- apiVersion: API_VERSION$8
3357
+ apiVersion: API_VERSION$c
3125
3358
  }), resourceType2 = options.resourceType || "project", resourceId = resourceType2 === "organization" ? options.organizationId : options.projectId;
3126
3359
  return resourceId ? client.observable.request({
3127
3360
  method: "GET",
3128
3361
  uri: `access/${resourceType2}/${resourceId}/users/${userId}`,
3129
3362
  tag: "users.get"
3130
3363
  }).pipe(
3131
- map$1((response) => "sanityUserId" in response ? {
3364
+ map((response) => "sanityUserId" in response ? {
3132
3365
  data: [response],
3133
3366
  totalCount: 1,
3134
3367
  nextCursor: null
@@ -3139,14 +3372,14 @@ const organizations = createFetcherStore({
3139
3372
  }
3140
3373
  const projectId = options.projectId, resourceType = options.resourceType ?? (options.organizationId ? "organization" : projectId ? "project" : "organization"), organizationId$ = options.organizationId ? of(options.organizationId) : getDashboardOrganizationId$1(instance).observable.pipe(
3141
3374
  filter$1((i) => typeof i == "string")
3142
- ), resource$ = resourceType === "project" ? projectId ? of({ type: "project", id: projectId }) : throwError(() => new Error("Project ID required for this API.")) : organizationId$.pipe(map$1((id) => ({ type: "organization", id }))), client$ = getClientState(instance, {
3375
+ ), resource$ = resourceType === "project" ? projectId ? of({ type: "project", id: projectId }) : throwError(() => new Error("Project ID required for this API.")) : organizationId$.pipe(map((id) => ({ type: "organization", id }))), client$ = getClientState(instance, {
3143
3376
  scope: "global",
3144
- apiVersion: API_VERSION$8
3377
+ apiVersion: API_VERSION$c
3145
3378
  }).observable, loadMore$ = state.observable.pipe(
3146
- map$1((s) => s.users[group$.key]?.lastLoadMoreRequest),
3379
+ map((s) => s.users[group$.key]?.lastLoadMoreRequest),
3147
3380
  distinctUntilChanged()
3148
3381
  ), cursor$ = state.observable.pipe(
3149
- map$1((s) => s.users[group$.key]?.nextCursor),
3382
+ map((s) => s.users[group$.key]?.nextCursor),
3150
3383
  distinctUntilChanged(),
3151
3384
  filter$1((cursor) => cursor !== null)
3152
3385
  );
@@ -3209,7 +3442,7 @@ const organizations = createFetcherStore({
3209
3442
  ) : NEVER;
3210
3443
  state.set("initializeRequest", initializeRequest(key));
3211
3444
  const resolved$ = state.observable.pipe(
3212
- map$1(getCurrent),
3445
+ map(getCurrent),
3213
3446
  first$1((i) => i !== void 0)
3214
3447
  );
3215
3448
  return firstValueFrom(race([resolved$, aborted$]));
@@ -3233,7 +3466,7 @@ const organizations = createFetcherStore({
3233
3466
  ), getUserState = bindActionGlobally(
3234
3467
  usersStore,
3235
3468
  ({ instance }, { userId, ...options }) => getUsersState(instance, { userId, ...options }).observable.pipe(
3236
- map$1((res) => res?.data[0]),
3469
+ map((res) => res?.data[0]),
3237
3470
  distinctUntilChanged((a, b) => a?.profile.updatedAt === b?.profile.updatedAt)
3238
3471
  )
3239
3472
  ), resolveUser = bindActionGlobally(
@@ -3289,7 +3522,7 @@ const handleIncomingMessage = (event) => {
3289
3522
  throw new Error(`Got unknown presence event: ${JSON.stringify(event)}`);
3290
3523
  }
3291
3524
  }, createBifurTransport = (options) => {
3292
- const { client, token$, sessionId } = options, bifur = getBifurClient(client, token$), incomingEvents$ = bifur.listen("presence").pipe(map(handleIncomingMessage)), dispatchMessage = (message) => {
3525
+ const { client, token$, sessionId } = options, bifur = getBifurClient(client, token$), incomingEvents$ = bifur.listen("presence").pipe(map$1(handleIncomingMessage)), dispatchMessage = (message) => {
3293
3526
  switch (message.type) {
3294
3527
  case "rollCall":
3295
3528
  return bifur.request("presence_rollcall", { session: sessionId });
@@ -3381,12 +3614,12 @@ const handleIncomingMessage = (event) => {
3381
3614
  selector: (context) => selectPresence(context.state),
3382
3615
  onSubscribe: (context) => {
3383
3616
  const resource = context.key.resource, userIds$ = context.state.observable.pipe(
3384
- map$1(
3617
+ map(
3385
3618
  (state) => Array.from(state.locations.values()).map((l) => l.userId).filter((id) => !!id)
3386
3619
  ),
3387
3620
  distinctUntilChanged((a, b) => a.length === b.length && a.every((v, i) => v === b[i]))
3388
3621
  ), organizationId$ = isCanvasResource(resource) ? context.state.observable.pipe(
3389
- map$1((s) => s.organizationId),
3622
+ map((s) => s.organizationId),
3390
3623
  filter$1((id) => id !== void 0),
3391
3624
  first$1()
3392
3625
  ) : of(void 0), subscription = combineLatest([userIds$, organizationId$]).pipe(
@@ -3505,10 +3738,10 @@ const BATCH_DEBOUNCE_TIME = 50, isSetEqual = (a, b) => a.size === b.size && Arra
3505
3738
  key: { resource, perspective }
3506
3739
  }) => {
3507
3740
  const documentProjections$ = state.observable.pipe(
3508
- map$1((s) => s.documentProjections),
3741
+ map((s) => s.documentProjections),
3509
3742
  distinctUntilChanged(isDeepEqual)
3510
3743
  ), activeDocumentIds$ = state.observable.pipe(
3511
- map$1(({ subscriptions }) => new Set(Object.keys(subscriptions).map((id) => DocumentId(id)))),
3744
+ map(({ subscriptions }) => new Set(Object.keys(subscriptions).map((id) => DocumentId(id)))),
3512
3745
  distinctUntilChanged(isSetEqual)
3513
3746
  ), pendingUpdateSubscription = activeDocumentIds$.pipe(
3514
3747
  debounceTime(BATCH_DEBOUNCE_TIME),
@@ -3585,14 +3818,14 @@ const BATCH_DEBOUNCE_TIME = 50, isSetEqual = (a, b) => a.size === b.size && Arra
3585
3818
  filter$1(
3586
3819
  (pair) => pair[0] !== void 0 && pair[1] !== void 0
3587
3820
  ),
3588
- map$1(([projection, status]) => ({
3821
+ map(([projection, status]) => ({
3589
3822
  data: projection,
3590
3823
  ids,
3591
3824
  statusResults: status
3592
3825
  }))
3593
3826
  );
3594
3827
  }),
3595
- map$1(({ ids, data, statusResults }) => {
3828
+ map(({ ids, data, statusResults }) => {
3596
3829
  const documentStatuses = processStatusQueryResults(statusResults);
3597
3830
  state.set("updateStatuses", (prev) => ({
3598
3831
  documentStatuses: {
@@ -3712,7 +3945,7 @@ function getPreviewState(instance, options) {
3712
3945
  return {
3713
3946
  getCurrent: () => transformResult(projectionState.getCurrent()),
3714
3947
  subscribe: (callback) => projectionState.subscribe(callback),
3715
- observable: projectionState.observable.pipe(map$1(transformResult))
3948
+ observable: projectionState.observable.pipe(map(transformResult))
3716
3949
  };
3717
3950
  }
3718
3951
  function resolveProjection(...args) {
@@ -3740,91 +3973,6 @@ async function resolvePreview(instance, options) {
3740
3973
  isPending: projectionResult.isPending
3741
3974
  } : { data: null, isPending: projectionResult.isPending };
3742
3975
  }
3743
- const API_VERSION = "v2025-02-19";
3744
- function normalizeProjectsOptions(options) {
3745
- return {
3746
- organizationId: options?.organizationId,
3747
- includeMembers: options?.includeMembers ?? !1,
3748
- includeFeatures: options?.includeFeatures ?? !0,
3749
- onlyExplicitMembership: options?.onlyExplicitMembership ?? !1
3750
- };
3751
- }
3752
- function getProjectsCacheKey(_instance, options) {
3753
- const { organizationId, includeMembers, includeFeatures, onlyExplicitMembership } = normalizeProjectsOptions(options);
3754
- return `projects${organizationId ? `:org:${organizationId}` : ""}${includeMembers ? ":members" : ""}${includeFeatures ? ":features" : ""}${onlyExplicitMembership ? ":explicit" : ""}`;
3755
- }
3756
- const projects = createFetcherStore({
3757
- name: "Projects",
3758
- getKey: getProjectsCacheKey,
3759
- fetcher: (instance) => (options) => getClientState(instance, {
3760
- apiVersion: API_VERSION,
3761
- scope: "global"
3762
- }).observable.pipe(
3763
- switchMap((client) => {
3764
- const normalized = normalizeProjectsOptions(options), query = Object.fromEntries(
3765
- Object.entries(normalized).filter(([, value]) => value !== void 0).map(([key, value]) => [key, String(value)])
3766
- );
3767
- return client.observable.request({
3768
- uri: "/projects",
3769
- query,
3770
- tag: "projects.get"
3771
- });
3772
- })
3773
- )
3774
- }), getProjectsState = projects.getState, resolveProjects = projects.resolveState;
3775
- function defineIntent(intent) {
3776
- if (!intent.id)
3777
- throw new Error("Intent must have an id");
3778
- if (!intent.action)
3779
- throw new Error("Intent must have an action");
3780
- if (!intent.title)
3781
- throw new Error("Intent must have a title");
3782
- if (!Array.isArray(intent.filters))
3783
- throw new Error("Intent must have a filters array");
3784
- if (intent.filters.length === 0)
3785
- throw new Error(
3786
- "Intent must have at least one filter. If you want to match everything, use {types: ['*']}"
3787
- );
3788
- return intent.filters.forEach((filter2, index) => {
3789
- validateFilter(filter2, index);
3790
- }), intent;
3791
- }
3792
- function validateFilter(filter2, index) {
3793
- const filterContext = `Filter at index ${index}`;
3794
- if (!filter2 || typeof filter2 != "object")
3795
- throw new Error(`${filterContext} must be an object`);
3796
- if (filter2.types === void 0)
3797
- throw new Error(
3798
- `${filterContext} must have a types property. Use ['*'] to match all document types.`
3799
- );
3800
- if (filter2.projectId !== void 0) {
3801
- if (typeof filter2.projectId != "string")
3802
- throw new Error(`${filterContext}: projectId must be a string`);
3803
- if (filter2.projectId.trim() === "")
3804
- throw new Error(`${filterContext}: projectId cannot be empty`);
3805
- }
3806
- if (filter2.dataset !== void 0) {
3807
- if (typeof filter2.dataset != "string")
3808
- throw new Error(`${filterContext}: dataset must be a string`);
3809
- if (filter2.dataset.trim() === "")
3810
- throw new Error(`${filterContext}: dataset cannot be empty`);
3811
- if (filter2.projectId === void 0)
3812
- throw new Error(`${filterContext}: dataset cannot be specified without projectId`);
3813
- }
3814
- if (!Array.isArray(filter2.types))
3815
- throw new Error(`${filterContext}: types must be an array`);
3816
- if (filter2.types.length === 0)
3817
- throw new Error(`${filterContext}: types array cannot be empty`);
3818
- if (filter2.types.forEach((type, typeIndex) => {
3819
- if (typeof type != "string")
3820
- throw new Error(`${filterContext}: types[${typeIndex}] must be a string`);
3821
- if (type.trim() === "")
3822
- throw new Error(`${filterContext}: types[${typeIndex}] cannot be empty`);
3823
- }), filter2.types.includes("*") && filter2.types.length > 1)
3824
- throw new Error(
3825
- `${filterContext}: when using wildcard '*', it must be the only type in the array`
3826
- );
3827
- }
3828
3976
  function getCorsErrorProjectId(error) {
3829
3977
  if (!(error instanceof CorsOriginError)) return null;
3830
3978
  const projMatch = (error.message || "").match(/manage\/project\/([^/?#]+)/);
@@ -3845,8 +3993,11 @@ export {
3845
3993
  agentPrompt,
3846
3994
  agentTransform,
3847
3995
  agentTranslate,
3996
+ application,
3997
+ applications,
3848
3998
  applyDocumentActions,
3849
3999
  archiveRelease,
4000
+ checkPermissions,
3850
4001
  configureLogging,
3851
4002
  createDatasetHandle,
3852
4003
  createDocument,
@@ -3856,9 +4007,11 @@ export {
3856
4007
  createProjectHandle,
3857
4008
  createRelease,
3858
4009
  createSanityInstance,
3859
- defineIntent,
4010
+ createUserApplication,
4011
+ deleteApplication,
3860
4012
  deleteDocument,
3861
4013
  deleteRelease,
4014
+ deleteUserApplication,
3862
4015
  destroyController,
3863
4016
  discardDocument,
3864
4017
  editDocument,
@@ -3885,16 +4038,12 @@ export {
3885
4038
  getOrCreateChannel,
3886
4039
  getOrCreateController,
3887
4040
  getOrCreateNode,
3888
- getOrganizationState,
3889
- getOrganizationsState,
3890
4041
  getPathDepth,
3891
4042
  getPermissionsState,
3892
4043
  getPerspectiveState,
3893
4044
  getPresence,
3894
4045
  getPreviewState,
3895
- getProjectState,
3896
4046
  getProjectionState,
3897
- getProjectsState,
3898
4047
  getQueryKey,
3899
4048
  getQueryState,
3900
4049
  getReleaseDocumentId,
@@ -3903,6 +4052,8 @@ export {
3903
4052
  getUsersKey,
3904
4053
  getUsersState,
3905
4054
  handleAuthCallback,
4055
+ installation,
4056
+ installations,
3906
4057
  isCanvasResource,
3907
4058
  isCanvasSource,
3908
4059
  isDatasetResource,
@@ -3917,8 +4068,12 @@ export {
3917
4068
  loadMoreUsers,
3918
4069
  logout,
3919
4070
  observeOrganizationVerificationState,
4071
+ organization,
4072
+ organizations,
3920
4073
  parseQueryKey,
3921
4074
  parseUsersKey,
4075
+ project,
4076
+ projects,
3922
4077
  publishDocument,
3923
4078
  publishRelease,
3924
4079
  releaseChannel,
@@ -3926,13 +4081,9 @@ export {
3926
4081
  resolveDatasets,
3927
4082
  resolveDocument,
3928
4083
  resolveFavoritesState,
3929
- resolveOrganization,
3930
- resolveOrganizations,
3931
4084
  resolvePermissions,
3932
4085
  resolvePreview,
3933
- resolveProject,
3934
4086
  resolveProjection,
3935
- resolveProjects,
3936
4087
  resolveQuery,
3937
4088
  resolveUser,
3938
4089
  resolveUsers,
@@ -3944,6 +4095,10 @@ export {
3944
4095
  transformProjectionToPreview,
3945
4096
  unarchiveRelease,
3946
4097
  unpublishDocument,
3947
- unscheduleRelease
4098
+ unscheduleRelease,
4099
+ updateApplication,
4100
+ updateUserApplication,
4101
+ userApplication,
4102
+ userApplications
3948
4103
  };
3949
4104
  //# sourceMappingURL=index.js.map