npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@baseworks/billing

v1.5.0

Published

Billing capability: typed HTTP client, event catalog, projections, and CLI plugin for billing-service (usage-based billing: metrics, plans, subscriptions, usage). Contract-first, versioned with the service.

Readme

@baseworks/billing

Typed client, event catalog, projections, and CLI plugin for billing-service — the per-org usage-based billing core (metrics, plans, subscriptions). Contract-first, versioned with the service.

pnpm add @baseworks/billing

Client

Everything is org-scoped (X-Org-Id + token). Money is integer cents throughout. The wire is snake_case (0.4.0, workspace ADR 0003): options, inputs and everything the service answers. A service calling this on behalf of a request passes the request's realm token (c.get('realm_token')), never the raw Authorization header.

import { createBillingClient } from '@baseworks/billing'

const billing = createBillingClient({
  base_url: process.env.BILLING_SERVICE_URL!,
  token:    realmToken,
  org_id:   activeOrgId,
})

// 1. a billable metric
const apiCalls = await billing.createMetric({
  code: 'api_calls', name: 'API calls', aggregation: 'sum', unit: 'request',
})

// 2. a plan — base fee + per-metric usage charges (all integer cents)
const pro = await billing.createPlan({
  code: 'pro', name: 'Pro', currency: 'USD',
  base_amount_cents: 4900,                                       // $49.00 / month
  charges: [{ metric_code: 'api_calls', unit_amount_cents: 2 }], // $0.02 / call
})

// 3. subscribe a customer (customer_id is a customers-service ref — validated,
//    name snapshotted). Opens a one-month billing period.
const sub = await billing.createSubscription({ customer_id: 'acct-42', plan_id: 'pro' })

await billing.listSubscriptions({ status: 'active' })
await billing.getSubscription(sub.id)

// 4. meter usage — idempotent by transaction_id (re-sending is a no-op)
await billing.recordUsage({ subscription_id: sub.id, metric_code: 'api_calls', quantity: 100, transaction_id: 'req-1' })
await billing.recordUsage({ subscription_id: sub.id, metric_code: 'api_calls', quantity: 250, transaction_id: 'req-2' })
await billing.listUsage({ subscription_id: sub.id })

// 5. rate the current period — base fee + Σ(aggregated usage × charge). No invoice.
const rating = await billing.rateSubscription(sub.id)
// → { base_amount_cents: 4900, lines: [{ metric_code: 'api_calls', quantity: 350, amount_cents: 700 }], total_cents: 5600 }

// 6. close the period → finalized invoice (idempotent + resumable + locked).
//    Re-running is safe: one invoice per subscription-period. `force` closes the
//    current period even before it ends (a real cron omits it and closes on due).
const report = await billing.closePeriods({ subscription_id: sub.id, force: true })
// → { locked: true, closed: [{ subscription_short_id, invoice_number, total_cents, status: 'closed' }], skipped: [] }

await billing.cancelSubscription(sub.id, 'downgraded')

Errors throw BillingError (.status, .code): 409 code_taken, 400 unknown_metric (charge/usage references a missing metric), 404 customer_not_found, 404 plan_not_found, 404 subscription_not_found, 409 already_canceled, 409 subscription_canceled (usage on a canceled sub), 403 forbidden with permission (the action org-service says the caller lacks: billing.read, .subscribe, .meter, .configure, .close).

Dates (1.5.0)

await billing.recordUsage({ subscription_id: sub.id, metric_code: 'api_calls', quantity: 5, transaction_id: 'req-9',
  occurred_at: '2027-01-31T23:50:00Z' })             // or epoch ms; default now. It chooses the period
await billing.listUsage({ subscription_id: sub.id, from: '2027-01-01', to: '2027-01-31' })   // by occurred_at
const r = await billing.closePeriods({ due_date: '2027-02-14' })
// every ended period, oldest first; each entry has display_number, and a refused one reason + message
r.closed.filter((e) => e.date_shifted_from)          // dated later than the day it belongs to: the series was already there

