@proofchain/sdk 2.15.0 → 2.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -1858,6 +1858,7 @@ interface UserReward {
1858
1858
  id: string;
1859
1859
  reward_name: string;
1860
1860
  reward_type: string;
1861
+ category?: string;
1861
1862
  slug?: string;
1862
1863
  description?: string;
1863
1864
  status: string;
@@ -1914,6 +1915,23 @@ interface ManualRewardRequest {
1914
1915
  trigger_data?: Record<string, any>;
1915
1916
  distribute_immediately?: boolean;
1916
1917
  }
1918
+ interface ClaimNFTResult {
1919
+ success: boolean;
1920
+ reward_id: string;
1921
+ token_id?: number;
1922
+ tx_hash: string;
1923
+ wallet_address: string;
1924
+ }
1925
+ interface DistributeResult {
1926
+ success: boolean;
1927
+ reward_id: string;
1928
+ message: string;
1929
+ }
1930
+ interface RevokeResult {
1931
+ success: boolean;
1932
+ reward_id: string;
1933
+ status: string;
1934
+ }
1917
1935
  interface ListRewardsOptions {
1918
1936
  is_active?: boolean;
1919
1937
  reward_type?: string;
@@ -1962,37 +1980,108 @@ declare class RewardsClient {
1962
1980
  offset?: number;
1963
1981
  }): Promise<EarnedReward[]>;
1964
1982
  /**
1965
- * Get earned rewards for a user (with full badge/reward details)
1983
+ * Get earned rewards for a user (with full badge/reward details).
1984
+ * Use this to display a user's reward collection on a dedicated screen.
1985
+ *
1986
+ * @example
1987
+ * ```ts
1988
+ * // All user rewards
1989
+ * const all = await client.rewards.getUserRewards('user-123');
1990
+ *
1991
+ * // Only badges in the "Fan Pass" category
1992
+ * const badges = await client.rewards.getUserRewards('user-123', {
1993
+ * reward_type: 'badge',
1994
+ * category: 'Fan Pass',
1995
+ * });
1996
+ *
1997
+ * // Only distributed rewards
1998
+ * const distributed = await client.rewards.getUserRewards('user-123', {
1999
+ * status: 'distributed',
2000
+ * });
2001
+ * ```
1966
2002
  */
1967
2003
  getUserRewards(userId: string, options?: {
1968
2004
  status?: string;
1969
2005
  reward_type?: string;
2006
+ category?: string;
1970
2007
  }): Promise<UserReward[]>;
1971
2008
  /**
1972
- * Get the public reward catalog (active, public reward definitions)
2009
+ * Get the public reward catalog (active, public reward definitions).
1973
2010
  * Available to both API key and end-user JWT clients.
2011
+ *
2012
+ * @param category - Optional category filter (e.g. "Fan Pass", "Partner: Acme")
2013
+ *
2014
+ * @example
2015
+ * ```ts
2016
+ * // All available rewards
2017
+ * const all = await client.rewards.getCatalog();
2018
+ *
2019
+ * // Only "Fan Pass" rewards
2020
+ * const fanPass = await client.rewards.getCatalog('Fan Pass');
2021
+ * ```
1974
2022
  */
1975
- getCatalog(): Promise<RewardDefinition[]>;
2023
+ getCatalog(category?: string): Promise<RewardDefinition[]>;
1976
2024
  /**
1977
2025
  * Claim a lazy-minted NFT reward.
1978
2026
  * The wallet_address receives the minted NFT. The tenant's treasury pays gas.
1979
2027
  * Available to both API key and end-user JWT clients (scoped to own rewards).
2028
+ *
2029
+ * For non-NFT rewards, use {@link distribute} instead.
1980
2030
  */
1981
- claimReward(earnedRewardId: string, walletAddress: string): Promise<{
1982
- success: boolean;
1983
- reward_id: string;
1984
- token_id?: number;
1985
- tx_hash: string;
1986
- wallet_address: string;
1987
- }>;
2031
+ claimNFT(earnedRewardId: string, walletAddress: string): Promise<ClaimNFTResult>;
2032
+ /**
2033
+ * @deprecated Use {@link claimNFT} instead — this method only works for lazy-mint NFTs.
2034
+ */
2035
+ claimReward(earnedRewardId: string, walletAddress: string): Promise<ClaimNFTResult>;
1988
2036
  /**
1989
- * Manually award rewards to users
2037
+ * Manually award rewards to one or more users.
2038
+ * Works for all reward types: points, tokens, NFTs, badges, custom.
2039
+ *
2040
+ * @example
2041
+ * ```ts
2042
+ * // Award a badge to two users
2043
+ * const rewards = await client.rewards.award({
2044
+ * definition_id: 'badge-def-id',
2045
+ * user_ids: ['user-1', 'user-2'],
2046
+ * distribute_immediately: true,
2047
+ * });
2048
+ * ```
2049
+ */
2050
+ award(request: ManualRewardRequest): Promise<EarnedReward[]>;
2051
+ /**
2052
+ * @deprecated Use {@link award} instead.
1990
2053
  */
1991
2054
  awardManual(request: ManualRewardRequest): Promise<EarnedReward[]>;
1992
2055
  /**
1993
- * Distribute pending rewards (mint NFTs, transfer tokens)
2056
+ * Distribute a pending or failed reward.
2057
+ * Works for all reward types — triggers the appropriate distribution
2058
+ * (mint NFT, transfer tokens, issue badge, credit points, etc.).
2059
+ *
2060
+ * @example
2061
+ * ```ts
2062
+ * // Distribute a pending reward
2063
+ * const result = await client.rewards.distribute('earned-reward-id');
2064
+ * ```
2065
+ */
2066
+ distribute(earnedRewardId: string): Promise<DistributeResult>;
2067
+ /**
2068
+ * @deprecated Use {@link distribute} instead.
2069
+ */
2070
+ distributePending(earnedRewardId: string): Promise<DistributeResult>;
2071
+ /**
2072
+ * Distribute all pending rewards for the tenant.
2073
+ * Queues every pending reward for background distribution.
2074
+ */
2075
+ distributeAll(): Promise<{
2076
+ queued: number;
2077
+ }>;
2078
+ /**
2079
+ * Revoke an earned reward.
2080
+ *
2081
+ * @param earnedRewardId - The earned reward ID to revoke
2082
+ * @param reason - Reason for revocation
1994
2083
  */
1995
- distributePending(earnedRewardId: string): Promise<EarnedReward>;
2084
+ revoke(earnedRewardId: string, reason: string): Promise<RevokeResult>;
1996
2085
  /**
1997
2086
  * Upload an asset for a reward (image, metadata JSON)
1998
2087
  */
@@ -2859,6 +2948,94 @@ declare class FanpassLeaderboardClient {
2859
2948
  }): Promise<FanpassUserComparisonResponse>;
2860
2949
  }
2861
2950
 
