@hjam91/billing 0.12.0 → 0.14.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/README.md CHANGED
@@ -77,6 +77,19 @@ for (const o of await billing.offers(orgId)) {
77
77
  discount on the account's own live discounted subscriptions so the next invoice is full price, and answers the
78
78
  account status (`support` scope, like `cancel`; 404 `discount_not_found` when there is none, 409
79
79
  `operation_in_progress` under a pending plan change). The code or offer itself is untouched.
80
+ - Admin, since 0.13.0: `grantFreeMonths(accountId, {idempotencyKey, months?, reason?})` gives the account's own paying
81
+ monthly subscription free renewals (100% off from now; it stays active; rewards add up; a retried key answers the
82
+ first grant) and answers a `FreeMonthsGrant` (`support` scope; 409 `no_subscription` → give a trial instead,
83
+ `subscription_ending`, `interval_not_supported`, `idempotency_key_reused`). `freeMonths(accountId)` lists the grants
84
+ (`read`). `AccountStatus.first_paid_at` says when the account first paid real money (absent = never).
85
+ - Since 0.14.0: `billing.setExternalSubscription(accountId, source, {eventId, plan, status, periodEnd, …})` reports a
86
+ subscription bought outside Stripe (`source` 'app_store', 'play_store', …): idempotent per `eventId`, an older
87
+ `eventAt` changes nothing; it answers the status with `outcome` ('applied' | 'stale' | 'replayed').
88
+ `clearExternalSubscription(accountId, source)` forgets it. Entitlement is the best of Stripe and the stores (a store
89
+ subscription never overrides one Stripe grants); apps that report them get `Entitlement.billing_source`,
90
+ `AccountStatus.source` and `external_subscriptions`. Admin: `externalSubscriptions({source?, status?, accountId?})`
91
+ (`read`). The `subscription.renewal_upcoming` event (opt in via `event_types`; `renewal_notice_days`, default 7) carries
92
+ `RenewalUpcomingData`.
80
93
  - `billingRoutes` (Hono) adds `GET /offers`, `POST /discount {code, plan?}`, `POST /accept-offer {offer_id}`, and
81
94
  `discount_code` / `offer_id` on `POST /checkout`; a refused code answers its `reason`.
82
95
 
package/dist/admin.d.ts CHANGED
@@ -13,7 +13,7 @@
13
13
  * Every method throws BillingError on failure (nothing here fails open: these
14
14
  * are actions and owner reads, not entitlement checks).
15
15
  */
16
- import type { AccountStatus, DiscountView, OfferAudience } from './types.js';
16
+ import type { AccountStatus, DiscountView, ExternalStatus, ExternalSubscriptionView, FreeMonthsGrant, OfferAudience } from './types.js';
17
17
  export interface BillingAdminOptions {
18
18
  baseUrl: string;
19
19
  appId: string;
@@ -330,6 +330,32 @@ export interface BillingAdmin {
330
330
  removeDiscount(accountId: string, params?: {
331
331
  subscriptionId?: string;
332
332
  }): Promise<AccountStatus>;
333
+ /**
334
+ * Free months on the account's OWN paying monthly subscription (a referral reward): the next `months` (default 1,
335
+ * at most 12) renewals are invoiced at 0 and it stays active; rewards add up. Idempotent per `idempotencyKey` (a
336
+ * retry answers the first grant, `replayed: true`). 409 no_subscription (give a trial instead: setTrial),
337
+ * subscription_ending, interval_not_supported, operation_in_progress, idempotency_key_reused. Support scope; since 0.13.0.
338
+ */
339
+ grantFreeMonths(accountId: string, params: {
340
+ idempotencyKey: string;
341
+ months?: number;
342
+ reason?: string;
343
+ }): Promise<FreeMonthsGrant>;
344
+ /** The account's free-month grants, newest first (read; since 0.13.0). */
345
+ freeMonths(accountId: string): Promise<{
346
+ grants: FreeMonthsGrant[];
347
+ }>;
348
+ /** External (store) subscriptions the app reported, newest change first (read; since 0.14.0). Default limit 100, at most 500. */
349
+ externalSubscriptions(opts?: {
350
+ source?: string;
351
+ status?: ExternalStatus;
352
+ accountId?: string;
353
+ limit?: number;
354
+ }): Promise<{
355
+ external_subscriptions: Array<ExternalSubscriptionView & {
356
+ account_id: string;
357
+ }>;
358
+ }>;
333
359
  }
334
360
  export declare function createBillingAdmin(opts: BillingAdminOptions): BillingAdmin;
335
361
  export {};
package/dist/admin.js CHANGED
@@ -112,6 +112,24 @@ export function createBillingAdmin(opts) {
112
112
  })).offer,
