Skip to content

src/credits.ts

33 lines · 1.3 KB · TypeScript
Raw
import { readCredits, type CreditsSummary } from './credits-core.ts'
import { AudibleApiError, sendAudible } from './request.ts'

/**
 * The one fixed, read-only account call this package makes for credits. No
 * caller picks the path or the query. Without `source=Credit`, Audible
 * ignores the response groups.
 */
export const CREDITS_PATH = '/1.0/account/information'
export const CREDITS_QUERY = { response_groups: 'customer_benefits,plan_summary,subscription_details', source: 'Credit' }

/**
 * Read the connected account's Audible credit balance, when Audible reports
 * it, and the plan's next charge. Read-only; returns numbers, a date, and key
 * paths, never account details.
 *
 * @returns credits, nextCharge, fieldPaths, and numbers
 *
 * @example
 * import readAccountCredits from 'kody:@danj/audible-auth/credits'
 *
 * const { credits, nextCharge } = await readAccountCredits()
 * // nextCharge: { date: '2026-10-15', credits: 1, cents: 1495, currency: 'CAD' }
 */
export default async function readAccountCredits(): Promise<CreditsSummary> {
	try {
		return readCredits(await sendAudible('GET', CREDITS_PATH, CREDITS_QUERY, undefined))
	} catch (error) {
		// Drop Audible's error body: it could echo account details.
		if (error instanceof AudibleApiError) throw new Error(`Audible credits → HTTP ${error.status}`)
		throw error
	}
}