@ai4b-team/fsaos-gateway-sdk 5.7.0 → 5.7.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.
package/dist/index.d.cts CHANGED
@@ -1710,6 +1710,32 @@ type TranscriptPage = ChannelMessagesPage & {
1710
1710
  olderBefore?: number;
1711
1711
  };
1712
1712
 
1713
+ /** Native item actions supported by the existing check-item-access method. */
1714
+ type PermissionAction = 'view' | 'edit' | 'delete' | 'admin';
1715
+ /**
1716
+ * Native item access for the seated identity. Pass an already-known item UUID
1717
+ * to avoid resolving its path. This does not predict approval, entitlement or
1718
+ * method-specific mutation checks; the actual operation remains authoritative.
1719
+ * Disabled, loading, refreshing and failed checks never expose cached grants.
1720
+ */
1721
+ declare function usePermissions(item?: string | null, requested?: string[]): {
1722
+ data: Record<string, boolean>;
1723
+ loading: boolean;
1724
+ error: Error | null;
1725
+ /** Explicit refresh for a user action; no automatic retry or polling. */
1726
+ refetch: () => Promise<void>;
1727
+ };
1728
+ /** Shares the same query as usePermissions for this identity/item/action. */
1729
+ declare function usePermission(action?: string, item?: string | null): {
1730
+ data: {
1731
+ allowed: boolean;
1732
+ };
1733
+ loading: boolean;
1734
+ error: Error | null;
1735
+ /** Explicit refresh for a user action; no automatic retry or polling. */
1736
+ refetch: () => Promise<void>;
1737
+ };
1738
+
1713
1739
  /**
1714
1740
  * Returns whether scope has been established. Useful for gating UI that
1715
1741
  * depends on scope-aware data.
@@ -2464,20 +2490,7 @@ declare function useTheme(): {
2464
2490
  loading: boolean;
2465
2491
  error: null;
2466
2492
  };
2467
- /** Check permission for an action on a path. */
2468
- declare function usePermission(_action?: string, _path?: string): {
2469
- data: {
2470
- allowed: boolean;
2471
- };
2472
- loading: boolean;
2473
- error: null;
2474
- };
2475
- /** Check multiple permissions at once. */
2476
- declare function usePermissions(_path?: string, actions?: string[]): {
2477
- data: Record<string, boolean>;
2478
- loading: boolean;
2479
- error: null;
2480
- };
2493
+
2481
2494
  interface PrincipalData {
2482
2495
  id: string;
2483
2496
  principalId: string | null;
@@ -4200,4 +4213,4 @@ declare function usePersonalSections(contextId: string | null, collection: Secti
4200
4213
  contextKey: string;
4201
4214
  };
4202
4215
 
4203
- export { type AcceptInviteParams, type AcceptInviteResult, type AccountInfo, type AnswerInputParams, type ArtifactDeltaEvent, type ArtifactDoneEvent, type ArtifactEvent, type ArtifactOpenedEvent, type ArtifactState, type ArtifactStatus, type ArtifactStreamState, type ArtifactSurfaceType, CHANNEL_AI_MODES, type CancelQueuedTurnOptions, type CancelQueuedTurnResponse, type CancelQueuedTurnState, type CancelTurnOptions, type CancelTurnResponse, type CancelTurnState, type Channel, type ChannelAiMode, type ChannelCard, type ChannelMessage, type ChannelMessagesOptions, type ChannelMessagesPage, type ChannelMessagesResponse, type ChannelsOptions, type ComponentOpener, ComponentRenderer, type ConnectionState, type CreateAgentParams, type CreateAgentResult, type CreateInvitationParams, type CreateParams, type DeleteParams, EnforcementDeniedError, type EnforcementPayload, type FieldDescriptor, type FilePurchaseReceipt, type FileRef, FormSubmissionError, type FormSubmissionReceipt, type FsaosRuntime, type GatewayParams, GatewayRequestError, type GatewayRequestOptions, type GatewayResponse, HostSessionUnavailableError, type HostSessionWelcome, type IncrementalItemsOptions, type InfiniteChannelMessagesOptions, type InfiniteItemsOptions, type InitializeFsaosOptions, type InteractionReceipt, InteractionTrackingError, type InvitationChangeReceipt, type InvitationPage, type InvitationReceipt, type InvitationSummary, type InviteMemberParams, type InviteMemberResult, type ItemVersionsOptions, type ItemVersionsResult, type ItemsDiscovery, type ItemsFilter, type ItemsFilterGroup, KernelProvider, type LinkParams, type LoadMountsOptions, type MemberRole, type MessageRepliesCursor, type MessageRepliesOptions, type MessageRepliesPage, type MessageReplyContext, type MintedAsset, type MintedAssetState, type MountRef, type MoveParams, type Notification, type NotificationsOptions, type OpenEnvelope, type OpenOptions, type PathSubscriptionState, type PersonalItemOrderKey, type PersonalSection, type PinTarget, type PinnedItem, type PrincipalData, type PublicSourceConfig, type PublishedBundle, type PublishedComponentSource, type PublishedComponentStatus, type PurchaseJourneyRequest, type ReadPriority, type ReadTiming, type ResolveItemsResponse, type ResolveParams, type ResolveResponse, type ResolveResultItem, type ResolvedItem, type SeatMemberParams, type SectionChange, type SectionCollection, type SectionDestination, type SectionSnapshot, type SectionTarget, type SendMessageParams, type SendMessageResult, type ServeHostSessionOptions, type SessionEntry, type SourceCaptureAdapter, type SourceIdentityStorage, type StartTrackingOptions, type SteerTurnOptions, type SteerTurnResponse, type SteerTurnState, type SubmitFormOptions, type SwitcherAccount, type TimelineEvent, type TimelineHistoryEvent, type TimelineHistoryOptions, type TrackEventOptions, type TurnQueueEntry, type TurnQueueEntryState, type TypeDefinition, type TypeHelpers, type TypeSchema, type UnreadCountsOptions, type UpdateParams, type UpdatePrincipalParams, type UploadItem, type UploadOptions, type UploadResult, type UseArtifactStreamReturn, type UseFileUploadReturn, type UseTimelineHistoryReturn, type VFSEdge, type VFSItem, type VfsItemChange, type WorkCorrelation, type WorkspaceOptions, type WorkspaceSession, acceptInvitation, acceptInvite, answerInput, assignPersonalSection, auth, awaitAnchorReady, awaitScopeReady, callTool, cancelInvitation, cancelQueuedTurn, cancelTurn, clearCachedToken, clearSession, configureGatewayReads, connectHostSession, createAgent, createInvitation, createItem, disconnectSSE, disposeVfsRealtimeWs, electHomeAnchor, emitEvent, fetchChannelMessages, fetchChannelMessagesPage, fetchChannelMessagesWithCards, fetchEdgesForItem, fetchItemHistory, fetchItemVersions, fetchItems, fetchMemberFocus, fetchMessageReplies, fetchMessageReplyContexts, fetchOpenEnvelope, fetchRecentActivity, fetchResolvedItems, fetchTimelineHistory, fetchTurnQueueEntries, fetchTypeDefinitions, fetchVfsChildren, fetchVfsChildrenPage, fetchVfsItem, fetchVfsItemById, fetchVfsTree, filePurchaseNextUrl, funnelCheckoutLink, gatewayCall, getAccessToken, getAnchor, getAnchorRef, getAnchorVersion, getAssetUrl, getDefaultSort, getFilePurchase, getHomeAnchor, getInvitation, getMountVersion, getMounts, getPathSubscriptionState, getQueryClient, getRequiredFormFields, getScope, getScopeVersion, getServerClockOffsetMs, getServerClockSyncedAt, getSessionEntry, hasServerClock, initSession, initVfsRealtimeWs, initializeFsaos, initializeWorkspace, interpretSchema, invalidateAllVfs, invalidateChannelMessages, invalidateChildren, invalidateItem, invalidateOpenEnvelope, invalidatePathAndParent, invalidateSubtree, invalidateTypes, inviteMember, isAnchorReady, isChannelPath, isListableItemsFilter, isScopeReady, itemsFilterFromQueryFilter, listChildren, listInvitations, loadMounts, loadPublishedBundle, mount, mountRealtimeScope, normalizeItem, onConnectionStateChange, pathSubscriptionMatches, personalSectionsKey, ping, pushChanges, queryClient, readItem, refreshQuery, registerCleanup, rejectInvitation, replaceMounts, resendInvitation, resetAllSdkState, resolvePrincipalId, resubscribePath, seatMember, selectMount, sendMessage, serveHostSession, serverDeadlinePassed, serverMsUntil, serverNow, setAnchor, setCachedToken, setQueryClient, setScope, setupRequireShim, signal, startFileCheckout, startTracking, steerTurn, submitForm, subscribeAnchor, subscribeArtifactStream, subscribeMounts, subscribeScope, subscribeToEvents, subscribeToPath, subscribeToScope, trackAction, trackEvent, trackPageView, unmountRealtimeScope, updateItem, uploadFile, useAcceptInvite, useAccounts, useAgentTimeline, useAllChannels, useAnswerInput, useArrangement, useArtifactStream, useAsset, useAuth, useChannelMessages, useChannels, useChildren, useComponent, useCreate, useCreateAgent, useDelete, useDmChannels, useEdges, useEventStream, useFileUpload, useIncrementalItems, useInfiniteChannelMessages, useInfiniteChildren, useInfiniteItems, useInviteMember, useItem, useItemById, useItemHistory, useItemVersions, useItems, useLink, useList, useMemberFocus, useMessageReplies, useMintedAsset, useMounts, useMove, useMutation, useNotifications, useOpen, usePermission, usePermissions, usePersonalItemOrder, usePersonalSections, usePinnedItems, usePrincipal, usePublishedComponent, useRealtimeQuery, useRecentActivity, useResolve, useResolvedItems, useScope, useScopeReady, useSearch, useSeatMember, useTheme, useTimelineHistory, useTree, useType, useTypeHelpers, useTypes, useUnreadCounts, useUpdate, useUpdatePrincipal, vfsKeys, waitForPathReady };
4216
+ export { type AcceptInviteParams, type AcceptInviteResult, type AccountInfo, type AnswerInputParams, type ArtifactDeltaEvent, type ArtifactDoneEvent, type ArtifactEvent, type ArtifactOpenedEvent, type ArtifactState, type ArtifactStatus, type ArtifactStreamState, type ArtifactSurfaceType, CHANNEL_AI_MODES, type CancelQueuedTurnOptions, type CancelQueuedTurnResponse, type CancelQueuedTurnState, type CancelTurnOptions, type CancelTurnResponse, type CancelTurnState, type Channel, type ChannelAiMode, type ChannelCard, type ChannelMessage, type ChannelMessagesOptions, type ChannelMessagesPage, type ChannelMessagesResponse, type ChannelsOptions, type ComponentOpener, ComponentRenderer, type ConnectionState, type CreateAgentParams, type CreateAgentResult, type CreateInvitationParams, type CreateParams, type DeleteParams, EnforcementDeniedError, type EnforcementPayload, type FieldDescriptor, type FilePurchaseReceipt, type FileRef, FormSubmissionError, type FormSubmissionReceipt, type FsaosRuntime, type GatewayParams, GatewayRequestError, type GatewayRequestOptions, type GatewayResponse, HostSessionUnavailableError, type HostSessionWelcome, type IncrementalItemsOptions, type InfiniteChannelMessagesOptions, type InfiniteItemsOptions, type InitializeFsaosOptions, type InteractionReceipt, InteractionTrackingError, type InvitationChangeReceipt, type InvitationPage, type InvitationReceipt, type InvitationSummary, type InviteMemberParams, type InviteMemberResult, type ItemVersionsOptions, type ItemVersionsResult, type ItemsDiscovery, type ItemsFilter, type ItemsFilterGroup, KernelProvider, type LinkParams, type LoadMountsOptions, type MemberRole, type MessageRepliesCursor, type MessageRepliesOptions, type MessageRepliesPage, type MessageReplyContext, type MintedAsset, type MintedAssetState, type MountRef, type MoveParams, type Notification, type NotificationsOptions, type OpenEnvelope, type OpenOptions, type PathSubscriptionState, type PermissionAction, type PersonalItemOrderKey, type PersonalSection, type PinTarget, type PinnedItem, type PrincipalData, type PublicSourceConfig, type PublishedBundle, type PublishedComponentSource, type PublishedComponentStatus, type PurchaseJourneyRequest, type ReadPriority, type ReadTiming, type ResolveItemsResponse, type ResolveParams, type ResolveResponse, type ResolveResultItem, type ResolvedItem, type SeatMemberParams, type SectionChange, type SectionCollection, type SectionDestination, type SectionSnapshot, type SectionTarget, type SendMessageParams, type SendMessageResult, type ServeHostSessionOptions, type SessionEntry, type SourceCaptureAdapter, type SourceIdentityStorage, type StartTrackingOptions, type SteerTurnOptions, type SteerTurnResponse, type SteerTurnState, type SubmitFormOptions, type SwitcherAccount, type TimelineEvent, type TimelineHistoryEvent, type TimelineHistoryOptions, type TrackEventOptions, type TurnQueueEntry, type TurnQueueEntryState, type TypeDefinition, type TypeHelpers, type TypeSchema, type UnreadCountsOptions, type UpdateParams, type UpdatePrincipalParams, type UploadItem, type UploadOptions, type UploadResult, type UseArtifactStreamReturn, type UseFileUploadReturn, type UseTimelineHistoryReturn, type VFSEdge, type VFSItem, type VfsItemChange, type WorkCorrelation, type WorkspaceOptions, type WorkspaceSession, acceptInvitation, acceptInvite, answerInput, assignPersonalSection, auth, awaitAnchorReady, awaitScopeReady, callTool, cancelInvitation, cancelQueuedTurn, cancelTurn, clearCachedToken, clearSession, configureGatewayReads, connectHostSession, createAgent, createInvitation, createItem, disconnectSSE, disposeVfsRealtimeWs, electHomeAnchor, emitEvent, fetchChannelMessages, fetchChannelMessagesPage, fetchChannelMessagesWithCards, fetchEdgesForItem, fetchItemHistory, fetchItemVersions, fetchItems, fetchMemberFocus, fetchMessageReplies, fetchMessageReplyContexts, fetchOpenEnvelope, fetchRecentActivity, fetchResolvedItems, fetchTimelineHistory, fetchTurnQueueEntries, fetchTypeDefinitions, fetchVfsChildren, fetchVfsChildrenPage, fetchVfsItem, fetchVfsItemById, fetchVfsTree, filePurchaseNextUrl, funnelCheckoutLink, gatewayCall, getAccessToken, getAnchor, getAnchorRef, getAnchorVersion, getAssetUrl, getDefaultSort, getFilePurchase, getHomeAnchor, getInvitation, getMountVersion, getMounts, getPathSubscriptionState, getQueryClient, getRequiredFormFields, getScope, getScopeVersion, getServerClockOffsetMs, getServerClockSyncedAt, getSessionEntry, hasServerClock, initSession, initVfsRealtimeWs, initializeFsaos, initializeWorkspace, interpretSchema, invalidateAllVfs, invalidateChannelMessages, invalidateChildren, invalidateItem, invalidateOpenEnvelope, invalidatePathAndParent, invalidateSubtree, invalidateTypes, inviteMember, isAnchorReady, isChannelPath, isListableItemsFilter, isScopeReady, itemsFilterFromQueryFilter, listChildren, listInvitations, loadMounts, loadPublishedBundle, mount, mountRealtimeScope, normalizeItem, onConnectionStateChange, pathSubscriptionMatches, personalSectionsKey, ping, pushChanges, queryClient, readItem, refreshQuery, registerCleanup, rejectInvitation, replaceMounts, resendInvitation, resetAllSdkState, resolvePrincipalId, resubscribePath, seatMember, selectMount, sendMessage, serveHostSession, serverDeadlinePassed, serverMsUntil, serverNow, setAnchor, setCachedToken, setQueryClient, setScope, setupRequireShim, signal, startFileCheckout, startTracking, steerTurn, submitForm, subscribeAnchor, subscribeArtifactStream, subscribeMounts, subscribeScope, subscribeToEvents, subscribeToPath, subscribeToScope, trackAction, trackEvent, trackPageView, unmountRealtimeScope, updateItem, uploadFile, useAcceptInvite, useAccounts, useAgentTimeline, useAllChannels, useAnswerInput, useArrangement, useArtifactStream, useAsset, useAuth, useChannelMessages, useChannels, useChildren, useComponent, useCreate, useCreateAgent, useDelete, useDmChannels, useEdges, useEventStream, useFileUpload, useIncrementalItems, useInfiniteChannelMessages, useInfiniteChildren, useInfiniteItems, useInviteMember, useItem, useItemById, useItemHistory, useItemVersions, useItems, useLink, useList, useMemberFocus, useMessageReplies, useMintedAsset, useMounts, useMove, useMutation, useNotifications, useOpen, usePermission, usePermissions, usePersonalItemOrder, usePersonalSections, usePinnedItems, usePrincipal, usePublishedComponent, useRealtimeQuery, useRecentActivity, useResolve, useResolvedItems, useScope, useScopeReady, useSearch, useSeatMember, useTheme, useTimelineHistory, useTree, useType, useTypeHelpers, useTypes, useUnreadCounts, useUpdate, useUpdatePrincipal, vfsKeys, waitForPathReady };
package/dist/index.d.ts CHANGED
@@ -1710,6 +1710,32 @@ type TranscriptPage = ChannelMessagesPage & {
1710
1710
  olderBefore?: number;
1711
1711
  };
1712
1712
 
1713
+ /** Native item actions supported by the existing check-item-access method. */
1714
+ type PermissionAction = 'view' | 'edit' | 'delete' | 'admin';
1715
+ /**
1716
+ * Native item access for the seated identity. Pass an already-known item UUID
1717
+ * to avoid resolving its path. This does not predict approval, entitlement or
1718
+ * method-specific mutation checks; the actual operation remains authoritative.
1719
+ * Disabled, loading, refreshing and failed checks never expose cached grants.
1720
+ */
1721
+ declare function usePermissions(item?: string | null, requested?: string[]): {
1722
+ data: Record<string, boolean>;
1723
+ loading: boolean;
1724
+ error: Error | null;
1725
+ /** Explicit refresh for a user action; no automatic retry or polling. */
1726
+ refetch: () => Promise<void>;
1727
+ };
1728
+ /** Shares the same query as usePermissions for this identity/item/action. */
1729
+ declare function usePermission(action?: string, item?: string | null): {
1730
+ data: {
1731
+ allowed: boolean;
1732
+ };
1733
+ loading: boolean;
1734
+ error: Error | null;
1735
+ /** Explicit refresh for a user action; no automatic retry or polling. */
1736
+ refetch: () => Promise<void>;
1737
+ };
1738
+
1713
1739
  /**
1714
1740
  * Returns whether scope has been established. Useful for gating UI that
1715
1741
  * depends on scope-aware data.
@@ -2464,20 +2490,7 @@ declare function useTheme(): {
2464
2490
  loading: boolean;
2465
2491
  error: null;
2466
2492
  };
2467
- /** Check permission for an action on a path. */
2468
- declare function usePermission(_action?: string, _path?: string): {
2469
- data: {
2470
- allowed: boolean;
2471
- };
2472
- loading: boolean;
2473
- error: null;
2474
- };
2475
- /** Check multiple permissions at once. */
2476
- declare function usePermissions(_path?: string, actions?: string[]): {
2477
- data: Record<string, boolean>;
2478
- loading: boolean;
2479
- error: null;
2480
- };
2493
+
2481
2494
  interface PrincipalData {
2482
2495
  id: string;
2483
2496
  principalId: string | null;
@@ -4200,4 +4213,4 @@ declare function usePersonalSections(contextId: string | null, collection: Secti
4200
4213
  contextKey: string;
4201
4214
  };
4202
4215
 
4203
- export { type AcceptInviteParams, type AcceptInviteResult, type AccountInfo, type AnswerInputParams, type ArtifactDeltaEvent, type ArtifactDoneEvent, type ArtifactEvent, type ArtifactOpenedEvent, type ArtifactState, type ArtifactStatus, type ArtifactStreamState, type ArtifactSurfaceType, CHANNEL_AI_MODES, type CancelQueuedTurnOptions, type CancelQueuedTurnResponse, type CancelQueuedTurnState, type CancelTurnOptions, type CancelTurnResponse, type CancelTurnState, type Channel, type ChannelAiMode, type ChannelCard, type ChannelMessage, type ChannelMessagesOptions, type ChannelMessagesPage, type ChannelMessagesResponse, type ChannelsOptions, type ComponentOpener, ComponentRenderer, type ConnectionState, type CreateAgentParams, type CreateAgentResult, type CreateInvitationParams, type CreateParams, type DeleteParams, EnforcementDeniedError, type EnforcementPayload, type FieldDescriptor, type FilePurchaseReceipt, type FileRef, FormSubmissionError, type FormSubmissionReceipt, type FsaosRuntime, type GatewayParams, GatewayRequestError, type GatewayRequestOptions, type GatewayResponse, HostSessionUnavailableError, type HostSessionWelcome, type IncrementalItemsOptions, type InfiniteChannelMessagesOptions, type InfiniteItemsOptions, type InitializeFsaosOptions, type InteractionReceipt, InteractionTrackingError, type InvitationChangeReceipt, type InvitationPage, type InvitationReceipt, type InvitationSummary, type InviteMemberParams, type InviteMemberResult, type ItemVersionsOptions, type ItemVersionsResult, type ItemsDiscovery, type ItemsFilter, type ItemsFilterGroup, KernelProvider, type LinkParams, type LoadMountsOptions, type MemberRole, type MessageRepliesCursor, type MessageRepliesOptions, type MessageRepliesPage, type MessageReplyContext, type MintedAsset, type MintedAssetState, type MountRef, type MoveParams, type Notification, type NotificationsOptions, type OpenEnvelope, type OpenOptions, type PathSubscriptionState, type PersonalItemOrderKey, type PersonalSection, type PinTarget, type PinnedItem, type PrincipalData, type PublicSourceConfig, type PublishedBundle, type PublishedComponentSource, type PublishedComponentStatus, type PurchaseJourneyRequest, type ReadPriority, type ReadTiming, type ResolveItemsResponse, type ResolveParams, type ResolveResponse, type ResolveResultItem, type ResolvedItem, type SeatMemberParams, type SectionChange, type SectionCollection, type SectionDestination, type SectionSnapshot, type SectionTarget, type SendMessageParams, type SendMessageResult, type ServeHostSessionOptions, type SessionEntry, type SourceCaptureAdapter, type SourceIdentityStorage, type StartTrackingOptions, type SteerTurnOptions, type SteerTurnResponse, type SteerTurnState, type SubmitFormOptions, type SwitcherAccount, type TimelineEvent, type TimelineHistoryEvent, type TimelineHistoryOptions, type TrackEventOptions, type TurnQueueEntry, type TurnQueueEntryState, type TypeDefinition, type TypeHelpers, type TypeSchema, type UnreadCountsOptions, type UpdateParams, type UpdatePrincipalParams, type UploadItem, type UploadOptions, type UploadResult, type UseArtifactStreamReturn, type UseFileUploadReturn, type UseTimelineHistoryReturn, type VFSEdge, type VFSItem, type VfsItemChange, type WorkCorrelation, type WorkspaceOptions, type WorkspaceSession, acceptInvitation, acceptInvite, answerInput, assignPersonalSection, auth, awaitAnchorReady, awaitScopeReady, callTool, cancelInvitation, cancelQueuedTurn, cancelTurn, clearCachedToken, clearSession, configureGatewayReads, connectHostSession, createAgent, createInvitation, createItem, disconnectSSE, disposeVfsRealtimeWs, electHomeAnchor, emitEvent, fetchChannelMessages, fetchChannelMessagesPage, fetchChannelMessagesWithCards, fetchEdgesForItem, fetchItemHistory, fetchItemVersions, fetchItems, fetchMemberFocus, fetchMessageReplies, fetchMessageReplyContexts, fetchOpenEnvelope, fetchRecentActivity, fetchResolvedItems, fetchTimelineHistory, fetchTurnQueueEntries, fetchTypeDefinitions, fetchVfsChildren, fetchVfsChildrenPage, fetchVfsItem, fetchVfsItemById, fetchVfsTree, filePurchaseNextUrl, funnelCheckoutLink, gatewayCall, getAccessToken, getAnchor, getAnchorRef, getAnchorVersion, getAssetUrl, getDefaultSort, getFilePurchase, getHomeAnchor, getInvitation, getMountVersion, getMounts, getPathSubscriptionState, getQueryClient, getRequiredFormFields, getScope, getScopeVersion, getServerClockOffsetMs, getServerClockSyncedAt, getSessionEntry, hasServerClock, initSession, initVfsRealtimeWs, initializeFsaos, initializeWorkspace, interpretSchema, invalidateAllVfs, invalidateChannelMessages, invalidateChildren, invalidateItem, invalidateOpenEnvelope, invalidatePathAndParent, invalidateSubtree, invalidateTypes, inviteMember, isAnchorReady, isChannelPath, isListableItemsFilter, isScopeReady, itemsFilterFromQueryFilter, listChildren, listInvitations, loadMounts, loadPublishedBundle, mount, mountRealtimeScope, normalizeItem, onConnectionStateChange, pathSubscriptionMatches, personalSectionsKey, ping, pushChanges, queryClient, readItem, refreshQuery, registerCleanup, rejectInvitation, replaceMounts, resendInvitation, resetAllSdkState, resolvePrincipalId, resubscribePath, seatMember, selectMount, sendMessage, serveHostSession, serverDeadlinePassed, serverMsUntil, serverNow, setAnchor, setCachedToken, setQueryClient, setScope, setupRequireShim, signal, startFileCheckout, startTracking, steerTurn, submitForm, subscribeAnchor, subscribeArtifactStream, subscribeMounts, subscribeScope, subscribeToEvents, subscribeToPath, subscribeToScope, trackAction, trackEvent, trackPageView, unmountRealtimeScope, updateItem, uploadFile, useAcceptInvite, useAccounts, useAgentTimeline, useAllChannels, useAnswerInput, useArrangement, useArtifactStream, useAsset, useAuth, useChannelMessages, useChannels, useChildren, useComponent, useCreate, useCreateAgent, useDelete, useDmChannels, useEdges, useEventStream, useFileUpload, useIncrementalItems, useInfiniteChannelMessages, useInfiniteChildren, useInfiniteItems, useInviteMember, useItem, useItemById, useItemHistory, useItemVersions, useItems, useLink, useList, useMemberFocus, useMessageReplies, useMintedAsset, useMounts, useMove, useMutation, useNotifications, useOpen, usePermission, usePermissions, usePersonalItemOrder, usePersonalSections, usePinnedItems, usePrincipal, usePublishedComponent, useRealtimeQuery, useRecentActivity, useResolve, useResolvedItems, useScope, useScopeReady, useSearch, useSeatMember, useTheme, useTimelineHistory, useTree, useType, useTypeHelpers, useTypes, useUnreadCounts, useUpdate, useUpdatePrincipal, vfsKeys, waitForPathReady };
4216
+ export { type AcceptInviteParams, type AcceptInviteResult, type AccountInfo, type AnswerInputParams, type ArtifactDeltaEvent, type ArtifactDoneEvent, type ArtifactEvent, type ArtifactOpenedEvent, type ArtifactState, type ArtifactStatus, type ArtifactStreamState, type ArtifactSurfaceType, CHANNEL_AI_MODES, type CancelQueuedTurnOptions, type CancelQueuedTurnResponse, type CancelQueuedTurnState, type CancelTurnOptions, type CancelTurnResponse, type CancelTurnState, type Channel, type ChannelAiMode, type ChannelCard, type ChannelMessage, type ChannelMessagesOptions, type ChannelMessagesPage, type ChannelMessagesResponse, type ChannelsOptions, type ComponentOpener, ComponentRenderer, type ConnectionState, type CreateAgentParams, type CreateAgentResult, type CreateInvitationParams, type CreateParams, type DeleteParams, EnforcementDeniedError, type EnforcementPayload, type FieldDescriptor, type FilePurchaseReceipt, type FileRef, FormSubmissionError, type FormSubmissionReceipt, type FsaosRuntime, type GatewayParams, GatewayRequestError, type GatewayRequestOptions, type GatewayResponse, HostSessionUnavailableError, type HostSessionWelcome, type IncrementalItemsOptions, type InfiniteChannelMessagesOptions, type InfiniteItemsOptions, type InitializeFsaosOptions, type InteractionReceipt, InteractionTrackingError, type InvitationChangeReceipt, type InvitationPage, type InvitationReceipt, type InvitationSummary, type InviteMemberParams, type InviteMemberResult, type ItemVersionsOptions, type ItemVersionsResult, type ItemsDiscovery, type ItemsFilter, type ItemsFilterGroup, KernelProvider, type LinkParams, type LoadMountsOptions, type MemberRole, type MessageRepliesCursor, type MessageRepliesOptions, type MessageRepliesPage, type MessageReplyContext, type MintedAsset, type MintedAssetState, type MountRef, type MoveParams, type Notification, type NotificationsOptions, type OpenEnvelope, type OpenOptions, type PathSubscriptionState, type PermissionAction, type PersonalItemOrderKey, type PersonalSection, type PinTarget, type PinnedItem, type PrincipalData, type PublicSourceConfig, type PublishedBundle, type PublishedComponentSource, type PublishedComponentStatus, type PurchaseJourneyRequest, type ReadPriority, type ReadTiming, type ResolveItemsResponse, type ResolveParams, type ResolveResponse, type ResolveResultItem, type ResolvedItem, type SeatMemberParams, type SectionChange, type SectionCollection, type SectionDestination, type SectionSnapshot, type SectionTarget, type SendMessageParams, type SendMessageResult, type ServeHostSessionOptions, type SessionEntry, type SourceCaptureAdapter, type SourceIdentityStorage, type StartTrackingOptions, type SteerTurnOptions, type SteerTurnResponse, type SteerTurnState, type SubmitFormOptions, type SwitcherAccount, type TimelineEvent, type TimelineHistoryEvent, type TimelineHistoryOptions, type TrackEventOptions, type TurnQueueEntry, type TurnQueueEntryState, type TypeDefinition, type TypeHelpers, type TypeSchema, type UnreadCountsOptions, type UpdateParams, type UpdatePrincipalParams, type UploadItem, type UploadOptions, type UploadResult, type UseArtifactStreamReturn, type UseFileUploadReturn, type UseTimelineHistoryReturn, type VFSEdge, type VFSItem, type VfsItemChange, type WorkCorrelation, type WorkspaceOptions, type WorkspaceSession, acceptInvitation, acceptInvite, answerInput, assignPersonalSection, auth, awaitAnchorReady, awaitScopeReady, callTool, cancelInvitation, cancelQueuedTurn, cancelTurn, clearCachedToken, clearSession, configureGatewayReads, connectHostSession, createAgent, createInvitation, createItem, disconnectSSE, disposeVfsRealtimeWs, electHomeAnchor, emitEvent, fetchChannelMessages, fetchChannelMessagesPage, fetchChannelMessagesWithCards, fetchEdgesForItem, fetchItemHistory, fetchItemVersions, fetchItems, fetchMemberFocus, fetchMessageReplies, fetchMessageReplyContexts, fetchOpenEnvelope, fetchRecentActivity, fetchResolvedItems, fetchTimelineHistory, fetchTurnQueueEntries, fetchTypeDefinitions, fetchVfsChildren, fetchVfsChildrenPage, fetchVfsItem, fetchVfsItemById, fetchVfsTree, filePurchaseNextUrl, funnelCheckoutLink, gatewayCall, getAccessToken, getAnchor, getAnchorRef, getAnchorVersion, getAssetUrl, getDefaultSort, getFilePurchase, getHomeAnchor, getInvitation, getMountVersion, getMounts, getPathSubscriptionState, getQueryClient, getRequiredFormFields, getScope, getScopeVersion, getServerClockOffsetMs, getServerClockSyncedAt, getSessionEntry, hasServerClock, initSession, initVfsRealtimeWs, initializeFsaos, initializeWorkspace, interpretSchema, invalidateAllVfs, invalidateChannelMessages, invalidateChildren, invalidateItem, invalidateOpenEnvelope, invalidatePathAndParent, invalidateSubtree, invalidateTypes, inviteMember, isAnchorReady, isChannelPath, isListableItemsFilter, isScopeReady, itemsFilterFromQueryFilter, listChildren, listInvitations, loadMounts, loadPublishedBundle, mount, mountRealtimeScope, normalizeItem, onConnectionStateChange, pathSubscriptionMatches, personalSectionsKey, ping, pushChanges, queryClient, readItem, refreshQuery, registerCleanup, rejectInvitation, replaceMounts, resendInvitation, resetAllSdkState, resolvePrincipalId, resubscribePath, seatMember, selectMount, sendMessage, serveHostSession, serverDeadlinePassed, serverMsUntil, serverNow, setAnchor, setCachedToken, setQueryClient, setScope, setupRequireShim, signal, startFileCheckout, startTracking, steerTurn, submitForm, subscribeAnchor, subscribeArtifactStream, subscribeMounts, subscribeScope, subscribeToEvents, subscribeToPath, subscribeToScope, trackAction, trackEvent, trackPageView, unmountRealtimeScope, updateItem, uploadFile, useAcceptInvite, useAccounts, useAgentTimeline, useAllChannels, useAnswerInput, useArrangement, useArtifactStream, useAsset, useAuth, useChannelMessages, useChannels, useChildren, useComponent, useCreate, useCreateAgent, useDelete, useDmChannels, useEdges, useEventStream, useFileUpload, useIncrementalItems, useInfiniteChannelMessages, useInfiniteChildren, useInfiniteItems, useInviteMember, useItem, useItemById, useItemHistory, useItemVersions, useItems, useLink, useList, useMemberFocus, useMessageReplies, useMintedAsset, useMounts, useMove, useMutation, useNotifications, useOpen, usePermission, usePermissions, usePersonalItemOrder, usePersonalSections, usePinnedItems, usePrincipal, usePublishedComponent, useRealtimeQuery, useRecentActivity, useResolve, useResolvedItems, useScope, useScopeReady, useSearch, useSeatMember, useTheme, useTimelineHistory, useTree, useType, useTypeHelpers, useTypes, useUnreadCounts, useUpdate, useUpdatePrincipal, vfsKeys, waitForPathReady };
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- import React, { createElement, useMemo, useState, useRef, useEffect, useSyncExternalStore, useCallback, useLayoutEffect } from 'react';
2
- import { QueryClient, QueryClientProvider, useQuery, useInfiniteQuery, useQueryClient, useMutation as useMutation$1 } from '@tanstack/react-query';
1
+ import React, { createElement, useSyncExternalStore, useMemo, useState, useRef, useEffect, useCallback, useLayoutEffect } from 'react';
2
+ import { QueryClient, QueryClientProvider, useQuery, useQueries, useInfiniteQuery, useQueryClient, useMutation as useMutation$1 } from '@tanstack/react-query';
3
3
  export { QueryClientProvider } from '@tanstack/react-query';
4
4
  import { createClient } from '@supabase/supabase-js';
5
5
  import * as ReactDOM from 'react-dom';
@@ -711,7 +711,7 @@ function resetGatewayReads() {
711
711
  }
712
712
  function isScheduledRead(method, params) {
713
713
  if (method === "query") return !("materialize" in params);
714
- return ["read", "list", "search", "resolve", "resolve-items", "get-channel-messages", "list-memberships", "message-replies"].includes(method);
714
+ return ["read", "list", "search", "resolve", "resolve-items", "get-channel-messages", "list-memberships", "message-replies", "check-item-access"].includes(method);
715
715
  }
716
716
  function readRequestKey(value) {
717
717
  if (Array.isArray(value)) return `[${value.map(readRequestKey).join(",")}]`;
@@ -734,18 +734,18 @@ function scheduleRead(key, method, options, run) {
734
734
  };
735
735
  jobs.set(key, job);
736
736
  waiting.push(job);
737
- const pending4 = job;
737
+ const pending5 = job;
738
738
  job.timer = setTimeout(() => {
739
- pending4.controller.abort();
739
+ pending5.controller.abort();
740
740
  const error = new Error("The read timed out. Please retry.");
741
741
  error.name = "TimeoutError";
742
- for (const consumer of pending4.consumers) {
742
+ for (const consumer of pending5.consumers) {
743
743
  consumer.detach();
744
744
  consumer.reject(error);
745
745
  }
746
- pending4.consumers.clear();
747
- if (jobs.get(pending4.key) === pending4) jobs.delete(pending4.key);
748
- discardQueued(pending4);
746
+ pending5.consumers.clear();
747
+ if (jobs.get(pending5.key) === pending5) jobs.delete(pending5.key);
748
+ discardQueued(pending5);
749
749
  }, config.timeoutMs);
750
750
  } else if (rank[options.priority ?? "normal"] < rank[job.priority]) {
751
751
  job.priority = options.priority ?? "normal";
@@ -968,8 +968,8 @@ function refreshQuery(client2, queryKey, options = {}) {
968
968
  queued = /* @__PURE__ */ new Map();
969
969
  trailing.set(client2, queued);
970
970
  }
971
- const pending4 = queued.get(hash);
972
- if (pending4) return pending4;
971
+ const pending5 = queued.get(hash);
972
+ if (pending5) return pending5;
973
973
  const queue = queued;
974
974
  const next = Promise.allSettled(running2).then(() => {
975
975
  queue.delete(hash);
@@ -1028,6 +1028,52 @@ function clearArrangementRefreshes(client2) {
1028
1028
  pending2.get(client2)?.forEach(clearTimeout);
1029
1029
  pending2.delete(client2);
1030
1030
  }
1031
+
1032
+ // src/permission-cache.ts
1033
+ var pending3 = /* @__PURE__ */ new WeakMap();
1034
+ var accessEdges = /* @__PURE__ */ new Set(["shared_with", "has_member", "member_of", "owned_by"]);
1035
+ function invalidate(client2, query) {
1036
+ let timers = pending3.get(client2);
1037
+ if (!timers) {
1038
+ timers = /* @__PURE__ */ new Map();
1039
+ pending3.set(client2, timers);
1040
+ }
1041
+ if (timers.has(query)) return;
1042
+ void client2.cancelQueries({ queryKey: query.queryKey, exact: true });
1043
+ void client2.invalidateQueries({ queryKey: query.queryKey, exact: true, refetchType: "none" });
1044
+ if (!query.isActive()) return;
1045
+ timers.set(query, setTimeout(() => {
1046
+ timers.delete(query);
1047
+ if (client2.getQueryCache().get(query.queryHash) !== query || !query.isActive()) return;
1048
+ void refreshQuery(client2, query.queryKey, { exact: true });
1049
+ }, 250));
1050
+ }
1051
+ function handlePermissionChange(client2, event, type) {
1052
+ const edge = type === "ccm_change";
1053
+ if (edge && !accessEdges.has(event.edge_type)) return;
1054
+ const paths = [event.path, event.old_path, event.source_path].filter((path) => typeof path === "string");
1055
+ const ids = [event.item_id, event.source_item_id, event.source_id, event.target_item_id, event.target_id].filter(Boolean);
1056
+ if (!paths.length && !ids.length) return;
1057
+ for (const query of client2.getQueryCache().findAll({ queryKey: ["vfs"] })) {
1058
+ const meta = query.meta?.permissionQuery;
1059
+ if (!meta?.scope) continue;
1060
+ const direct = Boolean(meta.itemId && ids.includes(meta.itemId));
1061
+ const ancestor = Boolean(meta.path && paths.some((path) => isChannelPath(meta.path, path)));
1062
+ const scope = meta.scope;
1063
+ const scoped = paths.some((path) => isChannelPath(path, scope) || isChannelPath(scope, path)) || [event.scope_item_id, event.account_item_id, event.space_item_id].some((id) => id && meta.scopeIds.includes(id));
1064
+ const inherited = scoped && (event.item_type === "member" || event.item_type === "principal" || edge);
1065
+ if (direct || ancestor || !meta.targetLookup && inherited) invalidate(client2, query);
1066
+ }
1067
+ }
1068
+ function refreshPermissionsAfterReconnect(client2) {
1069
+ for (const query of client2.getQueryCache().findAll({ queryKey: ["vfs"] })) {
1070
+ if (query.meta?.permissionQuery) invalidate(client2, query);
1071
+ }
1072
+ }
1073
+ function clearPermissionRefreshes(client2) {
1074
+ pending3.get(client2)?.forEach((timer) => clearTimeout(timer));
1075
+ pending3.delete(client2);
1076
+ }
1031
1077
  var client = null;
1032
1078
  registerCleanup(() => {
1033
1079
  if (!client) return;
@@ -1068,7 +1114,7 @@ var queryClient = new Proxy({}, {
1068
1114
  });
1069
1115
 
1070
1116
  // src/item-query-realtime.ts
1071
- var pending3 = /* @__PURE__ */ new WeakMap();
1117
+ var pending4 = /* @__PURE__ */ new WeakMap();
1072
1118
  function listingFilter(query) {
1073
1119
  return query.meta?.infiniteItemsRealtime?.filter;
1074
1120
  }
@@ -1107,10 +1153,10 @@ function affectsListing(query, filter, event) {
1107
1153
  return hasPath || Boolean(filter.parent_id && event.parent_id === filter.parent_id);
1108
1154
  }
1109
1155
  function schedule(client2, query) {
1110
- let timers = pending3.get(client2);
1156
+ let timers = pending4.get(client2);
1111
1157
  if (!timers) {
1112
1158
  timers = /* @__PURE__ */ new Map();
1113
- pending3.set(client2, timers);
1159
+ pending4.set(client2, timers);
1114
1160
  }
1115
1161
  const previous = timers.get(query.queryHash);
1116
1162
  if (previous) clearTimeout(previous);
@@ -1133,8 +1179,8 @@ function refreshInfiniteItemsAfterReconnect(client2) {
1133
1179
  }
1134
1180
  }
1135
1181
  function clearInfiniteItemsRefreshes(client2) {
1136
- pending3.get(client2)?.forEach(clearTimeout);
1137
- pending3.delete(client2);
1182
+ pending4.get(client2)?.forEach(clearTimeout);
1183
+ pending4.delete(client2);
1138
1184
  }
1139
1185
 
1140
1186
  // src/items-selection.ts
@@ -1484,6 +1530,7 @@ function catchUpAfterGap(reason) {
1484
1530
  const qc = getQueryClient();
1485
1531
  refreshInfiniteItemsAfterReconnect(qc);
1486
1532
  reconnectArrangements(qc);
1533
+ refreshPermissionsAfterReconnect(qc);
1487
1534
  for (const sub of activePaths.values()) {
1488
1535
  void qc.invalidateQueries({ queryKey: vfsKeys.item(sub.path) });
1489
1536
  void qc.invalidateQueries({ queryKey: vfsKeys.children(sub.path) });
@@ -1521,6 +1568,9 @@ function handleMessage(raw) {
1521
1568
  if (msg.type === "event" || msg.event_type) {
1522
1569
  const eventType = msg.event_type || "message";
1523
1570
  const data = msg.data || msg;
1571
+ if (eventType === "vfs_change" || eventType === "ccm_change") {
1572
+ handlePermissionChange(getQueryClient(), data, eventType);
1573
+ }
1524
1574
  if (eventType === "vfs_change") {
1525
1575
  handleInfiniteItemsChange(getQueryClient(), data);
1526
1576
  handleArrangementChange(getQueryClient(), data);
@@ -1650,6 +1700,7 @@ function disconnectSSE() {
1650
1700
  log("disconnectSSE: tearing down");
1651
1701
  clearInfiniteItemsRefreshes(getQueryClient());
1652
1702
  clearArrangementRefreshes(getQueryClient());
1703
+ clearPermissionRefreshes(getQueryClient());
1653
1704
  intentionalClose = true;
1654
1705
  stopPing();
1655
1706
  if (ws) {
@@ -3020,13 +3071,13 @@ function watchChannelTranscript(client2, key, channel, limit) {
3020
3071
  let timer;
3021
3072
  let running2 = false;
3022
3073
  let stopped = false;
3023
- const pending4 = /* @__PURE__ */ new Map();
3074
+ const pending5 = /* @__PURE__ */ new Map();
3024
3075
  const current = () => client2.getQueryData(key);
3025
3076
  const query = () => client2.getQueryCache().find({ queryKey: key, exact: true });
3026
3077
  const reload = () => refreshQuery(client2, key, { exact: true });
3027
3078
  const read = (after_seq, before_seq) => fetchChannelMessagesPage(channel, { transcriptOnly: true, limit, after_seq, before_seq });
3028
3079
  const schedule2 = () => {
3029
- if (stopped || running2 || timer || !pending4.size) return;
3080
+ if (stopped || running2 || timer || !pending5.size) return;
3030
3081
  timer = setTimeout(() => {
3031
3082
  timer = void 0;
3032
3083
  void flush();
@@ -3034,8 +3085,8 @@ function watchChannelTranscript(client2, key, channel, limit) {
3034
3085
  };
3035
3086
  const flush = async () => {
3036
3087
  running2 = true;
3037
- const changes = [...pending4.values()];
3038
- pending4.clear();
3088
+ const changes = [...pending5.values()];
3089
+ pending5.clear();
3039
3090
  const owner = query();
3040
3091
  try {
3041
3092
  if (owner?.state.fetchStatus === "fetching") await owner.promise?.catch(() => void 0);
@@ -3109,15 +3160,15 @@ function watchChannelTranscript(client2, key, channel, limit) {
3109
3160
  };
3110
3161
  const stop = subscribeToEvents("vfs_change", (change) => {
3111
3162
  const id = change.item_id ?? change.path;
3112
- const previous = pending4.get(id);
3113
- pending4.set(id, previous && (previous.inserted || isNewPost(previous, channel)) && actionOf(change) === "update" && previous.path === change.path ? { ...change, inserted: true } : change);
3163
+ const previous = pending5.get(id);
3164
+ pending5.set(id, previous && (previous.inserted || isNewPost(previous, channel)) && actionOf(change) === "update" && previous.path === change.path ? { ...change, inserted: true } : change);
3114
3165
  schedule2();
3115
3166
  }, (change) => channelMessageChange(change, channel, void 0, []) || !!change.old_path && channelMessageChange({ ...change, path: change.old_path }, channel, void 0, []) || change.item_type === "message" && !!change.parent_id && isChannelPath(change.path, channel) && !!current()?.pages.some((page) => page.messages.some((root) => root.id === change.parent_id)));
3116
3167
  watch = { users: 0, stop: () => {
3117
3168
  stopped = true;
3118
3169
  stop();
3119
3170
  if (timer) clearTimeout(timer);
3120
- pending4.clear();
3171
+ pending5.clear();
3121
3172
  } };
3122
3173
  entries.set(hash, watch);
3123
3174
  }
@@ -3163,7 +3214,7 @@ function watchChannels(client2, key, normalize) {
3163
3214
  running2 = true;
3164
3215
  const reload = inventory;
3165
3216
  inventory = false;
3166
- const pending4 = [...channels];
3217
+ const pending5 = [...channels];
3167
3218
  const checkRename = new Set(renames);
3168
3219
  renames.clear();
3169
3220
  channels.clear();
@@ -3171,7 +3222,7 @@ function watchChannels(client2, key, normalize) {
3171
3222
  if (reload) {
3172
3223
  await refreshQuery(client2, key, { exact: true });
3173
3224
  } else {
3174
- const results = await Promise.allSettled(pending4.map(async (id) => {
3225
+ const results = await Promise.allSettled(pending5.map(async (id) => {
3175
3226
  const owner = client2.getQueryCache().find({ queryKey: key, exact: true });
3176
3227
  if (!owner) return;
3177
3228
  const result = await gatewayCall("read", { id });
@@ -3303,6 +3354,92 @@ function watchMessageReplies(client2, key, target) {
3303
3354
  }
3304
3355
  };
3305
3356
  }
3357
+ var actions = /* @__PURE__ */ new Set(["view", "edit", "delete", "admin"]);
3358
+ var uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
3359
+ function targetFromRead(response) {
3360
+ const raw = response.item ?? response;
3361
+ const id = raw.id ?? raw.item_id;
3362
+ const path = raw.path ?? raw.item_path;
3363
+ if (response.success !== true || typeof id !== "string" || !uuid.test(id)) {
3364
+ throw new Error("PERMISSION_TARGET_UNAVAILABLE");
3365
+ }
3366
+ return { id, ...typeof path === "string" ? { path } : {} };
3367
+ }
3368
+ function usePermissions(item, requested) {
3369
+ useSyncExternalStore(subscribeScope, getScopeVersion, getScopeVersion);
3370
+ const epoch = useSyncExternalStore(subscribeSession, getSessionVersion, getSessionVersion);
3371
+ const mounts = useSyncExternalStore(subscribeMounts, getMountVersion, getMountVersion);
3372
+ const scope = getScope();
3373
+ const principal = getSessionEntry()?.principal_id;
3374
+ const target = item?.trim() ?? "";
3375
+ const wanted = [...new Set(requested ?? [])].sort();
3376
+ const directId = uuid.test(target);
3377
+ const validTarget = directId || (target.startsWith("/root/") || target === "/root");
3378
+ const invalid = wanted.some((action) => !actions.has(action)) || Boolean(target && !validTarget);
3379
+ const enabled2 = Boolean(scope && principal && target && wanted.length && !invalid);
3380
+ const root = ["vfs", scope ?? "__unscoped__", "permissions", principal ?? "__anonymous__", epoch, mounts];
3381
+ const scopeIds = [...new Set([getAnchorRef()?.id, ...getMounts().map((mount3) => mount3.id)].filter((id) => Boolean(id)))];
3382
+ const targetKey = [...root, "target", target];
3383
+ const identity = useQuery({
3384
+ queryKey: targetKey,
3385
+ queryFn: async ({ signal: signal2 }) => {
3386
+ if (!enabled2 || !scope) throw new Error("PERMISSION_CONTEXT_REQUIRED");
3387
+ return targetFromRead(await gatewayCall("read", { path: target, _scope_path: scope }, { signal: signal2 }));
3388
+ },
3389
+ enabled: enabled2 && !directId,
3390
+ staleTime: Infinity,
3391
+ gcTime: 0,
3392
+ retry: false,
3393
+ refetchOnWindowFocus: false,
3394
+ refetchOnReconnect: false,
3395
+ refetchOnMount: false,
3396
+ meta: { permissionQuery: { scope, scopeIds, path: target, targetLookup: true } }
3397
+ });
3398
+ const resolved = directId ? { id: target } : identity.data;
3399
+ const identityReady = directId || identity.isSuccess && !identity.isFetching && !identity.isStale;
3400
+ const checks = useQueries({ queries: wanted.filter((action) => actions.has(action)).map((action) => ({
3401
+ queryKey: [...root, "check", resolved?.id ?? target, action],
3402
+ queryFn: async ({ signal: signal2 }) => {
3403
+ if (!enabled2 || !scope || !resolved) throw new Error("PERMISSION_CONTEXT_REQUIRED");
3404
+ const result = await gatewayCall("check-item-access", { id: resolved.id, action, _scope_path: scope }, { signal: signal2 });
3405
+ if (result.success !== true || typeof result.allowed !== "boolean") throw new Error("PERMISSION_RESPONSE_INVALID");
3406
+ return result.allowed;
3407
+ },
3408
+ enabled: enabled2 && identityReady && Boolean(resolved),
3409
+ staleTime: Infinity,
3410
+ gcTime: 0,
3411
+ retry: false,
3412
+ refetchOnWindowFocus: false,
3413
+ refetchOnReconnect: false,
3414
+ refetchOnMount: false,
3415
+ meta: { permissionQuery: { scope, scopeIds, itemId: resolved?.id, path: resolved?.path ?? (directId ? void 0 : target) } }
3416
+ })) });
3417
+ const error = invalid ? new Error("PERMISSION_INPUT_INVALID") : !directId && identity.error || checks.find((check) => check.error)?.error || null;
3418
+ const verified = enabled2 && identityReady && !error;
3419
+ const supported = wanted.filter((action) => actions.has(action));
3420
+ const data = Object.fromEntries(wanted.map((action) => {
3421
+ const check = checks[supported.indexOf(action)];
3422
+ return [action, Boolean(verified && check?.isSuccess && !check.isFetching && !check.isStale && check.data === true)];
3423
+ }));
3424
+ return {
3425
+ data,
3426
+ loading: Boolean(enabled2 && (!directId && identity.isFetching || checks.some((check) => check.isFetching || check.isPending)) && !error),
3427
+ error,
3428
+ /** Explicit refresh for a user action; no automatic retry or polling. */
3429
+ refetch: async () => {
3430
+ if (!enabled2) return;
3431
+ if (!directId && (!identity.data || identity.isError)) {
3432
+ await identity.refetch();
3433
+ return;
3434
+ }
3435
+ await Promise.all(checks.map((check) => check.refetch()));
3436
+ }
3437
+ };
3438
+ }
3439
+ function usePermission(action, item) {
3440
+ const result = usePermissions(item, action ? [action] : []);
3441
+ return { ...result, data: { allowed: Boolean(action && result.data[action]) } };
3442
+ }
3306
3443
 
3307
3444
  // src/hooks.ts
3308
3445
  function useScopeKey() {
@@ -3511,7 +3648,7 @@ function useIncrementalItems(filter, options = {}) {
3511
3648
  let wasConnected = false;
3512
3649
  let missed = false;
3513
3650
  let generation = 0;
3514
- const pending4 = /* @__PURE__ */ new Map();
3651
+ const pending5 = /* @__PURE__ */ new Map();
3515
3652
  const reconcile = () => {
3516
3653
  const started = generation;
3517
3654
  void refetch.current().then((result) => {
@@ -3528,18 +3665,18 @@ function useIncrementalItems(filter, options = {}) {
3528
3665
  delete upserts[path];
3529
3666
  return { identity, upserts, deleted: new Set(state.deleted).add(path) };
3530
3667
  });
3531
- const earlier = pending4.get("__reconcile__");
3668
+ const earlier = pending5.get("__reconcile__");
3532
3669
  if (earlier) clearTimeout(earlier);
3533
- pending4.set("__reconcile__", setTimeout(() => {
3534
- pending4.delete("__reconcile__");
3670
+ pending5.set("__reconcile__", setTimeout(() => {
3671
+ pending5.delete("__reconcile__");
3535
3672
  reconcile();
3536
3673
  }, 250));
3537
3674
  };
3538
3675
  const readOne = (path) => {
3539
- const earlier = pending4.get(path);
3676
+ const earlier = pending5.get(path);
3540
3677
  if (earlier) clearTimeout(earlier);
3541
- pending4.set(path, setTimeout(() => {
3542
- pending4.delete(path);
3678
+ pending5.set(path, setTimeout(() => {
3679
+ pending5.delete(path);
3543
3680
  void client2.fetchQuery({ queryKey: vfsKeys.item(path), queryFn: () => fetchVfsItem(path), staleTime: 0 }).then((item) => {
3544
3681
  if (stopped) return;
3545
3682
  if (!item || !itemMatchesIncrementalFilter(item, selected)) {
@@ -3602,7 +3739,7 @@ function useIncrementalItems(filter, options = {}) {
3602
3739
  stopped = true;
3603
3740
  stopEvents();
3604
3741
  stopConnection();
3605
- pending4.forEach(clearTimeout);
3742
+ pending5.forEach(clearTimeout);
3606
3743
  };
3607
3744
  }, [client2, identity]);
3608
3745
  return { ...query, allItems };
@@ -4358,15 +4495,15 @@ async function readPublishedBundle(componentId, releaseItemId, version) {
4358
4495
  return { status: "ready", releaseItemId, version, script, stylesheet: stylesheet?.trim() ? stylesheet : null };
4359
4496
  }
4360
4497
  function publishedBundle(componentId, releaseItemId, version) {
4361
- let pending4 = publishedBundles.get(releaseItemId);
4362
- if (!pending4) {
4363
- pending4 = readPublishedBundle(componentId, releaseItemId, version);
4364
- publishedBundles.set(releaseItemId, pending4);
4365
- pending4.catch(() => {
4366
- if (publishedBundles.get(releaseItemId) === pending4) publishedBundles.delete(releaseItemId);
4498
+ let pending5 = publishedBundles.get(releaseItemId);
4499
+ if (!pending5) {
4500
+ pending5 = readPublishedBundle(componentId, releaseItemId, version);
4501
+ publishedBundles.set(releaseItemId, pending5);
4502
+ pending5.catch(() => {
4503
+ if (publishedBundles.get(releaseItemId) === pending5) publishedBundles.delete(releaseItemId);
4367
4504
  });
4368
4505
  }
4369
- return pending4;
4506
+ return pending5;
4370
4507
  }
4371
4508
  function loadPublishedBundle(source) {
4372
4509
  const live = liveRelease(source);
@@ -4490,16 +4627,6 @@ function useTheme() {
4490
4627
  }, []);
4491
4628
  return { data: themeData, loading: false, error: null };
4492
4629
  }
4493
- function usePermission(_action, _path) {
4494
- return { data: { allowed: true }, loading: false, error: null };
4495
- }
4496
- function usePermissions(_path, actions) {
4497
- const perms = {};
4498
- (actions || []).forEach((a) => {
4499
- perms[a] = true;
4500
- });
4501
- return { data: perms, loading: false, error: null };
4502
- }
4503
4630
  var _principalIdCache = null;
4504
4631
  var _principalIdPromise = null;
4505
4632
  var _principalListeners = /* @__PURE__ */ new Set();
@@ -5596,7 +5723,7 @@ function usePersonalItemOrder(key, items, space) {
5596
5723
  return [...unplaced, ...arranged.filter((item) => savedIds.has(item.id))];
5597
5724
  }, [key, items, query.applyTo, query.order]);
5598
5725
  const client2 = useQueryClient();
5599
- const pending4 = useRef(false);
5726
+ const pending5 = useRef(false);
5600
5727
  const ready = Boolean(supported && !query.error && query.arrangement?.item_id && query.resolutionLevel === "member" && query.arrangement.write_target_id === query.arrangement.item_id);
5601
5728
  const mutation = useMutation$1({
5602
5729
  mutationFn: async (change) => {
@@ -5614,7 +5741,7 @@ function usePersonalItemOrder(key, items, space) {
5614
5741
  if (!ready || !scopePath || identity !== activeIdentity.current || generation !== getScopeVersion() || getScope() !== mountedScope) {
5615
5742
  throw new Error("Personal order is not available in this Space");
5616
5743
  }
5617
- if (pending4.current) throw new Error("An order change is already being saved");
5744
+ if (pending5.current) throw new Error("An order change is already being saved");
5618
5745
  const visibleIds = items.map((item) => item.id);
5619
5746
  if (ids.length !== visibleIds.length || new Set(ids).size !== visibleIds.length || visibleIds.some((id) => !ids.includes(id))) throw new Error("Order must include each displayed item exactly once");
5620
5747
  const cached = client2.getQueryData(query.arrangementQueryKey);
@@ -5627,7 +5754,7 @@ function usePersonalItemOrder(key, items, space) {
5627
5754
  let index = 0;
5628
5755
  const saved = (query.order ?? []).map((id) => visible.has(id) ? ids[index++] : id);
5629
5756
  const order = [...saved, ...ids.slice(index)];
5630
- pending4.current = true;
5757
+ pending5.current = true;
5631
5758
  try {
5632
5759
  return await mutation.mutateAsync({
5633
5760
  ids: order,
@@ -5636,7 +5763,7 @@ function usePersonalItemOrder(key, items, space) {
5636
5763
  queryKey: query.arrangementQueryKey
5637
5764
  });
5638
5765
  } finally {
5639
- pending4.current = false;
5766
+ pending5.current = false;
5640
5767
  }
5641
5768
  }
5642
5769
  return {
@@ -7384,7 +7511,7 @@ function usePersonalSections(contextId, collection) {
7384
7511
  meta: { arrangementRealtime: true, personalSections: true },
7385
7512
  structuralSharing: (previous, next) => newestSnapshot(previous, next)
7386
7513
  });
7387
- const pending4 = useRef(false);
7514
+ const pending5 = useRef(false);
7388
7515
  const mutation = useMutation$1({ mutationFn: async (write) => {
7389
7516
  const data = await call(write.scope, write.context, write.collection, {
7390
7517
  ...write.change,
@@ -7397,12 +7524,12 @@ function usePersonalSections(contextId, collection) {
7397
7524
  if (!scopePath || !contextId || generation !== getScopeVersion() || getScope() !== scopePath || !query.data || query.error) {
7398
7525
  throw new Error("Select the Space again before changing sections");
7399
7526
  }
7400
- if (pending4.current) throw new Error("A section change is still being saved");
7401
- pending4.current = true;
7527
+ if (pending5.current) throw new Error("A section change is still being saved");
7528
+ pending5.current = true;
7402
7529
  try {
7403
7530
  return await mutation.mutateAsync({ change: value, scope: scopePath, context: contextId, collection, version: query.data.version });
7404
7531
  } finally {
7405
- pending4.current = false;
7532
+ pending5.current = false;
7406
7533
  }
7407
7534
  }
7408
7535
  function destination(sectionId) {