113
113
  redemptions: (o = {}) => call('GET', `/redemptions${o.accountId ? `?account=${enc(o.accountId)}` : ''}`),
114
114
  removeDiscount: (accountId, p = {}) => call('POST', `/accounts/${enc(accountId)}/discount/remove`, p.subscriptionId ? { subscription_id: p.subscriptionId } : {}),
115
+ grantFreeMonths: (accountId, p) => call('POST', `/accounts/${enc(accountId)}/free-months`, {
116
+ idempotency_key: p.idempotencyKey,
117
+ ...(p.months !== undefined ? { months: p.months } : {}),
118
+ ...(p.reason !== undefined ? { reason: p.reason } : {}),
119
+ }),
120
+ freeMonths: (accountId) => call('GET', `/accounts/${enc(accountId)}/free-months`),
121
+ externalSubscriptions: (o = {}) => {
122
+ const q = new URLSearchParams();
123
+ if (o.source)
124
+ q.set('source', o.source);
125
+ if (o.status)
126
+ q.set('status', o.status);
127
+ if (o.accountId)
128
+ q.set('account', o.accountId);
129
+ if (o.limit)
130
+ q.set('limit', String(o.limit));
131
+ return call('GET', `/external-subscriptions${q.size ? `?${q}` : ''}`);
132
+ },
115
133
  purchases: (accountId) => call('GET', `/accounts/${enc(accountId)}/purchases`),
116
134
  refundPurchase: (accountId, purchaseId, o) => call('POST', `/accounts/${enc(accountId)}/purchases/${enc(purchaseId)}/refund`, o),
117
135
  invoices: (accountId, o = {}) => call('GET', `/accounts/${enc(accountId)}/invoices${o.limit ? `?limit=${o.limit}` : ''}`),
package/dist/index.d.ts CHANGED
@@ -29,7 +29,7 @@
29
29
  import { type CacheStore } from './cache.js';
30
30
  import { type UsageRecord, type UsageStatus, type UsageStore } from './usage.js';
31
31
  export { memoryUsageStore, d1UsageStore, USAGE_QUEUE_SCHEMA, type UsageRecord, type UsageStatus, type UsageStore, type UsageDatabase } from './usage.js';
32
- import type { AccountInput, AccountStatus, Balances, ChangePreview, CheckResult, DiscountCheck, EntitlementResult, Lock, OfferView, PlanChange, PublicPlan, TrackResult, UpsertResult, UsageSettingsInput } from './types.js';
32
+ import type { AccountInput, AccountStatus, Balances, ExternalSubscriptionInput, ChangePreview, CheckResult, DiscountCheck, EntitlementResult, Lock, OfferView, PlanChange, PublicPlan, TrackResult, UpsertResult, UsageSettingsInput } from './types.js';
33
33
  export * from './types.js';
34
34
  export { BillingError, isOutage, killSignal } from './errors.js';
35
35
  export { type BillingConfig, type ConfigChange, type ConfigPushResult, type PlanSpec, type PriceSpec, defineConfig, formatChanges } from './config.js';
@@ -266,6 +266,15 @@ export interface Billing {
266
266
  }): Promise<AccountStatus>;
267
267
  /** Declares that `coveredBy` pays for `accountId` (null removes it). */
268
268
  setCoverage(accountId: string, coveredBy: string | null): Promise<AccountStatus>;