2951
+ /**
2952
+ * Notifications Client
2953
+ *
2954
+ * Provides real-time notification streaming via Server-Sent Events (SSE).
2955
+ * Notifications are pushed from the backend when quest/reward events occur.
2956
+ *
2957
+ * @example
2958
+ * ```typescript
2959
+ * // Subscribe to notifications
2960
+ * const unsub = client.notifications.subscribe('user-123', (event) => {
2961
+ * switch (event.event) {
2962
+ * case 'quest_step_completed':
2963
+ * showToast(`Step completed: ${event.data.step_name}`);
2964
+ * break;
2965
+ * case 'quest_completed':
2966
+ * showToast(`Quest completed: ${event.data.quest_name}!`);
2967
+ * break;
2968
+ * case 'badge_earned':
2969
+ * showBadgeModal(event.data);
2970
+ * break;
2971
+ * case 'reward_claimable':
2972
+ * showClaimButton(event.data);
2973
+ * break;
2974
+ * }
2975
+ * });
2976
+ *
2977
+ * // Later, unsubscribe
2978
+ * unsub();
2979
+ * ```
2980
+ */
2981
+
2982
+ /** Notification event types pushed by the server. */
2983
+ type NotificationEventType = 'connected' | 'quest_step_completed' | 'quest_completed' | 'reward_earned' | 'reward_distributed' | 'reward_claimable' | 'points_awarded' | 'badge_earned' | 'level_up';
2984
+ /** A notification event received from the SSE stream. */
2985
+ interface NotificationEvent {
2986
+ /** Unique event ID */
2987
+ id: string;
2988
+ /** Event type */
2989
+ event: NotificationEventType;
2990
+ /** Event-specific payload */
2991
+ data: Record<string, any>;
2992
+ /** Tenant ID */
2993
+ tenant_id: string;
2994
+ /** User ID */
2995
+ user_id: string;
2996
+ /** ISO timestamp */
2997
+ timestamp: string;
2998
+ }
2999
+ /** Callback invoked for each notification event. */
3000
+ type NotificationCallback = (event: NotificationEvent) => void;
3001
+ /** Options for the subscribe method. */
3002
+ interface SubscribeOptions {
3003
+ /** Called when the connection is established */
3004
+ onConnect?: () => void;
3005
+ /** Called when the connection is lost (will auto-reconnect) */
3006
+ onDisconnect?: () => void;
3007
+ /** Called on error */
3008
+ onError?: (error: Error) => void;
3009
+ /** Auto-reconnect on disconnect (default: true) */
3010
+ autoReconnect?: boolean;
3011
+ /** Reconnect delay in ms (default: 3000) */
3012
+ reconnectDelay?: number;
3013
+ }
3014
+ /** Function to call to unsubscribe / close the SSE connection. */
3015
+ type Unsubscribe = () => void;
3016
+ declare class NotificationsClient {
3017
+ private baseUrl;
3018
+ private authHeaders;
3019
+ constructor(http: HttpClient);
3020
+ /**
3021
+ * Subscribe to real-time notifications for a user.
3022
+ *
3023
+ * Opens a Server-Sent Events connection and calls the callback
3024
+ * for each notification event (quest progress, rewards, etc.).
3025
+ *
3026
+ * Returns an unsubscribe function to close the connection.
3027
+ *
3028
+ * **Browser usage:** Works out of the box with EventSource.
3029
+ * **Node.js usage:** Requires the `eventsource` package.
3030
+ *
3031
+ * @param userId - The external user ID to subscribe for
3032
+ * @param callback - Function called for each notification event
3033
+ * @param options - Connection options (reconnect, callbacks)
3034
+ * @returns Unsubscribe function to close the connection
3035
+ */
3036
+ subscribe(userId: string, callback: NotificationCallback, options?: SubscribeOptions): Unsubscribe;
3037
+ }
3038
+
2862
3039
  /**
2863
3040
  * ProofChain Client
2864
3041
  */
