import * as NDK from '@nostr-dev-kit/ndk'; import NDK__default, { Hexpubkey, NDKEvent, NDKKind, NDKUserProfile, NDKSubscriptionOptions, NDKSubscription, NDKSigner, NDKUser, NDKList, NDKFilter, NDKConstructorParams } from '@nostr-dev-kit/ndk'; export * from '@nostr-dev-kit/ndk'; export { default } from '@nostr-dev-kit/ndk'; import * as zustand from 'zustand'; /** * Hook to login a new session. * @param userOrSigner - A user (for read-only sessions) or a signer to login with. * @returns */ declare const useNDKSessionLogin: () => any; /** * Hook to logout the sessions * * @params pubkey - The pubkey of the user to logout. If not provided, it will use the current user's pubkey. * If no pubkey is provided and there is no current user, an error will be logged. * @returns */ declare const useNDKSessionLogout: () => any; /** * Hook to swtich the active session. * @returns */ declare const useNDKSessionSwitch: () => any; /** * Returns the list of followed pubkeys for the active session. * Returns an empty array if there is no active session or no follows list. */ declare const useFollows: () => Set; interface UseNDKSessionEventOptions { /** * Optional class (e.g., NDKList) to create a new, default instance * of the event type if none is found in the session. * The class should extend NDKEvent and have a constructor compatible with `new (ndk?: NDK) => T`. */ create?: typeof NDKEvent & (new (ndk?: NDK__default) => T); } /** * Hook to retrieve a specific replaceable event (by kind) from the active user's session. * Creates a new instance if the event doesn't exist and the `create` option is provided. * * @param kind The NDKKind of the replaceable event to retrieve. * @param options Configuration object containing the `create` option. * @returns The NDKEvent (or subclass instance T). Guaranteed to return an instance if `create` is provided. */ declare function useNDKSessionEvent(kind: NDKKind, options: UseNDKSessionEventOptions & Required, "create">>): T; /** * Hook to retrieve a specific replaceable event (by kind) from the active user's session. * * @param kind The NDKKind of the replaceable event to retrieve. * @param options Optional configuration (without `create` specified). * @returns The NDKEvent (or subclass instance T), or undefined if not found. */ declare function useNDKSessionEvent(kind: NDKKind, options?: Omit, "create">): T | undefined; /** * Hook to retrieve the NDKUser profile object for the currently active session user. * * This hook combines session management with profile fetching. * It identifies the active user's public key from the session * and then uses `useProfileValue` to fetch and return their profile data. * * @returns The NDKUserProfile object for the active user, or undefined if no session is active * or the profile hasn't been fetched yet. */ declare const useCurrentUserProfile: () => NDKUserProfile | undefined; declare const useNDKSessionSigners: () => Map; declare const useNDKSessionSessions: () => Map; declare const useNDKSessionStart: () => (pubkey: NDK.Hexpubkey, opts: SessionStartOptions) => void; declare const useNDKSessionStop: () => (pubkey: NDK.Hexpubkey) => void; /** * Extends NDKEvent with a 'from' method to wrap events with a kind-specific handler */ type NDKEventWithFrom = T & { from: (event: NDKEvent) => T; }; type NDKEventWithAsyncFrom = T & { from: (event: NDKEvent) => Promise; }; type UseSubscribeOptions = NDKSubscriptionOptions & { /** * Whether to include deleted events */ includeDeleted?: boolean; /** * Buffer time in ms, false to disable buffering */ bufferMs?: number | false; /** * Whether to include events from muted authors (default: false) */ includeMuted?: boolean; }; /** * User-specific session data stored within the main store. */ interface NDKUserSession { pubkey: Hexpubkey; profile?: NDKUserProfile; followSet?: Set; /** * Follows per kind. * * Each kind has a map where the key is the user's pubkey. * We keep the followed boolean and the last updated timestamp, * so that we can track delete events of the follow event. */ kindFollowSet?: Map>; /** * Events that are unique per kind, part of the session; * we will keep a subscription permanently opened monitoring this * event kinds */ events: Map; /** * The active subscription fetching session data. */ subscription?: NDKSubscription; /** * Last time the session was set to be the active one (in seconds) */ lastActive: number; } /** * Options for starting a user session subscription. * Corresponds to NDK['subscribe'] filters and options. */ interface SessionStartOptions { profile?: boolean; /** * Fetch contacts (follows) for the user. * * true = Fetch default contact list * false = Do not fetch contacts * NDKKind[] = Fetch contact list + kind-scoped follows. */ follows?: boolean | NDKKind[]; /** * Fetch other specific replaceable event kinds (10k-20k, 30k-40k). * Provide a map where keys are NDKKind and values are optional NDKFilters * to apply specifically to that kind (e.g., for NIP-65 relay lists). * If the value is null or undefined, a default filter `{ authors: [pubkey], kinds: [kind], limit: 1 }` is used. */ events?: Map>; } /** * The state structure for the NDK Sessions Zustand store. */ interface NDKSessionsState { ndk?: NDK__default; sessions: Map; signers: Map; activePubkey: Hexpubkey | undefined; /** Initializes the store with an NDK instance. */ init: (ndk: NDK__default) => void; /** * Ensures a session exists for the given user or signer. * If a signer is provided, it's added to the signers map, * its user is fetched, and the session is created/updated. * If only a user is provided, ensures a basic session entry exists. * Does NOT automatically start the session subscription or set it active. * @param userOrSigner - The NDKUser or NDKSigner to add. * @param setActive - If true, sets the session as active. * @returns The Hexpubkey of the added/ensured session. */ addSession: (userOrSigner: NDKUser | NDKSigner, setActive: boolean) => Promise; /** * Starts fetching data for a specific session by creating an NDK subscription. * Stores the subscription handle to allow stopping it later. * @param pubkey - The Hexpubkey of the session to start. * @param opts - Subscription options (filters like kinds, authors, etc.). */ startSession: (pubkey: Hexpubkey, opts: SessionStartOptions) => void; /** * Stops the active data subscription for a specific session. * @param pubkey - The Hexpubkey of the session to stop. */ stopSession: (pubkey: Hexpubkey) => void; /** * Switches the active user session. * Sets the `activePubkey` and configures `ndk.signer` if the session has one. * @param pubkey - The Hexpubkey of the user to switch to, or null to deactivate. */ switchToUser: (pubkey: Hexpubkey | null) => void; /** * Removes a session and its associated signer (if present and not used by other sessions). * If the removed session was active, attempts to set another session as active. * @param pubkey - The Hexpubkey of the session to remove. */ removeSession: (pubkey: Hexpubkey) => void; /** * Updates the data for an existing session. Used internally. * @param pubkey - The Hexpubkey of the session to update. * @param data - Partial session data to merge. */ updateSession: (pubkey: Hexpubkey, data: Partial) => void; } /** * Interface for a synchronous storage adapter for NDK session management. * This allows applications to provide their own storage implementations * (e.g., localStorage for web, SecureStore for mobile). */ interface NDKSessionStorageAdapter { /** * Get an item from storage by key. * @param key The key to retrieve. * @returns The stored value or null if not found. */ getItem(key: string): string | null; /** * Set an item in storage. * @param key The key to store. * @param value The value to store. */ setItem(key: string, value: string): void; /** * Delete an item from storage. * @param key The key to delete. */ deleteItem(key: string): void; } /** * Default implementation of NDKSessionStorageAdapter using browser localStorage. */ declare class NDKSessionLocalStorage implements NDKSessionStorageAdapter { /** * Get an item from localStorage. * @param key The key to retrieve. * @returns The stored value or null if not found. */ getItem(key: string): string | null; /** * Set an item in localStorage. * @param key The key to store. * @param value The value to store. */ setItem(key: string, value: string): void; /** * Delete an item from localStorage. * @param key The key to delete. */ deleteItem(key: string): void; } /** * Load sessions from storage. * @param storage The storage adapter to use * @returns An array of stored sessions */ declare function loadSessionsFromStorage(storage: NDKSessionStorageAdapter): StoredSession[]; /** * Save sessions to storage. * @param storage The storage adapter to use * @param sessions An array of sessions to save */ declare function saveSessionsToStorage(storage: NDKSessionStorageAdapter, sessions: StoredSession[]): void; /** * Add or update a session in storage. * @param storage The storage adapter to use * @param pubkey The pubkey of the session * @param signerPayload Optional stringified signer payload */ declare function addOrUpdateStoredSession(storage: NDKSessionStorageAdapter, pubkey: Hexpubkey, signerPayload?: string): Promise; /** * Remove a session from storage. * @param storage The storage adapter to use * @param pubkey The pubkey of the session to remove */ declare function removeStoredSession(storage: NDKSessionStorageAdapter, pubkey: Hexpubkey): Promise; /** * Get the active pubkey from storage. * @param storage The storage adapter to use * @returns The active pubkey or undefined if not set */ declare function getActivePubkey(storage: NDKSessionStorageAdapter): Hexpubkey | undefined; /** * Set the active pubkey in storage. * @param storage The storage adapter to use * @param pubkey The pubkey to set as active */ declare function storeActivePubkey(storage: NDKSessionStorageAdapter, pubkey: Hexpubkey): void; /** * Clear the active pubkey from storage. * @param storage The storage adapter to use */ declare function clearActivePubkey(storage: NDKSessionStorageAdapter): Promise; /** * Interface for a stored user session, mirroring the structure used for persistence. */ interface StoredSession { pubkey: Hexpubkey; signerPayload?: string; } /** * Hook to monitor NDK session state and persist changes to the provided storage adapter. * It also loads persisted sessions on initial mount. * * @param sessionStorage A storage adapter implementing NDKSessionStorageAdapter * @param opts Optional session start options */ declare function useNDKSessionMonitor(sessionStorage: NDKSessionStorageAdapter | false, opts?: SessionStartOptions): null; /** * Hook to access the NDK instance */ declare const useNDK: () => { ndk: NDK__default | null; }; /** * Gets the current active pubkey from the NDK session store. * @returns Hexpubkey | null - The active pubkey or null if no session is active. */ declare const useNDKCurrentPubkey: () => string | undefined; /** * Hook to access the NDKUser instance corresponding to the currently active session. * Retrieves the active pubkey from the session store and returns the NDKUser object. * Returns null if no session is active or NDK is not initialized. */ declare const useNDKCurrentUser: () => NDKUser | null; /** * Hook to get the list of unpublished events from the NDK cache adapter. * It listens for publish failures and updates the list accordingly. * Requires the cache adapter to implement `getUnpublishedEvents`. * @returns An array of objects, each containing the unpublished event, optional target relays, and last attempt timestamp. */ declare function useNDKUnpublishedEvents(): any; /** * Hook to initialize the NDK instance and related stores. * * This hook provides a function to set the NDK instance in the NDK store * and subsequently initialize other dependent stores like the user profiles store. * * @returns An initialization function `initializeNDK`. */ declare function useNDKInit(): any; /** * Interface for the NDK store state */ interface NDKStoreState { /** * The NDK instance */ ndk: NDK__default | null; /** * Sets the NDK instance */ setNDK: (ndk: NDK__default) => void; setSigner: (signer: NDKSigner | undefined) => void; } /** * Zustand store for managing the NDK instance and current user */ declare const useNDKStore: zustand.UseBoundStore>; /** * Options for useProfileValue and fetchProfile */ interface UseProfileValueOptions { /** Whether to force a refresh of the profile */ refresh?: boolean; /** Subscription options to use when fetching the profile */ subOpts?: NDKSubscriptionOptions; } /** * Hook to get an NDKUser instance from various input formats. * Accepts pubkey (hex), npub, nip05, or nprofile and resolves to an NDKUser. * * @param input - The user identifier (pubkey, npub, nip05, or nprofile) * @returns An NDKUser instance or undefined * * @example * ```ts * // Using hex pubkey * const user = useUser("abc123..."); * * // Using npub * const user = useUser("npub1..."); * * // Using nip05 * const user = useUser("alice@example.com"); * * // Using nprofile * const user = useUser("nprofile1..."); * ``` */ declare function useUser(input?: string): NDKUser | undefined; /** * @deprecated Use `useProfileValue` instead. */ declare function useProfile(pubkey?: Hexpubkey | undefined, forceRefresh?: boolean): NDKUserProfile | undefined; /** * Get a user's profile. * Otherwise, it fetches the profile from the global profile store. * @param userOrPubkey - The NDKUser, pubkey, null or undefined * @param opts - Options for fetching the profile * @returns The user profile or undefined if not available */ declare function useProfileValue(userOrPubkey?: Hexpubkey | NDKUser | null | undefined, opts?: UseProfileValueOptions): NDKUserProfile | undefined; /** * Update a user's profile. This will create a new kind:0 event representing the user's profile * and update the local store with the new profile for immediate reactivity. * * @example Update a user's profile * ```ts * const updateProfile = useSetProfile(); * const newProfile = { name: "New Name", picture: "new_picture_url" }; * updateProfile(newProfile); * ``` */ declare function useSetProfile(): any; interface UserProfilesItems { /** * The NDK instance */ ndk: NDK__default | undefined; /** * The profile map */ profiles: Map; /** * Map of timestamps in seconds of the last time a profile was fetched * (even if we couldn't find one) */ lastFetchedAt: Map; } interface UserProfilesStoreActions { initialize: (ndk: NDK__default) => void; /** * Store an already fetched profile * @param pubkey - The pubkey of the profile to store * @param profile - The profile to store * @param cachedAt - The timestamp in seconds when the profile was retrieved */ setProfile: (pubkey: string, profile: NDKUserProfile, cachedAt?: number) => void; fetchProfile: (pubkey?: string, opts?: UseProfileValueOptions) => void; } type UserProfilesStore = UserProfilesItems & UserProfilesStoreActions; declare const useUserProfilesStore: zustand.UseBoundStore>; /** * Mute criteria used for filtering events */ /** * Criteria used for filtering events based on mute settings. */ interface MuteCriteria$1 { pubkeys: Set; eventIds: Set; hashtags: Set; words: Set; } /** * User-specific mute data */ interface NDKUserMutes { pubkeys: Set; hashtags: Set; words: Set; eventIds: Set; /** * The NDKEvent representing the mute list (kind 10000) */ muteListEvent?: NDKList; } /** * Type for items that can be muted */ type MuteableItem = NDKEvent | NDKUser | string; /** * The state structure for the NDK Mutes Zustand store */ interface NDKMutesState { /** * The NDK instance used for mute operations */ ndk: NDK__default | undefined; /** * Map of user mutes by pubkey */ mutes: Map; /** * Extra mutes that won't be included in the published mute list * This is at the application level, not per user */ extraMutes: NDKUserMutes; /** * The active pubkey for mute operations */ activePubkey: Hexpubkey | null; /** * The active mute list */ muteList: NDKList; /** * The combined mute criteria for the active pubkey and extraMutes */ muteCriteria: MuteCriteria$1; init(ndk: NDK__default): void; /** * Initialize mutes for a user * @param pubkey The pubkey of the user */ initMutes: (pubkey: Hexpubkey) => void; /** * Load mute list for a user from an event * @param event The mute list event */ loadMuteList: (event: NDKEvent) => void; /** * Mute an item for a user * @param pubkey The pubkey of the user * @param item The item to mute * @param type The type of the item * @param options Options for publishing the mute list */ /** * Mute an item for a user * @param item The item to mute * @param pubkey The pubkey of the user (optional, uses active pubkey if undefined) */ mute: (item: MuteableItem, pubkey?: Hexpubkey) => void; /** * Unmute an item for a user * @param item The item to unmute * @param pubkey The pubkey of the user (optional, uses active pubkey if undefined) */ unmute: (item: MuteableItem, pubkey?: Hexpubkey) => void; /** * Set the active pubkey for mute operations * @param pubkey The pubkey to set as active */ setActivePubkey: (pubkey: Hexpubkey | null) => void; /** * Add multiple extra mute items that won't be included in the published mute list * @param items Array of items to mute */ addExtraMuteItems: (items: MuteableItem[]) => void; } /** * React hook to check if an item is muted for the current user. * @param item The item to check * @returns True if the item is muted, false otherwise */ declare function useIsItemMuted(item: MuteableItem): boolean; /** * React hook to get the mute criteria for the active user. * The mute store is automatically synchronized with the session store * through the session store functions. * * @returns The mute criteria for the active user, or empty criteria if no user is active. */ declare function useActiveMuteCriteria(): MuteCriteria$1; declare function useMuteCriteria(pubkey?: string): MuteCriteria$1; declare const EMPTY_MUTE_CRITERIA: MuteCriteria$1; /** * Hook that returns a fresh, stable `isMuted()` function that always reflects current mute state. * * This implementation avoids infinite loops by: * 1. Using a single selector to get all mute data at once * 2. Creating a stable reference to the filter function with useMemo * 3. Using a stable dependency (the serialized state) for the memoization */ declare function useMuteFilter(): (event: NDKEvent) => boolean; declare const useNDKMutes: zustand.UseBoundStore>; /** * Subscribes to NDK events based on the provided filters and returns the matching events. * * This hook is designed for efficiently observing events from the cache. * It incorporates several optimizations: * * - **Cache First:** Prioritizes fetching events synchronously from the NDK cache (`cacheUsage: ONLY_CACHE` by default). * - **Deduplication:** Ensures each unique event (based on `event.tagId()`) is added only once. * - **Buffering:** Asynchronous events received from relays are buffered for a short period (50ms) * to batch updates and reduce re-renders. Synchronous events from the cache are flushed immediately. * - **Automatic Cleanup:** Stops the NDK subscription when the component unmounts or when filters/dependencies change. * * @template T - The specific type of NDKEvent expected (defaults to NDKEvent). * @param {NDKFilter | NDKFilter[] | false} filters - A single NDK filter, an array of filters, or `false` to disable the subscription. * If `false`, the hook will return an empty array and perform no subscription. * @param {NDKSubscriptionOptions} [opts={}] - Optional NDK subscription options to override the defaults. * @param {any[]} [dependencies=[]] - Optional React useEffect dependency array. The hook will re-subscribe * if any value in this array changes. The `filters` parameter is implicitly included as a dependency. * @returns {T[]} An array containing the unique events matching the filters. */ interface UseObserverOptions extends NDKSubscriptionOptions { /** * Whether to include muted events (default: false) */ includeMuted?: boolean; } declare function useObserver(filters: NDKFilter[] | false, opts?: UseObserverOptions, dependencies?: unknown[]): T[]; /** * React hook for subscribing to Nostr events * @param filters - Filters to run or false to avoid running the subscription. Note that when setting the filters to false, changing the filters prop * to have a different value will run the subscription, but changing the filters won't. * @param opts - UseSubscribeOptions * @param dependencies - unknown[] - dependencies to re-run the subscription when they change * @returns {UseSubscribeResult} Subscription state including events, eose flag, subscription, and store reference */ declare function useSubscribe(filters: NDKFilter[] | false, opts?: UseSubscribeOptions, dependencies?: unknown[]): { events: T[]; eose: boolean; }; /** * Fetches an event. * * @example * const event = useEvent("naddr1qvzqqqr4gupzqmjxss3dld622uu8q25gywum9qtg4w4cv4064jmg20xsac2aam5nqy88wumn8ghj7mn0wvhxcmmv9uq32amnwvaz7tmjv4kxz7fwv3sk6atn9e5k7tcqp5cnvwpsxccnywfjxc6njwg4ef260", { wrap: true }); * * if (event === undefined) return
Loading...
; * if (event === null) return
Not found
; * if (event) return
{event.content}
; * * @param filters * @param opts * @param dependencies * @returns */ declare function useEvent(idOrFilter: string | NDKFilter | NDKFilter[] | false, opts?: UseSubscribeOptions, dependencies?: unknown[]): NDKEvent | null; /** * Interface for the useAvailableSessions hook return value */ interface UseAvailableSessionsResult { /** * An array of hex pubkeys for which signers are available in the store. * Represents the available user sessions (started sessions). */ availablePubkeys: Hexpubkey[]; } /** * Hook to get a list of available session pubkeys. * * This hook retrieves the list of signers from the NDK store * and returns an array of their corresponding public keys (from started sessions). * This represents the sessions that the user can potentially switch to. * * @returns {UseAvailableSessionsResult} Object containing an array of available pubkeys. */ declare const useAvailableSessions: () => UseAvailableSessionsResult; /** * Store interface for managing subscription state * @interface SubscribeStore * @property {T[]} events - Array of received events * @property {Map} eventMap - Map of events by ID * @property {boolean} eose - End of stored events flag */ interface MuteCriteria { mutedPubkeys: Set; mutedEventIds: Set; mutedHashtags: Set; mutedWords: Set; } interface SubscribeStore { events: T[]; eventMap: Map; eose: boolean; subscriptionRef: NDKSubscription | undefined; addEvent: (event: T) => void; addEvents: (events: T[]) => void; removeEventId: (id: string) => void; filterMutedEvents: (muteFilter: (event: NDKEvent) => boolean) => void; filterExistingEvents: (filters: NDKFilter[]) => void; setEose: () => void; reset: () => void; } /** * Creates a store to manage subscription state with optional event buffering * @param bufferMs - Buffer time in milliseconds, false to disable buffering */ declare const createSubscribeStore: (bufferMs?: number | false) => zustand.StoreApi>; /** * Hook to manage the user's NDK Cashu Wallet instance and its balance. * Automatically loads the wallet from the user's NIP-60 events. */ declare const useNDKWallet: () => { wallet: any; balance: any; loading: any; error: any; }; /** * Hook to manage and interact with the NDKNutzapMonitor. * Uses a singleton pattern to prevent duplicate monitors from competing for nutzaps. * The monitor will use the wallet's published mint list (kind:10019) for configuration. */ declare const useNutzapMonitor: () => { nutzaps: any; isMonitoring: any; error: any; start: any; stop: any; }; declare const useNDKNutzapMonitor: () => { nutzaps: any; isMonitoring: any; error: any; start: any; stop: any; }; interface NDKHeadlessProps { ndk: NDKConstructorParams; session?: { storage: NDKSessionStorageAdapter; opts: SessionStartOptions; } | false; } /** * Add a headless component to make it simpler to instantiate NDK in React apps. * * @example * ```tsx * import { NDKHeadless } from "@nostr-dev-kit/ndk-hooks"; * * function App() { * return ( * <> * * * * ); * } */ declare function NDKHeadless({ ndk, session }: NDKHeadlessProps): null; export { EMPTY_MUTE_CRITERIA, type MuteCriteria, type NDKEventWithAsyncFrom, type NDKEventWithFrom, NDKHeadless, NDKSessionLocalStorage, type NDKSessionStorageAdapter, type NDKSessionsState, type NDKStoreState, type NDKUserSession, type SessionStartOptions, type StoredSession, type SubscribeStore, type UseObserverOptions, type UseSubscribeOptions, type UserProfilesStore, addOrUpdateStoredSession, clearActivePubkey, createSubscribeStore, getActivePubkey, loadSessionsFromStorage, removeStoredSession, saveSessionsToStorage, storeActivePubkey, useActiveMuteCriteria, useAvailableSessions, useCurrentUserProfile, useEvent, useFollows, useIsItemMuted, useMuteCriteria, useMuteFilter, useNDK, useNDKCurrentPubkey, useNDKCurrentUser, useNDKInit, useNDKMutes, useNDKNutzapMonitor, useNDKSessionEvent, useNDKSessionLogin, useNDKSessionLogout, useNDKSessionMonitor, useNDKSessionSessions, useNDKSessionSigners, useNDKSessionStart, useNDKSessionStop, useNDKSessionSwitch, useNDKStore, useNDKUnpublishedEvents, useNDKWallet, useNutzapMonitor, useObserver, useProfile, useProfileValue, useSetProfile, useSubscribe, useUser, useUserProfilesStore };