@streamoid/settings 0.24.0 → 0.25.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
@@ -2847,16 +2847,32 @@ declare function capMoney(credits: number, view: Pick<AutoTopUpView, "pricePerCr
2847
2847
  declare function autoTopUpBlockedReason(view: Pick<AutoTopUpView, "paidPlan" | "paymentMethod" | "pricePerCredit" | "currency">): string | null;
2848
2848
  /** Why billing turned it off: "Card declined on 30 Nov — auto top-up turned off." */
2849
2849
  declare function autoTopUpDisabledMessage(reason: string | null, at: string | null): string | null;
2850
- /** "Bought 1,000 of 5,000 credits this billing cycle (resets 30 Dec)." */
2850
+ /**
2851
+ * "Bought 1,000 of 5,000 credits this billing cycle (resets 30 Dec)." Once
2852
+ * the cap is used up (or lowered below what was bought), it says so rather
2853
+ * than read "2,000 of 1,000".
2854
+ */
2851
2855
  declare function autoTopUpCycleText(view: Pick<AutoTopUpView, "spentThisCycleCredits" | "cycleCapCredits" | "cycle">): string;
2856
+ /**
2857
+ * Why auto top-up is paused, when its latest attempt this cycle was skipped
2858
+ * for the cap and the cap still has no room for a pack: "Cap reached on
2859
+ * 1 Dec — auto top-up is paused until 1 Jan. Raise the cap per billing cycle
2860
+ * to keep topping up." `null` once the cap is raised enough, a later top-up
2861
+ * is attempted, or a new cycle starts. Billing sends no email for this and
2862
+ * leaves the setting on.
2863
+ */
2864
+ declare function autoTopUpCapNotice(view: Pick<AutoTopUpView, "enabled" | "lastAttempt" | "cycle" | "spentThisCycleCredits" | "packCredits" | "cycleCapCredits">, now?: Date): string | null;
2852
2865
 
2853
2866
  /**
2854
2867
  * Auto top-up: when credits fall below a threshold, billing buys the chosen
2855
2868
  * pack on the saved card, up to a cap per billing cycle. Admins only: render
2856
2869
  * it only for workspace or org admins. Renders nothing when the host has no
2857
- * `api.fetchAutoTopUp`.
2870
+ * `api.fetchAutoTopUp`. `onTopUpSettled` runs when a top-up the card watched
2871
+ * finishes, so the host can reload the balance.
2858
2872
  */
2859
- declare function AutoTopUpCard(): react.JSX.Element | null;
2873
+ declare function AutoTopUpCard({ onTopUpSettled }?: {
2874
+ onTopUpSettled?: () => void;
2875
+ }): react.JSX.Element | null;
2860
2876
 
2861
2877
  /**
2862
2878
  * Shared credit pool rules and copy, kept out of the components so a host can
@@ -3288,4 +3304,4 @@ interface AppSettingsRowProps {
3288
3304
  }
3289
3305
  declare function AppSettingsRow({ title, description, summary, href, onClick, disabled, disabledReason, ariaLabel, trailing }: AppSettingsRowProps): react.JSX.Element;
3290
3306
 
3291
- export { APP_KEYS, AUTO_TOPUP_DEFAULTS, type AddCreditPoolMemberInput, AdministrationOverview, type AdministrationOverviewProps, type AdministrativeNavigationOptions, type ApiToken, type AppKey, AppSettingsHeader, type AppSettingsHeaderProps, AppSettingsPage, type AppSettingsPageProps, AppSettingsRow, type AppSettingsRowProps, AppSettingsSection, type AppSettingsSectionProps, AutoTopUpCard, type AutoTopUpSettings, type AutoTopUpValidation, type AutoTopUpView, type AvailableCreditsResponse, BILLING_TABLE_FRAME_STYLE, BILLING_TABLE_MIN_HEIGHT, BILLING_TABLE_PAGER_STYLE, BillingContent, type BillingEntitlement, type BillingEventPayload, type BillingProduct, type BillingSubscription, BuyCreditsModal, type BuyCreditsPayload, type BuyCreditsResponse, ConfirmDeleteModal, ConfirmLeaveModal, type ConnectedApp, ConnectedAppsContent, type CreatedToken, type CreditCycleUnit, type CreditLimitUnit, type CreditLimitValidation, type CreditPoolCandidate, type CreditPoolFormerMember, type CreditPoolMember, CreditPoolMemberModal, type CreditPoolMemberModalProps, type CreditPoolMemberStatus, type CreditPoolMode, type CreditPoolResponse, type CreditPoolSelfShare, type CreditsMeter, type CurrentPlanState, type CustomCreditInfo, type CustomCreditResponse, DEFAULT_PERMISSIONS, DEFAULT_USER_LANGUAGE, EMPTY_USAGE_LOGS_PAGE, ExportDateModal, type FetchUsageLogs, type FetchUsageLogsInRangeOptions, INITIAL_USAGE_LOGS_STATE, INVOICE_DOWNLOAD_FAILED_MESSAGE, INVOICE_NOT_AVAILABLE_MESSAGE, InviteUpdateModal, type InvoiceDownloadKind, type InvoicePdfResponse, type LoginMethodsMember, type LoginMethodsSettings, type LoginMethodsSwitchState, MOCK_REFERRED_USERS, type MemberCreditLimit, MemberCreditLimitModal, type MemberCreditLimitRow, type MemberCreditLimitSource, type MemberCreditLimitsResponse, MemberListFrame, type MemberListFrameProps, type MemberListTab, MemberListToolbar, type MemberListToolbarProps, type MemberPermissionsPayload, OrganizationContent, type OrganizationData, type OrganizationDetails, OrganizationIntegrationsContent, type OrganizationInvite, type OrganizationJoinRequest, type OrganizationJoinableWorkspace, OrganizationLoginMethodsContent, type OrganizationMember, OrganizationMemberModal, type OrganizationMemberModalProps, type OrganizationMemberRole, OrganizationModal, OrganizationPicker, type OrganizationPickerItem, type OrganizationPickerProps, type OrganizationPickerType, type OrganizationView, type OrganizationWorkspaceItem, POOL_ERROR_CODES, POOL_EXPIRY_MAX_MONTHS, POOL_NOTE_MAX_LENGTH, PerUserLimitsView, type PoolEndsAtResult, type PoolErrorCode, type PoolExpiryChoice, type PoolValueValidation, type Price, type PriceMetadata, type ProductsResponse, ProfileAvatar, ProfileTab, REMOVE_REASON_MAX_LENGTH, ReferralHistoryView, type ReferralHistoryViewProps, ReferralTab, type ReferredUser, RemovePoolMemberModal, type RemovePoolMemberModalProps, RemoveSelfShareModal, type RemoveSelfShareModalProps, SCOPE_LABELS, ScopeHeader, type ScopeHeaderProps, type ServiceItem, type SetCreditPoolSelfShareInput, type SettingsAdapters, SettingsAdaptersProvider, type SettingsApiAdapter, type SettingsAuthAdapter, type SettingsAuthUser, SettingsContent, type SettingsContentProps, type SettingsImageUploadAdapter, type SettingsIntegrationsAdapter, type SettingsLoginMethodsAdapter, type SettingsNavigationAdapter, type SettingsOrganizationAdapter, type SettingsOrganizationCreateOptions, type SettingsOrganizationCurrent, type SettingsOrganizationJoinableItem, type SettingsOrganizationListItem, type SettingsOrganizationType, type SettingsOrganizationWorkspaceJoin, type SettingsScope, type SettingsTab, type SettingsToastAdapter, SettingsTooltip, type SettingsTooltipPlacement, type SettingsTooltipProps, type SettingsWorkspaceAdapter, type SettingsWorkspaceCurrent, type SettingsWorkspaceListItem, SharedCreditsView, type SharedPoolBalance, SiconKey, type SponsorShareBalance, type StoreItem, type SubscriptionPlan, type SubscriptionResponse, TAB_DESCRIPTIONS, TAB_LABELS, TAB_SCOPE, TAB_TO_URL, type TeamMember, TeamsContent, type TokenExpiry, TokensContent, URL_TO_TAB, USAGE_LOGS_EXPORT_BATCH_SIZE, USAGE_LOGS_EXPORT_EXTRA_REQUESTS, USAGE_LOGS_EXPORT_MAX_ROWS, USAGE_LOGS_PAGE_SIZE, USER_LANGUAGES, type UpdateCreditPoolMemberInput, type UpdateSubscriptionPayload, type UpdateSubscriptionResponse, type UsageHistoryItem, type UsageHistoryPagination, type UsageHistoryResponse, type UsageLogsAction, type UsageLogsExportResult, type UsageLogsPage, UsageLogsPager, type UsageLogsQuery, type UsageLogsState, UsageLogsTable, type UsedByNamesLoader, type UserLanguage, type UserPermissions, WORKSPACE_CREDIT_LIMIT_REACHED, WORKSPACE_CREDIT_LIMIT_REACHED_MESSAGE, WORKSPACE_LIST_PAGE_SIZE, type WorkspaceCreditLimit, WorkspaceCreditLimitCard, type WorkspaceCreditLimitSummary, type WorkspaceData, WorkspaceGeneralTab, type WorkspaceGeneralTabProps, type WorkspaceInvite, type WorkspaceListOrganization, WorkspaceListTab, type WorkspaceMember, WorkspaceModal, type WorkspaceOrganization, type WorkspaceOrganizationRequest, WorkspacePicker, type WorkspacePickerGroup, type WorkspacePickerItem, type WorkspacePickerProps, WorkspaceTab, type WorkspaceUsageResponse, aboveTotalReason, autoTopUpBlockedReason, autoTopUpCycleText, autoTopUpDisabledMessage, belowUsageReason, canManageOnlyWorkspaceCreditLimit, canShowSharedCredits, capMoney, checkPoolPercentTotal, cleanAutoTopUpInput, cleanCreditLimitInput, cleanPoolValueInput, countLabel, createUsedByNamesLoader, creditCycleUnit, creditsMeter, deriveWorkspaceInvitePermission, describeAllowance, describeDefaultLimit, describeMemberLimit, describeWorkspaceCreditLimit, entitlementFromBody, entitlementFromFailure, expiryChoiceFor, fetchUsageLogsInRange, findBillingError, findPoolError, formatAutoTopUpMoney, formatCreditLimit, formatCredits, formatPackOption, formatPoolEndsAt, formatPoolSplit, groupWorkspaceList, hasPaidFeatures, inviteUpdate, invoiceDownloadKind, isLimitAboveTotal, isLimitBelowUsage, isPaidPlan, isSponsoredEntitlement, isWorkspaceCreditLimitReached, joinMembersWithLimits, lastUsedLabel, limitAboveTotalTotal, limitBelowUsageUsed, limitSourceLabel, loadCurrentPlan, loadWorkspaceOrganization, loginMethodsSwitchState, maximumCreditLimit, memberRoleUpdate, minPoolEndDate, minimumCreditLimit, ownCreditsFirstText, parseBillingEntitlement, parseInviteEmails, pausedOwnCreditsText, poolAllocatedPercent, poolAllocationText, poolEndsAtFrom, poolErrorMessage, poolRenewsAtCycleEnd, poolSharesCredits, poolUnallocatedPercent, poolWorkspaceName, productsForCountry, readSettingsCaller, referralCodeOf, referralCountLabel, referralLink, referralSignupDate, rememberSettingsCaller, resolveSettingsTabFromPath, roundCredits, settingsReturnTarget, sharedPoolBannerText, sharedPoolEndsText, sliceUsageLogsPage, sortReferredUsers, sponsorShareBannerText, sponsorShareDetailText, sponsorShareSpentText, sponsoredCreditsText, ssoLabel, toCsv, toLocalDateInput, usageLogsCsvRows, usageLogsDateRange, usageLogsExportFileName, usageLogsPage, usageLogsReducer, usageLogsReloadPage, usageLogsShowWorkspace, usageLogsSpentByOthers, useBillingEntitlement, useSettingsAdapters, useWorkspaceInvitePermission, useWorkspaceOrganization, usedByNamesFrom, usedByWorkspaceKey, userLanguageLabel, validateAutoTopUpInput, validateCreditLimitInput, validateDefaultCreditLimitInput, validatePoolText, validatePoolValue };
3307
+ export { APP_KEYS, AUTO_TOPUP_DEFAULTS, type AddCreditPoolMemberInput, AdministrationOverview, type AdministrationOverviewProps, type AdministrativeNavigationOptions, type ApiToken, type AppKey, AppSettingsHeader, type AppSettingsHeaderProps, AppSettingsPage, type AppSettingsPageProps, AppSettingsRow, type AppSettingsRowProps, AppSettingsSection, type AppSettingsSectionProps, AutoTopUpCard, type AutoTopUpSettings, type AutoTopUpValidation, type AutoTopUpView, type AvailableCreditsResponse, BILLING_TABLE_FRAME_STYLE, BILLING_TABLE_MIN_HEIGHT, BILLING_TABLE_PAGER_STYLE, BillingContent, type BillingEntitlement, type BillingEventPayload, type BillingProduct, type BillingSubscription, BuyCreditsModal, type BuyCreditsPayload, type BuyCreditsResponse, ConfirmDeleteModal, ConfirmLeaveModal, type ConnectedApp, ConnectedAppsContent, type CreatedToken, type CreditCycleUnit, type CreditLimitUnit, type CreditLimitValidation, type CreditPoolCandidate, type CreditPoolFormerMember, type CreditPoolMember, CreditPoolMemberModal, type CreditPoolMemberModalProps, type CreditPoolMemberStatus, type CreditPoolMode, type CreditPoolResponse, type CreditPoolSelfShare, type CreditsMeter, type CurrentPlanState, type CustomCreditInfo, type CustomCreditResponse, DEFAULT_PERMISSIONS, DEFAULT_USER_LANGUAGE, EMPTY_USAGE_LOGS_PAGE, ExportDateModal, type FetchUsageLogs, type FetchUsageLogsInRangeOptions, INITIAL_USAGE_LOGS_STATE, INVOICE_DOWNLOAD_FAILED_MESSAGE, INVOICE_NOT_AVAILABLE_MESSAGE, InviteUpdateModal, type InvoiceDownloadKind, type InvoicePdfResponse, type LoginMethodsMember, type LoginMethodsSettings, type LoginMethodsSwitchState, MOCK_REFERRED_USERS, type MemberCreditLimit, MemberCreditLimitModal, type MemberCreditLimitRow, type MemberCreditLimitSource, type MemberCreditLimitsResponse, MemberListFrame, type MemberListFrameProps, type MemberListTab, MemberListToolbar, type MemberListToolbarProps, type MemberPermissionsPayload, OrganizationContent, type OrganizationData, type OrganizationDetails, OrganizationIntegrationsContent, type OrganizationInvite, type OrganizationJoinRequest, type OrganizationJoinableWorkspace, OrganizationLoginMethodsContent, type OrganizationMember, OrganizationMemberModal, type OrganizationMemberModalProps, type OrganizationMemberRole, OrganizationModal, OrganizationPicker, type OrganizationPickerItem, type OrganizationPickerProps, type OrganizationPickerType, type OrganizationView, type OrganizationWorkspaceItem, POOL_ERROR_CODES, POOL_EXPIRY_MAX_MONTHS, POOL_NOTE_MAX_LENGTH, PerUserLimitsView, type PoolEndsAtResult, type PoolErrorCode, type PoolExpiryChoice, type PoolValueValidation, type Price, type PriceMetadata, type ProductsResponse, ProfileAvatar, ProfileTab, REMOVE_REASON_MAX_LENGTH, ReferralHistoryView, type ReferralHistoryViewProps, ReferralTab, type ReferredUser, RemovePoolMemberModal, type RemovePoolMemberModalProps, RemoveSelfShareModal, type RemoveSelfShareModalProps, SCOPE_LABELS, ScopeHeader, type ScopeHeaderProps, type ServiceItem, type SetCreditPoolSelfShareInput, type SettingsAdapters, SettingsAdaptersProvider, type SettingsApiAdapter, type SettingsAuthAdapter, type SettingsAuthUser, SettingsContent, type SettingsContentProps, type SettingsImageUploadAdapter, type SettingsIntegrationsAdapter, type SettingsLoginMethodsAdapter, type SettingsNavigationAdapter, type SettingsOrganizationAdapter, type SettingsOrganizationCreateOptions, type SettingsOrganizationCurrent, type SettingsOrganizationJoinableItem, type SettingsOrganizationListItem, type SettingsOrganizationType, type SettingsOrganizationWorkspaceJoin, type SettingsScope, type SettingsTab, type SettingsToastAdapter, SettingsTooltip, type SettingsTooltipPlacement, type SettingsTooltipProps, type SettingsWorkspaceAdapter, type SettingsWorkspaceCurrent, type SettingsWorkspaceListItem, SharedCreditsView, type SharedPoolBalance, SiconKey, type SponsorShareBalance, type StoreItem, type SubscriptionPlan, type SubscriptionResponse, TAB_DESCRIPTIONS, TAB_LABELS, TAB_SCOPE, TAB_TO_URL, type TeamMember, TeamsContent, type TokenExpiry, TokensContent, URL_TO_TAB, USAGE_LOGS_EXPORT_BATCH_SIZE, USAGE_LOGS_EXPORT_EXTRA_REQUESTS, USAGE_LOGS_EXPORT_MAX_ROWS, USAGE_LOGS_PAGE_SIZE, USER_LANGUAGES, type UpdateCreditPoolMemberInput, type UpdateSubscriptionPayload, type UpdateSubscriptionResponse, type UsageHistoryItem, type UsageHistoryPagination, type UsageHistoryResponse, type UsageLogsAction, type UsageLogsExportResult, type UsageLogsPage, UsageLogsPager, type UsageLogsQuery, type UsageLogsState, UsageLogsTable, type UsedByNamesLoader, type UserLanguage, type UserPermissions, WORKSPACE_CREDIT_LIMIT_REACHED, WORKSPACE_CREDIT_LIMIT_REACHED_MESSAGE, WORKSPACE_LIST_PAGE_SIZE, type WorkspaceCreditLimit, WorkspaceCreditLimitCard, type WorkspaceCreditLimitSummary, type WorkspaceData, WorkspaceGeneralTab, type WorkspaceGeneralTabProps, type WorkspaceInvite, type WorkspaceListOrganization, WorkspaceListTab, type WorkspaceMember, WorkspaceModal, type WorkspaceOrganization, type WorkspaceOrganizationRequest, WorkspacePicker, type WorkspacePickerGroup, type WorkspacePickerItem, type WorkspacePickerProps, WorkspaceTab, type WorkspaceUsageResponse, aboveTotalReason, autoTopUpBlockedReason, autoTopUpCapNotice, autoTopUpCycleText, autoTopUpDisabledMessage, belowUsageReason, canManageOnlyWorkspaceCreditLimit, canShowSharedCredits, capMoney, checkPoolPercentTotal, cleanAutoTopUpInput, cleanCreditLimitInput, cleanPoolValueInput, countLabel, createUsedByNamesLoader, creditCycleUnit, creditsMeter, deriveWorkspaceInvitePermission, describeAllowance, describeDefaultLimit, describeMemberLimit, describeWorkspaceCreditLimit, entitlementFromBody, entitlementFromFailure, expiryChoiceFor, fetchUsageLogsInRange, findBillingError, findPoolError, formatAutoTopUpMoney, formatCreditLimit, formatCredits, formatPackOption, formatPoolEndsAt, formatPoolSplit, groupWorkspaceList, hasPaidFeatures, inviteUpdate, invoiceDownloadKind, isLimitAboveTotal, isLimitBelowUsage, isPaidPlan, isSponsoredEntitlement, isWorkspaceCreditLimitReached, joinMembersWithLimits, lastUsedLabel, limitAboveTotalTotal, limitBelowUsageUsed, limitSourceLabel, loadCurrentPlan, loadWorkspaceOrganization, loginMethodsSwitchState, maximumCreditLimit, memberRoleUpdate, minPoolEndDate, minimumCreditLimit, ownCreditsFirstText, parseBillingEntitlement, parseInviteEmails, pausedOwnCreditsText, poolAllocatedPercent, poolAllocationText, poolEndsAtFrom, poolErrorMessage, poolRenewsAtCycleEnd, poolSharesCredits, poolUnallocatedPercent, poolWorkspaceName, productsForCountry, readSettingsCaller, referralCodeOf, referralCountLabel, referralLink, referralSignupDate, rememberSettingsCaller, resolveSettingsTabFromPath, roundCredits, settingsReturnTarget, sharedPoolBannerText, sharedPoolEndsText, sliceUsageLogsPage, sortReferredUsers, sponsorShareBannerText, sponsorShareDetailText, sponsorShareSpentText, sponsoredCreditsText, ssoLabel, toCsv, toLocalDateInput, usageLogsCsvRows, usageLogsDateRange, usageLogsExportFileName, usageLogsPage, usageLogsReducer, usageLogsReloadPage, usageLogsShowWorkspace, usageLogsSpentByOthers, useBillingEntitlement, useSettingsAdapters, useWorkspaceInvitePermission, useWorkspaceOrganization, usedByNamesFrom, usedByWorkspaceKey, userLanguageLabel, validateAutoTopUpInput, validateCreditLimitInput, validateDefaultCreditLimitInput, validatePoolText, validatePoolValue };
package/dist/index.d.ts CHANGED
@@ -2847,16 +2847,32 @@ declare function capMoney(credits: number, view: Pick<AutoTopUpView, "pricePerCr
2847
2847
  declare function autoTopUpBlockedReason(view: Pick<AutoTopUpView, "paidPlan" | "paymentMethod" | "pricePerCredit" | "currency">): string | null;
2848
2848
  /** Why billing turned it off: "Card declined on 30 Nov — auto top-up turned off." */
2849
2849
  declare function autoTopUpDisabledMessage(reason: string | null, at: string | null): string | null;
2850
- /** "Bought 1,000 of 5,000 credits this billing cycle (resets 30 Dec)." */
2850
+ /**
2851
+ * "Bought 1,000 of 5,000 credits this billing cycle (resets 30 Dec)." Once
2852
+ * the cap is used up (or lowered below what was bought), it says so rather
2853
+ * than read "2,000 of 1,000".
2854
+ */
2851
2855
  declare function autoTopUpCycleText(view: Pick<AutoTopUpView, "spentThisCycleCredits" | "cycleCapCredits" | "cycle">): string;
2856
+ /**
2857
+ * Why auto top-up is paused, when its latest attempt this cycle was skipped
2858
+ * for the cap and the cap still has no room for a pack: "Cap reached on
2859
+ * 1 Dec — auto top-up is paused until 1 Jan. Raise the cap per billing cycle
2860
+ * to keep topping up." `null` once the cap is raised enough, a later top-up
2861
+ * is attempted, or a new cycle starts. Billing sends no email for this and
2862
+ * leaves the setting on.
2863
+ */
2864
+ declare function autoTopUpCapNotice(view: Pick<AutoTopUpView, "enabled" | "lastAttempt" | "cycle" | "spentThisCycleCredits" | "packCredits" | "cycleCapCredits">, now?: Date): string | null;
2852
2865
 
2853
2866
  /**
2854
2867
  * Auto top-up: when credits fall below a threshold, billing buys the chosen
2855
2868
  * pack on the saved card, up to a cap per billing cycle. Admins only: render
2856
2869
  * it only for workspace or org admins. Renders nothing when the host has no
2857
- * `api.fetchAutoTopUp`.
2870
+ * `api.fetchAutoTopUp`. `onTopUpSettled` runs when a top-up the card watched
2871
+ * finishes, so the host can reload the balance.
2858
2872
  */
2859
- declare function AutoTopUpCard(): react.JSX.Element | null;
2873
+ declare function AutoTopUpCard({ onTopUpSettled }?: {
2874
+ onTopUpSettled?: () => void;
2875
+ }): react.JSX.Element | null;
2860
2876
 
2861
2877
  /**
2862
2878
  * Shared credit pool rules and copy, kept out of the components so a host can
@@ -3288,4 +3304,4 @@ interface AppSettingsRowProps {
3288
3304
  }
3289
3305
  declare function AppSettingsRow({ title, description, summary, href, onClick, disabled, disabledReason, ariaLabel, trailing }: AppSettingsRowProps): react.JSX.Element;
3290
3306
 
3291
- export { APP_KEYS, AUTO_TOPUP_DEFAULTS, type AddCreditPoolMemberInput, AdministrationOverview, type AdministrationOverviewProps, type AdministrativeNavigationOptions, type ApiToken, type AppKey, AppSettingsHeader, type AppSettingsHeaderProps, AppSettingsPage, type AppSettingsPageProps, AppSettingsRow, type AppSettingsRowProps, AppSettingsSection, type AppSettingsSectionProps, AutoTopUpCard, type AutoTopUpSettings, type AutoTopUpValidation, type AutoTopUpView, type AvailableCreditsResponse, BILLING_TABLE_FRAME_STYLE, BILLING_TABLE_MIN_HEIGHT, BILLING_TABLE_PAGER_STYLE, BillingContent, type BillingEntitlement, type BillingEventPayload, type BillingProduct, type BillingSubscription, BuyCreditsModal, type BuyCreditsPayload, type BuyCreditsResponse, ConfirmDeleteModal, ConfirmLeaveModal, type ConnectedApp, ConnectedAppsContent, type CreatedToken, type CreditCycleUnit, type CreditLimitUnit, type CreditLimitValidation, type CreditPoolCandidate, type CreditPoolFormerMember, type CreditPoolMember, CreditPoolMemberModal, type CreditPoolMemberModalProps, type CreditPoolMemberStatus, type CreditPoolMode, type CreditPoolResponse, type CreditPoolSelfShare, type CreditsMeter, type CurrentPlanState, type CustomCreditInfo, type CustomCreditResponse, DEFAULT_PERMISSIONS, DEFAULT_USER_LANGUAGE, EMPTY_USAGE_LOGS_PAGE, ExportDateModal, type FetchUsageLogs, type FetchUsageLogsInRangeOptions, INITIAL_USAGE_LOGS_STATE, INVOICE_DOWNLOAD_FAILED_MESSAGE, INVOICE_NOT_AVAILABLE_MESSAGE, InviteUpdateModal, type InvoiceDownloadKind, type InvoicePdfResponse, type LoginMethodsMember, type LoginMethodsSettings, type LoginMethodsSwitchState, MOCK_REFERRED_USERS, type MemberCreditLimit, MemberCreditLimitModal, type MemberCreditLimitRow, type MemberCreditLimitSource, type MemberCreditLimitsResponse, MemberListFrame, type MemberListFrameProps, type MemberListTab, MemberListToolbar, type MemberListToolbarProps, type MemberPermissionsPayload, OrganizationContent, type OrganizationData, type OrganizationDetails, OrganizationIntegrationsContent, type OrganizationInvite, type OrganizationJoinRequest, type OrganizationJoinableWorkspace, OrganizationLoginMethodsContent, type OrganizationMember, OrganizationMemberModal, type OrganizationMemberModalProps, type OrganizationMemberRole, OrganizationModal, OrganizationPicker, type OrganizationPickerItem, type OrganizationPickerProps, type OrganizationPickerType, type OrganizationView, type OrganizationWorkspaceItem, POOL_ERROR_CODES, POOL_EXPIRY_MAX_MONTHS, POOL_NOTE_MAX_LENGTH, PerUserLimitsView, type PoolEndsAtResult, type PoolErrorCode, type PoolExpiryChoice, type PoolValueValidation, type Price, type PriceMetadata, type ProductsResponse, ProfileAvatar, ProfileTab, REMOVE_REASON_MAX_LENGTH, ReferralHistoryView, type ReferralHistoryViewProps, ReferralTab, type ReferredUser, RemovePoolMemberModal, type RemovePoolMemberModalProps, RemoveSelfShareModal, type RemoveSelfShareModalProps, SCOPE_LABELS, ScopeHeader, type ScopeHeaderProps, type ServiceItem, type SetCreditPoolSelfShareInput, type SettingsAdapters, SettingsAdaptersProvider, type SettingsApiAdapter, type SettingsAuthAdapter, type SettingsAuthUser, SettingsContent, type SettingsContentProps, type SettingsImageUploadAdapter, type SettingsIntegrationsAdapter, type SettingsLoginMethodsAdapter, type SettingsNavigationAdapter, type SettingsOrganizationAdapter, type SettingsOrganizationCreateOptions, type SettingsOrganizationCurrent, type SettingsOrganizationJoinableItem, type SettingsOrganizationListItem, type SettingsOrganizationType, type SettingsOrganizationWorkspaceJoin, type SettingsScope, type SettingsTab, type SettingsToastAdapter, SettingsTooltip, type SettingsTooltipPlacement, type SettingsTooltipProps, type SettingsWorkspaceAdapter, type SettingsWorkspaceCurrent, type SettingsWorkspaceListItem, SharedCreditsView, type SharedPoolBalance, SiconKey, type SponsorShareBalance, type StoreItem, type SubscriptionPlan, type SubscriptionResponse, TAB_DESCRIPTIONS, TAB_LABELS, TAB_SCOPE, TAB_TO_URL, type TeamMember, TeamsContent, type TokenExpiry, TokensContent, URL_TO_TAB, USAGE_LOGS_EXPORT_BATCH_SIZE, USAGE_LOGS_EXPORT_EXTRA_REQUESTS, USAGE_LOGS_EXPORT_MAX_ROWS, USAGE_LOGS_PAGE_SIZE, USER_LANGUAGES, type UpdateCreditPoolMemberInput, type UpdateSubscriptionPayload, type UpdateSubscriptionResponse, type UsageHistoryItem, type UsageHistoryPagination, type UsageHistoryResponse, type UsageLogsAction, type UsageLogsExportResult, type UsageLogsPage, UsageLogsPager, type UsageLogsQuery, type UsageLogsState, UsageLogsTable, type UsedByNamesLoader, type UserLanguage, type UserPermissions, WORKSPACE_CREDIT_LIMIT_REACHED, WORKSPACE_CREDIT_LIMIT_REACHED_MESSAGE, WORKSPACE_LIST_PAGE_SIZE, type WorkspaceCreditLimit, WorkspaceCreditLimitCard, type WorkspaceCreditLimitSummary, type WorkspaceData, WorkspaceGeneralTab, type WorkspaceGeneralTabProps, type WorkspaceInvite, type WorkspaceListOrganization, WorkspaceListTab, type WorkspaceMember, WorkspaceModal, type WorkspaceOrganization, type WorkspaceOrganizationRequest, WorkspacePicker, type WorkspacePickerGroup, type WorkspacePickerItem, type WorkspacePickerProps, WorkspaceTab, type WorkspaceUsageResponse, aboveTotalReason, autoTopUpBlockedReason, autoTopUpCycleText, autoTopUpDisabledMessage, belowUsageReason, canManageOnlyWorkspaceCreditLimit, canShowSharedCredits, capMoney, checkPoolPercentTotal, cleanAutoTopUpInput, cleanCreditLimitInput, cleanPoolValueInput, countLabel, createUsedByNamesLoader, creditCycleUnit, creditsMeter, deriveWorkspaceInvitePermission, describeAllowance, describeDefaultLimit, describeMemberLimit, describeWorkspaceCreditLimit, entitlementFromBody, entitlementFromFailure, expiryChoiceFor, fetchUsageLogsInRange, findBillingError, findPoolError, formatAutoTopUpMoney, formatCreditLimit, formatCredits, formatPackOption, formatPoolEndsAt, formatPoolSplit, groupWorkspaceList, hasPaidFeatures, inviteUpdate, invoiceDownloadKind, isLimitAboveTotal, isLimitBelowUsage, isPaidPlan, isSponsoredEntitlement, isWorkspaceCreditLimitReached, joinMembersWithLimits, lastUsedLabel, limitAboveTotalTotal, limitBelowUsageUsed, limitSourceLabel, loadCurrentPlan, loadWorkspaceOrganization, loginMethodsSwitchState, maximumCreditLimit, memberRoleUpdate, minPoolEndDate, minimumCreditLimit, ownCreditsFirstText, parseBillingEntitlement, parseInviteEmails, pausedOwnCreditsText, poolAllocatedPercent, poolAllocationText, poolEndsAtFrom, poolErrorMessage, poolRenewsAtCycleEnd, poolSharesCredits, poolUnallocatedPercent, poolWorkspaceName, productsForCountry, readSettingsCaller, referralCodeOf, referralCountLabel, referralLink, referralSignupDate, rememberSettingsCaller, resolveSettingsTabFromPath, roundCredits, settingsReturnTarget, sharedPoolBannerText, sharedPoolEndsText, sliceUsageLogsPage, sortReferredUsers, sponsorShareBannerText, sponsorShareDetailText, sponsorShareSpentText, sponsoredCreditsText, ssoLabel, toCsv, toLocalDateInput, usageLogsCsvRows, usageLogsDateRange, usageLogsExportFileName, usageLogsPage, usageLogsReducer, usageLogsReloadPage, usageLogsShowWorkspace, usageLogsSpentByOthers, useBillingEntitlement, useSettingsAdapters, useWorkspaceInvitePermission, useWorkspaceOrganization, usedByNamesFrom, usedByWorkspaceKey, userLanguageLabel, validateAutoTopUpInput, validateCreditLimitInput, validateDefaultCreditLimitInput, validatePoolText, validatePoolValue };
3307
+ export { APP_KEYS, AUTO_TOPUP_DEFAULTS, type AddCreditPoolMemberInput, AdministrationOverview, type AdministrationOverviewProps, type AdministrativeNavigationOptions, type ApiToken, type AppKey, AppSettingsHeader, type AppSettingsHeaderProps, AppSettingsPage, type AppSettingsPageProps, AppSettingsRow, type AppSettingsRowProps, AppSettingsSection, type AppSettingsSectionProps, AutoTopUpCard, type AutoTopUpSettings, type AutoTopUpValidation, type AutoTopUpView, type AvailableCreditsResponse, BILLING_TABLE_FRAME_STYLE, BILLING_TABLE_MIN_HEIGHT, BILLING_TABLE_PAGER_STYLE, BillingContent, type BillingEntitlement, type BillingEventPayload, type BillingProduct, type BillingSubscription, BuyCreditsModal, type BuyCreditsPayload, type BuyCreditsResponse, ConfirmDeleteModal, ConfirmLeaveModal, type ConnectedApp, ConnectedAppsContent, type CreatedToken, type CreditCycleUnit, type CreditLimitUnit, type CreditLimitValidation, type CreditPoolCandidate, type CreditPoolFormerMember, type CreditPoolMember, CreditPoolMemberModal, type CreditPoolMemberModalProps, type CreditPoolMemberStatus, type CreditPoolMode, type CreditPoolResponse, type CreditPoolSelfShare, type CreditsMeter, type CurrentPlanState, type CustomCreditInfo, type CustomCreditResponse, DEFAULT_PERMISSIONS, DEFAULT_USER_LANGUAGE, EMPTY_USAGE_LOGS_PAGE, ExportDateModal, type FetchUsageLogs, type FetchUsageLogsInRangeOptions, INITIAL_USAGE_LOGS_STATE, INVOICE_DOWNLOAD_FAILED_MESSAGE, INVOICE_NOT_AVAILABLE_MESSAGE, InviteUpdateModal, type InvoiceDownloadKind, type InvoicePdfResponse, type LoginMethodsMember, type LoginMethodsSettings, type LoginMethodsSwitchState, MOCK_REFERRED_USERS, type MemberCreditLimit, MemberCreditLimitModal, type MemberCreditLimitRow, type MemberCreditLimitSource, type MemberCreditLimitsResponse, MemberListFrame, type MemberListFrameProps, type MemberListTab, MemberListToolbar, type MemberListToolbarProps, type MemberPermissionsPayload, OrganizationContent, type OrganizationData, type OrganizationDetails, OrganizationIntegrationsContent, type OrganizationInvite, type OrganizationJoinRequest, type OrganizationJoinableWorkspace, OrganizationLoginMethodsContent, type OrganizationMember, OrganizationMemberModal, type OrganizationMemberModalProps, type OrganizationMemberRole, OrganizationModal, OrganizationPicker, type OrganizationPickerItem, type OrganizationPickerProps, type OrganizationPickerType, type OrganizationView, type OrganizationWorkspaceItem, POOL_ERROR_CODES, POOL_EXPIRY_MAX_MONTHS, POOL_NOTE_MAX_LENGTH, PerUserLimitsView, type PoolEndsAtResult, type PoolErrorCode, type PoolExpiryChoice, type PoolValueValidation, type Price, type PriceMetadata, type ProductsResponse, ProfileAvatar, ProfileTab, REMOVE_REASON_MAX_LENGTH, ReferralHistoryView, type ReferralHistoryViewProps, ReferralTab, type ReferredUser, RemovePoolMemberModal, type RemovePoolMemberModalProps, RemoveSelfShareModal, type RemoveSelfShareModalProps, SCOPE_LABELS, ScopeHeader, type ScopeHeaderProps, type ServiceItem, type SetCreditPoolSelfShareInput, type SettingsAdapters, SettingsAdaptersProvider, type SettingsApiAdapter, type SettingsAuthAdapter, type SettingsAuthUser, SettingsContent, type SettingsContentProps, type SettingsImageUploadAdapter, type SettingsIntegrationsAdapter, type SettingsLoginMethodsAdapter, type SettingsNavigationAdapter, type SettingsOrganizationAdapter, type SettingsOrganizationCreateOptions, type SettingsOrganizationCurrent, type SettingsOrganizationJoinableItem, type SettingsOrganizationListItem, type SettingsOrganizationType, type SettingsOrganizationWorkspaceJoin, type SettingsScope, type SettingsTab, type SettingsToastAdapter, SettingsTooltip, type SettingsTooltipPlacement, type SettingsTooltipProps, type SettingsWorkspaceAdapter, type SettingsWorkspaceCurrent, type SettingsWorkspaceListItem, SharedCreditsView, type SharedPoolBalance, SiconKey, type SponsorShareBalance, type StoreItem, type SubscriptionPlan, type SubscriptionResponse, TAB_DESCRIPTIONS, TAB_LABELS, TAB_SCOPE, TAB_TO_URL, type TeamMember, TeamsContent, type TokenExpiry, TokensContent, URL_TO_TAB, USAGE_LOGS_EXPORT_BATCH_SIZE, USAGE_LOGS_EXPORT_EXTRA_REQUESTS, USAGE_LOGS_EXPORT_MAX_ROWS, USAGE_LOGS_PAGE_SIZE, USER_LANGUAGES, type UpdateCreditPoolMemberInput, type UpdateSubscriptionPayload, type UpdateSubscriptionResponse, type UsageHistoryItem, type UsageHistoryPagination, type UsageHistoryResponse, type UsageLogsAction, type UsageLogsExportResult, type UsageLogsPage, UsageLogsPager, type UsageLogsQuery, type UsageLogsState, UsageLogsTable, type UsedByNamesLoader, type UserLanguage, type UserPermissions, WORKSPACE_CREDIT_LIMIT_REACHED, WORKSPACE_CREDIT_LIMIT_REACHED_MESSAGE, WORKSPACE_LIST_PAGE_SIZE, type WorkspaceCreditLimit, WorkspaceCreditLimitCard, type WorkspaceCreditLimitSummary, type WorkspaceData, WorkspaceGeneralTab, type WorkspaceGeneralTabProps, type WorkspaceInvite, type WorkspaceListOrganization, WorkspaceListTab, type WorkspaceMember, WorkspaceModal, type WorkspaceOrganization, type WorkspaceOrganizationRequest, WorkspacePicker, type WorkspacePickerGroup, type WorkspacePickerItem, type WorkspacePickerProps, WorkspaceTab, type WorkspaceUsageResponse, aboveTotalReason, autoTopUpBlockedReason, autoTopUpCapNotice, autoTopUpCycleText, autoTopUpDisabledMessage, belowUsageReason, canManageOnlyWorkspaceCreditLimit, canShowSharedCredits, capMoney, checkPoolPercentTotal, cleanAutoTopUpInput, cleanCreditLimitInput, cleanPoolValueInput, countLabel, createUsedByNamesLoader, creditCycleUnit, creditsMeter, deriveWorkspaceInvitePermission, describeAllowance, describeDefaultLimit, describeMemberLimit, describeWorkspaceCreditLimit, entitlementFromBody, entitlementFromFailure, expiryChoiceFor, fetchUsageLogsInRange, findBillingError, findPoolError, formatAutoTopUpMoney, formatCreditLimit, formatCredits, formatPackOption, formatPoolEndsAt, formatPoolSplit, groupWorkspaceList, hasPaidFeatures, inviteUpdate, invoiceDownloadKind, isLimitAboveTotal, isLimitBelowUsage, isPaidPlan, isSponsoredEntitlement, isWorkspaceCreditLimitReached, joinMembersWithLimits, lastUsedLabel, limitAboveTotalTotal, limitBelowUsageUsed, limitSourceLabel, loadCurrentPlan, loadWorkspaceOrganization, loginMethodsSwitchState, maximumCreditLimit, memberRoleUpdate, minPoolEndDate, minimumCreditLimit, ownCreditsFirstText, parseBillingEntitlement, parseInviteEmails, pausedOwnCreditsText, poolAllocatedPercent, poolAllocationText, poolEndsAtFrom, poolErrorMessage, poolRenewsAtCycleEnd, poolSharesCredits, poolUnallocatedPercent, poolWorkspaceName, productsForCountry, readSettingsCaller, referralCodeOf, referralCountLabel, referralLink, referralSignupDate, rememberSettingsCaller, resolveSettingsTabFromPath, roundCredits, settingsReturnTarget, sharedPoolBannerText, sharedPoolEndsText, sliceUsageLogsPage, sortReferredUsers, sponsorShareBannerText, sponsorShareDetailText, sponsorShareSpentText, sponsoredCreditsText, ssoLabel, toCsv, toLocalDateInput, usageLogsCsvRows, usageLogsDateRange, usageLogsExportFileName, usageLogsPage, usageLogsReducer, usageLogsReloadPage, usageLogsShowWorkspace, usageLogsSpentByOthers, useBillingEntitlement, useSettingsAdapters, useWorkspaceInvitePermission, useWorkspaceOrganization, usedByNamesFrom, usedByWorkspaceKey, userLanguageLabel, validateAutoTopUpInput, validateCreditLimitInput, validateDefaultCreditLimitInput, validatePoolText, validatePoolValue };
package/dist/index.js CHANGED
@@ -98,6 +98,7 @@ __export(index_exports, {
98
98
  WorkspaceTab: () => WorkspaceTab,
99
99
  aboveTotalReason: () => aboveTotalReason,
100
100
  autoTopUpBlockedReason: () => autoTopUpBlockedReason,
101
+ autoTopUpCapNotice: () => autoTopUpCapNotice,
101
102
  autoTopUpCycleText: () => autoTopUpCycleText,
102
103
  autoTopUpDisabledMessage: () => autoTopUpDisabledMessage,
103
104
  belowUsageReason: () => belowUsageReason,
@@ -8171,6 +8172,13 @@ function createBillingRequestGate(initialScope) {
8171
8172
  }
8172
8173
  };
8173
8174
  }
8175
+ async function refreshCreditBalance(begin, fetchCredits, apply) {
8176
+ const isCurrent = begin();
8177
+ if (!isCurrent) return;
8178
+ const res = await fetchCredits().catch(() => null);
8179
+ if (!isCurrent() || typeof res?.availableCredits !== "number") return;
8180
+ apply(res);
8181
+ }
8174
8182
 
8175
8183
  // src/plan-card-state.ts
8176
8184
  function planCardState(loaded, loading, failed, hasSubscription) {
@@ -8790,14 +8798,14 @@ function BuyCreditsModal({
8790
8798
  const maxCredits = Math.round(
8791
8799
  topupConfig.maxAmount / topupConfig.pricePerCredit
8792
8800
  );
8793
- const [credits2, setCredits] = (0, import_react16.useState)(minCredits);
8801
+ const [credits3, setCredits] = (0, import_react16.useState)(minCredits);
8794
8802
  const [creditsInput, setCreditsInput] = (0, import_react16.useState)(String(minCredits));
8795
8803
  const [priceInput, setPriceInput] = (0, import_react16.useState)(
8796
8804
  String(minCredits * topupConfig.pricePerCredit)
8797
8805
  );
8798
8806
  const [activeField, setActiveField] = (0, import_react16.useState)("credits");
8799
- const parsedCredits = creditsInput.length ? Number(creditsInput) : credits2;
8800
- const previewCredits = Number.isFinite(parsedCredits) ? parsedCredits : credits2;
8807
+ const parsedCredits = creditsInput.length ? Number(creditsInput) : credits3;
8808
+ const previewCredits = Number.isFinite(parsedCredits) ? parsedCredits : credits3;
8801
8809
  const pricedCredits = previewCredits > 0 ? previewCredits : 0;
8802
8810
  const price = Number(
8803
8811
  (pricedCredits * topupConfig.pricePerCredit).toFixed(2)
@@ -8819,8 +8827,8 @@ function BuyCreditsModal({
8819
8827
  setCreditsInput(String(derived));
8820
8828
  setPriceInput(String(amount));
8821
8829
  };
8822
- const handleDecrement = () => syncFromCredits(Math.max(minCredits, credits2 - STEP));
8823
- const handleIncrement = () => syncFromCredits(Math.min(maxCredits, credits2 + STEP));
8830
+ const handleDecrement = () => syncFromCredits(Math.max(minCredits, credits3 - STEP));
8831
+ const handleIncrement = () => syncFromCredits(Math.min(maxCredits, credits3 + STEP));
8824
8832
  const handleCreditsChange = (value) => {
8825
8833
  const raw = value.replace(/[^\d]/g, "");
8826
8834
  setCreditsInput(raw);
@@ -8954,7 +8962,7 @@ function BuyCreditsModal({
8954
8962
  style: {
8955
8963
  width: 24,
8956
8964
  height: 24,
8957
- opacity: credits2 <= minCredits ? 0.3 : 1,
8965
+ opacity: credits3 <= minCredits ? 0.3 : 1,
8958
8966
  transition: "opacity 0.15s ease"
8959
8967
  },
8960
8968
  onClick: handleDecrement,
@@ -9012,7 +9020,7 @@ function BuyCreditsModal({
9012
9020
  style: {
9013
9021
  width: 24,
9014
9022
  height: 24,
9015
- opacity: credits2 >= maxCredits ? 0.3 : 1,
9023
+ opacity: credits3 >= maxCredits ? 0.3 : 1,
9016
9024
  transition: "opacity 0.15s ease"
9017
9025
  },
9018
9026
  onClick: handleIncrement,
@@ -9144,7 +9152,7 @@ function BuyCreditsModal({
9144
9152
  pointerEvents: isInvalid ? "none" : "auto",
9145
9153
  transition: "opacity 0.2s ease"
9146
9154
  },
9147
- onClick: () => onBuy(credits2, price),
9155
+ onClick: () => onBuy(credits3, price),
9148
9156
  children: /* @__PURE__ */ (0, import_jsx_runtime22.jsx)(
9149
9157
  "span",
9150
9158
  {
@@ -10090,12 +10098,12 @@ function formatAutoTopUpMoney(amount, currency) {
10090
10098
  return symbol ? `${symbol}${text2}` : `${text2} ${(currency ?? "").toUpperCase()}`.trim();
10091
10099
  }
10092
10100
  function formatPackOption(pack, currency) {
10093
- const credits2 = `${pack.credits.toLocaleString("en-US")} credits`;
10094
- return pack.amount == null ? credits2 : `${credits2} \xB7 ${formatAutoTopUpMoney(pack.amount, currency)}`;
10101
+ const credits3 = `${pack.credits.toLocaleString("en-US")} credits`;
10102
+ return pack.amount == null ? credits3 : `${credits3} \xB7 ${formatAutoTopUpMoney(pack.amount, currency)}`;
10095
10103
  }
10096
- function capMoney(credits2, view) {
10104
+ function capMoney(credits3, view) {
10097
10105
  if (view.pricePerCredit == null) return null;
10098
- return formatAutoTopUpMoney(Math.round(credits2 * view.pricePerCredit * 100) / 100, view.currency);
10106
+ return formatAutoTopUpMoney(Math.round(credits3 * view.pricePerCredit * 100) / 100, view.currency);
10099
10107
  }
10100
10108
  function autoTopUpBlockedReason(view) {
10101
10109
  if (!view.paidPlan) return "Pro plan required";
@@ -10125,9 +10133,27 @@ function autoTopUpDisabledMessage(reason, at) {
10125
10133
  const when = shortDate(at);
10126
10134
  return `${what}${when ? ` on ${when}` : ""} \u2014 auto top-up turned off.`;
10127
10135
  }
10136
+ var credits = (n) => n.toLocaleString("en-US");
10137
+ var capAllows = (spent, pack, cap) => spent + pack <= cap;
10128
10138
  function autoTopUpCycleText(view) {
10129
10139
  const resets = shortDate(view.cycle?.end);
10130
- return `Bought ${view.spentThisCycleCredits.toLocaleString("en-US")} of ${view.cycleCapCredits.toLocaleString("en-US")} credits this billing cycle${resets ? ` (resets ${resets})` : ""}.`;
10140
+ const suffix = resets ? ` (resets ${resets})` : "";
10141
+ if (view.spentThisCycleCredits >= view.cycleCapCredits) {
10142
+ return `Bought ${credits(view.spentThisCycleCredits)} credits this billing cycle \u2014 cap of ${credits(view.cycleCapCredits)} reached${suffix}.`;
10143
+ }
10144
+ return `Bought ${credits(view.spentThisCycleCredits)} of ${credits(view.cycleCapCredits)} credits this billing cycle${suffix}.`;
10145
+ }
10146
+ function autoTopUpCapNotice(view, now = /* @__PURE__ */ new Date()) {
10147
+ const attempt = view.lastAttempt;
10148
+ if (!view.enabled || attempt?.status !== "skipped_cap" || !view.cycle) return null;
10149
+ const at = new Date(attempt.createdAt).getTime();
10150
+ const start = new Date(view.cycle.start).getTime();
10151
+ const end = new Date(view.cycle.end).getTime();
10152
+ if (!(at >= start && at < end && now.getTime() < end)) return null;
10153
+ if (capAllows(view.spentThisCycleCredits, view.packCredits, view.cycleCapCredits)) return null;
10154
+ const when = shortDate(attempt.createdAt);
10155
+ const until = shortDate(view.cycle.end);
10156
+ return `Cap reached${when ? ` on ${when}` : ""} \u2014 auto top-up is paused${until ? ` until ${until}` : " until the next billing cycle"}. Raise the cap per billing cycle to keep topping up.`;
10131
10157
  }
10132
10158
 
10133
10159
  // src/auto-top-up-card.tsx
@@ -10136,6 +10162,7 @@ var T16 = {
10136
10162
  primary: "var(--alias-text---icons-primary)",
10137
10163
  muted: "var(--alias-text---icons-muted)",
10138
10164
  error: "var(--alias-text---icons-error, var(--alias-text-and-icons-error, #ff6b6b))",
10165
+ warning: "var(--alias-text---icons-warning, var(--alias-text-and-icons-warning, #db8b00))",
10139
10166
  surfaceBase: "var(--alias-surface-base)",
10140
10167
  borderSubtle: "var(--alias-border-subtle)",
10141
10168
  fillPlus: "var(--alias-fill-neutral-neutralplus)",
@@ -10172,7 +10199,10 @@ var formOf = (view) => ({
10172
10199
  cap: String(view.cycleCapCredits)
10173
10200
  });
10174
10201
  var sameForm = (a, b) => a.enabled === b.enabled && a.threshold === b.threshold && a.packCredits === b.packCredits && a.cap === b.cap;
10175
- function AutoTopUpCard() {
10202
+ var AUTO_TOPUP_FOLLOW_MS = 1500;
10203
+ var AUTO_TOPUP_FOLLOW_LIMIT_MS = 3e4;
10204
+ var charging = (view) => view.pending || view.lastAttempt?.status === "pending";
10205
+ function AutoTopUpCard({ onTopUpSettled } = {}) {
10176
10206
  const { api, workspace, toast } = useSettingsAdapters();
10177
10207
  const workspaceId = workspace.current?.id ?? null;
10178
10208
  const [view, setView] = (0, import_react20.useState)(null);
@@ -10181,17 +10211,59 @@ function AutoTopUpCard() {
10181
10211
  const [saving, setSaving] = (0, import_react20.useState)(false);
10182
10212
  const latestLoad = (0, import_react20.useRef)(0);
10183
10213
  const workspaceRun = (0, import_react20.useRef)(0);
10214
+ const shown = (0, import_react20.useRef)({ view: null, form: null });
10215
+ shown.current = { view, form };
10216
+ const settledRef = (0, import_react20.useRef)(onTopUpSettled);
10217
+ settledRef.current = onTopUpSettled;
10218
+ const followTimer = (0, import_react20.useRef)(null);
10219
+ const stopFollowing = () => {
10220
+ if (followTimer.current) clearTimeout(followTimer.current);
10221
+ followTimer.current = null;
10222
+ };
10223
+ const follow = (0, import_react20.useCallback)(
10224
+ (run, start) => {
10225
+ stopFollowing();
10226
+ const until = Date.now() + AUTO_TOPUP_FOLLOW_LIMIT_MS;
10227
+ const since = start.lastAttempt?.createdAt ?? null;
10228
+ let ticks = 0;
10229
+ let sawCharge = charging(start);
10230
+ const tick = async () => {
10231
+ followTimer.current = null;
10232
+ if (run !== workspaceRun.current || !api.fetchAutoTopUp) return;
10233
+ const loadId = ++latestLoad.current;
10234
+ const next = await api.fetchAutoTopUp().catch(() => null);
10235
+ if (run !== workspaceRun.current || loadId !== latestLoad.current) return;
10236
+ if (next) {
10237
+ ticks += 1;
10238
+ const prev = shown.current;
10239
+ setView(next);
10240
+ if (!prev.form || !prev.view || sameForm(prev.form, formOf(prev.view))) setForm(formOf(next));
10241
+ if (charging(next)) sawCharge = true;
10242
+ else if (sawCharge || (next.lastAttempt?.createdAt ?? null) !== since) {
10243
+ settledRef.current?.();
10244
+ return;
10245
+ } else if (ticks >= 2) return;
10246
+ }
10247
+ if (Date.now() < until) followTimer.current = setTimeout(tick, AUTO_TOPUP_FOLLOW_MS);
10248
+ };
10249
+ followTimer.current = setTimeout(tick, AUTO_TOPUP_FOLLOW_MS);
10250
+ },
10251
+ [api]
10252
+ );
10184
10253
  const load = (0, import_react20.useCallback)(async () => {
10185
10254
  const loadId = ++latestLoad.current;
10186
10255
  if (!api.fetchAutoTopUp) return;
10256
+ const run = workspaceRun.current;
10187
10257
  const next = await api.fetchAutoTopUp().catch(() => null);
10188
10258
  if (loadId !== latestLoad.current) return;
10189
10259
  setView(next);
10190
10260
  setForm(next ? formOf(next) : null);
10191
10261
  setLoading(false);
10192
- }, [api]);
10262
+ if (next && charging(next)) follow(run, next);
10263
+ }, [api, follow]);
10193
10264
  (0, import_react20.useEffect)(() => {
10194
10265
  workspaceRun.current += 1;
10266
+ stopFollowing();
10195
10267
  setLoading(true);
10196
10268
  setSaving(false);
10197
10269
  setView(null);
@@ -10202,6 +10274,7 @@ function AutoTopUpCard() {
10202
10274
  () => () => {
10203
10275
  latestLoad.current += 1;
10204
10276
  workspaceRun.current += 1;
10277
+ stopFollowing();
10205
10278
  },
10206
10279
  []
10207
10280
  );
@@ -10231,6 +10304,8 @@ function AutoTopUpCard() {
10231
10304
  setView(next);
10232
10305
  setForm(formOf(next));
10233
10306
  toast.success(next.enabled ? "Auto top-up is on" : "Auto top-up is off");
10307
+ if (next.enabled) follow(run, next);
10308
+ else stopFollowing();
10234
10309
  } catch (err) {
10235
10310
  if (run !== workspaceRun.current) return;
10236
10311
  toast.error(errorMessage(err, { method: "PUT" }));
@@ -10244,6 +10319,7 @@ function AutoTopUpCard() {
10244
10319
  setForm({ ...form, enabled: next });
10245
10320
  };
10246
10321
  const disabledMessage = view ? autoTopUpDisabledMessage(view.disabledReason, view.disabledAt) : null;
10322
+ const capNotice = view ? autoTopUpCapNotice(view) : null;
10247
10323
  const capCredits = form && validation?.ok ? validation.value.cycleCapCredits : null;
10248
10324
  const capPrice = view && capCredits !== null ? capMoney(capCredits, view) : null;
10249
10325
  const toggleDisabled = saving || !api.setAutoTopUp || !form?.enabled && !!blocked;
@@ -10293,6 +10369,7 @@ function AutoTopUpCard() {
10293
10369
  ] }),
10294
10370
  loading ? /* @__PURE__ */ (0, import_jsx_runtime26.jsx)("span", { style: { ...cellText3, color: T16.muted }, children: "Loading\u2026" }) : !view || !form ? /* @__PURE__ */ (0, import_jsx_runtime26.jsx)("span", { style: { ...cellText3, color: T16.muted }, children: "Couldn't load auto top-up. Try again later." }) : /* @__PURE__ */ (0, import_jsx_runtime26.jsxs)(import_jsx_runtime26.Fragment, { children: [
10295
10371
  disabledMessage && /* @__PURE__ */ (0, import_jsx_runtime26.jsx)("span", { role: "status", style: { ...cellText3, color: T16.error }, children: disabledMessage }),
10372
+ capNotice && /* @__PURE__ */ (0, import_jsx_runtime26.jsx)("span", { role: "status", style: { ...cellText3, color: T16.warning }, children: capNotice }),
10296
10373
  !form.enabled && blocked && /* @__PURE__ */ (0, import_jsx_runtime26.jsx)("span", { style: { ...cellText3, color: T16.muted }, children: blocked }),
10297
10374
  form.enabled && /* @__PURE__ */ (0, import_jsx_runtime26.jsxs)("div", { className: "flex flex-wrap items-end", style: { gap: 12 }, children: [
10298
10375
  /* @__PURE__ */ (0, import_jsx_runtime26.jsxs)("label", { className: "flex flex-col", style: { gap: 4, minWidth: 160, flex: "1 1 160px" }, children: [
@@ -10692,13 +10769,13 @@ function poolAllocationText(pool) {
10692
10769
  const allocated = poolAllocatedPercent(pool);
10693
10770
  return `Allocated ${formatCredits(allocated)}% \xB7 Unallocated ${formatCredits(Math.max(0, round2(100 - allocated)))}%`;
10694
10771
  }
10695
- var credits = (value) => `${formatCredits(value)} ${value === 1 ? "credit" : "credits"}`;
10772
+ var credits2 = (value) => `${formatCredits(value)} ${value === 1 ? "credit" : "credits"}`;
10696
10773
  function formatPoolSplit(split) {
10697
10774
  if (split.mode === "percent") return `${formatCredits(split.value)}%`;
10698
- return credits(split.value);
10775
+ return credits2(split.value);
10699
10776
  }
10700
10777
  function describeAllowance(member) {
10701
- const allowance = `${credits(member.allowance)} this cycle`;
10778
+ const allowance = `${credits2(member.allowance)} this cycle`;
10702
10779
  return member.mode === "percent" ? `${formatPoolSplit(member)} \xB7 ${allowance}` : allowance;
10703
10780
  }
10704
10781
  var POOL_EXPIRY_MAX_MONTHS = 120;
@@ -10783,7 +10860,7 @@ function sponsorShareSpentText() {
10783
10860
  }
10784
10861
  function sponsorShareBannerText(share) {
10785
10862
  if (share.remaining <= 0) return sponsorShareSpentText();
10786
- return `This workspace's share: ${formatCredits(share.remaining)} of ${credits(share.allowance)} left this cycle`;
10863
+ return `This workspace's share: ${formatCredits(share.remaining)} of ${credits2(share.allowance)} left this cycle`;
10787
10864
  }
10788
10865
  function sponsorShareDetailText() {
10789
10866
  return "The rest of this workspace's credits are kept for the workspaces it shares them with. Organization admins change this in Shared credits.";
@@ -13481,7 +13558,15 @@ function BillingContent({
13481
13558
  const [planLoadFailed, setPlanLoadFailed] = (0, import_react25.useState)(false);
13482
13559
  const billingRequestGate = (0, import_react25.useRef)(createBillingRequestGate(workspaceId));
13483
13560
  billingRequestGate.current.setScope(workspaceId);
13484
- (0, import_react25.useEffect)(() => () => billingRequestGate.current.invalidate(), []);
13561
+ const creditsRequestGate = (0, import_react25.useRef)(createBillingRequestGate(workspaceId));
13562
+ creditsRequestGate.current.setScope(workspaceId);
13563
+ (0, import_react25.useEffect)(
13564
+ () => () => {
13565
+ billingRequestGate.current.invalidate();
13566
+ creditsRequestGate.current.invalidate();
13567
+ },
13568
+ []
13569
+ );
13485
13570
  const [billingOverviewLoaded, setBillingOverviewLoaded] = (0, import_react25.useState)(false);
13486
13571
  const [loadingTable, setLoadingTable] = (0, import_react25.useState)(false);
13487
13572
  const [showInitialLoader, setShowInitialLoader] = (0, import_react25.useState)(true);
@@ -13508,6 +13593,7 @@ function BillingContent({
13508
13593
  const fetchBillingOverview = (0, import_react25.useCallback)(async () => {
13509
13594
  const isCurrent = billingRequestGate.current.begin(workspaceId);
13510
13595
  if (!isCurrent) return;
13596
+ creditsRequestGate.current.invalidate();
13511
13597
  setLoadingBilling(true);
13512
13598
  setBillingOverviewLoaded(false);
13513
13599
  try {
@@ -13527,10 +13613,11 @@ function BillingContent({
13527
13613
  setSubscription(subRes.subscription);
13528
13614
  setEntitlement(subRes.entitlement);
13529
13615
  }
13530
- if (creditsRes?.availableCredits != null)
13616
+ if (creditsRes?.availableCredits != null) {
13531
13617
  setAvailableCredits(creditsRes.availableCredits);
13532
- setSharedPool(creditsRes?.sharedPool ?? null);
13533
- setSponsorShare(creditsRes?.sponsorShare ?? null);
13618
+ setSharedPool(creditsRes.sharedPool ?? null);
13619
+ setSponsorShare(creditsRes.sponsorShare ?? null);
13620
+ }
13534
13621
  if (productsRes?.data) setProducts(productsRes.data);
13535
13622
  if (customRes?.data?.credits != null) {
13536
13623
  setCustomPlanCredits(customRes.data.credits);
@@ -13544,6 +13631,18 @@ function BillingContent({
13544
13631
  }
13545
13632
  }
13546
13633
  }, [api, workspaceId]);
13634
+ const refreshCredits = (0, import_react25.useCallback)(
13635
+ () => refreshCreditBalance(
13636
+ () => creditsRequestGate.current.begin(workspaceId),
13637
+ () => api.fetchAvailableCredits(),
13638
+ (credits3) => {
13639
+ setAvailableCredits(credits3.availableCredits);
13640
+ setSharedPool(credits3.sharedPool ?? null);
13641
+ setSponsorShare(credits3.sponsorShare ?? null);
13642
+ }
13643
+ ),
13644
+ [api, workspaceId]
13645
+ );
13547
13646
  const fetchUserMap = (0, import_react25.useCallback)(async () => {
13548
13647
  try {
13549
13648
  const members = await api.fetchMembers();
@@ -13742,6 +13841,7 @@ function BillingContent({
13742
13841
  setEntitlement(null);
13743
13842
  setAvailableCredits(null);
13744
13843
  setSharedPool(null);
13844
+ setSponsorShare(null);
13745
13845
  setProducts([]);
13746
13846
  setTotalCredits(null);
13747
13847
  setCustomPlanCredits(null);
@@ -13934,7 +14034,7 @@ function BillingContent({
13934
14034
  document.body.removeChild(a);
13935
14035
  URL.revokeObjectURL(url);
13936
14036
  }
13937
- async function handleBuyCredits(credits2, price) {
14037
+ async function handleBuyCredits(credits3, price) {
13938
14038
  if (!workspaceId) {
13939
14039
  toast.error("Missing workspace details for credit top-up");
13940
14040
  return;
@@ -13946,14 +14046,14 @@ function BillingContent({
13946
14046
  "Buy credits confirmed",
13947
14047
  {
13948
14048
  action: "confirm_buy_credits",
13949
- additionalInfo: `${credits2}:${price}`
14049
+ additionalInfo: `${credits3}:${price}`
13950
14050
  }
13951
14051
  );
13952
14052
  try {
13953
14053
  const topupCurrency = workspace.current?.country?.trim().toUpperCase() === "IN" ? "inr" : "usd";
13954
14054
  const res = await api.buyCredits({
13955
14055
  serviceName: DEFAULT_TOPUP_SERVICE,
13956
- credits: credits2,
14056
+ credits: credits3,
13957
14057
  unitAmount: price,
13958
14058
  itemCount: 1,
13959
14059
  currency: topupCurrency,
@@ -13971,7 +14071,7 @@ function BillingContent({
13971
14071
  setAvailableCredits(payloadData.availableCredits);
13972
14072
  } else {
13973
14073
  setAvailableCredits(
13974
- (prev) => typeof prev === "number" ? prev + credits2 : prev
14074
+ (prev) => typeof prev === "number" ? prev + credits3 : prev
13975
14075
  );
13976
14076
  }
13977
14077
  toast.success("Top-up created");
@@ -14404,7 +14504,7 @@ function BillingContent({
14404
14504
  ]
14405
14505
  }
14406
14506
  ) : null,
14407
- /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(AutoTopUpCard, {}),
14507
+ /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(AutoTopUpCard, { onTopUpSettled: () => void refreshCredits() }),
14408
14508
  /* @__PURE__ */ (0, import_jsx_runtime31.jsxs)("div", { className: "flex items-center justify-between shrink-0 w-full", children: [
14409
14509
  /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(BillingTabBar, { activeTab, onTabChange: setActiveTab }),
14410
14510
  /* @__PURE__ */ (0, import_jsx_runtime31.jsxs)(
@@ -14496,8 +14596,8 @@ function BillingContent({
14496
14596
  workspace.current?.country
14497
14597
  ),
14498
14598
  onClose: () => setShowBuyCreditsModal(false),
14499
- onBuy: (credits2, price) => {
14500
- handleBuyCredits(credits2, price);
14599
+ onBuy: (credits3, price) => {
14600
+ handleBuyCredits(credits3, price);
14501
14601
  }
14502
14602
  }
14503
14603
  )
package/dist/index.mjs CHANGED
@@ -8013,6 +8013,13 @@ function createBillingRequestGate(initialScope) {
8013
8013
  }
8014
8014
  };
8015
8015
  }
8016
+ async function refreshCreditBalance(begin, fetchCredits, apply) {
8017
+ const isCurrent = begin();
8018
+ if (!isCurrent) return;
8019
+ const res = await fetchCredits().catch(() => null);
8020
+ if (!isCurrent() || typeof res?.availableCredits !== "number") return;
8021
+ apply(res);
8022
+ }
8016
8023
 
8017
8024
  // src/plan-card-state.ts
8018
8025
  function planCardState(loaded, loading, failed, hasSubscription) {
@@ -8655,14 +8662,14 @@ function BuyCreditsModal({
8655
8662
  const maxCredits = Math.round(
8656
8663
  topupConfig.maxAmount / topupConfig.pricePerCredit
8657
8664
  );
8658
- const [credits2, setCredits] = useState14(minCredits);
8665
+ const [credits3, setCredits] = useState14(minCredits);
8659
8666
  const [creditsInput, setCreditsInput] = useState14(String(minCredits));
8660
8667
  const [priceInput, setPriceInput] = useState14(
8661
8668
  String(minCredits * topupConfig.pricePerCredit)
8662
8669
  );
8663
8670
  const [activeField, setActiveField] = useState14("credits");
8664
- const parsedCredits = creditsInput.length ? Number(creditsInput) : credits2;
8665
- const previewCredits = Number.isFinite(parsedCredits) ? parsedCredits : credits2;
8671
+ const parsedCredits = creditsInput.length ? Number(creditsInput) : credits3;
8672
+ const previewCredits = Number.isFinite(parsedCredits) ? parsedCredits : credits3;
8666
8673
  const pricedCredits = previewCredits > 0 ? previewCredits : 0;
8667
8674
  const price = Number(
8668
8675
  (pricedCredits * topupConfig.pricePerCredit).toFixed(2)
@@ -8684,8 +8691,8 @@ function BuyCreditsModal({
8684
8691
  setCreditsInput(String(derived));
8685
8692
  setPriceInput(String(amount));
8686
8693
  };
8687
- const handleDecrement = () => syncFromCredits(Math.max(minCredits, credits2 - STEP));
8688
- const handleIncrement = () => syncFromCredits(Math.min(maxCredits, credits2 + STEP));
8694
+ const handleDecrement = () => syncFromCredits(Math.max(minCredits, credits3 - STEP));
8695
+ const handleIncrement = () => syncFromCredits(Math.min(maxCredits, credits3 + STEP));
8689
8696
  const handleCreditsChange = (value) => {
8690
8697
  const raw = value.replace(/[^\d]/g, "");
8691
8698
  setCreditsInput(raw);
@@ -8819,7 +8826,7 @@ function BuyCreditsModal({
8819
8826
  style: {
8820
8827
  width: 24,
8821
8828
  height: 24,
8822
- opacity: credits2 <= minCredits ? 0.3 : 1,
8829
+ opacity: credits3 <= minCredits ? 0.3 : 1,
8823
8830
  transition: "opacity 0.15s ease"
8824
8831
  },
8825
8832
  onClick: handleDecrement,
@@ -8877,7 +8884,7 @@ function BuyCreditsModal({
8877
8884
  style: {
8878
8885
  width: 24,
8879
8886
  height: 24,
8880
- opacity: credits2 >= maxCredits ? 0.3 : 1,
8887
+ opacity: credits3 >= maxCredits ? 0.3 : 1,
8881
8888
  transition: "opacity 0.15s ease"
8882
8889
  },
8883
8890
  onClick: handleIncrement,
@@ -9009,7 +9016,7 @@ function BuyCreditsModal({
9009
9016
  pointerEvents: isInvalid ? "none" : "auto",
9010
9017
  transition: "opacity 0.2s ease"
9011
9018
  },
9012
- onClick: () => onBuy(credits2, price),
9019
+ onClick: () => onBuy(credits3, price),
9013
9020
  children: /* @__PURE__ */ jsx22(
9014
9021
  "span",
9015
9022
  {
@@ -9955,12 +9962,12 @@ function formatAutoTopUpMoney(amount, currency) {
9955
9962
  return symbol ? `${symbol}${text2}` : `${text2} ${(currency ?? "").toUpperCase()}`.trim();
9956
9963
  }
9957
9964
  function formatPackOption(pack, currency) {
9958
- const credits2 = `${pack.credits.toLocaleString("en-US")} credits`;
9959
- return pack.amount == null ? credits2 : `${credits2} \xB7 ${formatAutoTopUpMoney(pack.amount, currency)}`;
9965
+ const credits3 = `${pack.credits.toLocaleString("en-US")} credits`;
9966
+ return pack.amount == null ? credits3 : `${credits3} \xB7 ${formatAutoTopUpMoney(pack.amount, currency)}`;
9960
9967
  }
9961
- function capMoney(credits2, view) {
9968
+ function capMoney(credits3, view) {
9962
9969
  if (view.pricePerCredit == null) return null;
9963
- return formatAutoTopUpMoney(Math.round(credits2 * view.pricePerCredit * 100) / 100, view.currency);
9970
+ return formatAutoTopUpMoney(Math.round(credits3 * view.pricePerCredit * 100) / 100, view.currency);
9964
9971
  }
9965
9972
  function autoTopUpBlockedReason(view) {
9966
9973
  if (!view.paidPlan) return "Pro plan required";
@@ -9990,9 +9997,27 @@ function autoTopUpDisabledMessage(reason, at) {
9990
9997
  const when = shortDate(at);
9991
9998
  return `${what}${when ? ` on ${when}` : ""} \u2014 auto top-up turned off.`;
9992
9999
  }
10000
+ var credits = (n) => n.toLocaleString("en-US");
10001
+ var capAllows = (spent, pack, cap) => spent + pack <= cap;
9993
10002
  function autoTopUpCycleText(view) {
9994
10003
  const resets = shortDate(view.cycle?.end);
9995
- return `Bought ${view.spentThisCycleCredits.toLocaleString("en-US")} of ${view.cycleCapCredits.toLocaleString("en-US")} credits this billing cycle${resets ? ` (resets ${resets})` : ""}.`;
10004
+ const suffix = resets ? ` (resets ${resets})` : "";
10005
+ if (view.spentThisCycleCredits >= view.cycleCapCredits) {
10006
+ return `Bought ${credits(view.spentThisCycleCredits)} credits this billing cycle \u2014 cap of ${credits(view.cycleCapCredits)} reached${suffix}.`;
10007
+ }
10008
+ return `Bought ${credits(view.spentThisCycleCredits)} of ${credits(view.cycleCapCredits)} credits this billing cycle${suffix}.`;
10009
+ }
10010
+ function autoTopUpCapNotice(view, now = /* @__PURE__ */ new Date()) {
10011
+ const attempt = view.lastAttempt;
10012
+ if (!view.enabled || attempt?.status !== "skipped_cap" || !view.cycle) return null;
10013
+ const at = new Date(attempt.createdAt).getTime();
10014
+ const start = new Date(view.cycle.start).getTime();
10015
+ const end = new Date(view.cycle.end).getTime();
10016
+ if (!(at >= start && at < end && now.getTime() < end)) return null;
10017
+ if (capAllows(view.spentThisCycleCredits, view.packCredits, view.cycleCapCredits)) return null;
10018
+ const when = shortDate(attempt.createdAt);
10019
+ const until = shortDate(view.cycle.end);
10020
+ return `Cap reached${when ? ` on ${when}` : ""} \u2014 auto top-up is paused${until ? ` until ${until}` : " until the next billing cycle"}. Raise the cap per billing cycle to keep topping up.`;
9996
10021
  }
9997
10022
 
9998
10023
  // src/auto-top-up-card.tsx
@@ -10001,6 +10026,7 @@ var T16 = {
10001
10026
  primary: "var(--alias-text---icons-primary)",
10002
10027
  muted: "var(--alias-text---icons-muted)",
10003
10028
  error: "var(--alias-text---icons-error, var(--alias-text-and-icons-error, #ff6b6b))",
10029
+ warning: "var(--alias-text---icons-warning, var(--alias-text-and-icons-warning, #db8b00))",
10004
10030
  surfaceBase: "var(--alias-surface-base)",
10005
10031
  borderSubtle: "var(--alias-border-subtle)",
10006
10032
  fillPlus: "var(--alias-fill-neutral-neutralplus)",
@@ -10037,7 +10063,10 @@ var formOf = (view) => ({
10037
10063
  cap: String(view.cycleCapCredits)
10038
10064
  });
10039
10065
  var sameForm = (a, b) => a.enabled === b.enabled && a.threshold === b.threshold && a.packCredits === b.packCredits && a.cap === b.cap;
10040
- function AutoTopUpCard() {
10066
+ var AUTO_TOPUP_FOLLOW_MS = 1500;
10067
+ var AUTO_TOPUP_FOLLOW_LIMIT_MS = 3e4;
10068
+ var charging = (view) => view.pending || view.lastAttempt?.status === "pending";
10069
+ function AutoTopUpCard({ onTopUpSettled } = {}) {
10041
10070
  const { api, workspace, toast } = useSettingsAdapters();
10042
10071
  const workspaceId = workspace.current?.id ?? null;
10043
10072
  const [view, setView] = useState18(null);
@@ -10046,17 +10075,59 @@ function AutoTopUpCard() {
10046
10075
  const [saving, setSaving] = useState18(false);
10047
10076
  const latestLoad = useRef11(0);
10048
10077
  const workspaceRun = useRef11(0);
10078
+ const shown = useRef11({ view: null, form: null });
10079
+ shown.current = { view, form };
10080
+ const settledRef = useRef11(onTopUpSettled);
10081
+ settledRef.current = onTopUpSettled;
10082
+ const followTimer = useRef11(null);
10083
+ const stopFollowing = () => {
10084
+ if (followTimer.current) clearTimeout(followTimer.current);
10085
+ followTimer.current = null;
10086
+ };
10087
+ const follow = useCallback8(
10088
+ (run, start) => {
10089
+ stopFollowing();
10090
+ const until = Date.now() + AUTO_TOPUP_FOLLOW_LIMIT_MS;
10091
+ const since = start.lastAttempt?.createdAt ?? null;
10092
+ let ticks = 0;
10093
+ let sawCharge = charging(start);
10094
+ const tick = async () => {
10095
+ followTimer.current = null;
10096
+ if (run !== workspaceRun.current || !api.fetchAutoTopUp) return;
10097
+ const loadId = ++latestLoad.current;
10098
+ const next = await api.fetchAutoTopUp().catch(() => null);
10099
+ if (run !== workspaceRun.current || loadId !== latestLoad.current) return;
10100
+ if (next) {
10101
+ ticks += 1;
10102
+ const prev = shown.current;
10103
+ setView(next);
10104
+ if (!prev.form || !prev.view || sameForm(prev.form, formOf(prev.view))) setForm(formOf(next));
10105
+ if (charging(next)) sawCharge = true;
10106
+ else if (sawCharge || (next.lastAttempt?.createdAt ?? null) !== since) {
10107
+ settledRef.current?.();
10108
+ return;
10109
+ } else if (ticks >= 2) return;
10110
+ }
10111
+ if (Date.now() < until) followTimer.current = setTimeout(tick, AUTO_TOPUP_FOLLOW_MS);
10112
+ };
10113
+ followTimer.current = setTimeout(tick, AUTO_TOPUP_FOLLOW_MS);
10114
+ },
10115
+ [api]
10116
+ );
10049
10117
  const load = useCallback8(async () => {
10050
10118
  const loadId = ++latestLoad.current;
10051
10119
  if (!api.fetchAutoTopUp) return;
10120
+ const run = workspaceRun.current;
10052
10121
  const next = await api.fetchAutoTopUp().catch(() => null);
10053
10122
  if (loadId !== latestLoad.current) return;
10054
10123
  setView(next);
10055
10124
  setForm(next ? formOf(next) : null);
10056
10125
  setLoading(false);
10057
- }, [api]);
10126
+ if (next && charging(next)) follow(run, next);
10127
+ }, [api, follow]);
10058
10128
  useEffect16(() => {
10059
10129
  workspaceRun.current += 1;
10130
+ stopFollowing();
10060
10131
  setLoading(true);
10061
10132
  setSaving(false);
10062
10133
  setView(null);
@@ -10067,6 +10138,7 @@ function AutoTopUpCard() {
10067
10138
  () => () => {
10068
10139
  latestLoad.current += 1;
10069
10140
  workspaceRun.current += 1;
10141
+ stopFollowing();
10070
10142
  },
10071
10143
  []
10072
10144
  );
@@ -10096,6 +10168,8 @@ function AutoTopUpCard() {
10096
10168
  setView(next);
10097
10169
  setForm(formOf(next));
10098
10170
  toast.success(next.enabled ? "Auto top-up is on" : "Auto top-up is off");
10171
+ if (next.enabled) follow(run, next);
10172
+ else stopFollowing();
10099
10173
  } catch (err) {
10100
10174
  if (run !== workspaceRun.current) return;
10101
10175
  toast.error(errorMessage(err, { method: "PUT" }));
@@ -10109,6 +10183,7 @@ function AutoTopUpCard() {
10109
10183
  setForm({ ...form, enabled: next });
10110
10184
  };
10111
10185
  const disabledMessage = view ? autoTopUpDisabledMessage(view.disabledReason, view.disabledAt) : null;
10186
+ const capNotice = view ? autoTopUpCapNotice(view) : null;
10112
10187
  const capCredits = form && validation?.ok ? validation.value.cycleCapCredits : null;
10113
10188
  const capPrice = view && capCredits !== null ? capMoney(capCredits, view) : null;
10114
10189
  const toggleDisabled = saving || !api.setAutoTopUp || !form?.enabled && !!blocked;
@@ -10158,6 +10233,7 @@ function AutoTopUpCard() {
10158
10233
  ] }),
10159
10234
  loading ? /* @__PURE__ */ jsx26("span", { style: { ...cellText3, color: T16.muted }, children: "Loading\u2026" }) : !view || !form ? /* @__PURE__ */ jsx26("span", { style: { ...cellText3, color: T16.muted }, children: "Couldn't load auto top-up. Try again later." }) : /* @__PURE__ */ jsxs23(Fragment10, { children: [
10160
10235
  disabledMessage && /* @__PURE__ */ jsx26("span", { role: "status", style: { ...cellText3, color: T16.error }, children: disabledMessage }),
10236
+ capNotice && /* @__PURE__ */ jsx26("span", { role: "status", style: { ...cellText3, color: T16.warning }, children: capNotice }),
10161
10237
  !form.enabled && blocked && /* @__PURE__ */ jsx26("span", { style: { ...cellText3, color: T16.muted }, children: blocked }),
10162
10238
  form.enabled && /* @__PURE__ */ jsxs23("div", { className: "flex flex-wrap items-end", style: { gap: 12 }, children: [
10163
10239
  /* @__PURE__ */ jsxs23("label", { className: "flex flex-col", style: { gap: 4, minWidth: 160, flex: "1 1 160px" }, children: [
@@ -10557,13 +10633,13 @@ function poolAllocationText(pool) {
10557
10633
  const allocated = poolAllocatedPercent(pool);
10558
10634
  return `Allocated ${formatCredits(allocated)}% \xB7 Unallocated ${formatCredits(Math.max(0, round2(100 - allocated)))}%`;
10559
10635
  }
10560
- var credits = (value) => `${formatCredits(value)} ${value === 1 ? "credit" : "credits"}`;
10636
+ var credits2 = (value) => `${formatCredits(value)} ${value === 1 ? "credit" : "credits"}`;
10561
10637
  function formatPoolSplit(split) {
10562
10638
  if (split.mode === "percent") return `${formatCredits(split.value)}%`;
10563
- return credits(split.value);
10639
+ return credits2(split.value);
10564
10640
  }
10565
10641
  function describeAllowance(member) {
10566
- const allowance = `${credits(member.allowance)} this cycle`;
10642
+ const allowance = `${credits2(member.allowance)} this cycle`;
10567
10643
  return member.mode === "percent" ? `${formatPoolSplit(member)} \xB7 ${allowance}` : allowance;
10568
10644
  }
10569
10645
  var POOL_EXPIRY_MAX_MONTHS = 120;
@@ -10648,7 +10724,7 @@ function sponsorShareSpentText() {
10648
10724
  }
10649
10725
  function sponsorShareBannerText(share) {
10650
10726
  if (share.remaining <= 0) return sponsorShareSpentText();
10651
- return `This workspace's share: ${formatCredits(share.remaining)} of ${credits(share.allowance)} left this cycle`;
10727
+ return `This workspace's share: ${formatCredits(share.remaining)} of ${credits2(share.allowance)} left this cycle`;
10652
10728
  }
10653
10729
  function sponsorShareDetailText() {
10654
10730
  return "The rest of this workspace's credits are kept for the workspaces it shares them with. Organization admins change this in Shared credits.";
@@ -13346,7 +13422,15 @@ function BillingContent({
13346
13422
  const [planLoadFailed, setPlanLoadFailed] = useState23(false);
13347
13423
  const billingRequestGate = useRef13(createBillingRequestGate(workspaceId));
13348
13424
  billingRequestGate.current.setScope(workspaceId);
13349
- useEffect20(() => () => billingRequestGate.current.invalidate(), []);
13425
+ const creditsRequestGate = useRef13(createBillingRequestGate(workspaceId));
13426
+ creditsRequestGate.current.setScope(workspaceId);
13427
+ useEffect20(
13428
+ () => () => {
13429
+ billingRequestGate.current.invalidate();
13430
+ creditsRequestGate.current.invalidate();
13431
+ },
13432
+ []
13433
+ );
13350
13434
  const [billingOverviewLoaded, setBillingOverviewLoaded] = useState23(false);
13351
13435
  const [loadingTable, setLoadingTable] = useState23(false);
13352
13436
  const [showInitialLoader, setShowInitialLoader] = useState23(true);
@@ -13373,6 +13457,7 @@ function BillingContent({
13373
13457
  const fetchBillingOverview = useCallback10(async () => {
13374
13458
  const isCurrent = billingRequestGate.current.begin(workspaceId);
13375
13459
  if (!isCurrent) return;
13460
+ creditsRequestGate.current.invalidate();
13376
13461
  setLoadingBilling(true);
13377
13462
  setBillingOverviewLoaded(false);
13378
13463
  try {
@@ -13392,10 +13477,11 @@ function BillingContent({
13392
13477
  setSubscription(subRes.subscription);
13393
13478
  setEntitlement(subRes.entitlement);
13394
13479
  }
13395
- if (creditsRes?.availableCredits != null)
13480
+ if (creditsRes?.availableCredits != null) {
13396
13481
  setAvailableCredits(creditsRes.availableCredits);
13397
- setSharedPool(creditsRes?.sharedPool ?? null);
13398
- setSponsorShare(creditsRes?.sponsorShare ?? null);
13482
+ setSharedPool(creditsRes.sharedPool ?? null);
13483
+ setSponsorShare(creditsRes.sponsorShare ?? null);
13484
+ }
13399
13485
  if (productsRes?.data) setProducts(productsRes.data);
13400
13486
  if (customRes?.data?.credits != null) {
13401
13487
  setCustomPlanCredits(customRes.data.credits);
@@ -13409,6 +13495,18 @@ function BillingContent({
13409
13495
  }
13410
13496
  }
13411
13497
  }, [api, workspaceId]);
13498
+ const refreshCredits = useCallback10(
13499
+ () => refreshCreditBalance(
13500
+ () => creditsRequestGate.current.begin(workspaceId),
13501
+ () => api.fetchAvailableCredits(),
13502
+ (credits3) => {
13503
+ setAvailableCredits(credits3.availableCredits);
13504
+ setSharedPool(credits3.sharedPool ?? null);
13505
+ setSponsorShare(credits3.sponsorShare ?? null);
13506
+ }
13507
+ ),
13508
+ [api, workspaceId]
13509
+ );
13412
13510
  const fetchUserMap = useCallback10(async () => {
13413
13511
  try {
13414
13512
  const members = await api.fetchMembers();
@@ -13607,6 +13705,7 @@ function BillingContent({
13607
13705
  setEntitlement(null);
13608
13706
  setAvailableCredits(null);
13609
13707
  setSharedPool(null);
13708
+ setSponsorShare(null);
13610
13709
  setProducts([]);
13611
13710
  setTotalCredits(null);
13612
13711
  setCustomPlanCredits(null);
@@ -13799,7 +13898,7 @@ function BillingContent({
13799
13898
  document.body.removeChild(a);
13800
13899
  URL.revokeObjectURL(url);
13801
13900
  }
13802
- async function handleBuyCredits(credits2, price) {
13901
+ async function handleBuyCredits(credits3, price) {
13803
13902
  if (!workspaceId) {
13804
13903
  toast.error("Missing workspace details for credit top-up");
13805
13904
  return;
@@ -13811,14 +13910,14 @@ function BillingContent({
13811
13910
  "Buy credits confirmed",
13812
13911
  {
13813
13912
  action: "confirm_buy_credits",
13814
- additionalInfo: `${credits2}:${price}`
13913
+ additionalInfo: `${credits3}:${price}`
13815
13914
  }
13816
13915
  );
13817
13916
  try {
13818
13917
  const topupCurrency = workspace.current?.country?.trim().toUpperCase() === "IN" ? "inr" : "usd";
13819
13918
  const res = await api.buyCredits({
13820
13919
  serviceName: DEFAULT_TOPUP_SERVICE,
13821
- credits: credits2,
13920
+ credits: credits3,
13822
13921
  unitAmount: price,
13823
13922
  itemCount: 1,
13824
13923
  currency: topupCurrency,
@@ -13836,7 +13935,7 @@ function BillingContent({
13836
13935
  setAvailableCredits(payloadData.availableCredits);
13837
13936
  } else {
13838
13937
  setAvailableCredits(
13839
- (prev) => typeof prev === "number" ? prev + credits2 : prev
13938
+ (prev) => typeof prev === "number" ? prev + credits3 : prev
13840
13939
  );
13841
13940
  }
13842
13941
  toast.success("Top-up created");
@@ -14269,7 +14368,7 @@ function BillingContent({
14269
14368
  ]
14270
14369
  }
14271
14370
  ) : null,
14272
- /* @__PURE__ */ jsx31(AutoTopUpCard, {}),
14371
+ /* @__PURE__ */ jsx31(AutoTopUpCard, { onTopUpSettled: () => void refreshCredits() }),
14273
14372
  /* @__PURE__ */ jsxs28("div", { className: "flex items-center justify-between shrink-0 w-full", children: [
14274
14373
  /* @__PURE__ */ jsx31(BillingTabBar, { activeTab, onTabChange: setActiveTab }),
14275
14374
  /* @__PURE__ */ jsxs28(
@@ -14361,8 +14460,8 @@ function BillingContent({
14361
14460
  workspace.current?.country
14362
14461
  ),
14363
14462
  onClose: () => setShowBuyCreditsModal(false),
14364
- onBuy: (credits2, price) => {
14365
- handleBuyCredits(credits2, price);
14463
+ onBuy: (credits3, price) => {
14464
+ handleBuyCredits(credits3, price);
14366
14465
  }
14367
14466
  }
14368
14467
  )
@@ -19252,6 +19351,7 @@ export {
19252
19351
  WorkspaceTab,
19253
19352
  aboveTotalReason,
19254
19353
  autoTopUpBlockedReason,
19354
+ autoTopUpCapNotice,
19255
19355
  autoTopUpCycleText,
19256
19356
  autoTopUpDisabledMessage,
19257
19357
  belowUsageReason,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@streamoid/settings",
3
- "version": "0.24.0",
3
+ "version": "0.25.0",
4
4
  "main": "./dist/index.js",
5
5
  "module": "./dist/index.mjs",
6
6
  "types": "./dist/index.d.ts",