@@ -3053,6 +3230,8 @@ declare class ProofChain {
3053
3230
  cohorts: CohortLeaderboardClient;
3054
3231
  /** Fanpass leaderboard client for composite score leaderboards */
3055
3232
  fanpassLeaderboard: FanpassLeaderboardClient;
3233
+ /** Notifications client for real-time SSE streaming */
3234
+ notifications: NotificationsClient;
3056
3235
  constructor(options: ProofChainOptions);
3057
3236
  /**
3058
3237
  * Create a client for end-user JWT authentication (PWA/frontend use).
@@ -3268,4 +3447,4 @@ declare class TimeoutError extends ProofChainError {
3268
3447
  constructor(message?: string);
3269
3448
  }
3270
3449
 
3271
- export { type Achievement, type ActivitySummaryView, type AddNFTRequest, type ApiKey, type AttestRequest, type AttestationMode, type AttestationResult, AuthenticationError, AuthorizationError, type AvailableView, type Badge, type BatchIngestRequest, type BatchIngestResponse, type BatchVerifyResult, type BlockchainProof, type BlockchainStats, type Certificate, type CertificateVerifyResult, CertificatesResource, type Channel, type ChannelState, type ChannelStatus, ChannelsResource, type ClaimRewardResult, type CohortDefinition, type CohortGroupStats, CohortLeaderboardClient, type CohortLeaderboardEntry, type CohortLeaderboardOptions, type CohortLeaderboardResponse, type ComprehensiveWalletInfo, type CreateAchievementRequest, type CreateApiKeyRequest, type CreateBadgeRequest, type CreateChannelRequest, type CreateDataViewRequest, type CreateDualWalletsRequest, type CreateEndUserRequest, type CreateEventRequest, type CreatePassportDefinitionRequest, type CreatePassportRequest, type CreateQuestRequest, type CreateQuestStepRequest, type CreateRewardDefinitionRequest, type CreateSchemaRequest, type CreateTemplateFieldRequest, type CreateTemplateRequest, type CreateWalletRequest as CreateUserWalletRequest, type CreateWalletRequest$1 as CreateWalletRequest, type CreateWebhookRequest, type DataViewColumn, type DataViewComputation, type DataViewDetail, type DataViewExecuteResult, type DataViewInfo, type DataViewListResponse, type DataViewPreviewRequest, type DataViewPreviewResult, type DataViewSummary, DataViewsClient, DocumentsResource, type DualWallets, type EarnedReward, type EndUser, EndUserIngestionClient, type EndUserIngestionClientOptions, type EndUserListResponse, EndUsersClient, type Event, type EventBatchProof, type EventMetadata, type EventStatus, EventsResource, type ExecuteSwapRequest, type Facet, type FacetsResponse, type FanProfileView, type FanpassGroupStats, FanpassLeaderboardClient, type FanpassLeaderboardEntry, type FanpassLeaderboardOptions, type FanpassLeaderboardResponse, type FanpassUserComparisonResponse, type FieldValue, type GDPRDeletionRequest, type GDPRDeletionResponse, type GDPRPreviewResponse, type IngestEventRequest, type IngestEventResponse, IngestionClient, type IngestionClientOptions, type IssueCertificateRequest, type LeaderboardUserProfile$1 as LeaderboardUserProfile, type LinkWalletRequest, type ListCertificatesRequest, type ListCohortsOptions, type ListEndUsersOptions, type ListEventsRequest, type ListQuestsOptions, type ListRewardsOptions, type ListSchemasOptions, type ManualRewardRequest, type MergeUsersRequest, type Milestone, type NFT, NetworkError, NotFoundError, type Passport, PassportClient, type PassportDefinition, type PassportFieldValue, type PassportHistory, type PassportTemplate, type PassportV2Data, type PassportWithFields, ProofChain, ProofChainError, type ProofChainOptions, type ProofVerifyResult, type Quest, type QuestStep, type QuestWithProgress, QuestsClient, RateLimitError, type RegisterWalletRequest, type RewardAsset, type RewardDefinition, type RewardEarned, RewardsClient, type Schema, type SchemaDetail, type SchemaField, type SchemaListResponse, type ValidationError$1 as SchemaValidationError, SchemasClient, type SearchFilters, type SearchQueryRequest, type SearchRequest, SearchResource, type SearchResponse, type SearchResult, type SearchStats, ServerError, type SetProfileRequest, type Settlement, type StepCompletionResult, type StepProgress, type StreamAck, type StreamEventRequest, type SwapQuote, type SwapQuoteRequest, type SwapResult, type TemplateField, type TenantInfo, TenantResource, type TierDefinition, TimeoutError, type TokenBalance, type TransferRequest, type TransferResult, type UpdateDataViewRequest, type UpdateEndUserRequest, type UpdatePassportRequest, type UpdateWebhookRequest, type UsageStats, type UserAchievement, type UserActivity, type UserActivityResponse, type UserBadge, type UserBreakdownResponse, type UserCohortBreakdownEntry, type UserQuestProgress, type UserReward$1 as UserReward, type UserRewardsResponse, type UserWalletSummary, type UserWithWallets, type UsersWithWalletsResponse, type ValidateDataRequest, ValidationError, type ValidationErrorDetail, type ValidationResult, type VaultFile, type VaultFolder, type VaultListResponse, VaultResource, type VaultStats, type VaultUploadRequest, type VerificationResult, VerifyResource, type ViewColumn, type ViewTemplate, type Wallet, type WalletBalance, WalletClient, type WalletCreationResult, type WalletStats, type Webhook, WebhooksResource };
3450
+ export { type Achievement, type ActivitySummaryView, type AddNFTRequest, type ApiKey, type AttestRequest, type AttestationMode, type AttestationResult, AuthenticationError, AuthorizationError, type AvailableView, type Badge, type BatchIngestRequest, type BatchIngestResponse, type BatchVerifyResult, type BlockchainProof, type BlockchainStats, type Certificate, type CertificateVerifyResult, CertificatesResource, type Channel, type ChannelState, type ChannelStatus, ChannelsResource, type ClaimNFTResult, type ClaimRewardResult, type CohortDefinition, type CohortGroupStats, CohortLeaderboardClient, type CohortLeaderboardEntry, type CohortLeaderboardOptions, type CohortLeaderboardResponse, type ComprehensiveWalletInfo, type CreateAchievementRequest, type CreateApiKeyRequest, type CreateBadgeRequest, type CreateChannelRequest, type CreateDataViewRequest, type CreateDualWalletsRequest, type CreateEndUserRequest, type CreateEventRequest, type CreatePassportDefinitionRequest, type CreatePassportRequest, type CreateQuestRequest, type CreateQuestStepRequest, type CreateRewardDefinitionRequest, type CreateSchemaRequest, type CreateTemplateFieldRequest, type CreateTemplateRequest, type CreateWalletRequest as CreateUserWalletRequest, type CreateWalletRequest$1 as CreateWalletRequest, type CreateWebhookRequest, type DataViewColumn, type DataViewComputation, type DataViewDetail, type DataViewExecuteResult, type DataViewInfo, type DataViewListResponse, type DataViewPreviewRequest, type DataViewPreviewResult, type DataViewSummary, DataViewsClient, type DistributeResult, DocumentsResource, type DualWallets, type EarnedReward, type EndUser, EndUserIngestionClient, type EndUserIngestionClientOptions, type EndUserListResponse, EndUsersClient, type Event, type EventBatchProof, type EventMetadata, type EventStatus, EventsResource, type ExecuteSwapRequest, type Facet, type FacetsResponse, type FanProfileView, type FanpassGroupStats, FanpassLeaderboardClient, type FanpassLeaderboardEntry, type FanpassLeaderboardOptions, type FanpassLeaderboardResponse, type FanpassUserComparisonResponse, type FieldValue, type GDPRDeletionRequest, type GDPRDeletionResponse, type GDPRPreviewResponse, type IngestEventRequest, type IngestEventResponse, IngestionClient, type IngestionClientOptions, type IssueCertificateRequest, type LeaderboardUserProfile$1 as LeaderboardUserProfile, type LinkWalletRequest, type ListCertificatesRequest, type ListCohortsOptions, type ListEndUsersOptions, type ListEventsRequest, type ListQuestsOptions, type ListRewardsOptions, type ListSchemasOptions, type ManualRewardRequest, type MergeUsersRequest, type Milestone, type NFT, NetworkError, NotFoundError, type NotificationCallback, type NotificationEvent, type NotificationEventType, NotificationsClient, type Passport, PassportClient, type PassportDefinition, type PassportFieldValue, type PassportHistory, type PassportTemplate, type PassportV2Data, type PassportWithFields, ProofChain, ProofChainError, type ProofChainOptions, type ProofVerifyResult, type Quest, type QuestStep, type QuestWithProgress, QuestsClient, RateLimitError, type RegisterWalletRequest, type RevokeResult, type RewardAsset, type RewardDefinition, type RewardEarned, RewardsClient, type Schema, type SchemaDetail, type SchemaField, type SchemaListResponse, type ValidationError$1 as SchemaValidationError, SchemasClient, type SearchFilters, type SearchQueryRequest, type SearchRequest, SearchResource, type SearchResponse, type SearchResult, type SearchStats, ServerError, type SetProfileRequest, type Settlement, type StepCompletionResult, type StepProgress, type StreamAck, type StreamEventRequest, type SubscribeOptions, type SwapQuote, type SwapQuoteRequest, type SwapResult, type TemplateField, type TenantInfo, TenantResource, type TierDefinition, TimeoutError, type TokenBalance, type TransferRequest, type TransferResult, type Unsubscribe, type UpdateDataViewRequest, type UpdateEndUserRequest, type UpdatePassportRequest, type UpdateWebhookRequest, type UsageStats, type UserAchievement, type UserActivity, type UserActivityResponse, type UserBadge, type UserBreakdownResponse, type UserCohortBreakdownEntry, type UserQuestProgress, type UserReward$1 as UserReward, type UserRewardsResponse, type UserWalletSummary, type UserWithWallets, type UsersWithWalletsResponse, type ValidateDataRequest, ValidationError, type ValidationErrorDetail, type ValidationResult, type VaultFile, type VaultFolder, type VaultListResponse, VaultResource, type VaultStats, type VaultUploadRequest, type VerificationResult, VerifyResource, type ViewColumn, type ViewTemplate, type Wallet, type WalletBalance, WalletClient, type WalletCreationResult, type WalletStats, type Webhook, WebhooksResource };
package/dist/index.d.ts CHANGED
@@ -1858,6 +1858,7 @@ interface UserReward {
1858
1858
  id: string;
1859
1859
  reward_name: string;
1860
1860
  reward_type: string;
1861
+ category?: string;
1861
1862
  slug?: string;
1862
1863
  description?: string;
1863
1864
  status: string;
@@ -1914,6 +1915,23 @@ interface ManualRewardRequest {
1914
1915
  trigger_data?: Record<string, any>;
1915
1916
  distribute_immediately?: boolean;
1916
1917
  }
1918
+ interface ClaimNFTResult {
1919
+ success: boolean;
1920
+ reward_id: string;
1921
+ token_id?: number;
1922
+ tx_hash: string;
1923
+ wallet_address: string;
1924
+ }
1925
+ interface DistributeResult {
1926
+ success: boolean;
1927
+ reward_id: string;
1928
+ message: string;
1929
+ }
1930
+ interface RevokeResult {
1931
+ success: boolean;
1932
+ reward_id: string;
1933
+ status: string;
1934
+ }
1917
1935
  interface ListRewardsOptions {
1918
1936
  is_active?: boolean;
1919
1937
  reward_type?: string;
@@ -1962,37 +1980,108 @@ declare class RewardsClient {
1962
1980
  offset?: number;
1963
1981
  }): Promise<EarnedReward[]>;
1964
1982
  /**
1965
- * Get earned rewards for a user (with full badge/reward details)
1983
+ * Get earned rewards for a user (with full badge/reward details).
1984
+ * Use this to display a user's reward collection on a dedicated screen.
1985
+ *
1986
+ * @example
1987
+ * ```ts
1988
+ * // All user rewards
1989
+ * const all = await client.rewards.getUserRewards('user-123');
1990
+ *
1991
+ * // Only badges in the "Fan Pass" category
1992
+ * const badges = await client.rewards.getUserRewards('user-123', {
1993
+ * reward_type: 'badge',
1994
+ * category: 'Fan Pass',
1995
+ * });
1996
+ *
1997
+ * // Only distributed rewards
1998
+ * const distributed = await client.rewards.getUserRewards('user-123', {
1999
+ * status: 'distributed',
2000
+ * });
2001
+ * ```
1966
2002
  */
1967
2003
  getUserRewards(userId: string, options?: {
1968
2004
  status?: string;
1969
2005
  reward_type?: string;
2006
+ category?: string;
1970
2007
  }): Promise<UserReward[]>;
1971
2008
  /**
1972
- * Get the public reward catalog (active, public reward definitions)
2009
+ * Get the public reward catalog (active, public reward definitions).
1973
2010
  * Available to both API key and end-user JWT clients.
2011
+ *
2012
+ * @param category - Optional category filter (e.g. "Fan Pass", "Partner: Acme")
2013
+ *
2014
+ * @example
2015
+ * ```ts
2016
+ * // All available rewards
2017
+ * const all = await client.rewards.getCatalog();
2018
+ *
2019
+ * // Only "Fan Pass" rewards
2020
+ * const fanPass = await client.rewards.getCatalog('Fan Pass');
2021
+ * ```
1974
2022
  */
1975
- getCatalog(): Promise<RewardDefinition[]>;
2023
+ getCatalog(category?: string): Promise<RewardDefinition[]>;
1976
2024
  /**
1977
2025
  * Claim a lazy-minted NFT reward.
1978
2026
  * The wallet_address receives the minted NFT. The tenant's treasury pays gas.
1979
2027
  * Available to both API key and end-user JWT clients (scoped to own rewards).
2028
+ *
2029
+ * For non-NFT rewards, use {@link distribute} instead.
1980
2030
  */
1981
- claimReward(earnedRewardId: string, walletAddress: string): Promise<{
1982
- success: boolean;
1983
- reward_id: string;
1984
- token_id?: number;
1985
- tx_hash: string;
1986
- wallet_address: string;
1987
- }>;
2031
+ claimNFT(earnedRewardId: string, walletAddress: string): Promise<ClaimNFTResult>;
2032
+ /**
2033
+ * @deprecated Use {@link claimNFT} instead — this method only works for lazy-mint NFTs.
2034
+ */
2035
+ claimReward(earnedRewardId: string, walletAddress: string): Promise<ClaimNFTResult>;
1988
2036
  /**
1989
- * Manually award rewards to users
2037
+ * Manually award rewards to one or more users.
2038
+ * Works for all reward types: points, tokens, NFTs, badges, custom.
2039
+ *
2040
+ * @example
2041
+ * ```ts
2042
+ * // Award a badge to two users
2043
+ * const rewards = await client.rewards.award({
2044
+ * definition_id: 'badge-def-id',
2045
+ * user_ids: ['user-1', 'user-2'],
2046
+ * distribute_immediately: true,
2047
+ * });
2048
+ * ```
2049
+ */
2050
+ award(request: ManualRewardRequest): Promise<EarnedReward[]>;
2051
+ /**
2052
+ * @deprecated Use {@link award} instead.
1990
2053
  */
1991
2054
  awardManual(request: ManualRewardRequest): Promise<EarnedReward[]>;
1992
2055
  /**
1993
- * Distribute pending rewards (mint NFTs, transfer tokens)
2056
+ * Distribute a pending or failed reward.
2057
+ * Works for all reward types — triggers the appropriate distribution
2058
+ * (mint NFT, transfer tokens, issue badge, credit points, etc.).
2059
+ *
2060
+ * @example
2061
+ * ```ts
2062
+ * // Distribute a pending reward
2063
+ * const result = await client.rewards.distribute('earned-reward-id');
2064
+ * ```
2065
+ */
2066
+ distribute(earnedRewardId: string): Promise<DistributeResult>;
2067
+ /**
2068
+ * @deprecated Use {@link distribute} instead.
2069
+ */
2070
+ distributePending(earnedRewardId: string): Promise<DistributeResult>;
2071
+ /**
2072
+ * Distribute all pending rewards for the tenant.
2073
+ * Queues every pending reward for background distribution.
2074
+ */
2075
+ distributeAll(): Promise<{
2076
+ queued: number;
2077
+ }>;
2078
+ /**
2079
+ * Revoke an earned reward.
2080
+ *
2081
+ * @param earnedRewardId - The earned reward ID to revoke
2082
+ * @param reason - Reason for revocation
1994
2083
  */
1995
- distributePending(earnedRewardId: string): Promise<EarnedReward>;
2084
+ revoke(earnedRewardId: string, reason: string): Promise<RevokeResult>;
1996
2085
  /**
1997
2086
  * Upload an asset for a reward (image, metadata JSON)
1998
2087
  */
@@ -2859,6 +2948,94 @@ declare class FanpassLeaderboardClient {
2859
2948
  }): Promise<FanpassUserComparisonResponse>;
