@pithy-sh/payments 0.3.10 → 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 (215) hide show
  1. package/README.md +11 -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 +38 -0
  14. package/dist/client/api.d.ts.map +1 -1
  15. package/dist/client/api.js +59 -1
  16. package/dist/client/hooks.d.ts +63 -1
  17. package/dist/client/hooks.d.ts.map +1 -1
  18. package/dist/client/hooks.js +96 -2
  19. package/dist/client/paddleLink.d.ts +31 -0
  20. package/dist/client/paddleLink.d.ts.map +1 -0
  21. package/dist/client/paddleLink.js +37 -0
  22. package/dist/client/projection.d.ts +29 -0
  23. package/dist/client/projection.d.ts.map +1 -1
  24. package/dist/config/allowances.d.ts +71 -0
  25. package/dist/config/allowances.d.ts.map +1 -0
  26. package/dist/config/allowances.js +115 -0
  27. package/dist/config/config.d.ts +155 -9
  28. package/dist/config/config.d.ts.map +1 -1
  29. package/dist/config/config.js +164 -14
  30. package/dist/data/meterCounter.d.ts +34 -0
  31. package/dist/data/meterCounter.d.ts.map +1 -0
  32. package/dist/data/meterCounter.js +33 -0
  33. package/dist/data/override.d.ts +56 -0
  34. package/dist/data/override.d.ts.map +1 -0
  35. package/dist/data/override.js +58 -0
  36. package/dist/data/paddleIds.d.ts +28 -0
  37. package/dist/data/paddleIds.d.ts.map +1 -0
  38. package/dist/data/paddleIds.js +73 -0
  39. package/dist/data/period.d.ts +10 -0
  40. package/dist/data/period.d.ts.map +1 -0
  41. package/dist/data/period.js +37 -0
  42. package/dist/data/purchase.d.ts +1 -0
  43. package/dist/data/purchase.d.ts.map +1 -1
  44. package/dist/data/purchase.js +1 -0
  45. package/dist/data/tables.d.ts +17 -1
  46. package/dist/data/tables.d.ts.map +1 -1
  47. package/dist/data/tables.js +24 -4
  48. package/dist/data/usageReport.d.ts +68 -0
  49. package/dist/data/usageReport.d.ts.map +1 -0
  50. package/dist/data/usageReport.js +55 -0
  51. package/dist/data/usageRun.d.ts +93 -0
  52. package/dist/data/usageRun.d.ts.map +1 -0
  53. package/dist/data/usageRun.js +50 -0
  54. package/dist/entitlement/allowance.d.ts +100 -0
  55. package/dist/entitlement/allowance.d.ts.map +1 -0
  56. package/dist/entitlement/allowance.js +171 -0
  57. package/dist/entitlement/manual.d.ts +5 -5
  58. package/dist/entitlement/manual.js +3 -3
  59. package/dist/entitlement/meter.d.ts +98 -0
  60. package/dist/entitlement/meter.d.ts.map +1 -0
  61. package/dist/entitlement/meter.js +177 -0
  62. package/dist/entitlement/override.d.ts +119 -0
  63. package/dist/entitlement/override.d.ts.map +1 -0
  64. package/dist/entitlement/override.js +256 -0
  65. package/dist/entitlement/resolver.d.ts +2 -1
  66. package/dist/entitlement/resolver.d.ts.map +1 -1
  67. package/dist/entitlement/resolver.js +32 -1
  68. package/dist/entitlement/unimplementedSubject.d.ts.map +1 -1
  69. package/dist/entitlement/unimplementedSubject.js +3 -2
  70. package/dist/error/errors.d.ts +19 -0
  71. package/dist/error/errors.d.ts.map +1 -1
  72. package/dist/error/errors.js +35 -2
  73. package/dist/http/responses.d.ts +390 -5
  74. package/dist/http/responses.d.ts.map +1 -1
  75. package/dist/http/responses.js +169 -13
  76. package/dist/http/routes.d.ts +6 -2
  77. package/dist/http/routes.d.ts.map +1 -1
  78. package/dist/http/routes.js +478 -52
  79. package/dist/http/schemas.d.ts +75 -1
  80. package/dist/http/schemas.d.ts.map +1 -1
  81. package/dist/http/schemas.js +80 -3
  82. package/dist/http/scopes.d.ts +25 -0
  83. package/dist/http/scopes.d.ts.map +1 -1
  84. package/dist/http/scopes.js +60 -1
  85. package/dist/http/view.d.ts +22 -4
  86. package/dist/http/view.d.ts.map +1 -1
  87. package/dist/http/view.js +88 -7
  88. package/dist/http/webhookGuard.d.ts.map +1 -1
  89. package/dist/http/webhookGuard.js +1 -1
  90. package/dist/index.d.ts +2 -1
  91. package/dist/index.d.ts.map +1 -1
  92. package/dist/index.js +3 -2
  93. package/dist/migrations/0002_allowances.d.ts +26 -0
  94. package/dist/migrations/0002_allowances.d.ts.map +1 -0
  95. package/dist/migrations/0002_allowances.js +62 -0
  96. package/dist/peer.d.ts +1 -0
  97. package/dist/peer.d.ts.map +1 -1
  98. package/dist/projection/event.d.ts +1 -0
  99. package/dist/projection/event.d.ts.map +1 -1
  100. package/dist/projection/event.js +1 -0
  101. package/dist/projection/writer.d.ts.map +1 -1
  102. package/dist/projection/writer.js +3 -1
  103. package/dist/rails/contract.d.ts +6 -0
  104. package/dist/rails/contract.d.ts.map +1 -1
  105. package/dist/rails/google/playApi.d.ts.map +1 -1
  106. package/dist/rails/google/playApi.js +2 -0
  107. package/dist/rails/paddle/events.d.ts.map +1 -1
  108. package/dist/rails/paddle/events.js +2 -1
  109. package/dist/rails/paddle/objects.d.ts +2 -0
  110. package/dist/rails/paddle/objects.d.ts.map +1 -1
  111. package/dist/rails/paddle/objects.js +7 -2
  112. package/dist/rails/paddle/refresh.d.ts +10 -5
  113. package/dist/rails/paddle/refresh.d.ts.map +1 -1
  114. package/dist/rails/paddle/refresh.js +8 -5
  115. package/dist/rails/paddle/refund.d.ts.map +1 -1
  116. package/dist/rails/paddle/refund.js +10 -2
  117. package/dist/rails/paddle/subscription.d.ts.map +1 -1
  118. package/dist/rails/paddle/subscription.js +8 -3
  119. package/dist/rails/paddle/usage.d.ts +11 -0
  120. package/dist/rails/paddle/usage.d.ts.map +1 -0
  121. package/dist/rails/paddle/usage.js +49 -0
  122. package/dist/rails/paddle/verify.d.ts.map +1 -1
  123. package/dist/rails/paddle/verify.js +2 -3
  124. package/dist/rails/quantity.d.ts +12 -0
  125. package/dist/rails/quantity.d.ts.map +1 -0
  126. package/dist/rails/quantity.js +16 -0
  127. package/dist/rails/stripe/checkout.d.ts.map +1 -1
  128. package/dist/rails/stripe/checkout.js +1 -1
  129. package/dist/rails/stripe/objects.d.ts.map +1 -1
  130. package/dist/rails/stripe/objects.js +3 -0
  131. package/dist/rails/stripe/usage.d.ts +10 -0
  132. package/dist/rails/stripe/usage.d.ts.map +1 -0
  133. package/dist/rails/stripe/usage.js +49 -0
  134. package/dist/secret/registry.d.ts.map +1 -1
  135. package/dist/secret/registry.js +3 -2
  136. package/dist/usage/pass.d.ts +120 -0
  137. package/dist/usage/pass.d.ts.map +1 -0
  138. package/dist/usage/pass.js +363 -0
  139. package/dist/usage/reporter.d.ts +36 -0
  140. package/dist/usage/reporter.d.ts.map +1 -0
  141. package/dist/usage/reporter.js +2 -0
  142. package/dist/version.generated.d.ts +1 -1
  143. package/dist/version.generated.d.ts.map +1 -1
  144. package/dist/version.generated.js +1 -1
  145. package/dist/workflows/specs.d.ts +28 -0
  146. package/dist/workflows/specs.d.ts.map +1 -1
  147. package/dist/workflows/specs.js +26 -1
  148. package/dist/workflows/usage.d.ts +38 -0
  149. package/dist/workflows/usage.d.ts.map +1 -0
  150. package/dist/workflows/usage.js +77 -0
  151. package/dist/workflows/worker.js +2 -2
  152. package/dist/workflows/workerConfig.d.ts.map +1 -1
  153. package/dist/workflows/workerConfig.js +8 -2
  154. package/docs/entitlements.md +249 -0
  155. package/docs/lemon-squeezy.md +1 -0
  156. package/docs/paddle.md +18 -2
  157. package/package.json +7 -7
  158. package/pithy.manifest.json +3 -8
  159. package/src/admin/coverage.ts +28 -0
  160. package/src/admin/read.ts +173 -1
  161. package/src/audit/actions.ts +13 -0
  162. package/src/capability.ts +87 -9
  163. package/src/client/api.ts +79 -0
  164. package/src/client/hooks.ts +122 -0
  165. package/src/client/paddleLink.ts +41 -0
  166. package/src/client/projection.ts +31 -0
  167. package/src/config/allowances.ts +211 -0
  168. package/src/config/config.ts +283 -15
  169. package/src/data/meterCounter.ts +38 -0
  170. package/src/data/override.ts +74 -0
  171. package/src/data/paddleIds.ts +74 -0
  172. package/src/data/period.ts +53 -0
  173. package/src/data/purchase.ts +9 -0
  174. package/src/data/tables.ts +25 -1
  175. package/src/data/usageReport.ts +64 -0
  176. package/src/data/usageRun.ts +66 -0
  177. package/src/entitlement/allowance.ts +213 -0
  178. package/src/entitlement/manual.ts +6 -6
  179. package/src/entitlement/meter.ts +252 -0
  180. package/src/entitlement/override.ts +381 -0
  181. package/src/entitlement/resolver.ts +43 -2
  182. package/src/entitlement/unimplementedSubject.ts +3 -4
  183. package/src/error/errors.ts +44 -1
  184. package/src/http/responses.ts +338 -10
  185. package/src/http/routes.ts +1089 -460
  186. package/src/http/schemas.ts +171 -2
  187. package/src/http/scopes.ts +68 -0
  188. package/src/http/view.ts +112 -7
  189. package/src/http/webhookGuard.ts +3 -2
  190. package/src/index.ts +18 -0
  191. package/src/migrations/0002_allowances.ts +149 -0
  192. package/src/projection/event.ts +9 -0
  193. package/src/projection/writer.ts +4 -0
  194. package/src/rails/contract.ts +6 -0
  195. package/src/rails/google/playApi.ts +2 -0
  196. package/src/rails/paddle/events.ts +2 -1
  197. package/src/rails/paddle/fixtures/subscription-charge.json +19 -0
  198. package/src/rails/paddle/objects.ts +6 -0
  199. package/src/rails/paddle/refresh.ts +17 -10
  200. package/src/rails/paddle/refund.ts +10 -2
  201. package/src/rails/paddle/subscription.ts +8 -3
  202. package/src/rails/paddle/usage.ts +66 -0
  203. package/src/rails/paddle/verify.ts +6 -4
  204. package/src/rails/quantity.ts +14 -0
  205. package/src/rails/stripe/checkout.ts +3 -1
  206. package/src/rails/stripe/fixtures/meter-event-created.json +12 -0
  207. package/src/rails/stripe/objects.ts +4 -0
  208. package/src/rails/stripe/usage.ts +61 -0
  209. package/src/secret/registry.ts +3 -2
  210. package/src/usage/pass.ts +539 -0
  211. package/src/usage/reporter.ts +38 -0
  212. package/src/version.generated.ts +1 -1
  213. package/src/workflows/specs.ts +34 -0
  214. package/src/workflows/usage.ts +97 -0
  215. package/src/workflows/workerConfig.ts +9 -3