A closed period refuses usage (period_closed); more than 5 minutes ahead is occurred_at_in_future. Invoices are dated the period's last day (a fee in advance: its first; an immediate cancel: that day), or the series' latest date when that is later (date_shifted_from; a fee's own invoice: fee_date_shifted_from). CLI: billing usage record --occurred-at <instant>, billing usage ls --from 2027-01-01 --to 2027-01-31, billing close --due-date 2027-02-14. Needs billing-service 1.5.0 and invoice-service 2.0.0; an older billing-service ignores occurred_at and due_date.

Anchors, included usage, advance fees and cancel (1.4.0)

await billing.createPlan({
  code: 'hobby', name: 'Hobby', currency: 'EUR', base_amount_cents: 500,
  included_usage_cents: 500, bill_base: 'advance', product_id: 'prod_hobby',
  charges: [{ metric_code: 'compute', unit_amount_cents: 1 }, { metric_code: 'ipv4', unit_amount_cents: 300, draws_on_included: false }],
})
const s = await billing.createSubscription({ customer_id: 'acct-42', plan_id: 'hobby', billing_anchor_day: 1 })  // or start_date: '2026-10-15'
s.warning                                                        // set when the first advance fee was not invoiced
await billing.cancelSubscription(s.id, 'moving', { at_period_end: true })
await billing.resumeSubscription(s.id)                           // before the period ends
const due = await billing.listRefunds({ status: 'due' })         // billing.refund.read
await billing.settleRefund(due[0]!.id, 'bank ref 42')            // billing moves no money

Anchors and dates are UTC. Cancelling at once is a member's only in the withdrawal window (14 days from the start by default, once per customer per year), where no fee is charged and an advance fee becomes a refund due; later it is 403 forbidden without billing.subscription.manage. Cancel-at-period-end changes are limited (429 too_many_changes).

An immediate cancelSubscription invoices the current period up to today (invoice_failed: nothing was canceled). New plan codes match ^[a-z0-9][a-z0-9_-]{1,39}$ and are not shaped like a short id (bad_code).

A downgrade (changeSubscriptionPlan to a lower base price or another currency) waits for the period to end: the answer has pending_plan_code and pending_plan_at. { effective: 'now' } (billing subscriptions plan <ref> <plan> --now) applies it at once and needs billing.subscription.manage.

CLI also: billing subscriptions resume <ref>, billing refunds ls [--status due], billing refunds settle <id> --note <n>.

CLI: billing plans create … --included 5.00 --bill-base advance --product <id> --flat-charge ipv4:3.00 --charge-product compute=<id>, billing subscriptions create … --anchor-day 1 | --start-date 2026-10-15, billing subscriptions cancel <ref> --at-period-end.

A subscription's invoices and paging (1.3.0)

await billing.listSubscriptionInvoices(sub.id, { expand: 'invoice' })
await billing.attachSubscriptionInvoice(sub.id, { invoice_id: 'inv_1', period_start: '2026-11-01' })  // billing.invoice.attach
const page = await billing.listPlansPage({ limit: 100 })   // page.next_offset: null on the last page

period_start is a period billing closed, the current one, or one of the 60 months before the first period (for invoices from before the subscription was in billing): its start in epoch ms, or any date inside it (UTC, YYYY-MM-DD).

CLI: billing subscriptions invoices <ref> [--expand], billing subscriptions attach <ref> 2026-11-01=inv_1 2026-12-01=inv_2. Every billing_list_* MCP tool takes limit (default 100, max 500) and cursor, and returns next.

Archiving and exact prices (1.2.0)

await billing.archivePlan('old')        // = deletePlan: hidden from lists and new subscriptions; its subscriptions keep it and are still rated
await billing.archiveMetric('cpu')      // = deleteMetric: 409 metric_in_use (BillingError, with the plans in the body) while a live plan charges for it
await billing.listPlans({ include_archived: true })   // also listMetrics({ include_archived: true }); every plan/metric has `archived`

// 1.00 per 21 900 RU-minutes: an exact price per N units. Give unit_amount_cents OR unit_price, never both.
await billing.createPlan({ code: 'ru', name: 'RU', currency: 'USD', charges: [
  { metric_code: 'ru_minutes', unit_price: { amount_cents: 100, per_units: 21_900 } },
  { metric_code: 'api_calls', unit_amount_cents: 2 },                       // whole cents per unit, as before
] })
// rating: { metric_code, quantity: 657000, unit_price: { amount_cents: 100, per_units: 21900 },
//           unit_price_text: '1.00 USD per 21900 ru_minutes', unit_amount_cents: 0, amount_cents: 3000 }

A line is quantity × price computed exactly and rounded half up to whole cents, once; unit_amount_cents on a charge is the price of one unit rounded for display, never used to rate. The CLI takes --charge metric:price/per_units (ru_minutes:1.00/21900). New types: UnitPrice; archived on Metric and Plan. See the service README for the rules.

Limits (1.1.0)

Plans carry limits and subscriptions limits + limits_override: Limits = Record<string, number | null> (keys ^[a-z][a-z0-9_]{0,31}$, at most 32; non-negative integers; null = unlimited; an absent key = the product decides). billing stores and answers, it enforces nothing.

await billing.createPlan({ code: 'team', name: 'Team', currency: 'EUR', limits: { projects: 5, seats: 10 } })
await billing.setPlanLimits('team', { projects: 9, seats: null })      // replaces the whole map; {} clears; needs billing.configure
await billing.updatePlan('team', { limits: { projects: 9 } })          // the same, through updatePlan
await billing.setSubscriptionLimits(sub.id, { seats: 50 })             // one customer's deal; null clears
const s = await billing.getSubscription(sub.id)
// s.limits          → the plan's current limits with the override over them, per key
// s.limits_override → { seats: 50 }

A bad shape throws BillingError 400 bad_limits and nothing is stored. A plan change reaches its subscriptions at once.

Deprecated names (0.3 → 0.4)

Until 0.4.0 the wire was camelCase. Every camelCase name the client exposed stays, deprecated, so a service that has not moved still builds and runs; they go when the last caller has moved (stripe-service, apps/cli).

| Where | Old (deprecated) | New | |---|---|---| | options | baseUrl, orgId | base_url, org_id | | inputs (renamed to snake_case before sending; the new name wins when both are given) | customerId, planId, baseAmountCents, metricCode, unitAmountCents (in a plan's charges), subscriptionId, transactionId (recordUsage; subscriptionId also in listUsage), providerRef, planCode, currentPeriodStart, currentPeriodEnd, cancelAtPeriodEnd, endedReason (reconcileProviderSubscription), subscriptionId, asOf, dueAt (closePeriods) | the same in snake_case | | metric answers | shortId, createdAt, updatedAt | short_id, created_at, updated_at | | plan answers | shortId, baseAmountCents, createdAt, updatedAt; charges: metricCode, unitAmountCents | snake_case | | subscription answers | shortId, customerId, customerName, planId, planCode, providerRef, cancelAtPeriodEnd, endedReason, currentPeriodStart, currentPeriodEnd, startedAt, createdAt, updatedAt | snake_case | | usage answers | subscriptionId, metricCode, transactionId, createdAt | snake_case | | rating answers | subscriptionId, planCode, periodStart, periodEnd, baseAmountCents, totalCents; lines: metricCode, unitAmountCents, amountCents | snake_case | | close report entries | subscriptionId, subscriptionShortId, invoiceId, invoiceNumber, totalCents | snake_case |

On answers the old names are non-enumerable getters of the snake_case field: sub.planCode reads, while JSON.stringify(sub) and toEqual see the snake_case object only. The types carry them @deprecated. Method names are unchanged. The GraphQL schema stays camelCase (that contract's own), with resolvers over the snake_case data.

A client 0.4.0 needs billing-service 0.4.0 (it sends and reads snake_case). Deploy the service first.

CLI plugin

import { buildBillingCommand } from '@baseworks/billing/cli'

program.addCommand(buildBillingCommand({ http, cliName: 'dtab' }))
// dtab billing | bill
//   metrics|metric        ls · create · get · update · delete
//   plans|plan            ls · create (--base, --charge metric:price) · get · update · delete
//   subscriptions|subs    ls (--status, --customer) · create (--customer <ref> --plan <code> [--collection]) · plan · get · cancel
//   usage                 record (--subscription --metric --quantity --txn) · ls · rate
//   close                 [--subscription <ref>] [--force] [--due-in <days> | --due-date <day>]

MCP tools

@baseworks/billing/mcp exports billingTools(), the tools a model would use, for an MCP server built with @baseworks/mcp (@modelcontextprotocol/sdk is an optional peer dependency):

import { composeTools } from '@baseworks/mcp'
import { billingTools } from '@baseworks/billing/mcp'

composeTools(customersTools(), invoiceTools(), billingTools())
// ctx.clients.billing is a BillingClient built from the realm token

| Tool | Access | Permission | |---|---|---| | billing_list_metrics, billing_list_plans, billing_get_plan, billing_list_subscriptions, billing_get_subscription, billing_list_usage, billing_list_subscription_invoices, billing_rate_subscription | read | billing.read | | billing_attach_subscription_invoices | write | billing.invoice.attach | | billing_create_subscription, billing_change_plan, billing_cancel_subscription | write | billing.subscribe | | billing_record_usage | write | billing.meter | | billing_create_metric, billing_create_plan, billing_update_plan, billing_archive_metric, billing_archive_plan, billing_set_plan_limits, billing_set_subscription_limits | write | billing.configure | | billing_close_periods | write | billing.close |

Each tool is a thin wrapper over the client, so it can never do what the API would refuse; permission is the name the service registered with org-service, used to hide a tool from somebody who may not use it. What only a payment provider may report has no tool.

Service integration

import { PROJECTIONS, POLICIES } from '@baseworks/billing/projections'
import { MetricEvents, PlanEvents, SubscriptionEvents, UsageEvents, CloseEvents } from '@baseworks/billing/events'

Payload fields are snake_case since 0.4.0; the projections fold the camelCase events written before it (foldbase reads a snake_case path from a camelCase payload). Projections metrics → read_metrics, plans → read_plans, subscriptions → read_subscriptions, usage → read_usage, closes → read_closes. Tenant = org id. Usage streams are keyed by sha256(subscription_id:transaction_id) and close markers by sha256(close:subscription_id:period) — the read-model row collapses duplicates, so dedup (and one-invoice-per-period) holds even if two runs race.

See also

Service: projects/billing-service · ADR-010 · ADR-011.