2860
2949
  }
2861
2950
 
2951
+ /**
2952
+ * Notifications Client
2953
+ *
2954
+ * Provides real-time notification streaming via Server-Sent Events (SSE).
2955
+ * Notifications are pushed from the backend when quest/reward events occur.
2956
+ *
2957
+ * @example
2958
+ * ```typescript
2959
+ * // Subscribe to notifications
2960
+ * const unsub = client.notifications.subscribe('user-123', (event) => {
2961
+ * switch (event.event) {
2962
+ * case 'quest_step_completed':
2963
+ * showToast(`Step completed: ${event.data.step_name}`);
2964
+ * break;
2965
+ * case 'quest_completed':
2966
+ * showToast(`Quest completed: ${event.data.quest_name}!`);
2967
+ * break;
2968
+ * case 'badge_earned':
2969
+ * showBadgeModal(event.data);
2970
+ * break;
2971
+ * case 'reward_claimable':
2972
+ * showClaimButton(event.data);
2973
+ * break;
2974
+ * }
2975
+ * });
2976
+ *
2977
+ * // Later, unsubscribe
2978
+ * unsub();
2979
+ * ```
2980
+ */
2981
+
2982
+ /** Notification event types pushed by the server. */
2983
+ type NotificationEventType = 'connected' | 'quest_step_completed' | 'quest_completed' | 'reward_earned' | 'reward_distributed' | 'reward_claimable' | 'points_awarded' | 'badge_earned' | 'level_up';
2984
+ /** A notification event received from the SSE stream. */
2985
+ interface NotificationEvent {
2986
+ /** Unique event ID */
2987
+ id: string;
2988
+ /** Event type */
2989
+ event: NotificationEventType;
2990
+ /** Event-specific payload */
2991
+ data: Record<string, any>;
2992
+ /** Tenant ID */
2993
+ tenant_id: string;
2994
+ /** User ID */
2995
+ user_id: string;
2996
+ /** ISO timestamp */
2997
+ timestamp: string;
2998
+ }
2999
+ /** Callback invoked for each notification event. */
3000
+ type NotificationCallback = (event: NotificationEvent) => void;
3001
+ /** Options for the subscribe method. */
3002
+ interface SubscribeOptions {
3003
+ /** Called when the connection is established */
3004
+ onConnect?: () => void;
3005
+ /** Called when the connection is lost (will auto-reconnect) */
3006
+ onDisconnect?: () => void;
3007
+ /** Called on error */
3008
+ onError?: (error: Error) => void;
3009
+ /** Auto-reconnect on disconnect (default: true) */
3010
+ autoReconnect?: boolean;
3011
+ /** Reconnect delay in ms (default: 3000) */
3012
+ reconnectDelay?: number;
3013
+ }
3014
+ /** Function to call to unsubscribe / close the SSE connection. */
3015
+ type Unsubscribe = () => void;
3016
+ declare class NotificationsClient {
3017
+ private baseUrl;
3018
+ private authHeaders;
3019
+ constructor(http: HttpClient);
3020
+ /**
3021
+ * Subscribe to real-time notifications for a user.
3022
+ *
3023
+ * Opens a Server-Sent Events connection and calls the callback
3024
+ * for each notification event (quest progress, rewards, etc.).
3025
+ *
3026
+ * Returns an unsubscribe function to close the connection.
3027
+ *
3028
+ * **Browser usage:** Works out of the box with EventSource.
3029
+ * **Node.js usage:** Requires the `eventsource` package.
3030
+ *
3031
+ * @param userId - The external user ID to subscribe for
3032
+ * @param callback - Function called for each notification event
3033
+ * @param options - Connection options (reconnect, callbacks)
3034
+ * @returns Unsubscribe function to close the connection
3035
+ */
3036
+ subscribe(userId: string, callback: NotificationCallback, options?: SubscribeOptions): Unsubscribe;
3037
+ }
3038
+
2862
3039
  /**
2863
3040
  * ProofChain Client
2864
3041
  */
