@pithy-sh/payments 0.4.0 → 0.5.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.
Files changed (177) hide show
  1. package/README.md +10 -3
  2. package/dist/admin/coverage.d.ts.map +1 -1
  3. package/dist/admin/coverage.js +26 -2
  4. package/dist/admin/read.d.ts +48 -1
  5. package/dist/admin/read.d.ts.map +1 -1
  6. package/dist/admin/read.js +89 -2
  7. package/dist/audit/actions.d.ts +13 -0
  8. package/dist/audit/actions.d.ts.map +1 -1
  9. package/dist/audit/actions.js +14 -1
  10. package/dist/capability.d.ts +33 -2
  11. package/dist/capability.d.ts.map +1 -1
  12. package/dist/capability.js +52 -9
  13. package/dist/client/api.d.ts +19 -0
  14. package/dist/client/api.d.ts.map +1 -1
  15. package/dist/client/api.js +34 -1
  16. package/dist/client/hooks.d.ts +20 -1
  17. package/dist/client/hooks.d.ts.map +1 -1
  18. package/dist/client/hooks.js +40 -2
  19. package/dist/client/projection.d.ts +29 -0
  20. package/dist/client/projection.d.ts.map +1 -1
  21. package/dist/config/allowances.d.ts +71 -0
  22. package/dist/config/allowances.d.ts.map +1 -0
  23. package/dist/config/allowances.js +115 -0
  24. package/dist/config/config.d.ts +155 -9
  25. package/dist/config/config.d.ts.map +1 -1
  26. package/dist/config/config.js +164 -14
  27. package/dist/data/meterCounter.d.ts +34 -0
  28. package/dist/data/meterCounter.d.ts.map +1 -0
  29. package/dist/data/meterCounter.js +33 -0
  30. package/dist/data/override.d.ts +56 -0
  31. package/dist/data/override.d.ts.map +1 -0
  32. package/dist/data/override.js +58 -0
  33. package/dist/data/period.d.ts +10 -0
  34. package/dist/data/period.d.ts.map +1 -0
  35. package/dist/data/period.js +37 -0
  36. package/dist/data/purchase.d.ts +1 -0
  37. package/dist/data/purchase.d.ts.map +1 -1
  38. package/dist/data/purchase.js +1 -0
  39. package/dist/data/tables.d.ts +17 -1
  40. package/dist/data/tables.d.ts.map +1 -1
  41. package/dist/data/tables.js +24 -4
  42. package/dist/data/usageReport.d.ts +68 -0
  43. package/dist/data/usageReport.d.ts.map +1 -0
  44. package/dist/data/usageReport.js +55 -0
  45. package/dist/data/usageRun.d.ts +93 -0
  46. package/dist/data/usageRun.d.ts.map +1 -0
  47. package/dist/data/usageRun.js +50 -0
  48. package/dist/entitlement/allowance.d.ts +100 -0
  49. package/dist/entitlement/allowance.d.ts.map +1 -0
  50. package/dist/entitlement/allowance.js +171 -0
  51. package/dist/entitlement/manual.d.ts +5 -5
  52. package/dist/entitlement/manual.js +3 -3
  53. package/dist/entitlement/meter.d.ts +98 -0
  54. package/dist/entitlement/meter.d.ts.map +1 -0
  55. package/dist/entitlement/meter.js +177 -0
  56. package/dist/entitlement/override.d.ts +119 -0
  57. package/dist/entitlement/override.d.ts.map +1 -0
  58. package/dist/entitlement/override.js +256 -0
  59. package/dist/entitlement/resolver.d.ts +2 -1
  60. package/dist/entitlement/resolver.d.ts.map +1 -1
  61. package/dist/entitlement/resolver.js +32 -1
  62. package/dist/error/errors.d.ts +19 -0
  63. package/dist/error/errors.d.ts.map +1 -1
  64. package/dist/error/errors.js +35 -2
  65. package/dist/http/responses.d.ts +367 -0
  66. package/dist/http/responses.d.ts.map +1 -1
  67. package/dist/http/responses.js +146 -7
  68. package/dist/http/routes.d.ts.map +1 -1
  69. package/dist/http/routes.js +270 -16
  70. package/dist/http/schemas.d.ts +54 -0
  71. package/dist/http/schemas.d.ts.map +1 -1
  72. package/dist/http/schemas.js +61 -2
  73. package/dist/http/scopes.d.ts +25 -0
  74. package/dist/http/scopes.d.ts.map +1 -1
  75. package/dist/http/scopes.js +60 -1
  76. package/dist/http/view.d.ts +22 -4
  77. package/dist/http/view.d.ts.map +1 -1
  78. package/dist/http/view.js +88 -7
  79. package/dist/index.d.ts +2 -1
  80. package/dist/index.d.ts.map +1 -1
  81. package/dist/index.js +3 -2
  82. package/dist/migrations/0002_allowances.d.ts +26 -0
  83. package/dist/migrations/0002_allowances.d.ts.map +1 -0
  84. package/dist/migrations/0002_allowances.js +62 -0
  85. package/dist/peer.d.ts +1 -0
  86. package/dist/peer.d.ts.map +1 -1
  87. package/dist/projection/event.d.ts +1 -0
  88. package/dist/projection/event.d.ts.map +1 -1
  89. package/dist/projection/event.js +1 -0
  90. package/dist/projection/writer.d.ts.map +1 -1
  91. package/dist/projection/writer.js +3 -1
  92. package/dist/rails/contract.d.ts +6 -0
  93. package/dist/rails/contract.d.ts.map +1 -1
  94. package/dist/rails/google/playApi.d.ts.map +1 -1
  95. package/dist/rails/google/playApi.js +2 -0
  96. package/dist/rails/paddle/objects.d.ts +2 -0
  97. package/dist/rails/paddle/objects.d.ts.map +1 -1
  98. package/dist/rails/paddle/objects.js +7 -2
  99. package/dist/rails/paddle/usage.d.ts +11 -0
  100. package/dist/rails/paddle/usage.d.ts.map +1 -0
  101. package/dist/rails/paddle/usage.js +49 -0
  102. package/dist/rails/quantity.d.ts +12 -0
  103. package/dist/rails/quantity.d.ts.map +1 -0
  104. package/dist/rails/quantity.js +16 -0
  105. package/dist/rails/stripe/checkout.d.ts.map +1 -1
  106. package/dist/rails/stripe/checkout.js +1 -1
  107. package/dist/rails/stripe/objects.d.ts.map +1 -1
  108. package/dist/rails/stripe/objects.js +3 -0
  109. package/dist/rails/stripe/usage.d.ts +10 -0
  110. package/dist/rails/stripe/usage.d.ts.map +1 -0
  111. package/dist/rails/stripe/usage.js +49 -0
  112. package/dist/usage/pass.d.ts +120 -0
  113. package/dist/usage/pass.d.ts.map +1 -0
  114. package/dist/usage/pass.js +363 -0
  115. package/dist/usage/reporter.d.ts +36 -0
  116. package/dist/usage/reporter.d.ts.map +1 -0
  117. package/dist/usage/reporter.js +2 -0
  118. package/dist/version.generated.d.ts +1 -1
  119. package/dist/version.generated.js +1 -1
  120. package/dist/workflows/specs.d.ts +28 -0
  121. package/dist/workflows/specs.d.ts.map +1 -1
  122. package/dist/workflows/specs.js +26 -1
  123. package/dist/workflows/usage.d.ts +38 -0
  124. package/dist/workflows/usage.d.ts.map +1 -0
  125. package/dist/workflows/usage.js +77 -0
  126. package/dist/workflows/worker.js +2 -2
  127. package/docs/entitlements.md +249 -0
  128. package/docs/lemon-squeezy.md +1 -0
  129. package/docs/paddle.md +1 -0
  130. package/package.json +5 -5
  131. package/pithy.manifest.json +3 -8
  132. package/src/admin/coverage.ts +28 -0
  133. package/src/admin/read.ts +173 -1
  134. package/src/audit/actions.ts +13 -0
  135. package/src/capability.ts +87 -9
  136. package/src/client/api.ts +44 -0
  137. package/src/client/hooks.ts +44 -0
  138. package/src/client/projection.ts +31 -0
  139. package/src/config/allowances.ts +211 -0
  140. package/src/config/config.ts +283 -15
  141. package/src/data/meterCounter.ts +38 -0
  142. package/src/data/override.ts +74 -0
  143. package/src/data/period.ts +53 -0
  144. package/src/data/purchase.ts +9 -0
  145. package/src/data/tables.ts +25 -1
  146. package/src/data/usageReport.ts +64 -0
  147. package/src/data/usageRun.ts +66 -0
  148. package/src/entitlement/allowance.ts +213 -0
  149. package/src/entitlement/manual.ts +6 -6
  150. package/src/entitlement/meter.ts +252 -0
  151. package/src/entitlement/override.ts +381 -0
  152. package/src/entitlement/resolver.ts +43 -2
  153. package/src/error/errors.ts +44 -1
  154. package/src/http/responses.ts +305 -4
  155. package/src/http/routes.ts +365 -11
  156. package/src/http/schemas.ts +139 -1
  157. package/src/http/scopes.ts +68 -0
  158. package/src/http/view.ts +112 -7
  159. package/src/index.ts +18 -0
  160. package/src/migrations/0002_allowances.ts +149 -0
  161. package/src/projection/event.ts +9 -0
  162. package/src/projection/writer.ts +4 -0
  163. package/src/rails/contract.ts +6 -0
  164. package/src/rails/google/playApi.ts +2 -0
  165. package/src/rails/paddle/fixtures/subscription-charge.json +19 -0
  166. package/src/rails/paddle/objects.ts +6 -0
  167. package/src/rails/paddle/usage.ts +66 -0
  168. package/src/rails/quantity.ts +14 -0
  169. package/src/rails/stripe/checkout.ts +3 -1
  170. package/src/rails/stripe/fixtures/meter-event-created.json +12 -0
  171. package/src/rails/stripe/objects.ts +4 -0
  172. package/src/rails/stripe/usage.ts +61 -0
  173. package/src/usage/pass.ts +539 -0
  174. package/src/usage/reporter.ts +38 -0
  175. package/src/version.generated.ts +1 -1
  176. package/src/workflows/specs.ts +34 -0
  177. package/src/workflows/usage.ts +97 -0
