@hjam91/billing 0.8.0 → 0.10.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 +110 -0
- package/dist/admin.d.ts +58 -0
- package/dist/admin.js +4 -0
- package/dist/config.d.ts +17 -2
- package/dist/hono.js +84 -1
- package/dist/index.d.ts +47 -1
- package/dist/index.js +129 -41
- package/dist/react.d.ts +98 -1
- package/dist/react.js +206 -5
- package/dist/types.d.ts +47 -4
- package/dist/usage.d.ts +39 -0
- package/dist/usage.js +65 -0
- package/package.json +7 -2
package/dist/types.d.ts
CHANGED
|
@@ -196,7 +196,7 @@ export interface UsageSettingsInput {
|
|
|
196
196
|
export interface UsageEvent {
|
|
197
197
|
id: string;
|
|
198
198
|
/** 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';
|
|
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';
|
|
200
200
|
created: string;
|
|
201
201
|
app_id: string;
|
|
202
202
|
account_id: string;
|
|
@@ -206,10 +206,18 @@ export interface UsageEvent {
|
|
|
206
206
|
export type BillingEvent = EntitlementChangedEvent | UsageEvent;
|
|
207
207
|
/** POST /v1/subscriptions/change (since 0.7.0): what happened to the plan. */
|
|
208
208
|
export interface PlanChange {
|
|
209
|
-
|
|
209
|
+
quantity?: number;
|
|
210
|
+
from_quantity?: number;
|
|
211
|
+
/** 'unchanged' (0.10): the reported quantity was already in place; nothing was sent to the provider. */
|
|
212
|
+
status: 'applied' | 'scheduled' | 'requires_action' | 'unchanged';
|
|
210
213
|
plan: string;
|
|
211
214
|
from_plan: string | null;
|
|
212
|
-
direction: 'upgrade' | 'downgrade' | 'interval';
|
|
215
|
+
direction: 'upgrade' | 'downgrade' | 'interval' | 'none';
|
|
216
|
+
/** 0.10, tiered plans: the count was above the ladder; the subscription is held at the top tier (see SubscriptionView.over_max). */
|
|
217
|
+
over_max?: boolean;
|
|
218
|
+
reported_quantity?: number | null;
|
|
219
|
+
/** 0.10: an unchanged report canceled a pending downgrade. */
|
|
220
|
+
schedule_canceled?: boolean;
|
|
213
221
|
effective_at: string | null;
|
|
214
222
|
/** requires_action: the invoice page where the customer completes 3DS / pays. */
|
|
215
223
|
action_url: string | null;
|
|
@@ -217,6 +225,8 @@ export interface PlanChange {
|
|
|
217
225
|
}
|
|
218
226
|
/** POST /v1/subscriptions/change/preview (since 0.7.0). Amounts in minor units. */
|
|
219
227
|
export interface ChangePreview {
|
|
228
|
+
quantity?: number;
|
|
229
|
+
from_quantity?: number;
|
|
220
230
|
plan: string;
|
|
221
231
|
from_plan: string | null;
|
|
222
232
|
direction: 'upgrade' | 'downgrade' | 'interval';
|
|
@@ -251,6 +261,18 @@ export interface PublicPlan {
|
|
|
251
261
|
amount: number;
|
|
252
262
|
expires_in_days?: number;
|
|
253
263
|
}>;
|
|
264
|
+
/** 0.10: a tiered plan's ladder, from its config: the flat amount (minor units) for each range of the quantity. */
|
|
265
|
+
tiers?: PlanTier[];
|
|
266
|
+
/** 0.10: the most a tiered plan sells; above it the service refuses Checkout and flags a subscription `over_max`. */
|
|
267
|
+
max_quantity?: number;
|
|
268
|
+
/** 0.10: what the quantity counts ("students"). */
|
|
269
|
+
unit?: string;
|
|
270
|
+
}
|
|
271
|
+
/** One tier of a tiered plan (since 0.10.0). `from`..`up_to` inclusive, `amount` is the flat price of the tier. */
|
|
272
|
+
export interface PlanTier {
|
|
273
|
+
from: number;
|
|
274
|
+
up_to: number;
|
|
275
|
+
amount: number;
|
|
254
276
|
}
|
|
255
277
|
/** A discount as an app shows it (since 0.8.0). Amounts in minor units. */
|
|
256
278
|
export interface DiscountView {
|
|
@@ -319,6 +341,27 @@ export interface EntitlementResult extends Entitlement {
|
|
|
319
341
|
error?: string;
|
|
320
342
|
}
|
|
321
343
|
export interface SubscriptionView {
|
|
344
|
+
scheduled_change?: {
|
|
345
|
+
plan: string;
|
|
346
|
+
quantity: number;
|
|
347
|
+
effective_at: string;
|
|
348
|
+
};
|
|
349
|
+
/** 0.10, tiered plans: the tier the current quantity falls in. */
|
|
350
|
+
tier?: PlanTier & {
|
|
351
|
+
currency: string;
|
|
352
|
+
interval: string | null;
|
|
353
|
+
};
|
|
354
|
+
/** 0.10, tiered plans: the ladder's top boundary. */
|
|
355
|
+
max_quantity?: number;
|
|
356
|
+
/** 0.10: the app reported a count above the ladder; the subscription stays at the top tier and access continues ("contact us"). */
|
|
357
|
+
over_max?: boolean;
|
|
358
|
+
/** 0.10: that reported count (null within the ladder). */
|
|
359
|
+
reported_quantity?: number | null;
|
|
360
|
+
invoice?: {
|
|
361
|
+
id: string;
|
|
362
|
+
due_at: string | null;
|
|
363
|
+
hosted_invoice_url: string | null;
|
|
364
|
+
};
|
|
322
365
|
id: string;
|
|
323
366
|
plan: string | null;
|
|
324
367
|
quantity: number;
|
|
@@ -439,7 +482,7 @@ export interface EntitlementChangedEvent {
|
|
|
439
482
|
/** Error codes the API returns (stable; branch on these, not on messages). */
|
|
440
483
|
export type BillingErrorCode = 'missing_credentials' | 'invalid_credentials' | 'app_disabled'
|
|
441
484
|
/** 0.7 security: the service is locked down (only the owner key works). */
|
|
442
|
-
| 'service_locked_down' | 'ip_not_allowed' | 'rate_limited' | 'too_many_auth_failures' | 'invalid_json' | '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' | 'add_on_requires_base' | 'not_an_add_on' | 'add_on_not_found' | 'already_entitled' | 'currency_mismatch' | 'pack_too_small'
|
|
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' | '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'
|
|
443
486
|
/** 0.7 review / prerelease: codes the service answers that earlier unions missed. */
|
|
444
487
|
| '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'
|
|
445
488
|
/** 0.8 discounts and offers. `discount_invalid` carries `details.reason` (a DiscountReason). */
|
package/dist/usage.d.ts
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/** Pluggable usage delivery storage. Store operations must be durable before resolving. */
|
|
2
|
+
export interface UsageRecord {
|
|
3
|
+
scope: string;
|
|
4
|
+
id: string;
|
|
5
|
+
body: Record<string, unknown>;
|
|
6
|
+
attempts: number;
|
|
7
|
+
createdAt: number;
|
|
8
|
+
status: 'pending' | 'rejected';
|
|
9
|
+
error?: string;
|
|
10
|
+
}
|
|
11
|
+
export interface UsageStatus {
|
|
12
|
+
pending: number;
|
|
13
|
+
rejected: number;
|
|
14
|
+
oldestPendingAt: number | null;
|
|
15
|
+
}
|
|
16
|
+
export interface UsageStore {
|
|
17
|
+
put(record: UsageRecord): Promise<void>;
|
|
18
|
+
remove(scope: string, id: string): Promise<void>;
|
|
19
|
+
list(scope: string, status: UsageRecord['status'], limit: number): Promise<UsageRecord[]>;
|
|
20
|
+
status(scope: string): Promise<UsageStatus>;
|
|
21
|
+
}
|
|
22
|
+
/** Process-local default. A persistent implementation can be shared by successive SDK instances. */
|
|
23
|
+
export declare function memoryUsageStore(maxRejected?: number): UsageStore;
|
|
24
|
+
/** Apply this schema in the consuming app's database before using d1UsageStore. */
|
|
25
|
+
export declare const USAGE_QUEUE_SCHEMA = "CREATE TABLE IF NOT EXISTS billing_usage_queue (\n scope TEXT NOT NULL, id TEXT NOT NULL, body TEXT NOT NULL, attempts INTEGER NOT NULL,\n created_at INTEGER NOT NULL, status TEXT NOT NULL, error TEXT, PRIMARY KEY (scope, id)\n);\nCREATE INDEX IF NOT EXISTS billing_usage_pending ON billing_usage_queue (scope, status, created_at, id);";
|
|
26
|
+
export interface UsageDatabase {
|
|
27
|
+
prepare(sql: string): {
|
|
28
|
+
bind(...args: (string | number | null)[]): {
|
|
29
|
+
run(): Promise<unknown>;
|
|
30
|
+
all<T>(): Promise<{
|
|
31
|
+
results: T[];
|
|
32
|
+
}>;
|
|
33
|
+
};
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
/** Cloudflare D1 adapter, without importing a platform package. Event keys survive process restarts. */
|
|
37
|
+
export declare function d1UsageStore(db: UsageDatabase): UsageStore;
|
|
38
|
+
/** A per-event failure inside a successful HTTP batch response. */
|
|
39
|
+
export declare function usageOutcome(result: unknown): 'sent' | 'retry' | 'rejected';
|
package/dist/usage.js
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
/** Process-local default. A persistent implementation can be shared by successive SDK instances. */
|
|
2
|
+
export function memoryUsageStore(maxRejected = 1000) {
|
|
3
|
+
const rows = new Map();
|
|
4
|
+
const key = (scope, id) => JSON.stringify([scope, id]);
|
|
5
|
+
return {
|
|
6
|
+
async put(row) {
|
|
7
|
+
rows.set(key(row.scope, row.id), structuredClone(row));
|
|
8
|
+
const rejected = [...rows.values()].filter((r) => r.scope === row.scope && r.status === 'rejected');
|
|
9
|
+
for (const r of rejected.slice(0, Math.max(0, rejected.length - maxRejected)))
|
|
10
|
+
rows.delete(key(r.scope, r.id));
|
|
11
|
+
},
|
|
12
|
+
async remove(scope, id) { rows.delete(key(scope, id)); },
|
|
13
|
+
async list(scope, status, limit) {
|
|
14
|
+
return structuredClone([...rows.values()].filter((r) => r.scope === scope && r.status === status)
|
|
15
|
+
.sort((a, b) => a.createdAt - b.createdAt).slice(0, limit));
|
|
16
|
+
},
|
|
17
|
+
async status(scope) {
|
|
18
|
+
const all = [...rows.values()].filter((r) => r.scope === scope);
|
|
19
|
+
const pending = all.filter((r) => r.status === 'pending');
|
|
20
|
+
return { pending: pending.length, rejected: all.length - pending.length, oldestPendingAt: pending.length ? Math.min(...pending.map((r) => r.createdAt)) : null };
|
|
21
|
+
},
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
/** Apply this schema in the consuming app's database before using d1UsageStore. */
|
|
25
|
+
export const USAGE_QUEUE_SCHEMA = `CREATE TABLE IF NOT EXISTS billing_usage_queue (
|
|
26
|
+
scope TEXT NOT NULL, id TEXT NOT NULL, body TEXT NOT NULL, attempts INTEGER NOT NULL,
|
|
27
|
+
created_at INTEGER NOT NULL, status TEXT NOT NULL, error TEXT, PRIMARY KEY (scope, id)
|
|
28
|
+
);
|
|
29
|
+
CREATE INDEX IF NOT EXISTS billing_usage_pending ON billing_usage_queue (scope, status, created_at, id);`;
|
|
30
|
+
/** Cloudflare D1 adapter, without importing a platform package. Event keys survive process restarts. */
|
|
31
|
+
export function d1UsageStore(db) {
|
|
32
|
+
return {
|
|
33
|
+
async put(r) {
|
|
34
|
+
await db.prepare(`INSERT INTO billing_usage_queue (scope,id,body,attempts,created_at,status,error) VALUES (?,?,?,?,?,?,?)
|
|
35
|
+
ON CONFLICT(scope,id) DO UPDATE SET body=excluded.body,attempts=excluded.attempts,status=excluded.status,error=excluded.error`)
|
|
36
|
+
.bind(r.scope, r.id, JSON.stringify(r.body), r.attempts, r.createdAt, r.status, r.error ?? null).run();
|
|
37
|
+
},
|
|
38
|
+
async remove(scope, id) { await db.prepare('DELETE FROM billing_usage_queue WHERE scope=? AND id=?').bind(scope, id).run(); },
|
|
39
|
+
async list(scope, status, limit) {
|
|
40
|
+
const r = await db.prepare('SELECT * FROM billing_usage_queue WHERE scope=? AND status=? ORDER BY created_at,id LIMIT ?').bind(scope, status, limit)
|
|
41
|
+
.all();
|
|
42
|
+
return r.results.map((x) => ({ scope: x.scope, id: x.id, body: JSON.parse(x.body), attempts: x.attempts, createdAt: x.created_at, status: x.status, ...(x.error ? { error: x.error } : {}) }));
|
|
43
|
+
},
|
|
44
|
+
async status(scope) {
|
|
45
|
+
const r = await db.prepare(`SELECT SUM(status='pending') AS pending,SUM(status='rejected') AS rejected,
|
|
46
|
+
MIN(CASE WHEN status='pending' THEN created_at END) AS oldestPendingAt FROM billing_usage_queue WHERE scope=?`).bind(scope)
|
|
47
|
+
.all();
|
|
48
|
+
const row = r.results[0];
|
|
49
|
+
return { pending: row?.pending ?? 0, rejected: row?.rejected ?? 0, oldestPendingAt: row?.oldestPendingAt ?? null };
|
|
50
|
+
},
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
/** A per-event failure inside a successful HTTP batch response. */
|
|
54
|
+
export function usageOutcome(result) {
|
|
55
|
+
if (!result || typeof result !== 'object')
|
|
56
|
+
return 'retry';
|
|
57
|
+
const r = result;
|
|
58
|
+
if (r.applied === true || r.replayed === true)
|
|
59
|
+
return 'sent';
|
|
60
|
+
if (typeof r.error === 'string')
|
|
61
|
+
return ['internal', 'storage_unavailable', 'stripe_error', 'network_error', 'timeout', 'rate_limited', 'service_locked_down', 'app_disabled'].includes(r.error) ? 'retry' : 'rejected';
|
|
62
|
+
if (r.allowed === false)
|
|
63
|
+
return 'rejected';
|
|
64
|
+
return 'retry';
|
|
65
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@hjam91/billing",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.10.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",
|
|
@@ -48,7 +48,12 @@
|
|
|
48
48
|
"import": "./dist/config.js",
|
|
49
49
|
"default": "./dist/config.js"
|
|
50
50
|
},
|
|
51
|
-
"./package.json": "./package.json"
|
|
51
|
+
"./package.json": "./package.json",
|
|
52
|
+
"./usage": {
|
|
53
|
+
"types": "./dist/usage.d.ts",
|
|
54
|
+
"import": "./dist/usage.js",
|
|
55
|
+
"default": "./dist/usage.js"
|
|
56
|
+
}
|
|
52
57
|
},
|
|
53
58
|
"bin": {
|
|
54
59
|
"billing-cli": "dist/cli.mjs"
|