269
+ /**
270
+ * Reports the account's subscription bought outside Stripe — `source` 'app_store', 'play_store' or another store
271
+ * name — e.g. from your RevenueCat webhook (since 0.14.0). Idempotent per `eventId`; an older event than the one
272
+ * applied changes nothing. Entitlement takes the best of Stripe and the stores: a store subscription never overrides
273
+ * one Stripe grants. Answers the status with `outcome`; refreshes the cache. Throws BillingError (an action).
274
+ */
275
+ setExternalSubscription(accountId: string, source: string, sub: ExternalSubscriptionInput): Promise<AccountStatus>;
276
+ /** Forgets the account's subscription at that store (e.g. the store account was unlinked). Since 0.14.0. */
277
+ clearExternalSubscription(accountId: string, source: string): Promise<AccountStatus>;
269
278
  /**
270
279
  * May the account use the feature (since 0.5.0)? NEVER throws. A boolean feature is answered from a
271
280
  * fresh cached entitlement when there is one; otherwise POST /v1/check. When the service is down:
package/dist/index.js CHANGED
@@ -660,6 +660,27 @@ export function createBilling(opts) {
660
660
  await cache.delete(key(accountId)).catch(() => undefined);
661
661
  return s;
662
662
  },
663
+ async setExternalSubscription(accountId, source, x) {
664
+ const t = (v) => (v instanceof Date ? v.toISOString() : v);
665
+ const body = { event_id: x.eventId, plan: x.plan, status: x.status };
666
+ const opt = [
667
+ ['event_at', t(x.eventAt)], ['period_start', t(x.periodStart)], ['period_end', t(x.periodEnd)], ['grace_ends_at', t(x.graceEndsAt)],
668
+ ['will_renew', x.willRenew], ['product_id', x.productId], ['external_id', x.externalId], ['amount', x.amount],
669
+ ['currency', x.currency], ['interval', x.interval], ['interval_count', x.intervalCount], ['sandbox', x.sandbox],
670
+ ];
671
+ for (const [k, v] of opt)
672
+ if (v !== undefined)
673
+ body[k] = v;
674
+ const s = await call('PUT', `/v1/accounts/${enc(accountId)}/external-subscriptions/${enc(source)}`, body);
675
+ // Accounts it covers may have changed too: they read fresh next time.
676
+ await cache.delete(key(accountId)).catch(() => undefined);
677
+ return s;
678
+ },
679
+ async clearExternalSubscription(accountId, source) {
680
+ const s = await call('DELETE', `/v1/accounts/${enc(accountId)}/external-subscriptions/${enc(source)}`);
681
+ await cache.delete(key(accountId)).catch(() => undefined);
682
+ return s;
683
+ },
663
684
  };
664
685
  return self;
665
686
  }
package/dist/types.d.ts CHANGED
@@ -32,6 +32,12 @@ export interface Entitlement {
32
32
  * (balances included). Apps without features never get this field.
33
33
  */
34
34
  features?: Record<string, FeatureEntry>;
35
+ /**
36
+ * Since 0.14.0, only for apps that report external (store) subscriptions: where the verdict's subscription is
37
+ * billed — 'stripe', the store ('app_store', 'play_store', …) — or null (exempt, local trial, prelaunch, none).
38
+ * Covered accounts carry their payer's. (Not `source`: that is the SDK's cache / live marker.)
39
+ */
40
+ billing_source?: string | null;
35
41
  }
36
42
  /** Since 0.5.0. */
37
43
  export type FeatureType = 'boolean' | 'metered' | 'static' | 'credit_system';