@@ -12,6 +12,7 @@ import {
12
12
  } from "../../error/errors";
13
13
  import type { PaymentsGoogleCredentials } from "../../secret/registry";
14
14
  import type { UnboundProviderEvent } from "../contract";
15
+ import { statedQuantity } from "../quantity";
15
16
  import { type GoogleHttpFetch, googleHttpFetch, googleJson } from "./http";
16
17
  import { base64UrlEncode, pemPrivateKey } from "./jwt";
17
18
  import type { GoogleNotificationPointer } from "./rtdn";
@@ -508,6 +509,7 @@ export function playProductEvent(
508
509
  originalTransactionId: null,
509
510
  amountMinor: null,
510
511
  currency: null,
512
+ quantity: statedQuantity(purchase.quantity),
511
513
  providerEventAt: context.eventAt,
512
514
  payload: purchase as Record<string, unknown>,
513
515
  };
@@ -0,0 +1,19 @@
1
+ {
2
+ "data": {
3
+ "id": "sub_01hv8wptq8987qeep44cyrewp9",
4
+ "status": "active",
5
+ "customer_id": "ctm_01hv8wptq8987qeep44cyrewp9",
6
+ "currency_code": "USD",
7
+ "next_billed_at": "2026-11-05T09:00:00.000000Z",
8
+ "items": [
9
+ {
10
+ "status": "active",
11
+ "quantity": 1,
12
+ "recurring": true,
13
+ "price": { "id": "pri_01kzvyz9e21z9vbhd7xqq3csyh" }
14
+ }
15
+ ],
16
+ "scheduled_change": null
17
+ },
18
+ "meta": { "request_id": "8f2c7a1e-5d4b-4c3a-9b2e-1f0a9d8c7b6a" }
19
+ }
@@ -8,6 +8,7 @@ import type { PurchaseStatus } from "../../data/status";
8
8
  import { decodeSubjectReference } from "../../data/subject";
