### Example: Using getWindowsUsername() Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference/database.md Shows how to import and call getWindowsUsername, with an example return value. ```typescript import { getWindowsUsername } from '../services/database'; const user = getWindowsUsername(); // e.g. "boxuser" when running under WSL ``` -------------------------------- ### checkAndNotifyUsage usage example Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference/notifications.md Example demonstrating usage-based gating and premium threshold alerts. ```ts import { checkAndNotifyUsage } from '../handlers/notifications'; // premium over limit β†’ allow usage-based alert await checkAndNotifyUsage({ percentage: 33.3, type: 'usage-based', limit: 50, premiumPercentage: 100 }); // premium alert at threshold await checkAndNotifyUsage({ percentage: 90, type: 'premium' }); ``` -------------------------------- ### Usage and Period Progress Bar Example Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference/progressBars.md Demonstrates how to initialize usage and period progress bars along with a daily remaining calculation. ```ts import { createUsageProgressBar, createPeriodProgressBar, calculateDailyRemaining } from '../utils/progressBars'; const usage = createUsageProgressBar(120, 500); // 'Usage: 🟩🟩🟨⬜⬜⬜⬜⬜⬜⬜' const period = createPeriodProgressBar('3 April - 3 May'); const daily = calculateDailyRemaining(120, 500, new Date(2026, 4, 3)); ``` -------------------------------- ### generateReport usage example Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference/report.md Demonstrates how to invoke the report generator and handle the resulting file path or failure status. ```ts import { generateReport } from '../utils/report'; const { reportPath, success } = await generateReport(); if (success) { console.log(`Report written to ${reportPath}`); } else { console.log('Report generation failed (reportPath empty)'); } ``` -------------------------------- ### Example: state flow using clearAllIntervals() Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference/cooldown.md Shows a typical sequence: start refresh interval, set cooldown start time, start countdown display, then clear all intervals on window blur or deactivation. After cooldown expires, the countdown loop calls startRefreshInterval() again. ```TypeScript import { startRefreshInterval, clearAllIntervals, getCooldownStartTime, startCountdownDisplay, setCooldownStartTime, resetConsecutiveErrorCount, } from '../utils/cooldown'; startRefreshInterval(); // periodic updateStats ticks setCooldownStartTime(Date.now()); // enter cooldown startCountdownDisplay(); // status bar shows 10:00 countdown clearAllIntervals(); // window blurred / deactivation // after the cooldown expires, the countdown loop itself calls startRefreshInterval() ``` -------------------------------- ### checkUsageBasedStatus usage example Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference/api.md Example showing how to call checkUsageBasedStatus and handle the returned status object. ```ts import { checkUsageBasedStatus } from '../services/api'; const status = await checkUsageBasedStatus(token, teamId); if (status.isEnabled && status.limit) { console.log(`Usage-based pricing enabled, limit $${status.limit}`); } else if (!status.isEnabled) { console.log('Disabled or status unknown β€” no exception was raised'); } ``` -------------------------------- ### setCooldownStartTime(time) Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference/cooldown.md Sets the cooldown start time. Passing null clears the cooldown. ```APIDOC ## setCooldownStartTime(time) ### Description Sets the cooldown start time. Passing null clears the cooldown. ### Parameters - **time** (number | null) - Required - The cooldown start time in milliseconds or null to clear. ### Returns void ``` -------------------------------- ### Example: fetch and extract user spend Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference/team.md Example usage of checkTeamMembership, getTeamSpend, and extractUserSpend together. It retrieves the extension context, checks team membership, and if the user is a team member with a teamId and userId, fetches team spend and extracts the user's spend, logging the name and spend in dollars. ```ts import { checkTeamMembership, getTeamSpend, extractUserSpend } from '../services/team'; import { getExtensionContext } from '../extension'; const context = getExtensionContext(); const info = await checkTeamMembership(token, context); if (info.isTeamMember && info.teamId && info.userId) { const teamSpend = await getTeamSpend(token, info.teamId); const mine = extractUserSpend(teamSpend, info.userId); console.log(`${mine.name} spent $${mine.spendCents / 100}`); } ``` -------------------------------- ### Example: Using getCursorTokenFromDB() Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference/database.md Shows how to import and call getCursorTokenFromDB, handle the undefined case, and extract the userId from the token. ```typescript import { getCursorTokenFromDB } from '../services/database'; const token = await getCursorTokenFromDB(); if (!token) { // Not signed in or state DB unavailable β€” show sign-in prompt return; } const userId = token.split('%3A%3A')[0]; ``` -------------------------------- ### Example usage of updateStats Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference/updateStats.md Shows how to import and call updateStats with a status bar item created with vscode.window.createStatusBarItem. The comment indicates a full refresh cycle. ```typescript import { updateStats } from '../utils/updateStats'; const item = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right, 100); await updateStats(item); // full refresh: token β†’ stats β†’ tooltip β†’ notifications ``` -------------------------------- ### fetchCursorStats usage with error handling Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference/api.md Example demonstrating how to fetch stats and handle potential errors, such as expired tokens or CORS issues. ```ts import { fetchCursorStats } from '../services/api'; try { const stats = await fetchCursorStats(token); const p = stats.premiumRequests; console.log(`${p.current}/${p.limit} fast requests, period starts ${p.startOfMonth}`); } catch (e) { // e is the raw axios error; status 401 = expired token, 403 = CORS/origin if (e.response?.status === 401) { /* refresh token from DB and retry */ } } ``` -------------------------------- ### Usage example from extension.ts Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference/github.md Shows how to call checkForUpdates after activation and after an extension update. The first call uses a 1.5s delay and hourly interval; the second forces a changelog for a specific version. ```typescript import { checkForUpdates } from '../services/github'; // post-activation: first check 1.5s after start, then at most once per hour await checkForUpdates(0, 1000 * 60 * 60); // after an extension update, force-changelog for the newly installed version setTimeout(() => checkForUpdates(0, 0, '1.1.6'), 3000); ``` -------------------------------- ### setOnLanguageChangeCallback usage Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference/i18n.md Example of registering a language change callback to display an information message. ```ts setOnLanguageChangeCallback((_newLanguage, languageLabel) => { vscode.window.showInformationMessage(t('commands.languageChanged', { language: languageLabel })); }); ``` -------------------------------- ### startCountdownDisplay() Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference/cooldown.md Starts a 1-second interval that renders the remaining cooldown in the status bar. When the countdown reaches zero, it clears the interval and triggers a refresh. ```APIDOC ## startCountdownDisplay() ### Description Starts a 1-second interval that renders the remaining cooldown in the status bar. The text is set to `$(warning) ` with the countdown substituted, and the item is shown. When the countdown reaches zero, it clears the interval and `_cooldownStartTime`, resets the error counter, calls `startRefreshInterval()`, and attempts an immediate `updateStats(_statusBarItem)`. ### Method Function ### Signature startCountdownDisplay(): void ### Parameters (none) ### Return void. If `_statusBarItem` is null or `_cooldownStartTime` is falsy, each tick returns without doing anything. ``` -------------------------------- ### GET https://api.github.com/repos/dwtexe/cursor-stats/releases/tags/ Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/endpoints.md Fetches a single release by its tag version. No authentication required. ```APIDOC ## GET https://api.github.com/repos/dwtexe/cursor-stats/releases/tags/ ### Description Fetches a single release by its tag version. ### Method GET ### Endpoint https://api.github.com/repos/dwtexe/cursor-stats/releases/tags/ ### Authentication None ### Path Parameters - **version** (string) - Required - The release version tag. A leading 'v' is added if missing (e.g., 'v1.2.3'). ### Response #### Success Response (200) - **tag_name** (string) - Release tag name. - **name** (string) - Release name. - **body** (string) - Release body in Markdown. - **prerelease** (boolean) - Whether it is a prerelease. - **html_url** (string) - URL to the release page. - **zipball_url** (string) - URL to the zip archive. - **tarball_url** (string) - URL to the tarball archive. - **assets** (array) - Array of assets with fields: name, browser_download_url. #### Response Example { "tag_name": "string", "name": "string", "body": "string", "prerelease": false, "html_url": "string", "zipball_url": "string", "tarball_url": "string", "assets": [ { "name": "string", "browser_download_url": "string" } ] } ``` -------------------------------- ### Logger usage example Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference/logger.md Shows how to import and use the logger functions: logging with error flag, logging with category tag, retrieving history, and clearing it. ```typescript import { log, getLogHistory, clearLogHistory } from '../utils/logger'; log('[API] Request failed', { status: error.response?.status }, true); // always logged log('[Stats] update completed'); // needs enableLogging + matching tag const snapshot = getLogHistory(); // most recent first clearLogHistory(); ``` -------------------------------- ### GET https://api.github.com/repos/dwtexe/cursor-stats/releases Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/endpoints.md Fetches the list of releases for the cursor-stats repository, newest first. No authentication required. ```APIDOC ## GET https://api.github.com/repos/dwtexe/cursor-stats/releases ### Description Fetches the list of releases for the cursor-stats repository, newest first. ### Method GET ### Endpoint https://api.github.com/repos/dwtexe/cursor-stats/releases ### Authentication None ### Response #### Success Response (200) - **tag_name** (string) - Release tag name. - **name** (string) - Release name. - **body** (string) - Release body in Markdown. - **prerelease** (boolean) - Whether it is a prerelease. - **html_url** (string) - URL to the release page. - **zipball_url** (string) - URL to the zip archive. - **tarball_url** (string) - URL to the tarball archive. - **assets** (array) - Array of assets with fields: name, browser_download_url. #### Response Example [ { "tag_name": "string", "name": "string", "body": "string", "prerelease": false, "html_url": "string", "zipball_url": "string", "tarball_url": "string", "assets": [ { "name": "string", "browser_download_url": "string" } ] } ] ``` -------------------------------- ### GET https://latest.currency-api.pages.dev/v1/currencies/usd.json Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/endpoints.md Fetches USD to target currency exchange rates. The response is cached on disk for 24 hours. No authentication is required. ```APIDOC ## GET https://latest.currency-api.pages.dev/v1/currencies/usd.json ### Description Fetches USD to target currency exchange rates. The response is cached on disk for 24 hours. ### Endpoint https://latest.currency-api.pages.dev/v1/currencies/usd.json ### Authentication None ### Response #### Success Response (200) - **date** (string) - The date of the exchange rates. - **usd** (object) - An object mapping lowercase currency codes to exchange rates relative to USD. #### Response Example { "date": "2025-01-01", "usd": { "eur": 0.92, "gbp": 0.79 } } ``` -------------------------------- ### Using convertAndFormatCurrency Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference/currency.md Example usage of convertAndFormatCurrency. It retrieves the current currency (e.g., 'EUR') and converts a USD amount (12.5) to the formatted string (e.g., '€11.63'). ```ts import { convertAndFormatCurrency, getCurrentCurrency } from '../utils/currency'; const cur = getCurrentCurrency(); // e.g. 'EUR' const text = await convertAndFormatCurrency(12.5); // e.g. '€11.63' (USD β†’ EUR) ``` -------------------------------- ### checkGitHubRelease() function signature Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference/github.md Exported async function that fetches the latest GitHub release and compares it with the installed version. Returns null on no update or error. ```typescript export async function checkGitHubRelease(): Promise { ``` -------------------------------- ### startCountdownDisplay function signature Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference/cooldown.md Declares the startCountdownDisplay function with no parameters and no explicit return type. It starts a 1-second interval that renders the remaining cooldown in the status bar, and when the countdown reaches zero it clears the interval, resets state, and triggers refresh. ```TypeScript export function startCountdownDisplay() { ``` -------------------------------- ### initializeLogging(context) Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference/logger.md Initializes the logging system by creating the 'Cursor Stats' output channel and registering it with the extension context. Must be called before using other logger functions. ```APIDOC ## initializeLogging(context) ### Description Creates the Cursor Stats output channel via vscode.window.createOutputChannel('Cursor Stats') and pushes it onto context.subscriptions. Throws an error if channel creation fails. ### Method Function ### Signature initializeLogging(context: vscode.ExtensionContext): void ### Parameters - **context** (vscode.ExtensionContext) - Required - Its subscriptions array receives the created output channel. ### Return Value void ### Throws - Error: 'Failed to initialize logging system' when channel creation fails (after a [Critical] log attempt). ### Example ```ts import { initializeLogging } from '../utils/logger'; initializeLogging(context); ``` ``` -------------------------------- ### initializeI18n() Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference/i18n.md Initializes the i18n system by loading language packs and setting up configuration change listeners. ```APIDOC ## initializeI18n() ### Description Initializes the i18n system by loading all language packs and setting up a configuration change listener. ### Method initializeI18n ### Endpoint src/utils/i18n.ts ### Parameters None ### Return void ### Behavior 1. Loads every pack found in `src/locales/.json`, `locales/.json` (packaged), or `out/locales/.json` (development) for the codes `['en', 'zh', 'ko', 'ja', 'de', 'ru', 'kk']` β€” the extension path is resolved via `vscode.extensions.getExtension('Dwtexe.cursor-stats')?.extensionPath`. Missing packs are logged and skipped; a missing English pack logs a critical warning. 2. Sets `currentLanguagePack` from the `cursorStats.language` config (default `'en'`), falling back to `'en'`. 3. Installs a `vscode.workspace.onDidChangeConfiguration` listener that calls `updateCurrentLanguage()` when `cursorStats.language` changes. Note: `updateCurrentLanguage()` is private; it swaps `currentLanguage`/`currentLanguagePack` and fires `onLanguageChangeCallback` only when leaving a non-`en` language (the guard `oldLanguage !== 'en'` avoids firing during initialization). ``` -------------------------------- ### t translation function usage Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference/i18n.md Example of using the translation function with parameter substitution. ```ts import { t } from '../utils/i18n'; const msg = t('commands.currentStatus', { status: t('statusBar.enabled'), limit: '$50', }); ``` -------------------------------- ### initializeLogging function signature Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference/logger.md Creates the 'Cursor Stats' output channel and registers it with the extension context. Throws an error if channel creation fails. ```typescript export function initializeLogging(context: vscode.ExtensionContext): void { ``` -------------------------------- ### createMarkdownTooltip(lines, isError?, allLines?) Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference/statusBar.md Builds the full status bar tooltip as a Markdown string. It includes a centered header, an error banner when isError is true, otherwise a premium-requests section and a usage-based pricing section, and a footer with action links. It supports embedded metadata for currency conversion and handles network errors gracefully. ```APIDOC ## createMarkdownTooltip(lines, isError?, allLines?) ### Description Builds the full status bar tooltip as a Markdown string. It includes a centered header, an error banner when isError is true, otherwise a premium-requests section and a usage-based pricing section, and a footer with action links. It supports embedded metadata for currency conversion and handles network errors gracefully. ### Signature ```ts export async function createMarkdownTooltip(lines: string[], isError: boolean = false, allLines: string[] = []): Promise ``` ### Parameters - **lines** (string[]) - Required - Base content lines produced by `updateStats` - **isError** (boolean) - Optional - Default: `false` - When `true`, renders only the error banner plus the lines - **allLines** (string[]) - Optional - Default: `[]` - Full content (including hidden metadata) used to recover original USD figures from the `__USD_USAGE_DATA__:` embedded JSON ### Return Value - **Promise** - A Markdown string with `isTrusted = true`, `supportHtml = true`, `supportThemeIcons = true`. ### Behavioral Notes - Embedded metadata: `allLines` is scanned for a line containing `__USD_USAGE_DATA__:` and JSON-parsed to recover `{ usdTotalCost, usdLimit, percentage }` for currency-converted tooltips. - The usage-based section calls the network (`checkUsageBasedStatus`, `getCurrentUsageLimit`, and possibly `getTeamSpend`/`extractUserSpend`); every error there is caught and rendered as `> ⚠️ `. - A missing token renders `> ⚠️ `. - All strings are i18n keys resolved through `t(...)`. ### Example ```ts import { createMarkdownTooltip } from '../handlers/statusBar'; const tooltip = await createMarkdownTooltip( ['⚑ Cursor Usage Stats', 'β€’ 42/500 requests used'], false, ['__USD_USAGE_DATA__:{"usdTotalCost":12.5,"usdLimit":50,"percentage":25}'], ); statusBarItem.tooltip = tooltip; ``` ``` -------------------------------- ### createMarkdownTooltip(lines, isError, allLines) Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference/statusBar.md Builds a complex Markdown tooltip for the status bar, including usage statistics and error banners. ```ts export async function createMarkdownTooltip(lines: string[], isError: boolean = false, allLines: string[] = []): Promise { ``` ```ts import { createMarkdownTooltip } from '../handlers/statusBar'; const tooltip = await createMarkdownTooltip( ['⚑ Cursor Usage Stats', 'β€’ 42/500 requests used'], false, ['__USD_USAGE_DATA__:{"usdTotalCost":12.5,"usdLimit":50,"percentage":25}'], ); statusBarItem.tooltip = tooltip; ``` -------------------------------- ### Consumer pattern: getExtensionContext and getRefreshIntervalMs Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference/extension.md Shows how to import and use getExtensionContext and getRefreshIntervalMs. getExtensionContext throws an Error if the extension is not activated, and getRefreshIntervalMs returns a value of at least 5000 ms. ```ts // Consumer pattern: any module that needs lifecycle context import { getExtensionContext, getRefreshIntervalMs } from './extension'; const context = getExtensionContext(); // throws Error if not activated const intervalMs = getRefreshIntervalMs(); // >= 5000 ms ``` -------------------------------- ### createStatusBarItem() Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference/statusBar.md Creates a VS Code status bar item, right-aligned with priority 100, and stores it in a module-level singleton. Returns the created status bar item. ```APIDOC ## createStatusBarItem() ### Description Creates a VS Code status bar item, right-aligned with priority 100, and stores it in a module-level singleton. ### Method Function ### Signature ts export function createStatusBarItem(): vscode.StatusBarItem ### Parameters None ### Return Value - **Type**: `vscode.StatusBarItem` - **Description**: The created status bar item, right-aligned with priority 100. ``` -------------------------------- ### GET https://cursor.com/api/stripeSession Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/endpoints.md Retrieves a Stripe billing session URL. Requires a cookie header for authentication and returns a quoted string that is stripped of quotes to obtain the URL. ```APIDOC ## GET https://cursor.com/api/stripeSession ### Description Retrieves a Stripe billing session URL. The response is a quoted string; the source strips all double quotes and treats the result as the billing URL. ### Method GET ### Endpoint https://cursor.com/api/stripeSession ### Authentication - **Cookie** (string) - Required - Cookie header only. ### Response #### Success Response (200) - **body** (string) - A quoted string representing the Stripe billing URL. The source removes all `"` characters to obtain the actual URL. #### Response Example ```json "https://billing.stripe.com/p/session/..." ``` ### Error Handling If the request fails, the fallback URL is `https://www.cursor.com/settings`. ``` -------------------------------- ### activate(context) function signature Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference/extension.md Exported async function called by the Cursor/VS Code runtime on activation. It initializes logging, i18n, status bar, commands, and configuration listeners. Returns a Promise that resolves to void. ```TypeScript export async function activate(context: vscode.ExtensionContext) { ``` -------------------------------- ### CursorUsageResponse interface Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/types.md Type definition for the response from `GET https://cursor.com/api/usage`. Contains per-model usage buckets for `gpt-4`, `gpt-3.5-turbo`, and `gpt-4-32k`, plus `startOfMonth` as the billing cycle anchor. ```ts export interface CursorUsageResponse { 'gpt-4': { numRequests: number; numRequestsTotal: number; numTokens: number; maxRequestUsage: number; maxTokenUsage: number | null; }; 'gpt-3.5-turbo': { numRequests: number; numRequestsTotal: number; numTokens: number; maxRequestUsage: number | null; maxTokenUsage: number | null; }; 'gpt-4-32k': { numRequests: number; numRequestsTotal: number; numTokens: number; maxRequestUsage: number | null; maxTokenUsage: number | null; }; startOfMonth: string; } ``` -------------------------------- ### initializeI18n function signature Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference/i18n.md Initializes the translation system by loading language packs and setting up configuration listeners. ```ts export function initializeI18n(): void { ``` -------------------------------- ### GET https://cursor.com/api/usage?user= Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/endpoints.md Retrieves Cursor usage statistics for a given user. Requires a session token cookie and a numeric user ID as a query parameter. ```APIDOC ## GET https://cursor.com/api/usage?user= ### Description Retrieves Cursor usage statistics for the specified user, including request and token usage for different models. ### Method GET ### Endpoint https://cursor.com/api/usage?user= ### Authentication - **Cookie**: `WorkosCursorSessionToken=` (required) ### Query Parameters - **user** (string) - Required - Numeric user ID, extracted from the session token as `token.split('%3A%3A')[0]`. ### Response #### Success Response (200) - **gpt-4** (object) - Contains `numRequests`, `numRequestsTotal`, `numTokens`, `maxRequestUsage`, `maxTokenUsage` (number or null). - **gpt-3.5-turbo** (object) - Same shape as `gpt-4`, both limits nullable. - **gpt-4-32k** (object) - Same shape as `gpt-4`, both limits nullable. - **startOfMonth** (string) - Billing-cycle start date in ISO format, used as the anchor for premium/usage-based period math. #### Response Example ```json { "gpt-4": { "numRequests": 0, "numRequestsTotal": 0, "numTokens": 0, "maxRequestUsage": null, "maxTokenUsage": null }, "gpt-3.5-turbo": { "numRequests": 0, "numRequestsTotal": 0, "numTokens": 0, "maxRequestUsage": null, "maxTokenUsage": null }, "gpt-4-32k": { "numRequests": 0, "numRequestsTotal": 0, "numTokens": 0, "maxRequestUsage": null, "maxTokenUsage": null }, "startOfMonth": "2023-01-01T00:00:00.000Z" } ``` ``` -------------------------------- ### Read and update cursorStats configuration Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/configuration.md Demonstrates how to retrieve configuration values using vscode.workspace.getConfiguration and update a setting globally using config.update. ```ts import * as vscode from 'vscode'; const config = vscode.workspace.getConfiguration('cursorStats'); const interval = config.get('refreshInterval', 60); const currency = config.get('currency', 'USD'); const thresholds = config.get('usageAlertThresholds', [10, 30, 50, 75, 90, 100]); await config.update('currency', 'EUR', vscode.ConfigurationTarget.Global); ``` -------------------------------- ### createUsageProgressBar(current, limit, label = t('statusBar.usage')) Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference/progressBars.md Creates a usage progress bar string based on current consumption and limit. Returns an empty string when disabled, otherwise a formatted label and progress bar. ```APIDOC ## createUsageProgressBar(current, limit, label = t('statusBar.usage')) ### Description Creates a usage progress bar string based on current consumption and limit. Returns an empty string when disabled, otherwise a formatted label and progress bar. ### Method Function ### Signature ```ts export function createUsageProgressBar( current: number, limit: number, label: string = t('statusBar.usage'), ): string ``` ### Parameters - **current** (number) - Required - Current consumption (requests or percent) - **limit** (number) - Required - Limit; `current / limit * 100` clamped 0-100 - **label** (string) - Optional, default `t('statusBar.usage')` - Prefix label ### Return - **string** - `''` when disabled, else `` `${label}: ${createProgressBar(...)}` `` using `getProgressBarSettings()`. ``` -------------------------------- ### createPeriodProgressBar function signature Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference/progressBars.md Creates a progress bar string for a period. Accepts a date range or ISO start date, optional end date, and a label. Returns empty string when progress bars are disabled, a formatted bar with clamped percentage, or an error message when date parsing fails. ```TypeScript export function createPeriodProgressBar( startDate: string, endDate?: string, label: string = t('statusBar.period'), ): string { ``` -------------------------------- ### Error handling: getExtensionContext in try/catch Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference/extension.md Demonstrates catching the error thrown by getExtensionContext when used before activate() completes. The error message is 'Extension context not initialized'. ```ts import { getExtensionContext } from './extension'; let ctx; try { ctx = getExtensionContext(); } catch (e) { // Error: 'Extension context not initialized' // Occurs when the accessor is used before activate() completes ctx = null; } ``` -------------------------------- ### createStatusBarItem() function signature Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference/statusBar.md Creates and returns a VS Code status bar item, right-aligned with priority 100, and stores it in a module-level singleton. ```TypeScript export function createStatusBarItem(): vscode.StatusBarItem { ``` -------------------------------- ### createReportCommand registration Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference/report.md The command registration for cursor-stats.createReport, which must be imported and pushed to context.subscriptions. ```ts export const createReportCommand = vscode.commands.registerCommand('cursor-stats.createReport', async () => { ``` -------------------------------- ### UsageLimitResponse interface Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/types.md Defines the UsageLimitResponse interface with optional fields for monthly dollar limit, per-user limit, and a flag indicating usage-based pricing is disabled. Returned by getCurrentUsageLimit and consumed by checkUsageBasedStatus, statusBar.ts, the setLimit command, and CursorReport.usageLimitResponse. ```ts export interface UsageLimitResponse { hardLimit?: number; hardLimitPerUser?: number; noUsageBasedAllowed?: boolean; } ``` -------------------------------- ### createProgressBar(percentage, length?, warningThreshold?, criticalThreshold?) Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference/progressBars.md Creates a string representing an emoji-based progress bar. The bar will show filled cells with a color based on thresholds, and empty cells. The percentage is clamped to 0-100. ```APIDOC ## createProgressBar ### Description Creates an emoji-based progress bar string. The bar length is fixed, with filled cells colored by thresholds. ### Method Not applicable (utility function). ### Endpoint Not applicable (utility function). ### Parameters #### Parameters - **percentage** (number) - Required - Usage/period percentage, clamped to 0–100. - **length** (number) - Optional - Total characters (filled + empty). Default: 10. - **warningThreshold** (number) - Optional - Threshold at or above which filled cells become 🟨. Default: 75. - **criticalThreshold** (number) - Optional - Threshold at or above which filled cells become πŸŸ₯. Default: 90. ### Request Example Not applicable. ### Response #### Success Response Returns a string of length `length` composed of filled and empty emoji. Filled count is calculated as `Math.round((clampedPercentage / 100) * length)`. Filled cells use '🟩' by default, '🟨' when `percentage >= warningThreshold`, 'πŸŸ₯' when `percentage >= criticalThreshold`. Empty cells use '⬜'. #### Response Example For `createProgressBar(50)` (length 10, thresholds 75/90): `🟩🟩🟩🟩🟩⬜⬜⬜⬜⬜` ``` -------------------------------- ### checkAndNotifyUsage(usageInfo) Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference/notifications.md Shows threshold-based usage alerts for premium or usage-based usage. It checks the current usage percentage against configured thresholds and displays a warning message with appropriate actions. ```APIDOC ## checkAndNotifyUsage(usageInfo) ### Description Shows threshold-based usage alerts for premium or usage-based usage. It checks the current usage percentage against configured thresholds and displays a warning message with appropriate actions. ### Method Function call ### Signature ```ts export async function checkAndNotifyUsage(usageInfo: UsageInfo): Promise ``` ### Parameters - **usageInfo** (UsageInfo) - Required - Object with properties: percentage (number), type ('premium' | 'usage-based'), limit (number, optional), totalSpent (number, optional), premiumPercentage (number, optional). ### Return Promise ### Behavior 1. Returns if a notification is in progress or cursorStats.enableAlerts is false (default true). 2. Reads cursorStats.usageAlertThresholds (default [10, 30, 50, 75, 90, 100]) and sorts descending. 3. Usage-based gating: if type === 'usage-based' and usageInfo.premiumPercentage is provided and < 100, the notification is skipped (usage-based alerts fire only when premium requests are exhausted). 4. Computes the highest exceeded threshold; if unannounced for this type, shows showWarningMessage: - premium + percentage > 100 β†’ message notifications.usageExceededLimit, detail notifications.enableUsageBasedDetail, button notifications.enableUsageBasedTitle (runs cursor-stats.setLimit). - premium otherwise β†’ notifications.usageThresholdReached / notifications.viewSettingsDetail, button notifications.viewSettingsTitle (opens @ext:Dwtexe.cursor-stats settings; falls back to generic settings + search replace, then an error message notifications.failedToOpenSettings). - usage-based β†’ message notifications.usageBasedSpendingThreshold (with limit: limit || 0), detail notifications.manageLimitDetail, button notifications.manageLimitTitle (runs cursor-stats.setLimit). 5. Marks all thresholds <= the exceeded one as notified; conversely, thresholds above the current percentage are removed from the set (re-arming them for later in the session). ### Example ```ts import { checkAndNotifyUsage } from '../handlers/notifications'; // premium over limit β†’ allow usage-based alert await checkAndNotifyUsage({ percentage: 33.3, type: 'usage-based', limit: 50, premiumPercentage: 100 }); // premium alert at threshold await checkAndNotifyUsage({ percentage: 90, type: 'premium' }); ``` ``` -------------------------------- ### updateStats(statusBarItem) Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference/updateStats.md Performs one full refresh cycle: retrieves the token, fetches stats, computes costs, updates the status bar, and triggers notifications. ```APIDOC ## `updateStats(statusBarItem)` ### Description Performs one full refresh cycle. It retrieves the Cursor token, fetches usage stats, computes costs, updates the status bar item, and triggers notifications. ### Method Function call ### Endpoint `updateStats(statusBarItem: vscode.StatusBarItem)` ### Parameters - **statusBarItem** (`vscode.StatusBarItem`) - Required - The status bar item to update. ### Return Type `Promise` ### Pipeline 1. **Token**: `getCursorTokenFromDB()`. On `undefined`, sets text `$(alert) `, color `new vscode.ThemeColor('statusBarItem.errorBackground')`, an error tooltip (`statusBar.couldNotRetrieveToken`), shows the item, and returns early. 2. **Stats fetch with auth retry**: `fetchCursorStats(token)`; on failure, HTTP 401 β†’ re-reads the token from the DB and retries once; HTTP 403 β†’ logged as "likely CORS/origin issue, not retrying token refresh"; any failure re-throws to the outer catch. 3. **Health restore**: on success, resets the consecutive-error count and clears any active cooldown (`setCooldownStartTime(null)` + `startRefreshInterval()`). 4. **Usage-based status**: `checkUsageBasedStatus(token, stats.teamId)` in a try/catch (non-critical; 403 β†’ logged "using default disabled state"). Defaults to `{ isEnabled: false }`. 5. **Cost computation**: - Team members with `stats.isTeamSpendData` β†’ `actualTotalCost = stats.teamSpendCents / 100`. - Otherwise, sums positive `totalDollars` of `activeMonthData.usageBasedPricing.items` (current month wins when it has items or team spend is present, else last month); mid-month credits (negative values) are excluded. - `usageBasedPercent = (actualTotalCost / usageStatus.limit) * 100` only when enabled and a limit exists. 6. **Status bar text**: `` `$(graph)/[ $(credit-card) ]` `` β€” the cost suffix appears only when `actualTotalCost > 0 || useTeamSpendData`. Color via `getStatusBarColor(premiumPercent)` (premium only, never combined). 7. **Tooltip content**: premium section (used/total, percent, `fastRequestsPeriod` with localized month names), optional `teamSpend` header, detailed per-model breakdown from a direct `GET https://cursor.com/api/usage` call (labeled GPT-4 / GPT-4-32k / GPT-3.5-turbo; team-vs-individual comparison lines for team members), usage-based section (period, current usage line `(Total: X - Unpaid: Y)` when `midMonthPayment > 0`, hidden metadata line `__USD_USAGE_DATA__:` consumed by `createMarkdownTooltip`, per-item lines `β€’ ➜ ****` with model-name annotations padded to a 70-column visual width, `youHavePaid` line, `totalCost` line), and footer `lastUpdated` β€” finalized through `createMarkdownTooltip(tooltipLines, false, contentLines)` after filtering the metadata line and inserting `createSeparator(getMaxLineWidth(contentLines))`. 8. **Unknown-model detection**: for items with `modelNameForTooltip === 'unknown-model'`, extracts a candidate term from the raw description (token-based regex, `extra fast premium requests? ()`, `^(\d+)\s+(.+?)( request| calls)?...`, simple-fallback), strips suffixes (`requests|beyond|*|per|usage`), filters generic keywords (month names, `usage`, `calls`, `premium`, `tool`, `fast`, `thinking` …) and near-duplicates, then accumulates into `detectedUnknownModels`. 9. **Notifications** (each after a 1 s `setTimeout`): when usage-based is enabled β€” premium `checkAndNotifyUsage`, and usage-based `checkAndNotifyUsage` **only if `premiumPercent >= 100`** (with `limit` and `premiumPercentage`), and `checkAndNotifyUnpaidInvoice` when `activeMonthData.usageBasedPricing.hasUnpaidMidMonthInvoice`; plus `checkAndNotifySpending(actualTotalCost)` (also 1 s later) when enabled. When disabled β€” only the premium usage alert. 10. **Unknown-model notification**: once per session, `showInformationMessage(notifications.unknownModelsDetected)` with actions `commands.createReport` (runs `cursor-stats.createReport`) and `commands.openGitHubIssues`. ### Error Contract The outer catch increments the consecutive-error count and logs `[Critical] API error: `; the error state (and any cooldown restart) is driven by [cooldown.md](cooldown.md) β€” the catch itself does not start the cooldown, it only counts failures. ### Example ```ts import { updateStats } from '../utils/updateStats'; const item = vscode.window.createStatusBarItem(vscode.StatusBarAlignment.Right, 100); await updateStats(item); // full refresh: token β†’ stats β†’ tooltip β†’ notifications ``` ``` -------------------------------- ### createPeriodProgressBar(startDate, endDate?, label?) Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference/progressBars.md Creates a progress bar string for a given period, showing elapsed time as a percentage. Handles date ranges and ISO dates, with optional weekend exclusion. ```APIDOC ## createPeriodProgressBar(startDate, endDate?, label?) ### Description Creates a progress bar string for a given period, showing elapsed time as a percentage. Handles date ranges and ISO dates, with optional weekend exclusion. ### Method Function ### Signature ```ts export function createPeriodProgressBar( startDate: string, endDate?: string, label: string = t('statusBar.period'), ): string ``` ### Parameters - **startDate** (string) - Required - Either a full range `"17 April - 17 May"` (split on `-`) or an ISO date - **endDate** (string) - Optional - Only used for ISO-format start dates; otherwise derived from the range - **label** (string) - Optional, default `t('statusBar.period')` - Prefix label ### Return Value - **string** - Returns: - `''` (empty string) when `shouldShowProgressBars()` is false. - `${label}: ${progressBar}` where the percentage is `Math.min(100, Math.max(0, (elapsedDays / totalDays) * 100))` β€” clamped 0–100. - `${label}: ${t('progressBar.errorParsingDates')}` when date parsing throws (errors are `console.error` logged). ### Date Handling - Ranges are parsed with `getMonthNumber` on the month token; year-boundary ranges shift the end date into the next year. - ISO start dates use `endDate ?? getEndOfPeriod(start)` (`getEndOfPeriod` is private: start + 1 month βˆ’ 1 day). - With `cursorStats.excludeWeekends`, totals use the private `calculateWeekdays` (Mon–Fri inclusive). ### Example ```ts const bar = createPeriodProgressBar('17 April - 17 May'); ``` ``` -------------------------------- ### getProgressBarSettings() Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference/progressBars.md Returns the current progress bar settings, including bar length and warning/critical thresholds, derived from cursorStats configuration. ```APIDOC ## getProgressBarSettings() ### Description Returns the current progress bar settings, including bar length and warning/critical thresholds, derived from cursorStats configuration. ### Method Function ### Signature ```ts export function getProgressBarSettings(): ProgressBarSettings ``` ### Parameters None ### Return Value - **ProgressBarSettings** - An object with the following properties: - `barLength` (number) - Default 10, from `cursorStats.progressBarLength` - `warningThreshold` (number) - Default 75, from `cursorStats.progressBarWarningThreshold` - `criticalThreshold` (number) - Default 90, from `cursorStats.progressBarCriticalThreshold` ### Example ```ts const settings = getProgressBarSettings(); ``` ``` -------------------------------- ### UsageItem interface Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/types.md Defines the shape of a usage item returned by fetchMonthData. calculation is a padded display string, totalDollars is a formatted cost (negatives represent credits), description is the raw invoice item, modelNameForTooltip is the extracted model or the sentinel t('statusBar.unknownModel'), and isDiscounted is true when the description contains 'discounted'. ```ts export interface UsageItem { calculation: string; totalDollars: string; description?: string; modelNameForTooltip?: string; isDiscounted?: boolean; } ``` -------------------------------- ### getExtensionContext() function signature Source: https://github.com/dwtexe/cursor-stats/blob/master/_autodocs/api-reference/extension.md Exported function that returns the extension context singleton. Throws an error if called before activation. ```TypeScript export function getExtensionContext(): vscode.ExtensionContext { ```