@@ -0,0 +1,49 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { PaymentsProviderUnavailableError } from "../../error/errors.js";
4
+ import { paddleHttpFetch, paddleJson } from "./api.js";
5
+ import { z } from "zod";
6
+ //#region src/rails/paddle/usage.ts
7
+ /**
8
+ * Reporting a count to Paddle: one one-time charge per reported period, on the subscription's next bill.
9
+ *
10
+ * **One per billing period, whatever the cadence.** Every charge is its own line on the bill, so a charge
11
+ * per day would bill the sum of the days. The pass sends a `daily-peak` product's period once, at the
12
+ * highest day it sampled (`usage/pass.ts`).
13
+ *
14
+ * `POST /subscriptions/{id}/charge` with `effective_from: "next_billing_period"` and one item — the product's
15
+ * one-time per-unit price at the reported quantity. Paddle adds it to the next renewal's transaction.
16
+ *
17
+ * **It never rewrites the subscription's items.** That is the licensed-seat model, and the rail refuses to
18
+ * rewrite an items array for anything but a single line. A charge adds; it changes nothing that is there,
19
+ * so the recurring line keeps its quantity whatever is reported. The period's row id travels as the
20
+ * idempotency key, so a report sent twice is one charge.
21
+ */
22
+ /** As much of Paddle's answer as proves the charge landed on this subscription. */
23
+ const PaddleChargedSubscription = z.object({ id: z.string().describe("The subscription the charge was added to.") }).loose().describe("The subscription Paddle answers a one-time charge with.");
24
+ /** The Paddle reporter, over the API key, the account and a transport. */
25
+ function paddleUsageReporter(options) {
26
+ const transport = options.transport ?? paddleHttpFetch;
27
+ return { async report(request) {
28
+ const priceId = request.billing.paddle?.priceId;
29
+ if (priceId === void 0) throw new PaymentsProviderUnavailableError({ detail: `Paddle usage for ${request.providerSubscriptionId} has no price to charge it at.` });
30
+ const answer = await paddleJson(transport, `/subscriptions/${encodeURIComponent(request.providerSubscriptionId)}/charge`, {
31
+ what: "a one-time usage charge",
32
+ apiKey: options.apiKey,
33
+ environment: options.environment,
34
+ method: "POST",
35
+ body: {
36
+ effective_from: "next_billing_period",
37
+ items: [{
38
+ price_id: priceId,
39
+ quantity: request.quantity
40
+ }]
41
+ },
42
+ idempotencyKey: request.idempotencyKey
43
+ });
44
+ const charged = PaddleChargedSubscription.safeParse(answer?.data);
45
+ if (!charged.success || charged.data.id !== request.providerSubscriptionId) throw new PaymentsProviderUnavailableError({ detail: `Paddle answered the usage charge for ${request.providerSubscriptionId} with a different subscription.` });
46
+ } };
47
+ }
48
+ //#endregion
49
+ export { paddleUsageReporter };
@@ -1 +1 @@
1
- {"version":3,"file":"verify.d.ts","sourceRoot":"","sources":["../../../src/rails/paddle/verify.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,uBAAuB,CAAC;AACvE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AACpD,OAAO,KAAK,EAAE,iBAAiB,EAAE,eAAe,EAAE,MAAM,OAAO,CAAC;AAIhE;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAEH,oDAAoD;AACpD,MAAM,WAAW,8BAA8B;IAC7C,wGAAwG;IACxG,WAAW,EAAE,yBAAyB,CAAC;IACvC,yCAAyC;IACzC,WAAW,EAAE,iBAAiB,CAAC;IAC/B,yGAAyG;IACzG,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,8FAA8F;IAC9F,GAAG,EAAE,IAAI,CAAC;IACV,qBAAqB;IACrB,SAAS,EAAE,eAAe,CAAC;CAC5B;AAKD,wFAAwF;AACxF,wBAAsB,uBAAuB,CAC3C,OAAO,EAAE,MAAM,EACf,OAAO,EAAE,8BAA8B,GACtC,OAAO,CAAC,gBAAgB,CAAC,CA2D3B"}
1
+ {"version":3,"file":"verify.d.ts","sourceRoot":"","sources":["../../../src/rails/paddle/verify.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,uBAAuB,CAAC;AACvE,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AACpD,OAAO,KAAK,EAAE,iBAAiB,EAAE,eAAe,EAAE,MAAM,OAAO,CAAC;AAIhE;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAEH,oDAAoD;AACpD,MAAM,WAAW,8BAA8B;IAC7C,wGAAwG;IACxG,WAAW,EAAE,yBAAyB,CAAC;IACvC,yCAAyC;IACzC,WAAW,EAAE,iBAAiB,CAAC;IAC/B,yGAAyG;IACzG,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,8FAA8F;IAC9F,GAAG,EAAE,IAAI,CAAC;IACV,qBAAqB;IACrB,SAAS,EAAE,eAAe,CAAC;CAC5B;AAED,wFAAwF;AACxF,wBAAsB,uBAAuB,CAC3C,OAAO,EAAE,MAAM,EACf,OAAO,EAAE,8BAA8B,GACtC,OAAO,CAAC,gBAAgB,CAAC,CA+D3B"}
@@ -3,13 +3,12 @@
3
3
  import { PaymentsInvalidReceiptError, PaymentsVerificationFailedError } from "../../error/errors.js";
4
4
  import { PADDLE_CUSTOM_ACCOUNT, accountReferenceOf, transactionEvent } from "./objects.js";
5
5
  import { readTransaction } from "./read.js";
6
+ import { isPaddleTransactionId } from "../../data/paddleIds.js";
6
7
  //#region src/rails/paddle/verify.ts
7
- /** Paddle's transaction ids. Checked before a round trip, so a malformed one costs nothing. */
8
- const TRANSACTION_ID = /^txn_[a-z0-9]+$/;
9
8
  /** Verify one submitted Paddle transaction id, and report who it says it belongs to. */
10
9
  async function verifyPaddleTransaction(receipt, options) {
11
10
  const id = receipt.trim();
12
- if (!TRANSACTION_ID.test(id)) throw new PaymentsInvalidReceiptError({
11
+ if (!isPaddleTransactionId(id)) throw new PaymentsInvalidReceiptError({
13
12
  message: "That isn't a Paddle transaction.",
14
13
  action: "Submit the `txn_…` the checkout's completion callback handed back.",
15
14
  detail: `A Paddle receipt is a transaction id of the form txn_…; this one is ${id.length} characters and does not match.`
@@ -0,0 +1,12 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ /**
4
+ * The quantity a store stated, or null — never a default.
5
+ *
6
+ * Every rail but one parses a quantity that is sometimes absent: a metered Stripe price carries none, a Paddle
7
+ * line on an old shape carries none, a Play one-time purchase of one omits it. Writing `1` for absent would
8
+ * invent a fact the store did not state, and a seat count read off it would be a number nobody reported.
9
+ * So a positive whole number crosses and anything else is null.
10
+ */
11
+ export declare function statedQuantity(value: unknown): number | null;
12
+ //# sourceMappingURL=quantity.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"quantity.d.ts","sourceRoot":"","sources":["../../src/rails/quantity.ts"],"names":[],"mappings":"AAGA;;;;;;;GAOG;AACH,wBAAgB,cAAc,CAAC,KAAK,EAAE,OAAO,GAAG,MAAM,GAAG,IAAI,CAE5D"}
@@ -0,0 +1,16 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ //#region src/rails/quantity.ts
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
+ function statedQuantity(value) {
13
+ return typeof value === "number" && Number.isInteger(value) && value > 0 ? value : null;
14
+ }
15
+ //#endregion
16
+ export { statedQuantity };
@@ -1 +1 @@
1
- {"version":3,"file":"checkout.d.ts","sourceRoot":"","sources":["../../../src/rails/stripe/checkout.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,uBAAuB,CAAC;AACvE,OAAO,KAAK,EAAE,eAAe,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AACzE,OAAO,EAAyB,KAAK,e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AAE,IAAI,EAAE,UAAU,CAAA;CAAE,CAUpG"}
@@ -24,7 +24,7 @@ async function createStripeCheckoutSession(input, options) {
24
24
  mode: input.subscription ? "subscription" : "payment",
25
25
  line_items: [{
26
26
  price: input.providerProductId,
27
- quantity: 1
27
+ quantity: input.reported ? void 0 : 1
28
28
  }],
29
29
  success_url: input.successUrl,
30
30
  cancel_url: input.cancelUrl,
@@ -1 +1 @@
1
- {"version":3,"file":"objects.d.ts","sourceRoot":"","sources":["../../../src/rails/stripe/objects.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAGxB,OAAO,EAA4B,KAAK,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAElF,OAAO,KAAK,EAAE,gBAAgB,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AAE1E;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA2CG;AAEH,kGAAkG;AAClG,eAAO,MAAM,iCAAiC,4BAA4B,CAAC;AAE3E,8EAA8E;AAC9E,eAAO,MAAM,qBAAqB,mBAAmB,CAAC;AA2DtD,eAAO,MAAM,kBAAkB;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAoD6C,CAAC;AAC7E,MAAM,MAAM,kBAAkB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,kBAAkB,CAAC,CAAC;AAYpE,eAAO,MAAM,YAAY;;;;;;;;;;;iBAqBuC,CAAC;AACjE,MAAM,MAAM,YAAY,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,YAAY,CAAC,CAAC;AAuBxD,eAAO,MAAM,qBAAqB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAqD8C,CAAC;AACjF,MAAM,MAAM,qBAAqB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,qBAAqB,CAAC,CAAC;AAE1E,eAAO,MAAM,WAAW;;;;;;;;;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EAAE,gBAAgB,GAAG,IAAI,CAAC;CAC/B;AAaD;;;;;;GAMG;AACH,wBAAgB,wBAAwB,CAAC,MAAM,EAAE,MAAM,EAAE,iBAAiB,EAAE,OAAO,GAAG,cAAc,CASnG;AAED,2CAA2C;AAC3C,wBAAgB,qBAAqB,CAAC,YAAY,EAAE,kBAAkB,EAAE,OAAO,EAAE,IAAI,GAAG,iBAAiB,CAiCxG;AAED,+GAA+G;AAC/G,MAAM,WAAW,oBAAoB;IACnC;;;;OAIG;IACH,OAAO,EAAE,IAAI,GAAG,IAAI,CAAC;IACrB,2FAA2F;IAC3F,GAAG,EAAE,IAAI,CAAC;IACV,4FAA4F;IAC5F,cAAc,CAAC,EAAE,cAAc,GAAG,IAAI,CAAC;CACxC;AAED,kGAAkG;AAClG,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,qBAAqB,EAAE,OAAO,EAAE,oBAAoB,GAAG,iBAAiB,CA6DjH;AA0BD,mFAAmF;AACnF,wBAAgB,eAAe,CAAC,MAAM,EAAE,YAAY,EAAE,OAAO,EAAE;IAAE,OAAO,EAAE,IAAI,CAAA;CAAE,GAAG,iBAAiB,CAmDnG;AAED;;;;;;;GAOG;AACH,wBAAgB,cAAc,CAAC,KAAK,EAAE,WAAW,GAAG,iBAAiB,CAsBpE"}
@@ -3,6 +3,7 @@
3
3
  import { ACCESS_GRANTING_STATUSES } from "../../data/status.js";
4
4
  import { PaymentsVerificationFailedError } from "../../error/errors.js";
5
5
  import { minorUnitDigits, minorUnitsFromScaled } from "../../data/money.js";
6
+ import { statedQuantity } from "../quantity.js";
6
7
  import { z } from "zod";
7
8
  //#region src/rails/stripe/objects.ts
8
9
  /**
@@ -202,6 +203,7 @@ function mapStripeSubscription(subscription, eventAt) {
202
203
  originalTransactionId: subscription.id,
203
204
  amountMinor: minorUnits(item.price.unit_amount ?? null, currency),
204
205
  currency,
206
+ quantity: statedQuantity(item.quantity),
205
207
  providerEventAt: eventAt,
206
208
  payload: subscription
207
209
  },
@@ -260,6 +262,7 @@ function mapStripeSession(session, options) {
260
262
  originalTransactionId: null,
261
263
  amountMinor: minorUnits(session.amount_total ?? null, currency),
262
264
  currency,
265
+ quantity: statedQuantity(session.line_items?.data[0]?.quantity),
263
266
  providerEventAt: options.eventAt ?? retrievedAt(session, charge, status, options.now),
264
267
  payload: session
265
268
  },
@@ -0,0 +1,10 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import type { UsageReporter } from "../../usage/reporter";
4
+ import { type StripeHttpFetch } from "./api";
5
+ /** The Stripe reporter, over the secret key and a transport. */
6
+ export declare function stripeUsageReporter(options: {
7
+ secretKey: string;
8
+ transport?: StripeHttpFetch;
9
+ }): UsageReporter;
10
+ //# sourceMappingURL=usage.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"usage.d.ts","sourceRoot":"","sources":["../../../src/rails/stripe/usage.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,aAAa,EAAsB,MAAM,sBAAsB,CAAC;AAC9E,OAAO,EAAE,KAAK,eAAe,EAA+B,MAAM,OAAO,CAAC;AAyB1E,gEAAgE;AAChE,wBAAgB,mBAAmB,CAAC,OAAO,EAAE;IAAE,SAAS,EAAE,MAAM,CAAC;IAAC,SAAS,CAAC,EAAE,eAAe,CAAA;CAAE,GAAG,aAAa,CA4B9G"}
@@ -0,0 +1,49 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { PaymentsProviderUnavailableError } from "../../error/errors.js";
4
+ import { stripeHttpFetch, stripeJson } from "./api.js";
5
+ import { z } from "zod";
6
+ //#region src/rails/stripe/usage.ts
7
+ /**
8
+ * Reporting a count to Stripe: one Billing Meter event per reported period.
9
+ *
10
+ * `POST /v1/billing/meter_events` with the meter's `event_name`, the customer, the count as `value`, and the
11
+ * period's row id as `identifier` — which Stripe enforces as unique, so a report sent twice is one event. The
12
+ * subscription's metered price reads the meter, and the meter's own aggregation over the period — a setting
13
+ * on the meter in Stripe, not here — is what the invoice bills. The pass sends one event per period for both
14
+ * cadences — a `daily-peak` event carries the period's highest day — so a summing meter bills that count.
15
+ *
16
+ * The timestamp is the report's own `at`, which the pass dates inside the period it bills, so the event
17
+ * lands on that period's invoice.
18
+ */
19
+ /** What Stripe answers for a recorded meter event — as much as proves it recorded this one. */
20
+ const StripeMeterEvent = z.object({
21
+ object: z.literal("billing.meter_event").describe("Always `billing.meter_event`."),
22
+ event_name: z.string().describe("The meter the event was recorded against."),
23
+ identifier: z.string().describe("The idempotency identifier the event was recorded under.")
24
+ }).loose().describe("A Stripe Billing Meter event, as Stripe answers its creation.");
25
+ /** The Stripe reporter, over the secret key and a transport. */
26
+ function stripeUsageReporter(options) {
27
+ const transport = options.transport ?? stripeHttpFetch;
28
+ return { async report(request) {
29
+ const meter = request.billing.stripe?.meterEventName;
30
+ if (meter === void 0 || request.providerCustomerId === void 0) throw new PaymentsProviderUnavailableError({ detail: `Stripe usage for ${request.providerSubscriptionId} has no ${meter === void 0 ? "meter event name" : "customer"} to report against.` });
31
+ const answer = await stripeJson(transport, "/billing/meter_events", {
32
+ what: "a meter event",
33
+ secretKey: options.secretKey,
34
+ form: {
35
+ event_name: meter,
36
+ identifier: request.idempotencyKey,
37
+ timestamp: Math.floor(request.at.getTime() / 1e3),
38
+ payload: {
39
+ stripe_customer_id: request.providerCustomerId,
40
+ value: String(request.quantity)
41
+ }
42
+ }
43
+ });
44
+ const event = StripeMeterEvent.safeParse(answer);
45
+ if (!event.success || event.data.identifier !== request.idempotencyKey) throw new PaymentsProviderUnavailableError({ detail: `Stripe answered the meter event for ${request.providerSubscriptionId} with something that is not that event.` });
46
+ } };
47
+ }
48
+ //#endregion
49
+ export { stripeUsageReporter };
@@ -1 +1 @@
1
- {"version":3,"file":"registry.d.ts","sourceRoot":"","sources":["../../src/secret/registry.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CA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AM,yBAAyB;;;kBAmBnC,CAAC;AACJ,MAAM,MAAM,yBAAyB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,yBAAyB,CAAC,CAAC;AAElF,eAAO,MAAM,2BAA2B;;;;;;;;;;;;;;;;;;;;;;;;;;kBAYrC,CAAC;AACJ,MAAM,MAAM,2BAA2B,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,2BAA2B,CAAC,CAAC;AAEtF,8FAA8F;AAC9F,eAAO,MAAM,uBAAuB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAmBlC,CAAC;AAEH;;;;;;;;;GASG;AACH,wBAAgB,eAAe,CAAC,CAAC,SAAS,YAAY,EACpD,WAAW,EAAE,2BAA2B,EACxC,IAAI,EAAE,CAAC,GACN,WAAW,CAAC,2BAA2B,CAAC,CAAC,CAAC,CAAC,CAS7C"}
@@ -2,6 +2,7 @@
2
2
  // SPDX-License-Identifier: MIT
3
3
  import { PaymentsRailNotConfiguredError } from "../error/errors.js";
4
4
  import { z } from "zod";
5
+ import { pithyCommand } from "@pithy-sh/core/src/cli/command";
5
6
  import { defineSecretRegistry } from "@pithy-sh/secrets/src/registry";
6
7
  //#region src/secret/registry.ts
7
8
  /**
@@ -147,8 +148,8 @@ const paymentsSecretsRegistry = defineSecretRegistry({ [PAYMENTS_PROVIDER_SECRET
147
148
  function railCredentials(credentials, rail) {
148
149
  const block = credentials[rail];
149
150
  if (!block) throw new PaymentsRailNotConfiguredError({
150
- detail: `The ${rail} rail has no credentials in "${PAYMENTS_PROVIDER_SECRET}" for this environment. Run \`pithy secrets set\` for it.`,
151
- action: `Take the ${rail} credentials from ${PAYMENTS_RAIL_CONSOLES[rail]} and set them with \`pithy secrets set ${PAYMENTS_PROVIDER_SECRET}\`.`
151
+ detail: `The ${rail} rail has no credentials in "${PAYMENTS_PROVIDER_SECRET}" for this environment. Run \`${pithyCommand("secrets update", { args: [PAYMENTS_PROVIDER_SECRET] })}\` for it.`,
152
+ action: `Take the ${rail} credentials from ${PAYMENTS_RAIL_CONSOLES[rail]} and set them with \`${pithyCommand("secrets update", { args: [PAYMENTS_PROVIDER_SECRET] })}\`.`
152
153
  });
153
154
  return block;
154
155
  }
@@ -0,0 +1,120 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import type { D1Database } from "@cloudflare/workers-types";
4
+ import type { Logger } from "@pithy-sh/core/src/logger/logger";
5
+ import { type PaymentsConfig, type PaymentsReportedBilling } from "../config/config";
6
+ import { type PaymentsSubject } from "../data/subject";
7
+ import { type UsageFinding, type UsageFindingReason } from "../data/usageRun";
8
+ import type { UsageReporter } from "./reporter";
9
+ /**
10
+ * The usage-reporting pass: ask the adopter how many, and tell the store.
11
+ *
12
+ * **Configuration decides what is billable and how often; a function decides the number.** The same split
13
+ * as `billingSubject` / `resolveSubject`, for the same reason — `PaymentsConfig` round-trips through JSON, so
14
+ * a function cannot live in it. `resolveQuantity` rides on the `payments(...)` options and reaches this pass
15
+ * through the composed capability, never through config.
16
+ *
17
+ * **Pulled, not pushed.** A cron walks the subscribed subjects and reports, the shape the reconcile pass
18
+ * already has. No proration, no mid-cycle rewrite of a subscription's items, and a missed report bills last
19
+ * period's number rather than the wrong number indefinitely.
20
+ *
21
+ * ## What it never does
22
+ *
23
+ * - **Report a guess.** A resolver answering `undefined` reports nothing for that subject, and is counted as
24
+ * skipped — never `0`, because a zeroed meter is a bill of nothing for a customer who owes something. A
25
+ * non-integer, a negative, or a count outside the product's `min`/`max` is skipped and named — never
26
+ * clamped, because a clamped value is a wrong number billed silently.
27
+ * - **Stop for one subject.** A resolver that throws is a failure in the tally, and the sweep goes on.
28
+ * - **Report a period twice.** One row per `(rail, subscription, period)`, claimed before the store is
29
+ * called, and the row id sent as the store's idempotency key.
30
+ * - **Read a meter.** The kit does not sell overage. What a kit meter counted is never a billable number,
31
+ * and nothing here imports one.
32
+ *
33
+ * ## The two cadences
34
+ *
35
+ * - `period-end` — one report per subscription per billing period, keyed on the period's end and sent on
36
+ * the first run inside its last {@link PERIOD_END_WINDOW_MS}, dated at that run. Every later run in the
37
+ * period finds the row.
38
+ * - `daily-peak` — every run asks, and the day's row keeps the highest answer; a lower later answer never
39
+ * lowers it. **A day is never sent on its own.** The period's report is the highest of its days, sent once,
40
+ * in the period's last {@link PERIOD_END_WINDOW_MS} — keyed and dated exactly as a `period-end` report.
41
+ * Both stores add up what they are sent: Stripe's meter sums its events, and every Paddle charge is a line
42
+ * on the bill. A report per day would bill the sum of thirty daily peaks, not the period's peak. The day
43
+ * rows stay behind, and they are the audit: the number billed is the largest of them up to the report.
44
+ *
45
+ * A `daily-peak` report goes out when the last day opens, as a `period-end` one does, so a peak reached in
46
+ * the period's final hours after it was sent is not billed. Under-billing an hour is the right way round.
47
+ */
48
+ /** How close to a period's end a `period-end` report goes out. A day, so an hourly or daily cron lands inside it. */
49
+ export declare const PERIOD_END_WINDOW_MS = 86400000;
50
+ /** What `resolveQuantity` is told besides who: the env, the product, and when. */
51
+ export interface PaymentsQuantityContext {
52
+ /** The worker env — the adopter's bindings, for counting their own rows. */
53
+ env: Record<string, unknown>;
54
+ /** The quantity-billed product being reported. */
55
+ productId: string;
56
+ /** What one unit is, from the product's `billing.unit`. */
57
+ unit: string;
58
+ /** The run's clock. */
59
+ now: Date;
60
+ }
61
+ /**
62
+ * The adopter's count for one subject — students, coaches, seats. `undefined` reports nothing this period.
63
+ *
64
+ * Called with no request: the pass runs on a schedule. So it is handed the env, not a Hono context, and counts
65
+ * from the adopter's own rows. Payments never counts members.
66
+ */
67
+ export type PaymentsQuantityResolver = (context: PaymentsQuantityContext, subject: PaymentsSubject) => Promise<number | undefined>;
68
+ /** What one pass needs. */
69
+ export interface UsagePassDeps {
70
+ /** The app database. */
71
+ d1: D1Database;
72
+ /** The resolved config. */
73
+ config: PaymentsConfig;
74
+ /** The adopter's resolver. */
75
+ resolveQuantity: PaymentsQuantityResolver;
76
+ /** One reporter per rail this pass may report on. A rail with none is counted as a failure per period. */
77
+ reporters: Partial<Record<"stripe" | "paddle", UsageReporter>>;
78
+ /** The env handed to the resolver. */
79
+ env: Record<string, unknown>;
80
+ /** The clock. */
81
+ now: () => Date;
82
+ /** Where every skip and failure is logged. */
83
+ log: Logger;
84
+ /** The id minter. Defaults to `crypto.randomUUID`. */
85
+ newId?: () => string;
86
+ }
87
+ /** The tally one pass records. */
88
+ export interface UsagePassTally {
89
+ /** The run's id. */
90
+ id: string;
91
+ /** Subscriptions examined. */
92
+ scanned: number;
93
+ /** Periods a store accepted. */
94
+ reported: number;
95
+ /** Daily-peak samples taken. */
96
+ sampled: number;
97
+ /** Periods found already reported, so nothing was sent. */
98
+ alreadyReported: number;
99
+ /** Subjects whose resolver answered nothing. */
100
+ skipped: number;
101
+ /** Subjects whose resolver answered a number that may not be billed. */
102
+ invalid: number;
103
+ /** Subjects whose resolver threw, or whose report a store refused. */
104
+ failed: number;
105
+ /** The subjects not reported, and why, up to {@link MAX_USAGE_FINDINGS}. */
106
+ findings: UsageFinding[];
107
+ }
108
+ /** Whether a resolver's answer may be billed, and if not, why. */
109
+ export declare function judgeQuantity(answer: unknown, billing: Pick<PaymentsReportedBilling, "min" | "max">): {
110
+ ok: true;
111
+ quantity: number;
112
+ } | {
113
+ ok: false;
114
+ reason: UsageFindingReason;
115
+ };
116
+ /** The UTC day `at` falls in, as `YYYY-MM-DD`. A `daily-peak` period's key. */
117
+ export declare function utcDay(at: Date): string;
118
+ /** Run one pass, record its tally, and return it. */
119
+ export declare function runUsageReport(deps: UsagePassDeps): Promise<UsagePassTally>;
120
+ //# sourceMappingURL=pass.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pass.d.ts","sourceRoot":"","sources":["../../src/usage/pass.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,2BAA2B,CAAC;AAG5D,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,kCAAkC,CAAC;AAE/D,OAAO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