@@ -3053,6 +3230,8 @@ declare class ProofChain {
3053
3230
  cohorts: CohortLeaderboardClient;
3054
3231
  /** Fanpass leaderboard client for composite score leaderboards */
3055
3232
  fanpassLeaderboard: FanpassLeaderboardClient;
3233
+ /** Notifications client for real-time SSE streaming */
3234
+ notifications: NotificationsClient;
3056
3235
  constructor(options: ProofChainOptions);
3057
3236
  /**
3058
3237
  * Create a client for end-user JWT authentication (PWA/frontend use).
@@ -3268,4 +3447,4 @@ declare class TimeoutError extends ProofChainError {
3268
3447
  constructor(message?: string);
3269
3448
  }
3270
3449
 
3271
- export { type Achievement, type ActivitySummaryView, type AddNFTRequest, type ApiKey, type AttestRequest, type AttestationMode, type AttestationResult, AuthenticationError, AuthorizationError, type AvailableView, type Badge, type BatchIngestRequest, type BatchIngestResponse, type BatchVerifyResult, type BlockchainProof, type BlockchainStats, type Certificate, type CertificateVerifyResult, CertificatesResource, type Channel, type ChannelState, type ChannelStatus, ChannelsResource, type ClaimRewardResult, type CohortDefinition, type CohortGroupStats, CohortLeaderboardClient, type CohortLeaderboardEntry, type CohortLeaderboardOptions, type CohortLeaderboardResponse, type ComprehensiveWalletInfo, type CreateAchievementRequest, type CreateApiKeyRequest, type CreateBadgeRequest, type CreateChannelRequest, type CreateDataViewRequest, type CreateDualWalletsRequest, type CreateEndUserRequest, type CreateEventRequest, type CreatePassportDefinitionRequest, type CreatePassportRequest, type CreateQuestRequest, type CreateQuestStepRequest, type CreateRewardDefinitionRequest, type CreateSchemaRequest, type CreateTemplateFieldRequest, type CreateTemplateRequest, type CreateWalletRequest as CreateUserWalletRequest, type CreateWalletRequest$1 as CreateWalletRequest, type CreateWebhookRequest, type DataViewColumn, type DataViewComputation, type DataViewDetail, type DataViewExecuteResult, type DataViewInfo, type DataViewListResponse, type DataViewPreviewRequest, type DataViewPreviewResult, type DataViewSummary, DataViewsClient, DocumentsResource, type DualWallets, type EarnedReward, type EndUser, EndUserIngestionClient, type EndUserIngestionClientOptions, type EndUserListResponse, EndUsersClient, type Event, type EventBatchProof, type EventMetadata, type EventStatus, EventsResource, type ExecuteSwapRequest, type Facet, type FacetsResponse, type FanProfileView, type FanpassGroupStats, FanpassLeaderboardClient, type FanpassLeaderboardEntry, type FanpassLeaderboardOptions, type FanpassLeaderboardResponse, type FanpassUserComparisonResponse, type FieldValue, type GDPRDeletionRequest, type GDPRDeletionResponse, type GDPRPreviewResponse, type IngestEventRequest, type IngestEventResponse, IngestionClient, type IngestionClientOptions, type IssueCertificateRequest, type LeaderboardUserProfile$1 as LeaderboardUserProfile, type LinkWalletRequest, type ListCertificatesRequest, type ListCohortsOptions, type ListEndUsersOptions, type ListEventsRequest, type ListQuestsOptions, type ListRewardsOptions, type ListSchemasOptions, type ManualRewardRequest, type MergeUsersRequest, type Milestone, type NFT, NetworkError, NotFoundError, type Passport, PassportClient, type PassportDefinition, type PassportFieldValue, type PassportHistory, type PassportTemplate, type PassportV2Data, type PassportWithFields, ProofChain, ProofChainError, type ProofChainOptions, type ProofVerifyResult, type Quest, type QuestStep, type QuestWithProgress, QuestsClient, RateLimitError, type RegisterWalletRequest, type RewardAsset, type RewardDefinition, type RewardEarned, RewardsClient, type Schema, type SchemaDetail, type SchemaField, type SchemaListResponse, type ValidationError$1 as SchemaValidationError, SchemasClient, type SearchFilters, type SearchQueryRequest, type SearchRequest, SearchResource, type SearchResponse, type SearchResult, type SearchStats, ServerError, type SetProfileRequest, type Settlement, type StepCompletionResult, type StepProgress, type StreamAck, type StreamEventRequest, type SwapQuote, type SwapQuoteRequest, type SwapResult, type TemplateField, type TenantInfo, TenantResource, type TierDefinition, TimeoutError, type TokenBalance, type TransferRequest, type TransferResult, type UpdateDataViewRequest, type UpdateEndUserRequest, type UpdatePassportRequest, type UpdateWebhookRequest, type UsageStats, type UserAchievement, type UserActivity, type UserActivityResponse, type UserBadge, type UserBreakdownResponse, type UserCohortBreakdownEntry, type UserQuestProgress, type UserReward$1 as UserReward, type UserRewardsResponse, type UserWalletSummary, type UserWithWallets, type UsersWithWalletsResponse, type ValidateDataRequest, ValidationError, type ValidationErrorDetail, type ValidationResult, type VaultFile, type VaultFolder, type VaultListResponse, VaultResource, type VaultStats, type VaultUploadRequest, type VerificationResult, VerifyResource, type ViewColumn, type ViewTemplate, type Wallet, type WalletBalance, WalletClient, type WalletCreationResult, type WalletStats, type Webhook, WebhooksResource };
3450
+ export { type Achievement, type ActivitySummaryView, type AddNFTRequest, type ApiKey, type AttestRequest, type AttestationMode, type AttestationResult, AuthenticationError, AuthorizationError, type AvailableView, type Badge, type BatchIngestRequest, type BatchIngestResponse, type BatchVerifyResult, type BlockchainProof, type BlockchainStats, type Certificate, type CertificateVerifyResult, CertificatesResource, type Channel, type ChannelState, type ChannelStatus, ChannelsResource, type ClaimNFTResult, type ClaimRewardResult, type CohortDefinition, type CohortGroupStats, CohortLeaderboardClient, type CohortLeaderboardEntry, type CohortLeaderboardOptions, type CohortLeaderboardResponse, type ComprehensiveWalletInfo, type CreateAchievementRequest, type CreateApiKeyRequest, type CreateBadgeRequest, type CreateChannelRequest, type CreateDataViewRequest, type CreateDualWalletsRequest, type CreateEndUserRequest, type CreateEventRequest, type CreatePassportDefinitionRequest, type CreatePassportRequest, type CreateQuestRequest, type CreateQuestStepRequest, type CreateRewardDefinitionRequest, type CreateSchemaRequest, type CreateTemplateFieldRequest, type CreateTemplateRequest, type CreateWalletRequest as CreateUserWalletRequest, type CreateWalletRequest$1 as CreateWalletRequest, type CreateWebhookRequest, type DataViewColumn, type DataViewComputation, type DataViewDetail, type DataViewExecuteResult, type DataViewInfo, type DataViewListResponse, type DataViewPreviewRequest, type DataViewPreviewResult, type DataViewSummary, DataViewsClient, type DistributeResult, DocumentsResource, type DualWallets, type EarnedReward, type EndUser, EndUserIngestionClient, type EndUserIngestionClientOptions, type EndUserListResponse, EndUsersClient, type Event, type EventBatchProof, type EventMetadata, type EventStatus, EventsResource, type ExecuteSwapRequest, type Facet, type FacetsResponse, type FanProfileView, type FanpassGroupStats, FanpassLeaderboardClient, type FanpassLeaderboardEntry, type FanpassLeaderboardOptions, type FanpassLeaderboardResponse, type FanpassUserComparisonResponse, type FieldValue, type GDPRDeletionRequest, type GDPRDeletionResponse, type GDPRPreviewResponse, type IngestEventRequest, type IngestEventResponse, IngestionClient, type IngestionClientOptions, type IssueCertificateRequest, type LeaderboardUserProfile$1 as LeaderboardUserProfile, type LinkWalletRequest, type ListCertificatesRequest, type ListCohortsOptions, type ListEndUsersOptions, type ListEventsRequest, type ListQuestsOptions, type ListRewardsOptions, type ListSchemasOptions, type ManualRewardRequest, type MergeUsersRequest, type Milestone, type NFT, NetworkError, NotFoundError, type NotificationCallback, type NotificationEvent, type NotificationEventType, NotificationsClient, type Passport, PassportClient, type PassportDefinition, type PassportFieldValue, type PassportHistory, type PassportTemplate, type PassportV2Data, type PassportWithFields, ProofChain, ProofChainError, type ProofChainOptions, type ProofVerifyResult, type Quest, type QuestStep, type QuestWithProgress, QuestsClient, RateLimitError, type RegisterWalletRequest, type RevokeResult, type RewardAsset, type RewardDefinition, type RewardEarned, RewardsClient, type Schema, type SchemaDetail, type SchemaField, type SchemaListResponse, type ValidationError$1 as SchemaValidationError, SchemasClient, type SearchFilters, type SearchQueryRequest, type SearchRequest, SearchResource, type SearchResponse, type SearchResult, type SearchStats, ServerError, type SetProfileRequest, type Settlement, type StepCompletionResult, type StepProgress, type StreamAck, type StreamEventRequest, type SubscribeOptions, type SwapQuote, type SwapQuoteRequest, type SwapResult, type TemplateField, type TenantInfo, TenantResource, type TierDefinition, TimeoutError, type TokenBalance, type TransferRequest, type TransferResult, type Unsubscribe, type UpdateDataViewRequest, type UpdateEndUserRequest, type UpdatePassportRequest, type UpdateWebhookRequest, type UsageStats, type UserAchievement, type UserActivity, type UserActivityResponse, type UserBadge, type UserBreakdownResponse, type UserCohortBreakdownEntry, type UserQuestProgress, type UserReward$1 as UserReward, type UserRewardsResponse, type UserWalletSummary, type UserWithWallets, type UsersWithWalletsResponse, type ValidateDataRequest, ValidationError, type ValidationErrorDetail, type ValidationResult, type VaultFile, type VaultFolder, type VaultListResponse, VaultResource, type VaultStats, type VaultUploadRequest, type VerificationResult, VerifyResource, type ViewColumn, type ViewTemplate, type Wallet, type WalletBalance, WalletClient, type WalletCreationResult, type WalletStats, type Webhook, WebhooksResource };
package/dist/index.js CHANGED
@@ -34,6 +34,7 @@ __export(index_exports, {
34
34
  IngestionClient: () => IngestionClient,
35
35
  NetworkError: () => NetworkError,
36
36
  NotFoundError: () => NotFoundError,
37
+ NotificationsClient: () => NotificationsClient,
37
38
  PassportClient: () => PassportClient,
38
39
  ProofChain: () => ProofChain,
39
40
  ProofChainError: () => ProofChainError,
@@ -1466,42 +1467,133 @@ var RewardsClient = class {
1466
1467
  return this.http.get(`/rewards/earned?${params.toString()}`);
1467
1468
  }
1468
1469
  /**
1469
- * Get earned rewards for a user (with full badge/reward details)
1470
+ * Get earned rewards for a user (with full badge/reward details).
1471
+ * Use this to display a user's reward collection on a dedicated screen.
1472
+ *
1473
+ * @example
1474
+ * ```ts
1475
+ * // All user rewards
1476
+ * const all = await client.rewards.getUserRewards('user-123');
1477
+ *
1478
+ * // Only badges in the "Fan Pass" category
1479
+ * const badges = await client.rewards.getUserRewards('user-123', {
1480
+ * reward_type: 'badge',
1481
+ * category: 'Fan Pass',
1482
+ * });
1483
+ *
1484
+ * // Only distributed rewards
1485
+ * const distributed = await client.rewards.getUserRewards('user-123', {
1486
+ * status: 'distributed',
1487
+ * });
1488
+ * ```
1470
1489
  */
1471
1490
  async getUserRewards(userId, options = {}) {
1472
1491
  const params = new URLSearchParams();
1473
1492
  if (options.status) params.append("status", options.status);
1474
1493
  if (options.reward_type) params.append("reward_type", options.reward_type);
1494
+ if (options.category) params.append("category", options.category);
1475
1495
  const query = params.toString();
1476
1496
  return this.http.get(`/rewards/users/${userId}/rewards${query ? "?" + query : ""}`);
1477
1497
  }
1478
1498
  /**
1479
- * Get the public reward catalog (active, public reward definitions)
1499
+ * Get the public reward catalog (active, public reward definitions).
1480
1500
  * Available to both API key and end-user JWT clients.
1501
+ *
1502
+ * @param category - Optional category filter (e.g. "Fan Pass", "Partner: Acme")
1503
+ *
1504
+ * @example
1505
+ * ```ts
1506
+ * // All available rewards
1507
+ * const all = await client.rewards.getCatalog();
1508
+ *
1509
+ * // Only "Fan Pass" rewards
1510
+ * const fanPass = await client.rewards.getCatalog('Fan Pass');
1511
+ * ```
1481
1512
  */
1482
- async getCatalog() {
1483
- return this.http.get("/rewards/catalog");
1513
+ async getCatalog(category) {
1514
+ const params = new URLSearchParams();
1515
+ if (category) params.append("category", category);
1516
+ const query = params.toString();
1517
+ return this.http.get(`/rewards/catalog${query ? "?" + query : ""}`);
1484
1518
  }
1485
1519
  /**
1486
1520
  * Claim a lazy-minted NFT reward.
1487
1521
  * The wallet_address receives the minted NFT. The tenant's treasury pays gas.
1488
1522
  * Available to both API key and end-user JWT clients (scoped to own rewards).
1523
+ *
1524
+ * For non-NFT rewards, use {@link distribute} instead.
1489
1525
  */
1490
- async claimReward(earnedRewardId, walletAddress) {
1526
+ async claimNFT(earnedRewardId, walletAddress) {
1491
1527
  return this.http.post(`/rewards/earned/${earnedRewardId}/claim?wallet_address=${encodeURIComponent(walletAddress)}`, {});
1492
1528
  }
1493
1529
  /**
1494
- * Manually award rewards to users
1530
+ * @deprecated Use {@link claimNFT} instead — this method only works for lazy-mint NFTs.
1495
1531
  */
1496
- async awardManual(request) {
1532
+ async claimReward(earnedRewardId, walletAddress) {
1533
+ return this.claimNFT(earnedRewardId, walletAddress);
1534
+ }
1535
+ /**
1536
+ * Manually award rewards to one or more users.
1537
+ * Works for all reward types: points, tokens, NFTs, badges, custom.
1538
+ *
1539
+ * @example
1540
+ * ```ts
1541
+ * // Award a badge to two users
1542
+ * const rewards = await client.rewards.award({
1543
+ * definition_id: 'badge-def-id',
1544
+ * user_ids: ['user-1', 'user-2'],
1545
+ * distribute_immediately: true,
1546
+ * });
1547
+ * ```
1548
+ */
1549
+ async award(request) {
1497
1550
  return this.http.post("/rewards/award", request);
1498
1551
  }
1499
1552
  /**
1500
- * Distribute pending rewards (mint NFTs, transfer tokens)
1553
+ * @deprecated Use {@link award} instead.
1501
1554
  */
1502
- async distributePending(earnedRewardId) {
1555
+ async awardManual(request) {
1556
+ return this.award(request);
1557
+ }
1558
+ /**
1559
+ * Distribute a pending or failed reward.
1560
+ * Works for all reward types — triggers the appropriate distribution
1561
+ * (mint NFT, transfer tokens, issue badge, credit points, etc.).
1562
+ *
1563
+ * @example
1564
+ * ```ts
1565
+ * // Distribute a pending reward
1566
+ * const result = await client.rewards.distribute('earned-reward-id');
1567
+ * ```
1568
+ */
1569
+ async distribute(earnedRewardId) {
1503
1570
  return this.http.post(`/rewards/earned/${earnedRewardId}/distribute`, {});
1504
1571
  }
1572
+ /**
1573
+ * @deprecated Use {@link distribute} instead.
1574
+ */
1575
+ async distributePending(earnedRewardId) {
1576
+ return this.distribute(earnedRewardId);
1577
+ }
1578
+ /**
1579
+ * Distribute all pending rewards for the tenant.
1580
+ * Queues every pending reward for background distribution.
1581
+ */
1582
+ async distributeAll() {
1583
+ return this.http.post("/rewards/distribute-all-pending", {});
1584
+ }
1585
+ /**
1586
+ * Revoke an earned reward.
1587
+ *
1588
+ * @param earnedRewardId - The earned reward ID to revoke
1589
+ * @param reason - Reason for revocation
1590
+ */
1591
+ async revoke(earnedRewardId, reason) {
1592
+ return this.http.post(
1593
+ `/rewards/earned/${earnedRewardId}/revoke?reason=${encodeURIComponent(reason)}`,
1594
+ {}
1595
+ );
1596
+ }
1505
1597
  // ---------------------------------------------------------------------------
1506
1598
  // Reward Assets
1507
1599
  // ---------------------------------------------------------------------------
@@ -2058,6 +2150,101 @@ var FanpassLeaderboardClient = class {
2058
2150
  }
2059
2151
  };
2060
2152
 
2153
+ // src/notifications.ts
2154
+ var NotificationsClient = class {
2155
+ constructor(http) {
2156
+ this.baseUrl = http.baseUrl || "https://api.proofchain.co.za";
2157
+ this.authHeaders = () => {
2158
+ const headers = {};
2159
+ if (http.apiKey) {
2160
+ headers["X-API-Key"] = http.apiKey;
2161
+ }
2162
+ if (http.userToken) {
2163
+ headers["Authorization"] = `Bearer ${http.userToken}`;
2164
+ if (http.tenantId) {
2165
+ headers["X-Tenant-ID"] = http.tenantId;
2166
+ }
2167
+ }
2168
+ return headers;
2169
+ };
2170
+ }
2171
+ /**
2172
+ * Subscribe to real-time notifications for a user.
2173
+ *
2174
+ * Opens a Server-Sent Events connection and calls the callback
2175
+ * for each notification event (quest progress, rewards, etc.).
2176
+ *
2177
+ * Returns an unsubscribe function to close the connection.
2178
+ *
2179
+ * **Browser usage:** Works out of the box with EventSource.
2180
+ * **Node.js usage:** Requires the `eventsource` package.
2181
+ *
2182
+ * @param userId - The external user ID to subscribe for
2183
+ * @param callback - Function called for each notification event
2184
+ * @param options - Connection options (reconnect, callbacks)
2185
+ * @returns Unsubscribe function to close the connection
2186
+ */
2187
+ subscribe(userId, callback, options = {}) {
2188
+ const {
2189
+ onConnect,
2190
+ onDisconnect,
2191
+ onError,
2192
+ autoReconnect = true,
2193
+ reconnectDelay = 3e3
2194
+ } = options;
2195
+ let eventSource = null;
2196
+ let closed = false;
2197
+ let reconnectTimer = null;
2198
+ const connect = () => {
2199
+ if (closed) return;
2200
+ const headers = this.authHeaders();
2201
+ const params = new URLSearchParams({ user_id: userId });
2202
+ if (headers["X-API-Key"]) {
2203
+ params.append("api_key", headers["X-API-Key"]);
2204
+ }
2205
+ if (headers["Authorization"]) {
2206
+ params.append("token", headers["Authorization"].replace("Bearer ", ""));
2207
+ }
2208
+ if (headers["X-Tenant-ID"]) {
2209
+ params.append("tenant_id", headers["X-Tenant-ID"]);
2210
+ }
2211
+ const url = `${this.baseUrl}/notifications/stream?${params.toString()}`;
2212
+ const ES = typeof EventSource !== "undefined" ? EventSource : (() => {
2213
+ throw new Error('EventSource not available. Install the "eventsource" package for Node.js.');
2214
+ })();
2215
+ eventSource = new ES(url);
2216
+ eventSource.onmessage = (e) => {
2217
+ try {
2218
+ const event = JSON.parse(e.data);
2219
+ if (event.event === "connected") {
2220
+ onConnect?.();
2221
+ } else {
2222
+ callback(event);
2223
+ }
2224
+ } catch (err) {
2225
+ onError?.(new Error(`Failed to parse notification: ${e.data}`));
2226
+ }
2227
+ };
2228
+ eventSource.onerror = () => {
2229
+ if (closed) return;
2230
+ onDisconnect?.();
2231
+ if (eventSource?.readyState === 2 && autoReconnect) {
2232
+ reconnectTimer = setTimeout(connect, reconnectDelay);
2233
+ }
2234
+ };
2235
+ };
2236
+ connect();
2237
+ return () => {
2238
+ closed = true;
2239
+ if (reconnectTimer) clearTimeout(reconnectTimer);
2240
+ if (eventSource) {
2241
+ eventSource.close();
2242
+ eventSource = null;
2243
+ }
2244
+ };
2245
+ }
2246
+ };
2247
+
2061
2248
  // src/client.ts
2062
2249
  var DocumentsResource = class {
2063
2250
  constructor(http) {
@@ -2355,6 +2542,7 @@ var ProofChain = class _ProofChain {
2355
2542
  this.dataViews = new DataViewsClient(this.http);
2356
2543
  this.cohorts = new CohortLeaderboardClient(this.http);
2357
2544
  this.fanpassLeaderboard = new FanpassLeaderboardClient(this.http);
2545
+ this.notifications = new NotificationsClient(this.http);
2358
2546
  }
2359
2547
  /**
2360
2548
  * Create a client for end-user JWT authentication (PWA/frontend use).
@@ -2698,6 +2886,7 @@ var EndUserIngestionClient = class {
2698
2886
  IngestionClient,
2699
2887
  NetworkError,
2700
2888
  NotFoundError,
2889
+ NotificationsClient,
2701
2890
  PassportClient,
2702
2891
  ProofChain,
2703
2892
  ProofChainError,
package/dist/index.mjs CHANGED
@@ -1411,42 +1411,133 @@ var RewardsClient = class {
1411
1411
  return this.http.get(`/rewards/earned?${params.toString()}`);
1412
1412
  }
1413
1413
  /**
1414
- * Get earned rewards for a user (with full badge/reward details)
1414
+ * Get earned rewards for a user (with full badge/reward details).
1415
+ * Use this to display a user's reward collection on a dedicated screen.
1416
+ *
1417
+ * @example
1418
+ * ```ts
1419
+ * // All user rewards
1420
+ * const all = await client.rewards.getUserRewards('user-123');
1421
+ *
1422
+ * // Only badges in the "Fan Pass" category
1423
+ * const badges = await client.rewards.getUserRewards('user-123', {
1424
+ * reward_type: 'badge',
1425
+ * category: 'Fan Pass',
1426
+ * });
1427
+ *
1428
+ * // Only distributed rewards
1429
+ * const distributed = await client.rewards.getUserRewards('user-123', {
1430
+ * status: 'distributed',
1431
+ * });
1432
+ * ```
1415
1433
  */
1416
1434
  async getUserRewards(userId, options = {}) {
1417
1435
  const params = new URLSearchParams();
1418
1436
  if (options.status) params.append("status", options.status);
1419
1437
  if (options.reward_type) params.append("reward_type", options.reward_type);
1438
+ if (options.category) params.append("category", options.category);
1420
1439
  const query = params.toString();
1421
1440
  return this.http.get(`/rewards/users/${userId}/rewards${query ? "?" + query : ""}`);
1422
1441
  }
1423
1442
  /**
1424
- * Get the public reward catalog (active, public reward definitions)
1443
+ * Get the public reward catalog (active, public reward definitions).
1425
1444
  * Available to both API key and end-user JWT clients.
1445
+ *
1446
+ * @param category - Optional category filter (e.g. "Fan Pass", "Partner: Acme")
1447
+ *
1448
+ * @example
1449
+ * ```ts
1450
+ * // All available rewards
1451
+ * const all = await client.rewards.getCatalog();
1452
+ *
1453
+ * // Only "Fan Pass" rewards
1454
+ * const fanPass = await client.rewards.getCatalog('Fan Pass');
1455
+ * ```
1426
1456
  */
1427
- async getCatalog() {
1428
- return this.http.get("/rewards/catalog");
1457
+ async getCatalog(category) {
1458
+ const params = new URLSearchParams();
1459
+ if (category) params.append("category", category);
1460
+ const query = params.toString();
1461
+ return this.http.get(`/rewards/catalog${query ? "?" + query : ""}`);
1429
1462
  }
1430
1463
  /**
1431
1464
  * Claim a lazy-minted NFT reward.
1432
1465
  * The wallet_address receives the minted NFT. The tenant's treasury pays gas.
1433
1466
  * Available to both API key and end-user JWT clients (scoped to own rewards).
1467
+ *
1468
+ * For non-NFT rewards, use {@link distribute} instead.
1434
1469
  */
1435
- async claimReward(earnedRewardId, walletAddress) {
1470
+ async claimNFT(earnedRewardId, walletAddress) {
1436
1471
  return this.http.post(`/rewards/earned/${earnedRewardId}/claim?wallet_address=${encodeURIComponent(walletAddress)}`, {});
1437
1472
  }
1438
1473
  /**
1439
- * Manually award rewards to users
1474
+ * @deprecated Use {@link claimNFT} instead — this method only works for lazy-mint NFTs.
1440
1475
  */
1441
- async awardManual(request) {
1476
+ async claimReward(earnedRewardId, walletAddress) {
1477
+ return this.claimNFT(earnedRewardId, walletAddress);
1478
+ }
1479
+ /**
1480
+ * Manually award rewards to one or more users.
1481
+ * Works for all reward types: points, tokens, NFTs, badges, custom.
1482
+ *
1483
+ * @example
1484
+ * ```ts
1485
+ * // Award a badge to two users
1486
+ * const rewards = await client.rewards.award({
1487
+ * definition_id: 'badge-def-id',
1488
+ * user_ids: ['user-1', 'user-2'],
1489
+ * distribute_immediately: true,
1490
+ * });
1491
+ * ```
1492
+ */
1493
+ async award(request) {
1442
1494
  return this.http.post("/rewards/award", request);
1443
1495
  }
1444
1496
  /**
1445
- * Distribute pending rewards (mint NFTs, transfer tokens)
1497
+ * @deprecated Use {@link award} instead.
1446
1498
  */
1447
- async distributePending(earnedRewardId) {
1499
+ async awardManual(request) {
1500
+ return this.award(request);
1501
+ }
1502
+ /**
1503
+ * Distribute a pending or failed reward.
1504
+ * Works for all reward types — triggers the appropriate distribution
1505
+ * (mint NFT, transfer tokens, issue badge, credit points, etc.).
1506
+ *
1507
+ * @example
1508
+ * ```ts
1509
+ * // Distribute a pending reward
1510
+ * const result = await client.rewards.distribute('earned-reward-id');
1511
+ * ```
1512
+ */
1513
+ async distribute(earnedRewardId) {
1448
1514
  return this.http.post(`/rewards/earned/${earnedRewardId}/distribute`, {});
1449
1515
  }
1516
+ /**
1517
+ * @deprecated Use {@link distribute} instead.
1518
+ */
1519
+ async distributePending(earnedRewardId) {
1520
+ return this.distribute(earnedRewardId);
1521
+ }
1522
+ /**
1523
+ * Distribute all pending rewards for the tenant.
1524
+ * Queues every pending reward for background distribution.
1525
+ */
1526
+ async distributeAll() {
1527
+ return this.http.post("/rewards/distribute-all-pending", {});
1528
+ }
1529
+ /**
1530
+ * Revoke an earned reward.
1531
+ *
1532
+ * @param earnedRewardId - The earned reward ID to revoke
1533
+ * @param reason - Reason for revocation
1534
+ */
1535
+ async revoke(earnedRewardId, reason) {
1536
+ return this.http.post(
1537
+ `/rewards/earned/${earnedRewardId}/revoke?reason=${encodeURIComponent(reason)}`,
1538
+ {}
1539
+ );
1540
+ }
1450
1541
  // ---------------------------------------------------------------------------
1451
1542
  // Reward Assets
1452
1543
  // ---------------------------------------------------------------------------
@@ -2003,6 +2094,101 @@ var FanpassLeaderboardClient = class {
2003
2094
  }
2004
2095
  };
2005
2096
 
2097
+ // src/notifications.ts
2098
+ var NotificationsClient = class {
2099
+ constructor(http) {
2100
+ this.baseUrl = http.baseUrl || "https://api.proofchain.co.za";
2101
+ this.authHeaders = () => {
2102
+ const headers = {};
2103
+ if (http.apiKey) {
2104
+ headers["X-API-Key"] = http.apiKey;
2105
+ }
2106
+ if (http.userToken) {
2107
+ headers["Authorization"] = `Bearer ${http.userToken}`;
2108
+ if (http.tenantId) {
2109
+ headers["X-Tenant-ID"] = http.tenantId;
2110
+ }
2111
+ }
2112
+ return headers;
2113
+ };
2114
+ }
2115
+ /**
2116
+ * Subscribe to real-time notifications for a user.
2117
+ *
2118
+ * Opens a Server-Sent Events connection and calls the callback
2119
+ * for each notification event (quest progress, rewards, etc.).
2120
+ *
2121
+ * Returns an unsubscribe function to close the connection.
2122
+ *
2123
+ * **Browser usage:** Works out of the box with EventSource.
2124
+ * **Node.js usage:** Requires the `eventsource` package.
2125
+ *
2126
+ * @param userId - The external user ID to subscribe for
2127
+ * @param callback - Function called for each notification event
2128
+ * @param options - Connection options (reconnect, callbacks)
2129
+ * @returns Unsubscribe function to close the connection
2130
+ */
2131
+ subscribe(userId, callback, options = {}) {
2132
+ const {
2133
+ onConnect,
2134
+ onDisconnect,
2135
+ onError,
2136
+ autoReconnect = true,
2137
+ reconnectDelay = 3e3
2138
+ } = options;
2139
+ let eventSource = null;
2140
+ let closed = false;
2141
+ let reconnectTimer = null;
2142
+ const connect = () => {
2143
+ if (closed) return;
2144
+ const headers = this.authHeaders();
2145
+ const params = new URLSearchParams({ user_id: userId });
2146
+ if (headers["X-API-Key"]) {
2147
+ params.append("api_key", headers["X-API-Key"]);
2148
+ }
2149
+ if (headers["Authorization"]) {
2150
+ params.append("token", headers["Authorization"].replace("Bearer ", ""));
2151
+ }
2152
+ if (headers["X-Tenant-ID"]) {
2153
+ params.append("tenant_id", headers["X-Tenant-ID"]);
2154
+ }
2155
+ const url = `${this.baseUrl}/notifications/stream?${params.toString()}`;
2156
+ const ES = typeof EventSource !== "undefined" ? EventSource : (() => {
2157
+ throw new Error('EventSource not available. Install the "eventsource" package for Node.js.');
2158
+ })();
2159
+ eventSource = new ES(url);
2160
+ eventSource.onmessage = (e) => {
2161
+ try {
2162
+ const event = JSON.parse(e.data);
2163
+ if (event.event === "connected") {
2164
+ onConnect?.();
2165
+ } else {
2166
+ callback(event);
2167
+ }
2168
+ } catch (err) {
2169
+ onError?.(new Error(`Failed to parse notification: ${e.data}`));
2170
+ }
2171
+ };
2172
+ eventSource.onerror = () => {
2173
+ if (closed) return;
2174
+ onDisconnect?.();
2175
+ if (eventSource?.readyState === 2 && autoReconnect) {
2176
+ reconnectTimer = setTimeout(connect, reconnectDelay);
2177
+ }
2178
+ };
2179
+ };
2180
+ connect();
2181
+ return () => {
2182
+ closed = true;
2183
+ if (reconnectTimer) clearTimeout(reconnectTimer);
2184
+ if (eventSource) {
2185
+ eventSource.close();
2186
+ eventSource = null;
2187
+ }
2188
+ };
2189
+ }
2190
+ };
2191
+
2006
2192
  // src/client.ts
2007
2193
  var DocumentsResource = class {
2008
2194
  constructor(http) {
@@ -2300,6 +2486,7 @@ var ProofChain = class _ProofChain {
2300
2486
  this.dataViews = new DataViewsClient(this.http);
2301
2487
  this.cohorts = new CohortLeaderboardClient(this.http);
2302
2488
  this.fanpassLeaderboard = new FanpassLeaderboardClient(this.http);
2489
+ this.notifications = new NotificationsClient(this.http);
2303
2490
  }
2304
2491
  /**
2305
2492
  * Create a client for end-user JWT authentication (PWA/frontend use).
@@ -2642,6 +2829,7 @@ export {
2642
2829
  IngestionClient,
2643
2830
  NetworkError,
2644
2831
  NotFoundError,
2832
+ NotificationsClient,
2645
2833
  PassportClient,
2646
2834
  ProofChain,
2647
2835
  ProofChainError,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@proofchain/sdk",
3
- "version": "2.15.0",
3
+ "version": "2.17.0",
4
4
  "description": "Official JavaScript/TypeScript SDK for ProofChain - blockchain-anchored document attestation",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",