@@ -196,7 +202,9 @@ export interface UsageSettingsInput {
196
202
  export interface UsageEvent {
197
203
  id: string;
198
204
  /** 0.6 usage events, and (since 0.7.0, only the types the app chose in event_types) lifecycle events. */
199
- type: 'usage.threshold_reached' | 'balance.low' | 'topup.succeeded' | 'topup.failed' | 'subscription.created' | 'subscription.updated' | 'subscription.canceled' | 'subscription.plan_changed' | 'trial.will_end' | 'invoice.paid' | 'invoice.payment_failed' | 'invoice.payment_action_required';
205
+ type: 'usage.threshold_reached' | 'balance.low' | 'topup.succeeded' | 'topup.failed' | 'subscription.created' | 'subscription.updated' | 'subscription.canceled' | 'subscription.plan_changed' | 'trial.will_end' | 'invoice.paid' | 'invoice.payment_failed' | 'invoice.payment_action_required'
206
+ /** Since 0.14.0: `data` is a RenewalUpcomingData. */
207
+ | 'subscription.renewal_upcoming';
200
208
  created: string;
201
209
  app_id: string;
202
210
  account_id: string;
@@ -446,6 +454,111 @@ export interface AccountStatus {
446
454
  created_at?: string | null;
447
455
  /** Only on auto-renew / cancel answers. Since 0.4.0. */
448
456
  results?: SubscriptionResult[];
457
+ /** When this account first paid an invoice with money in it (ISO); absent = never. Since 0.13.0. */
458
+ first_paid_at?: string | null;
459
+ /**
460
+ * Since 0.14.0, only for apps that report external subscriptions: where the access is billed ('stripe', a store
461
+ * name, or null) — the same as entitlement.billing_source — and the store rows the app reported for this account.
462
+ * `has_subscription`, `subscription` and `can_manage` stay about Stripe (the store manages its own).
463
+ */
464
+ source?: string | null;
465
+ external_subscriptions?: ExternalSubscriptionView[];
466
+ /** Only on setExternalSubscription answers: what the report did. Since 0.14.0. */
467
+ outcome?: 'applied' | 'stale' | 'replayed';
468
+ /** Only on clearExternalSubscription answers. Since 0.14.0. */
469
+ deleted?: boolean;
470
+ }
471
+ /** Store statuses an external subscription can report (since 0.14.0). */
472
+ export type ExternalStatus = 'active' | 'trialing' | 'in_grace' | 'billing_issue' | 'canceled' | 'expired' | 'refunded' | 'paused';
473
+ /**
474
+ * setExternalSubscription input (since 0.14.0): the store's latest word about the account's subscription there.
475
+ * Dates are ISO strings, Dates or epoch milliseconds.
476
+ */
477
+ export interface ExternalSubscriptionInput {
478
+ /** The store event's id (e.g. RevenueCat's event id): a retry with the same id is answered without writing. */
479
+ eventId: string;
480
+ /** When the store event happened; an event older than the one applied changes nothing (outcome 'stale'). Default now. */
481
+ eventAt?: string | Date | number;
482
+ /** The app's plan key this subscription stands for (features and plan limits follow it). */
483
+ plan: string;
484
+ status: ExternalStatus;
485
+ /** Required except for expired / refunded / paused. */
486
+ periodEnd?: string | Date | number | null;
487
+ periodStart?: string | Date | number | null;
488
+ /** The store's own grace end (in_grace / billing_issue). Without it the app's payment_failed grace counts from periodEnd. */
489
+ graceEndsAt?: string | Date | number | null;
490
+ /** Default: true for active / trialing / in_grace / billing_issue. */
491
+ willRenew?: boolean;
492
+ productId?: string;
493
+ /** The store's subscription / original transaction id. */
494
+ externalId?: string;
495
+ /** Minor units per interval, as the store charges it (before its fee); with `currency`. For the owner's MRR. */
496
+ amount?: number;
497
+ currency?: string;
498
+ interval?: 'day' | 'week' | 'month' | 'year';
499
+ intervalCount?: number;
500
+ /** Store sandbox (TestFlight, App Review): grants access, never counted as revenue. */
501
+ sandbox?: boolean;
502
+ }
503
+ /** One external (store) subscription as the status shows it (since 0.14.0). */
504
+ export interface ExternalSubscriptionView {
505
+ source: string;
506
+ plan: string;
507
+ product_id: string | null;
508
+ external_id: string | null;
509
+ status: ExternalStatus;
510
+ /** True while it grants access by itself (its dates and status; Stripe aside). */
511
+ grants_access: boolean;
512
+ will_renew: boolean;
513
+ period_start: string | null;
514
+ period_end: string | null;
515
+ grace_ends_at: string | null;
516
+ amount: number | null;
517
+ currency: string | null;
518
+ interval: string | null;
519
+ interval_count: number | null;
520
+ sandbox: boolean;
521
+ last_event_id: string;
522
+ last_event_at: string | null;
523
+ updated_at: string | null;
524
+ }
525
+ /** `data` of a subscription.renewal_upcoming event (since 0.14.0). */
526
+ export interface RenewalUpcomingData {
527
+ /** 'stripe' or the store the app reported. */
528
+ source: string;
529
+ /** The service's subscription id (sub_row_…); null for a store subscription. */
530
+ subscription_id: string | null;
531
+ product_id?: string | null;
532
+ plan: string | null;
533
+ quantity: number;
534
+ interval: string | null;
535
+ interval_count: number | null;
536
+ /** What the renewal charges, minor units before tax (Stripe: price × quantity less a discount still running); null if unknown. */
537
+ amount: number | null;
538
+ currency: string | null;
539
+ renews_at: string;
540
+ covers_account_id: string | null;
541
+ }
542
+ /** POST /admin/apps/:app/accounts/:id/free-months (admin.grantFreeMonths). Since 0.13.0. */
543
+ export interface FreeMonthsGrant {
544
+ /** The next N monthly renewals are invoiced at 0 (no charge, no tax); the subscription stays active. */
545
+ kind: 'free_invoices';
546
+ account_id: string;
547
+ subscription_id: string;
548
+ /** Months this grant added. */
549
+ months: number;
550
+ /** Free renewals now pending on the subscription (this grant plus earlier unused ones). */
551
+ free_months_total: number;
552
+ /** What one month is worth before tax and other discounts, minor units (an estimate). */
553
+ value_per_month: number | null;
554
+ currency: string | null;
555
+ /** End of the last free period (an estimate). */
556
+ free_until: string | null;
557
+ reason: string | null;
558
+ idempotency_key: string;
559
+ created_at: string;
560
+ /** True when a retried idempotency key answered the stored first grant. */
561
+ replayed: boolean;
449
562
  }
450
563
  /** PUT /v1/accounts/:id and POST /v1/accounts/upsert. A field left out is left alone; null clears it. Since 0.4.0. */
451
564
  export interface AccountInput {
@@ -482,7 +595,9 @@ export interface EntitlementChangedEvent {
482
595
  /** Error codes the API returns (stable; branch on these, not on messages). */
483
596
  export type BillingErrorCode = 'missing_credentials' | 'invalid_credentials' | 'app_disabled'
484
597
  /** 0.7 security: the service is locked down (only the owner key works). */
485
- | 'service_locked_down' | 'ip_not_allowed' | 'rate_limited' | 'too_many_auth_failures' | 'invalid_json' | 'invalid_response' | 'invalid_account_id' | 'invalid_field' | 'invalid_email' | 'invalid_url' | 'origin_not_allowed' | 'unknown_plan' | 'price_not_found' | 'exempt' | 'covered_by_account' | 'already_subscribed' | 'no_billing_customer' | 'no_subscription' | 'coverage_self' | 'coverage_chain' | 'trial_used' | 'trial_unavailable' | 'cancel_failed' | 'account_not_found' | 'portal_not_configured' | 'covers_self' | 'too_many_covers' | 'covered_elsewhere' | 'accounts_not_eligible' | 'not_launched' | 'promotion_code_not_supported' | 'parent_chain' | 'parent_self' | 'too_many_ids' | 'key_scope_denied' | 'invoice_not_found' | 'invoice_not_paid' | 'nothing_refundable' | 'over_refundable' | 'bad_amount' | 'no_charge' | 'feature_not_found' | 'feature_not_metered' | 'invalid_feature_id' | 'too_many_events' | 'plan_not_purchasable' | 'lock_not_found' | 'lock_not_held' | 'already_lifetime' | 'covers_not_supported' | 'resume_failed' | 'same_plan' | 'same_quantity' | 'custom_pricing_required' | 'tax_behavior_locked' | 'operation_in_progress' | 'invoice_billing_disabled' | 'invoice_required' | 'purchase_not_found' | 'purchase_not_refundable' | 'purchase_credits_reserved' | 'refund_conflict' | 'add_on_requires_base' | 'not_an_add_on' | 'add_on_not_found' | 'already_entitled' | 'currency_mismatch' | 'pack_too_small'
598
+ | 'service_locked_down' | 'ip_not_allowed' | 'rate_limited' | 'too_many_auth_failures' | 'invalid_json' | 'invalid_response' | 'invalid_account_id' | 'invalid_field' | 'invalid_email' | 'invalid_url' | 'origin_not_allowed' | 'unknown_plan' | 'price_not_found' | 'exempt' | 'covered_by_account' | 'already_subscribed' | 'no_billing_customer' | 'no_subscription' | 'coverage_self' | 'coverage_chain' | 'trial_used' | 'trial_unavailable' | 'cancel_failed' | 'account_not_found' | 'portal_not_configured' | 'covers_self' | 'too_many_covers' | 'covered_elsewhere' | 'accounts_not_eligible' | 'not_launched' | 'promotion_code_not_supported' | 'parent_chain' | 'parent_self' | 'too_many_ids' | 'key_scope_denied' | 'invoice_not_found' | 'invoice_not_paid' | 'nothing_refundable' | 'over_refundable' | 'bad_amount' | 'no_charge' | 'feature_not_found' | 'feature_not_metered' | 'invalid_feature_id' | 'too_many_events' | 'plan_not_purchasable' | 'lock_not_found' | 'lock_not_held' | 'already_lifetime' | 'covers_not_supported' | 'resume_failed' | 'same_plan' | 'same_quantity' | 'custom_pricing_required' | 'tax_behavior_locked'
599
+ /** 0.13 free months: refused when the subscription is set to end or not billed monthly, or a key is reused for another account. */
600
+ | 'subscription_ending' | 'interval_not_supported' | 'idempotency_key_reused' | 'operation_in_progress' | 'invoice_billing_disabled' | 'invoice_required' | 'purchase_not_found' | 'purchase_not_refundable' | 'purchase_credits_reserved' | 'refund_conflict' | 'add_on_requires_base' | 'not_an_add_on' | 'add_on_not_found' | 'already_entitled' | 'currency_mismatch' | 'pack_too_small'
486
601
  /** 0.7 review / prerelease: codes the service answers that earlier unions missed. */
487
602
  | 'price_not_owned' | 'reason_required' | 'prune_refused' | 'storage_unavailable' | 'invalid_admin_key' | 'app_not_found' | 'not_found' | 'forbidden' | 'misconfigured' | 'stripe_not_configured' | 'stripe_permission' | 'stripe_key_unreadable' | 'no_stripe_key' | 'invalid_config' | 'invalid_items' | 'invalid_plans' | 'invalid_origin' | 'invalid_event' | 'invalid_signature' | 'invalid_app_id' | 'confirm_required' | 'feature_exists' | 'feature_in_use' | 'too_many_features' | 'plan_exists' | 'plan_not_found' | 'version_not_found' | 'key_not_found' | 'too_many_keys' | 'has_live_subscriptions' | 'mark_key_in_use' | 'no_accounts' | 'no_customer' | 'no_payment_method' | 'no_pending_setup' | 'no_subscription_item' | 'price_unreadable' | 'customer_owned_by_another_account' | 'different_customer_already_linked' | 'subscription_customer_mismatch' | 'subscription_missing_in_stripe' | 'subscription_owned_by_another_account' | 'webhook_not_found' | 'no_webhook_url' | 'no_webhook_secret' | 'invalid_webhook_secret' | 'invalid_stripe_key' | 'stripe_mode_mismatch' | 'endpoint_exists' | 'unsupported_media_type'
488
603
  /** 0.8 discounts and offers. `discount_invalid` carries `details.reason` (a DiscountReason). */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hjam91/billing",
3
- "version": "0.12.0",
3
+ "version": "0.14.0",
4
4
  "description": "Zero-dependency client for a billing-kit service: cached, fail-open entitlement and feature checks, usage tracking, Stripe Checkout / portal, signed webhook verification, a Hono gate and an optional React billing card.",
5
5
  "keywords": [
6
6
  "billing",