9
9
  import { PaymentsVerificationFailedError } from "../../error/errors";
10
10
  import type { UnboundProviderEvent } from "../contract";
11
+ import { statedQuantity } from "../quantity";
11
12
 
12
13
  /**
13
14
  * Paddle's objects, and the mapping from what its events say to what this package stores.
@@ -136,6 +137,7 @@ const PaddleTransactionItem = z
136
137
  .optional()
137
138
  .describe("The price object, which is where a transaction carries its SKU."),
138
139
  price_id: z.string().optional().describe("The price id, on the shapes that carry it flat."),
140
+ quantity: z.number().int().optional().describe("How many of the price this line sold."),
139
141
  })
140
142
  .loose()
141
143
  .describe("One line of a transaction. Single-product checkouts have exactly one.");
@@ -289,6 +291,7 @@ export const PaddleSubscription = z
289
291
  .optional()
290
292
  .describe("The price this item is billed at."),
291
293
  status: z.string().optional().describe("The item's own status, which can differ from the subscription's."),
294
+ quantity: z.number().int().optional().describe("How many of the price the subscription bills."),
292
295
  })
293
296
  .loose()
294
297
  .describe("One priced item on the subscription."),
@@ -641,6 +644,7 @@ export function transactionEvent(
641
644
  revokedAt: null,
642
645
  amountMinor: minorAmount(transaction.details?.totals?.grand_total),
643
646
  currency: currencyOf(transaction.details?.totals?.currency_code ?? transaction.currency_code),
647
+ quantity: statedQuantity(transaction.items?.[0]?.quantity),
644
648
  providerEventAt: occurredAt,
645
649
  payload: { ...transaction },
646
650
  };
@@ -745,6 +749,8 @@ export function subscriptionEvent(
745
749
  resumesAt: pauseResumesAt({ rail: "paddle", status, reported: subscriptionResumesAt(subscription) }),
746
750
  amountMinor: null,
747
751
  currency: null,
752
+ // The line's own quantity, the one a plan change carries back unchanged (`subscription.ts`).
753
+ quantity: statedQuantity(subscription.items?.[0]?.quantity),
748
754
  providerEventAt: occurredAt,
749
755
  payload: { ...subscription },
750
756
  };
@@ -0,0 +1,66 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { z } from "zod";
5
+ import { PaymentsProviderUnavailableError } from "../../error/errors";
6
+ import type { UsageReporter, UsageReportRequest } from "../../usage/reporter";
7
+ import { type PaddleEnvironment, type PaddleHttpFetch, paddleHttpFetch, paddleJson } from "./api";
8
+
9
+ /**
10
+ * Reporting a count to Paddle: one one-time charge per reported period, on the subscription's next bill.
11
+ *
12
+ * **One per billing period, whatever the cadence.** Every charge is its own line on the bill, so a charge
13
+ * per day would bill the sum of the days. The pass sends a `daily-peak` product's period once, at the
14
+ * highest day it sampled (`usage/pass.ts`).
15
+ *
16
+ * `POST /subscriptions/{id}/charge` with `effective_from: "next_billing_period"` and one item — the product's
17
+ * one-time per-unit price at the reported quantity. Paddle adds it to the next renewal's transaction.
18
+ *
19
+ * **It never rewrites the subscription's items.** That is the licensed-seat model, and the rail refuses to
20
+ * rewrite an items array for anything but a single line. A charge adds; it changes nothing that is there,
21
+ * so the recurring line keeps its quantity whatever is reported. The period's row id travels as the
22
+ * idempotency key, so a report sent twice is one charge.
23
+ */
24
+
25
+ /** As much of Paddle's answer as proves the charge landed on this subscription. */
26
+ const PaddleChargedSubscription = z
27
+ .object({ id: z.string().describe("The subscription the charge was added to.") })
28
+ .loose()
29
+ .describe("The subscription Paddle answers a one-time charge with.");
30
+
31
+ /** The Paddle reporter, over the API key, the account and a transport. */
32
+ export function paddleUsageReporter(options: {
33
+ apiKey: string;
34
+ environment: PaddleEnvironment;
35
+ transport?: PaddleHttpFetch;
36
+ }): UsageReporter {
37
+ const transport = options.transport ?? paddleHttpFetch;
38
+ return {
39
+ async report(request: UsageReportRequest): Promise<void> {
40
+ const priceId = request.billing.paddle?.priceId;
41
+ if (priceId === undefined) {
42
+ throw new PaymentsProviderUnavailableError({
43
+ detail: `Paddle usage for ${request.providerSubscriptionId} has no price to charge it at.`,
44
+ });
45
+ }
46
+ const answer = await paddleJson(
47
+ transport,
48
+ `/subscriptions/${encodeURIComponent(request.providerSubscriptionId)}/charge`,
49
+ {
50
+ what: "a one-time usage charge",
51
+ apiKey: options.apiKey,
52
+ environment: options.environment,
53
+ method: "POST",
54
+ body: { effective_from: "next_billing_period", items: [{ price_id: priceId, quantity: request.quantity }] },
55
+ idempotencyKey: request.idempotencyKey,
56
+ },
57
+ );
58
+ const charged = PaddleChargedSubscription.safeParse(answer?.data);
59
+ if (!charged.success || charged.data.id !== request.providerSubscriptionId) {
60
+ throw new PaymentsProviderUnavailableError({
61
+ detail: `Paddle answered the usage charge for ${request.providerSubscriptionId} with a different subscription.`,
62
+ });
63
+ }
64
+ },
65
+ };
66
+ }
@@ -0,0 +1,14 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ /**
5
+ * The quantity a store stated, or null — never a default.
6
+ *
7
+ * Every rail but one parses a quantity that is sometimes absent: a metered Stripe price carries none, a Paddle
8
+ * line on an old shape carries none, a Play one-time purchase of one omits it. Writing `1` for absent would
9
+ * invent a fact the store did not state, and a seat count read off it would be a number nobody reported.
10
+ * So a positive whole number crosses and anything else is null.
11
+ */
12
+ export function statedQuantity(value: unknown): number | null {
13
+ return typeof value === "number" && Number.isInteger(value) && value > 0 ? value : null;
14
+ }
@@ -91,7 +91,9 @@ export async function createStripeCheckoutSession(
91
91
 
92
92
  const form: StripeFormObject = {
93
93
  mode: input.subscription ? "subscription" : "payment",
94
- line_items: [{ price: input.providerProductId, quantity: 1 }],
94
+ // One of a flat price. A reported product's price is metered, and Stripe refuses a quantity on a metered
95
+ // line: the count is reported per period instead (`usage/pass.ts`).
96
+ line_items: [{ price: input.providerProductId, quantity: input.reported ? undefined : 1 }],
95
97
  success_url: input.successUrl,
96
98
  cancel_url: input.cancelUrl,
97
99
  // The resolved subject, both halves. Never a value from a request body — see the module doc.
@@ -0,0 +1,12 @@
1
+ {
2
+ "object": "billing.meter_event",
3
+ "created": 1792022399,
4
+ "event_name": "academy_students",
5
+ "identifier": "usage_8c1f2a4e-6b3d-4f5a-9e7c-2d1b0a9f8e7d",
6
+ "livemode": false,
7
+ "payload": {
8
+ "stripe_customer_id": "cus_PithyAcme",
9
+ "value": "25"
10
+ },
11
+ "timestamp": 1792022399
12
+ }
@@ -7,6 +7,7 @@ import type { PurchaseEnvironment } from "../../data/purchase";
7
7
  import { ACCESS_GRANTING_STATUSES, type PurchaseStatus } from "../../data/status";
8
8
  import { PaymentsVerificationFailedError } from "../../error/errors";
9
9
  import type { NotificationNote, UnboundProviderEvent } from "../contract";
10
+ import { statedQuantity } from "../quantity";
10
11
 
11
12
  /**
12
13
  * Stripe's objects, and the mapping from what Stripe calls a thing to what the projection stores.
@@ -386,6 +387,8 @@ export function mapStripeSubscription(subscription: StripeSubscription, eventAt:
386
387
  originalTransactionId: subscription.id,
387
388
  amountMinor: minorUnits(item.price.unit_amount ?? null, currency),
388
389
  currency,
390
+ // The seat count Stripe states on the item. A metered price carries none, and null says so.
391
+ quantity: statedQuantity(item.quantity),
389
392
  providerEventAt: eventAt,
390
393
  payload: subscription as Record<string, unknown>,
391
394
  },
@@ -465,6 +468,7 @@ export function mapStripeSession(session: StripeCheckoutSession, options: Stripe
465
468
  originalTransactionId: null,
466
469
  amountMinor: minorUnits(session.amount_total ?? null, currency),
467
470
  currency,
471
+ quantity: statedQuantity(session.line_items?.data[0]?.quantity),
468
472
  providerEventAt: options.eventAt ?? retrievedAt(session, charge, status, options.now),
469
473
  payload: session as Record<string, unknown>,
470
474
  },
@@ -0,0 +1,61 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { z } from "zod";
5
+ import { PaymentsProviderUnavailableError } from "../../error/errors";
6
+ import type { UsageReporter, UsageReportRequest } from "../../usage/reporter";
7
+ import { type StripeHttpFetch, stripeHttpFetch, stripeJson } from "./api";
8
+
9
+ /**
10
+ * Reporting a count to Stripe: one Billing Meter event per reported period.
11
+ *
12
+ * `POST /v1/billing/meter_events` with the meter's `event_name`, the customer, the count as `value`, and the
13
+ * period's row id as `identifier` — which Stripe enforces as unique, so a report sent twice is one event. The
14
+ * subscription's metered price reads the meter, and the meter's own aggregation over the period — a setting
15
+ * on the meter in Stripe, not here — is what the invoice bills. The pass sends one event per period for both
16
+ * cadences — a `daily-peak` event carries the period's highest day — so a summing meter bills that count.
17
+ *
18
+ * The timestamp is the report's own `at`, which the pass dates inside the period it bills, so the event
19
+ * lands on that period's invoice.
20
+ */
21
+
22
+ /** What Stripe answers for a recorded meter event — as much as proves it recorded this one. */
23
+ const StripeMeterEvent = z
24
+ .object({
25
+ object: z.literal("billing.meter_event").describe("Always `billing.meter_event`."),
26
+ event_name: z.string().describe("The meter the event was recorded against."),
27
+ identifier: z.string().describe("The idempotency identifier the event was recorded under."),
28
+ })
29
+ .loose()
30
+ .describe("A Stripe Billing Meter event, as Stripe answers its creation.");
31
+
32
+ /** The Stripe reporter, over the secret key and a transport. */
33
+ export function stripeUsageReporter(options: { secretKey: string; transport?: StripeHttpFetch }): UsageReporter {
34
+ const transport = options.transport ?? stripeHttpFetch;
35
+ return {
36
+ async report(request: UsageReportRequest): Promise<void> {
37
+ const meter = request.billing.stripe?.meterEventName;
38
+ if (meter === undefined || request.providerCustomerId === undefined) {
39
+ throw new PaymentsProviderUnavailableError({
40
+ detail: `Stripe usage for ${request.providerSubscriptionId} has no ${meter === undefined ? "meter event name" : "customer"} to report against.`,
41
+ });
42
+ }
43
+ const answer = await stripeJson(transport, "/billing/meter_events", {
44
+ what: "a meter event",
45
+ secretKey: options.secretKey,
46
+ form: {
47
+ event_name: meter,
48
+ identifier: request.idempotencyKey,
49
+ timestamp: Math.floor(request.at.getTime() / 1000),
50
+ payload: { stripe_customer_id: request.providerCustomerId, value: String(request.quantity) },
51
+ },
52
+ });
53
+ const event = StripeMeterEvent.safeParse(answer);
54
+ if (!event.success || event.data.identifier !== request.idempotencyKey) {
55
+ throw new PaymentsProviderUnavailableError({
56
+ detail: `Stripe answered the meter event for ${request.providerSubscriptionId} with something that is not that event.`,
57
+ });
58
+ }
59
+ },
60
+ };
61
+ }