@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,115 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { z } from "zod";
4
+ //#region src/config/allowances.ts
5
+ /**
6
+ * What an entitlement buys: a display name, numbered allowances, and switches. Declared once per key.
7
+ *
8
+ * A key is the thing gating code names and the thing a product mentions — `growth` — and until this
9
+ * existed it was declared nowhere. It was only ever *mentioned*, in the array a product grants and in a
10
+ * second list of comp-only keys, and those two could disagree about the same key with no answer for which
11
+ * won. There was also nowhere to write what a key buys: "up to 25 students" could gate on the key and
12
+ * could not tell 25 from 26.
13
+ *
14
+ * **The declaration hangs on the key, not on the product, because a tier is sold by more than one
15
+ * product.** `growth_monthly` and `growth_annual` are two SKUs on two rails for one tier. Writing the
16
+ * numbers on the product writes them twice and reconciles them forever.
17
+ *
18
+ * **Two maps, not one.** A single `limits: { emails: 5000, sso: true }` reads well and answers
19
+ * `number | boolean | null`, and from there no caller can tell `0` from `false` from *nothing was
20
+ * declared* without writing the same narrowing every time. `quotas` holds integers and `null`, and
21
+ * `features` holds booleans, so each reader answers one type.
22
+ *
23
+ * **`null` is unlimited, and it is written, never inferred.** A quota a key does not mention is not
24
+ * unlimited for that key — it falls to `defaults`, then to `0`. Unlimited is a decision somebody wrote
25
+ * down, because a paywall that silently does not exist is invisible until the invoice.
26
+ */
27
+ /** The longest an allowance name may be. Long enough to read, short enough to sit in an audit row. */
28
+ const MAX_ALLOWANCE_NAME_LENGTH = 64;
29
+ /** The longest a declared tier name may be — the same bound a product's display name carries. */
30
+ const MAX_TIER_NAME_LENGTH = 120;
31
+ /**
32
+ * A quota or feature name — `emails`, `seats`, `auditExport`. camelCase or snake_case, starting with a
33
+ * lowercase letter, because it is an identifier code names and never copy a screen renders.
34
+ */
35
+ const AllowanceName = z.string().min(1).max(MAX_ALLOWANCE_NAME_LENGTH).regex(/^[a-z][A-Za-z0-9_]*$/, "An allowance name starts with a lowercase letter and holds only letters, digits, and underscores.").describe("A quota or feature name — `emails`, `seats`, `auditExport`. An identifier gating code reads, never display copy, and never translated.");
36
+ /**
37
+ * One quota's value: a whole number of things, or `null` for unlimited. Never a float, never negative,
38
+ * never a string — a number that costs money to serve is not something to coerce.
39
+ */
40
+ const QuotaValue = z.number().int("A quota is a whole number, or null for unlimited.").min(0, "A quota is never negative. Use 0 for none and null for unlimited.").nullable().describe("How many of a thing this grants: a whole number from 0, or null for unlimited.");
41
+ /** A ceiling an operator's override may not pass. A whole number, and never unlimited — that is not a ceiling. */
42
+ const OverrideCeiling = z.number().int("An override ceiling is a whole number.").min(0, "An override ceiling is never negative.").describe("The largest number an operator's override may set for this quota. A set past it is refused naming it, never clamped.");
43
+ /** A quota map: name → whole number or unlimited. */
44
+ const QuotaMap = z.record(AllowanceName, QuotaValue).describe("Numbered allowances by name. A whole number from 0, or null for unlimited.");
45
+ /** A feature map: name → on or off. */
46
+ const FeatureMap = z.record(AllowanceName, z.boolean().describe("Whether this switch is on.")).describe("Switches by name. A feature is read, never enforced: `false` denies nothing on its own.");
47
+ const PaymentsEntitlementDeclaration = z.object({
48
+ name: z.string().min(1).max(MAX_TIER_NAME_LENGTH).describe("The tier's display name — `Growth`. A product name, so it is not translated, the way a product's own name is not."),
49
+ quotas: QuotaMap.default({}).describe("What this key allows, by name — `{ emails: 5000, seats: 10 }`. A whole number from 0, or null for unlimited. Read with `quota(c, name)`, which resolves across every key the subject holds and answers the highest."),
50
+ features: FeatureMap.default({}).describe("The switches this key turns on or off, by name — `{ sso: true }`. Read with `feature(c, name)`, which is true when any held key says true. Never enforced on its own."),
51
+ overrideMax: z.record(AllowanceName, OverrideCeiling).optional().describe("Optional. Per quota, the largest number an operator's override may set — so `200000000` is refused where `20000` was meant. A quota with no ceiling accepts any whole number. Must name a quota this key declares, and must not sit below that quota's own value.")
52
+ }).describe("What one entitlement key buys: its display name, its numbered quotas, and its switches. Declared once, however many products sell it.");
53
+ const PaymentsAllowanceDefaults = z.object({
54
+ quotas: QuotaMap.default({}).describe("What a subject holding no key that speaks to a quota gets — the free floor. A name absent here resolves to 0."),
55
+ features: FeatureMap.default({}).describe("The switches a subject holding no key that speaks to them gets. A name absent here resolves to false.")
56
+ }).describe("The free floor: what a caller holding no key gets. Optional, and omitting it means an unentitled caller gets 0 of every quota and no feature.");
57
+ /**
58
+ * Every quota name this project declares, on any key or on the floor, sorted.
59
+ *
60
+ * Derived, never written down, the way the set of grantable keys is derived from the products — a second
61
+ * list of names would be a list that disagrees with the declarations the first time one is added.
62
+ */
63
+ function declaredQuotaNames(declarations) {
64
+ const names = new Set(Object.keys(declarations.defaults?.quotas ?? {}));
65
+ for (const declaration of Object.values(declarations.entitlements)) for (const name of Object.keys(declaration.quotas)) names.add(name);
66
+ return [...names].sort();
67
+ }
68
+ /** Every feature name this project declares, on any key or on the floor, sorted. */
69
+ function declaredFeatureNames(declarations) {
70
+ const names = new Set(Object.keys(declarations.defaults?.features ?? {}));
71
+ for (const declaration of Object.values(declarations.entitlements)) for (const name of Object.keys(declaration.features)) names.add(name);
72
+ return [...names].sort();
73
+ }
74
+ /**
75
+ * Check the rules a schema cannot state field by field: a name that is a quota on one key and a feature on
76
+ * another, and an `overrideMax` that names an undeclared quota or sits below the quota it bounds.
77
+ */
78
+ function declarationProblems(declarations) {
79
+ const problems = [];
80
+ const quotas = new Set(declaredQuotaNames(declarations));
81
+ for (const name of declaredFeatureNames(declarations)) {
82
+ if (!quotas.has(name)) continue;
83
+ problems.push({
84
+ path: ["entitlements"],
85
+ message: `"${name}" is declared as both a quota and a feature. A name is a number or a switch, never both. Rename one.`
86
+ });
87
+ }
88
+ for (const [key, declaration] of Object.entries(declarations.entitlements)) for (const [name, ceiling] of Object.entries(declaration.overrideMax ?? {})) {
89
+ if (!(name in declaration.quotas)) {
90
+ problems.push({
91
+ path: [
92
+ "entitlements",
93
+ key,
94
+ "overrideMax",
95
+ name
96
+ ],
97
+ message: `Entitlement "${key}" sets an overrideMax for "${name}", which it declares no quota for. A ceiling bounds a quota the key declares. Declared: ${Object.keys(declaration.quotas).sort().join(", ") || "none"}.`
98
+ });
99
+ continue;
100
+ }
101
+ const value = declaration.quotas[name];
102
+ if (value === null || value !== void 0 && ceiling < value) problems.push({
103
+ path: [
104
+ "entitlements",
105
+ key,
106
+ "overrideMax",
107
+ name
108
+ ],
109
+ message: `Entitlement "${key}" caps overrides of "${name}" at ${ceiling}, below the ${value === null ? "unlimited" : value} the plan itself grants. A ceiling under the plan would refuse an override the plan already allows.`
110
+ });
111
+ }
112
+ return problems;
113
+ }
114
+ //#endregion
115
+ export { AllowanceName, FeatureMap, OverrideCeiling, PaymentsAllowanceDefaults, PaymentsEntitlementDeclaration, QuotaMap, QuotaValue, declarationProblems, declaredFeatureNames, declaredQuotaNames };
@@ -1,7 +1,8 @@
1
1
  // SPDX-FileCopyrightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: MIT
3
3
  import { z } from "zod";
4
- import { type PaymentsRail } from "../data/rail";
4
+ import { PaymentsRail } from "../data/rail";
5
+ import { type DeclarationProblem } from "./allowances";
5
6
  export declare const PaymentsRailToggles: z.ZodObject<{
6
7
  apple: z.ZodDefault<z.ZodBoolean>;
7
8
  google: z.ZodDefault<z.ZodBoolean>;
@@ -77,6 +78,47 @@ export declare const PaymentsGrants: z.ZodObject<{
77
78
  }, z.core.$strip>>;
78
79
  }, z.core.$strip>;
79
80
  export type PaymentsGrants = z.infer<typeof PaymentsGrants>;
81
+ /**
82
+ * The rails a reported quantity can be billed on. Stripe takes a meter event; Paddle takes a one-time charge
83
+ * against the subscription. **Apple and Google cannot**: in-app purchase has no concept of a seat, so a
84
+ * quantity-billed product is web-rails-only and says so at boot.
85
+ *
86
+ * **Lemon Squeezy is deferred, with the reason recorded on pithy-sh/pithy#561.** Its usage records are
87
+ * written against a subscription *item*, which the projection does not store, so the same call shape does
88
+ * not fit without a new column and a refresh of every Lemon Squeezy subscription. Named here so the refusal
89
+ * can say so, rather than reading as an oversight.
90
+ */
91
+ export declare const REPORTED_BILLING_RAILS: readonly ["stripe", "paddle"];
92
+ /** How often a reported quantity goes to the store. */
93
+ export declare const PaymentsReportCadence: z.ZodEnum<{
94
+ "daily-peak": "daily-peak";
95
+ "period-end": "period-end";
96
+ }>;
97
+ export type PaymentsReportCadence = z.infer<typeof PaymentsReportCadence>;
98
+ export declare const PaymentsReportedBilling: z.ZodObject<{
99
+ kind: z.ZodLiteral<"reported">;
100
+ unit: z.ZodString;
101
+ cadence: z.ZodDefault<z.ZodEnum<{
102
+ "daily-peak": "daily-peak";
103
+ "period-end": "period-end";
104
+ }>>;
105
+ min: z.ZodDefault<z.ZodNumber>;
106
+ max: z.ZodNumber;
107
+ rails: z.ZodArray<z.ZodEnum<{
108
+ apple: "apple";
109
+ google: "google";
110
+ lemonSqueezy: "lemonSqueezy";
111
+ paddle: "paddle";
112
+ stripe: "stripe";
113
+ }>>;
114
+ stripe: z.ZodOptional<z.ZodObject<{
115
+ meterEventName: z.ZodString;
116
+ }, z.core.$strict>>;
117
+ paddle: z.ZodOptional<z.ZodObject<{
118
+ priceId: z.ZodString;
119
+ }, z.core.$strict>>;
120
+ }, z.core.$strict>;
121
+ export type PaymentsReportedBilling = z.output<typeof PaymentsReportedBilling>;
80
122
  export declare const PaymentsProduct: z.ZodObject<{
81
123
  type: z.ZodEnum<{
82
124
  consumable: "consumable";
@@ -106,9 +148,51 @@ export declare const PaymentsProduct: z.ZodObject<{
106
148
  amount: z.ZodNumber;
107
149
  }, z.core.$strip>>;
108
150
  }, z.core.$strip>>;
151
+ billing: z.ZodOptional<z.ZodObject<{
152
+ kind: z.ZodLiteral<"reported">;
153
+ unit: z.ZodString;
154
+ cadence: z.ZodDefault<z.ZodEnum<{
155
+ "daily-peak": "daily-peak";
156
+ "period-end": "period-end";
157
+ }>>;
158
+ min: z.ZodDefault<z.ZodNumber>;
159
+ max: z.ZodNumber;
160
+ rails: z.ZodArray<z.ZodEnum<{
161
+ apple: "apple";
162
+ google: "google";
163
+ lemonSqueezy: "lemonSqueezy";
164
+ paddle: "paddle";
165
+ stripe: "stripe";
166
+ }>>;
167
+ stripe: z.ZodOptional<z.ZodObject<{
168
+ meterEventName: z.ZodString;
169
+ }, z.core.$strict>>;
170
+ paddle: z.ZodOptional<z.ZodObject<{
171
+ priceId: z.ZodString;
172
+ }, z.core.$strict>>;
173
+ }, z.core.$strict>>;
109
174
  clawback: z.ZodDefault<z.ZodBoolean>;
110
175
  }, z.core.$strip>;
111
176
  export type PaymentsProduct = z.infer<typeof PaymentsProduct>;
177
+ /**
178
+ * The meters the kit counts itself, because the kit writes the rows they count. Everything the kit cannot
179
+ * see — seats, students, projects — is the adopter's count, read through `quota()`. Payments never counts
180
+ * members. Forever.
181
+ */
182
+ export declare const KIT_METERS: readonly ["emails", "storageBytes", "mediaItems"];
183
+ export type KitMeter = (typeof KIT_METERS)[number];
184
+ export declare const PaymentsMeters: z.ZodObject<{
185
+ emails: z.ZodOptional<z.ZodObject<{
186
+ enforce: z.ZodDefault<z.ZodBoolean>;
187
+ }, z.core.$strict>>;
188
+ storageBytes: z.ZodOptional<z.ZodObject<{
189
+ enforce: z.ZodDefault<z.ZodBoolean>;
190
+ }, z.core.$strict>>;
191
+ mediaItems: z.ZodOptional<z.ZodObject<{
192
+ enforce: z.ZodDefault<z.ZodBoolean>;
193
+ }, z.core.$strict>>;
194
+ }, z.core.$strict>;
195
+ export type PaymentsMeters = z.output<typeof PaymentsMeters>;
112
196
  export declare const PaymentsConfig: z.ZodObject<{
113
197
  billingSubject: z.ZodEnum<{
114
198
  organization: "organization";
@@ -150,9 +234,53 @@ export declare const PaymentsConfig: z.ZodObject<{
150
234
  amount: z.ZodNumber;
151
235
  }, z.core.$strip>>;
152
236
  }, z.core.$strip>>;
237
+ billing: z.ZodOptional<z.ZodObject<{
238
+ kind: z.ZodLiteral<"reported">;
239
+ unit: z.ZodString;
240
+ cadence: z.ZodDefault<z.ZodEnum<{
241
+ "daily-peak": "daily-peak";
242
+ "period-end": "period-end";
243
+ }>>;
244
+ min: z.ZodDefault<z.ZodNumber>;
245
+ max: z.ZodNumber;
246
+ rails: z.ZodArray<z.ZodEnum<{
247
+ apple: "apple";
248
+ google: "google";
249
+ lemonSqueezy: "lemonSqueezy";
250
+ paddle: "paddle";
251
+ stripe: "stripe";
252
+ }>>;
253
+ stripe: z.ZodOptional<z.ZodObject<{
254
+ meterEventName: z.ZodString;
255
+ }, z.core.$strict>>;
256
+ paddle: z.ZodOptional<z.ZodObject<{
257
+ priceId: z.ZodString;
258
+ }, z.core.$strict>>;
259
+ }, z.core.$strict>>;
153
260
  clawback: z.ZodDefault<z.ZodBoolean>;
154
261
  }, z.core.$strip>>>;
155
- manualEntitlements: z.ZodDefault<z.ZodArray<z.ZodString>>;
262
+ entitlements: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodObject<{
263
+ name: z.ZodString;
264
+ quotas: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodNullable<z.ZodNumber>>>;
265
+ features: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodBoolean>>;
266
+ overrideMax: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodNumber>>;
267
+ }, z.core.$strip>>>;
268
+ defaults: z.ZodOptional<z.ZodObject<{
269
+ quotas: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodNullable<z.ZodNumber>>>;
270
+ features: z.ZodDefault<z.ZodRecord<z.ZodString, z.ZodBoolean>>;
271
+ }, z.core.$strip>>;
272
+ meters: z.ZodDefault<z.ZodObject<{
273
+ emails: z.ZodOptional<z.ZodObject<{
274
+ enforce: z.ZodDefault<z.ZodBoolean>;
275
+ }, z.core.$strict>>;
276
+ storageBytes: z.ZodOptional<z.ZodObject<{
277
+ enforce: z.ZodDefault<z.ZodBoolean>;
278
+ }, z.core.$strict>>;
279
+ mediaItems: z.ZodOptional<z.ZodObject<{
280
+ enforce: z.ZodDefault<z.ZodBoolean>;
281
+ }, z.core.$strict>>;
282
+ }, z.core.$strict>>;
283
+ manualEntitlements: z.ZodOptional<z.ZodNever>;
156
284
  stripe: z.ZodOptional<z.ZodObject<{
157
285
  successUrl: z.ZodURL;
158
286
  cancelUrl: z.ZodURL;
@@ -212,6 +340,18 @@ export interface PaymentsCatalogEntry {
212
340
  }
213
341
  /** The provider SKU this product is listed under on `rail`, or undefined when it does not ship there. */
214
342
  export declare function providerProductId(product: PaymentsProduct, rail: PaymentsRail): string | undefined;
343
+ /**
344
+ * What is wrong with one product's reported billing, as sentences naming the product — empty for a product
345
+ * that has none, or one that is sound.
346
+ *
347
+ * Every refusal here is at boot, because a reported product that cannot be reported is a subscription that
348
+ * bills nothing for a quantity the customer is using — invisible until somebody reads an invoice.
349
+ */
350
+ export declare function reportedBillingProblems(id: string, product: PaymentsProduct, config: Pick<PaymentsConfig, "rails">): DeclarationProblem[];
351
+ /** Every product billed by a reported quantity, with its id. */
352
+ export declare function reportedProducts(config: PaymentsConfig): (PaymentsCatalogEntry & {
353
+ billing: PaymentsReportedBilling;
354
+ })[];
215
355
  /** The product with this logical id, or undefined. Ids come from config, so an unknown one is a 404. */
216
356
  export declare function resolveProduct(config: PaymentsConfig, id: string): PaymentsCatalogEntry | undefined;
217
357
  /**
@@ -222,17 +362,23 @@ export declare function resolveProduct(config: PaymentsConfig, id: string): Paym
222
362
  */
223
363
  export declare function productForProviderSku(config: PaymentsConfig, rail: PaymentsRail, sku: string): PaymentsCatalogEntry | undefined;
224
364
  /**
225
- * Every entitlement key this project defines — what the catalog's products grant, plus what the adopter
226
- * declared grantable with no sale behind it.
365
+ * Every entitlement key this project defines — the keys `entitlements` declares. Every key a product
366
+ * mentions is among them, because the config refuses a mention with no declaration.
227
367
  *
228
- * The set a manual grant is checked against, and the set the control-plane catalog read publishes the first
229
- * half of. Computed once per composition: the catalog is config, so it cannot change under a running Worker.
368
+ * The set a manual grant is checked against, and the set the control-plane catalog read publishes.
369
+ * Computed once per composition: the catalog is config, so it cannot change under a running Worker.
230
370
  *
231
- * **Empty is a real answer.** A project composing payments with nothing to sell and nothing declared defines
232
- * no keys, and every grant against it is refused — which is correct, because there is no vocabulary to grant
233
- * in. It is the same statement `clientProjection` makes as `{ enabled: false }`.
371
+ * **Empty is a real answer.** A project composing payments with nothing declared defines no keys, and every
372
+ * grant against it is refused — which is correct, because there is no vocabulary to grant in. It is the same
373
+ * statement `clientProjection` makes as `{ enabled: false }`.
234
374
  */
235
375
  export declare function grantableEntitlements(config: PaymentsConfig): ReadonlySet<string>;
376
+ /**
377
+ * The declared keys no product sells — comp-only. Granted by hand through the control plane, sold by no
378
+ * checkout. What `manualEntitlements` used to list, said by the shape of the config rather than by a
379
+ * second list that could disagree with the first.
380
+ */
381
+ export declare function compOnlyEntitlements(config: PaymentsConfig): string[];
236
382
  /** The entitlement keys a product grants, or an empty list for an unknown product or one that grants none. */
237
383
  export declare function entitlementsForProduct(config: PaymentsConfig, id: string): readonly string[];
238
384
  /** Whether a rail is enabled for this project. A disabled rail refuses its routes and its webhook. */
@@ -1 +1 @@
1
- {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../../src/config/config.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAkB,KAAK,YAAY,EAAE,MAAM,cAAc,CAAC;AAoCjE,eAAO,MAAM,mBAAmB;;;;;;iBA6B+E,CAAC;AAChH,MAAM,MAAM,mBAAmB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,mBAAmB,CAAC,CAAC;AAEtE,eAAO,MAAM,mBAAmB;;;;EAI7B,CAAC;AACJ,MAAM,MAAM,mBAAmB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,mBAAmB,CAAC,CAAC;AAEtE,eAAO,MAAM,oBAAoB;;iBAQyE,CAAC;AAC3G,MAAM,MAAM,oBAAoB,GAAG,CAAC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ightText: 2026 Pithy
2
2
  // SPDX-License-Identifier: MIT
3
- import { PAYMENTS_RAILS } from "../data/rail.js";
3
+ import { PAYMENTS_RAILS, PaymentsRail } from "../data/rail.js";
4
4
  import { PaymentsSubjectType } from "../data/subject.js";
5
+ import { PaymentsAllowanceDefaults, PaymentsEntitlementDeclaration, declarationProblems, declaredQuotaNames } from "./allowances.js";
5
6
  import { EntitlementKey } from "@pithy-sh/core/src/entitlement/entitlement";
6
7
  import { SIGNED_WEBHOOK_MAX_TOLERANCE_SECONDS } from "@pithy-sh/core/src/http/webhookWindow";
7
8
  import { z } from "zod";
@@ -75,18 +76,58 @@ const PaymentsLedgerGrant = z.object({
75
76
  amount: z.number().int().positive().describe("How much to credit, as an integer in the currency's minor unit. Never a float, never zero.")
76
77
  }).describe("A balance credit performed on fulfillment, once per provider transaction.");
77
78
  const PaymentsGrants = z.object({ ledger: PaymentsLedgerGrant.optional().describe("Credit a `@pithy-sh/ledger` balance when this product is fulfilled. The only point of contact between the two capabilities, and opt-in — most products never touch a balance.") }).describe("What a purchase fulfills beyond its entitlements. Absent for the products that only unlock a feature.");
79
+ /**
80
+ * The rails a reported quantity can be billed on. Stripe takes a meter event; Paddle takes a one-time charge
81
+ * against the subscription. **Apple and Google cannot**: in-app purchase has no concept of a seat, so a
82
+ * quantity-billed product is web-rails-only and says so at boot.
83
+ *
84
+ * **Lemon Squeezy is deferred, with the reason recorded on pithy-sh/pithy#561.** Its usage records are
85
+ * written against a subscription *item*, which the projection does not store, so the same call shape does
86
+ * not fit without a new column and a refresh of every Lemon Squeezy subscription. Named here so the refusal
87
+ * can say so, rather than reading as an oversight.
88
+ */
89
+ const REPORTED_BILLING_RAILS = ["stripe", "paddle"];
90
+ /** How often a reported quantity goes to the store. */
91
+ const PaymentsReportCadence = z.enum(["period-end", "daily-peak"]).describe("How often the count is reported. `period-end` sends one count per subscription per billing period — simplest, and what a store's metering expects to be fed. `daily-peak` samples every run and keeps each day's high-water mark, then sends the period's highest day once, in its last day — the period's peak, never the sum of its days. The day rows stay as the audit a customer disputing an invoice can check.");
92
+ const PaymentsReportedBilling = z.strictObject({
93
+ kind: z.literal("reported").describe("The quantity is reported by payments, from a count the adopter's `resolveQuantity` computes. The only kind there is."),
94
+ unit: z.string().min(1).max(MAX_NAME_LENGTH).describe("What one unit is — `student`, `coach`, `seat`. For people reading the catalog and the run log."),
95
+ cadence: PaymentsReportCadence.default("period-end").describe("How often the count is reported. Defaults to `period-end`. Per product, because a project can sell two things metered differently."),
96
+ min: z.number().int().min(0).default(0).describe("The smallest count that may be reported. A resolver answering below it is skipped and logged — never clamped, because a clamped value is a wrong number billed silently."),
97
+ max: z.number().int().positive().describe("The largest count that may be reported. A resolver answering above it is skipped and logged — never clamped. A value that becomes money is bounded by somebody who meant it."),
98
+ rails: z.array(PaymentsRail).min(1).describe("Which rails report this product's count. Stripe and Paddle only — in-app purchase has no seats, and Lemon Squeezy is deferred."),
99
+ stripe: z.strictObject({ meterEventName: z.string().min(1).max(100).describe("The `event_name` of the Stripe Billing Meter this product's metered price reads — what each report is sent as.") }).optional().describe("How Stripe hears the count: the meter it is reported to. Required when `rails` lists stripe."),
100
+ paddle: z.strictObject({ priceId: z.string().min(1).max(MAX_SKU_LENGTH).describe("The one-time Paddle price charged per unit — `pri_01…`. Each report is a one-time charge of this price, at the reported quantity, on the subscription's next bill.") }).optional().describe("How Paddle hears the count: the one-time price it is charged at. Required when `rails` lists paddle.")
101
+ }).describe("Bill by a count the adopter's code owns. Payments asks `resolveQuantity` and reports the answer to the store; it never counts anybody's members itself, and never reports a number a kit meter counted.");
78
102
  const PaymentsProduct = z.object({
79
103
  type: PaymentsProductType.describe("What kind of product this is. Decides how a renewal and a restore behave."),
80
104
  name: z.string().min(1).max(MAX_NAME_LENGTH).describe("The display name a paywall renders — `Pro`, `Remove ads`. Required: it is the one product field a browser is given, and a paywall with no copy renders nothing."),
81
- entitlements: z.array(EntitlementKey).default([]).describe("The entitlement keys this product grants. Many products across many rails may grant one key, which is the whole point — gating code names the key, never this product. Empty for a product that only credits a balance."),
105
+ entitlements: z.array(EntitlementKey).default([]).describe("The entitlement keys this product grants — mentioned here, declared in the top-level `entitlements` map. Many products across many rails may grant one key, which is the whole point — gating code names the key, never this product. Every key must be declared. Empty for a product that only credits a balance."),
82
106
  apple: PaymentsAppleProduct.optional().describe("The Apple listing, if this product ships on the App Store."),
83
107
  google: PaymentsGoogleProduct.optional().describe("The Google listing, if this product ships on Google Play."),
84
108
  stripe: PaymentsStripeProduct.optional().describe("The Stripe price, if this product is sold through Stripe."),
85
109
  lemonSqueezy: PaymentsLemonSqueezyProduct.optional().describe("The Lemon Squeezy variant, if this product is sold through Lemon Squeezy."),
86
110
  paddle: PaymentsPaddleProduct.optional().describe("The Paddle price, if this product is sold through Paddle."),
87
111
  grants: PaymentsGrants.optional().describe("What this purchase fulfills beyond its entitlements. Opt-in per product; a subscription's grant fires once per billing period, since each renewal is a distinct provider transaction."),
112
+ billing: PaymentsReportedBilling.optional().describe("Bill this subscription by a reported quantity — students, coaches, seats — rather than a flat price. Requires `resolveQuantity` on `payments(...)`. Omit for a flat-priced product."),
88
113
  clawback: z.boolean().default(false).describe("Whether a refund attempts to debit back what `grants` credited. Off by default: the user may already have spent it, and a clawback that would overdraw is refused by the ledger rather than routed around. A failed clawback is recorded and queryable, not an exception.")
89
114
  }).describe("One logical catalog product — what it is, what it grants, and how each store lists it.");
115
+ /**
116
+ * The meters the kit counts itself, because the kit writes the rows they count. Everything the kit cannot
117
+ * see — seats, students, projects — is the adopter's count, read through `quota()`. Payments never counts
118
+ * members. Forever.
119
+ */
120
+ const KIT_METERS = [
121
+ "emails",
122
+ "storageBytes",
123
+ "mediaItems"
124
+ ];
125
+ const MeterPolicy = z.strictObject({ enforce: z.boolean().default(false).describe("Whether the quota of the same name binds. Off by default: declaring a quota makes it readable, and turning this on makes it refuse. Two steps, because the first is a pricing decision and the second is a production one.") }).describe("Whether one kit meter is enforced.");
126
+ const PaymentsMeters = z.strictObject({
127
+ emails: MeterPolicy.optional().describe("Emails enqueued through `@pithy-sh/email` for a subject, per billing period. Enforced at enqueue: past the quota the enqueue throws `payments/quota_exceeded` and writes no job."),
128
+ storageBytes: MeterPolicy.optional().describe("Bytes the billing subject holds in `@pithy-sh/storage`: a user's own, or under organization billing every member's bytes stored for the organization. Enforced, the quota replaces the configured `bytesPerOwner` as the ceiling, and a write past it throws `payments/quota_exceeded`."),
129
+ mediaItems: MeterPolicy.optional().describe("Media items the billing subject holds in `@pithy-sh/media`: a user's own, or under organization billing every member's records for the organization. Enforced at create: past the quota the create throws `payments/quota_exceeded`.")
130
+ }).describe("Which kit meters enforce their quota. Every meter is advisory until named here with `enforce: true`, because a cap that arrives by surprise breaks an adopter already over it. A meter refuses at its limit and never bills.");
90
131
  const PaymentsConfig = z.object({
91
132
  billingSubject: PaymentsSubjectType.describe("Who a purchase belongs to, and who its entitlements reach. `user` is one person buying for themselves: they pay, they are entitled, nobody else is. `organization` is a company buying for its people: the company is invoiced, and everybody the adopter counts as a member holds what it bought — so a colleague who joined this morning is entitled and one who left this afternoon is not, with no row rewritten either time. Required, and decided once for the project: a codebase that could grant to a user on one route and an organization on the next eventually disagrees with itself about who is entitled, and the disagreement surfaces as somebody being refused what they paid for. Changing it later is a migration of every entitlement, purchase, and store link, so it is worth the minute now."),
92
133
  rails: PaymentsRailToggles.default({
@@ -97,7 +138,10 @@ const PaymentsConfig = z.object({
97
138
  paddle: false
98
139
  }).describe("Which stores this project sells through. Every rail is off until named."),
99
140
  products: z.record(z.string(), PaymentsProduct).default({}).describe("The catalog, keyed by logical product id — the id that lands in every purchase row. Keys are yours and outlive any store's SKU, so renaming a SKU in a console never rewrites history."),
100
- manualEntitlements: z.array(EntitlementKey).default([]).describe("Entitlement keys the control plane may grant that no product sells — a beta flag, an internal tier, a key that exists only to be comped. Declared, because the alternative to declaring is not checking: with this empty, a grant of any key outside the catalog is refused, which is what turns `pr` for `pro` into a 400 instead of a row nobody notices. Only grants are constrained; a revoke of a key the catalog has since dropped stays legal, or a catalog edit would be irreversible for everyone still holding it."),
141
+ entitlements: z.record(EntitlementKey, PaymentsEntitlementDeclaration).default({}).describe("What each entitlement key means — its display name, its numbered `quotas`, its `features` — declared once, however many products sell it. A key a product mentions must be declared here. A key declared here and sold by no product is comp-only: the control plane may grant it and no checkout sells it."),
142
+ defaults: PaymentsAllowanceDefaults.optional().describe("The free floor: the quotas and features a caller holding no key gets. Optional. Without it an unentitled caller gets 0 of every quota and no feature, which is fail-closed and correct."),
143
+ meters: PaymentsMeters.default({}).describe("Which kit meters — `emails`, `storageBytes`, `mediaItems` — enforce the quota of the same name. All advisory until named."),
144
+ manualEntitlements: z.never({ error: "`manualEntitlements` is gone. Declare each comp-only key in the top-level `entitlements` map instead — a key declared there and sold by no product is grantable by hand." }).optional().describe("Removed. Declare each comp-only key in `entitlements` instead: a declared key no product sells is what this field used to mean. Refused rather than ignored, because ignoring it would drop a comp-only key and nobody would see it."),
101
145
  stripe: PaymentsStripeSettings.optional().describe("Where Stripe's hosted Checkout and Billing Portal return the browser. Required when the Stripe rail is on — the two routes cannot create a session without them."),
102
146
  lemonSqueezy: PaymentsLemonSqueezySettings.optional().describe("Where Lemon Squeezy's hosted checkout returns the browser. Required when that rail is on — the checkout route cannot create a session without it."),
103
147
  paddle: PaymentsPaddleSettings.optional().describe("How this project sells through Paddle: the account, the publishable client token, the checkout mode, and where a buyer lands. Required when the Paddle rail is on — the rail cannot initialize Paddle.js or create a transaction without it."),
@@ -142,6 +186,41 @@ const PaymentsConfig = z.object({
142
186
  path: ["paddle"],
143
187
  message: "`paddle` declares settings, but `rails.paddle` is off. Enable the rail, or drop the block."
144
188
  });
189
+ for (const [id, product] of entries) for (const key of product.entitlements) {
190
+ if (key in config.entitlements) continue;
191
+ ctx.issues.push({
192
+ code: "custom",
193
+ input: ctx.value,
194
+ path: [
195
+ "products",
196
+ id,
197
+ "entitlements"
198
+ ],
199
+ message: `Product "${id}" grants "${key}", which \`entitlements\` does not declare. Declare it — \`entitlements: { ${key}: { name: "…" } }\` — or correct the product.`
200
+ });
201
+ }
202
+ for (const problem of declarationProblems(config)) ctx.issues.push({
203
+ code: "custom",
204
+ input: ctx.value,
205
+ path: problem.path,
206
+ message: problem.message
207
+ });
208
+ const quotaNames = new Set(declaredQuotaNames(config));
209
+ for (const meter of KIT_METERS) {
210
+ if (config.meters[meter]?.enforce !== true || quotaNames.has(meter)) continue;
211
+ ctx.issues.push({
212
+ code: "custom",
213
+ input: ctx.value,
214
+ path: ["meters", meter],
215
+ message: `The ${meter} meter is enforced, and no quota named "${meter}" is declared. Declare one on an entitlement or in \`defaults\`, or leave the meter advisory — enforced with nothing declared, it would refuse everyone.`
216
+ });
217
+ }
218
+ for (const [id, product] of entries) for (const problem of reportedBillingProblems(id, product, config)) ctx.issues.push({
219
+ code: "custom",
220
+ input: ctx.value,
221
+ path: problem.path,
222
+ message: problem.message
223
+ });
145
224
  for (const [id, product] of entries) {
146
225
  for (const rail of PAYMENTS_RAILS) if (product[rail] !== void 0 && !config.rails[rail]) ctx.issues.push({
147
226
  code: "custom",
@@ -204,6 +283,69 @@ function providerProductId(product, rail) {
204
283
  case "google": return product.google?.productId;
205
284
  }
206
285
  }
286
+ /**
287
+ * What is wrong with one product's reported billing, as sentences naming the product — empty for a product
288
+ * that has none, or one that is sound.
289
+ *
290
+ * Every refusal here is at boot, because a reported product that cannot be reported is a subscription that
291
+ * bills nothing for a quantity the customer is using — invisible until somebody reads an invoice.
292
+ */
293
+ function reportedBillingProblems(id, product, config) {
294
+ const billing = product.billing;
295
+ if (billing === void 0) return [];
296
+ const problems = [];
297
+ const at = (...rest) => [
298
+ "products",
299
+ id,
300
+ "billing",
301
+ ...rest
302
+ ];
303
+ if (product.type !== "subscription") problems.push({
304
+ path: at(),
305
+ message: `Product "${id}" reports a quantity and is a ${product.type}. A reported quantity is billed per period, so only a subscription can carry one.`
306
+ });
307
+ if (billing.min > billing.max) problems.push({
308
+ path: at("min"),
309
+ message: `Product "${id}" reports between ${billing.min} and ${billing.max}. The minimum must not exceed the maximum.`
310
+ });
311
+ for (const rail of billing.rails) {
312
+ if (rail === "apple" || rail === "google") {
313
+ problems.push({
314
+ path: at("rails"),
315
+ message: `Product "${id}" reports its quantity on ${rail}. In-app purchase has no concept of a seat, so a quantity-billed product sells on the web rails only. Remove ${rail} from \`billing.rails\`.`
316
+ });
317
+ continue;
318
+ }
319
+ if (rail === "lemonSqueezy") {
320
+ problems.push({
321
+ path: at("rails"),
322
+ message: `Product "${id}" reports its quantity on lemonSqueezy, which payments does not report to yet: its usage records are written against a subscription item the projection does not store. Report on stripe or paddle.`
323
+ });
324
+ continue;
325
+ }
326
+ if (!config.rails[rail] || product[rail] === void 0) problems.push({
327
+ path: at("rails"),
328
+ message: `Product "${id}" reports its quantity on ${rail}, and is not sold there. Enable \`rails.${rail}\` and give the product a \`${rail}\` block, or remove ${rail} from \`billing.rails\`.`
329
+ });
330
+ }
331
+ if (billing.rails.includes("stripe") && billing.stripe === void 0) problems.push({
332
+ path: at("stripe"),
333
+ message: `Product "${id}" reports its quantity on stripe and names no meter. Set \`billing.stripe.meterEventName\` to the event name of the meter its price reads.`
334
+ });
335
+ if (billing.rails.includes("paddle") && billing.paddle === void 0) problems.push({
336
+ path: at("paddle"),
337
+ message: `Product "${id}" reports its quantity on paddle and names no price to charge it at. Set \`billing.paddle.priceId\` to a one-time price.`
338
+ });
339
+ return problems;
340
+ }
341
+ /** Every product billed by a reported quantity, with its id. */
342
+ function reportedProducts(config) {
343
+ return Object.entries(config.products).flatMap(([id, product]) => product.billing === void 0 ? [] : [{
344
+ id,
345
+ product,
346
+ billing: product.billing
347
+ }]);
348
+ }
207
349
  /** The product with this logical id, or undefined. Ids come from config, so an unknown one is a 404. */
208
350
  function resolveProduct(config, id) {
209
351
  const product = config.products[id];
@@ -225,20 +367,28 @@ function productForProviderSku(config, rail, sku) {
225
367
  };
226
368
  }
227
369
  /**
228
- * Every entitlement key this project defines — what the catalog's products grant, plus what the adopter
229
- * declared grantable with no sale behind it.
370
+ * Every entitlement key this project defines — the keys `entitlements` declares. Every key a product
371
+ * mentions is among them, because the config refuses a mention with no declaration.
230
372
  *
231
- * The set a manual grant is checked against, and the set the control-plane catalog read publishes the first
232
- * half of. Computed once per composition: the catalog is config, so it cannot change under a running Worker.
373
+ * The set a manual grant is checked against, and the set the control-plane catalog read publishes.
374
+ * Computed once per composition: the catalog is config, so it cannot change under a running Worker.
233
375
  *
234
- * **Empty is a real answer.** A project composing payments with nothing to sell and nothing declared defines
235
- * no keys, and every grant against it is refused — which is correct, because there is no vocabulary to grant
236
- * in. It is the same statement `clientProjection` makes as `{ enabled: false }`.
376
+ * **Empty is a real answer.** A project composing payments with nothing declared defines no keys, and every
377
+ * grant against it is refused — which is correct, because there is no vocabulary to grant in. It is the same
378
+ * statement `clientProjection` makes as `{ enabled: false }`.
237
379
  */
238
380
  function grantableEntitlements(config) {
239
- const keys = new Set(config.manualEntitlements);
240
- for (const product of Object.values(config.products)) for (const key of product.entitlements) keys.add(key);
241
- return keys;
381
+ return new Set(Object.keys(config.entitlements));
382
+ }
383
+ /**
384
+ * The declared keys no product sells — comp-only. Granted by hand through the control plane, sold by no
385
+ * checkout. What `manualEntitlements` used to list, said by the shape of the config rather than by a
386
+ * second list that could disagree with the first.
387
+ */
388
+ function compOnlyEntitlements(config) {
389
+ const sold = /* @__PURE__ */ new Set();
390
+ for (const product of Object.values(config.products)) for (const key of product.entitlements) sold.add(key);
391
+ return Object.keys(config.entitlements).filter((key) => !sold.has(key));
242
392
  }
243
393
  /** The entitlement keys a product grants, or an empty list for an unknown product or one that grants none. */
244
394
  function entitlementsForProduct(config, id) {
@@ -249,4 +399,4 @@ function railEnabled(config, rail) {
249
399
  return config.rails[rail];
250
400
  }
251
401
  //#endregion
252
- export { PaymentsAppleProduct, PaymentsConfig, PaymentsGoogleProduct, PaymentsGrants, PaymentsLedgerGrant, PaymentsLemonSqueezyProduct, PaymentsLemonSqueezySettings, PaymentsPaddleProduct, PaymentsPaddleSettings, PaymentsProduct, PaymentsProductType, PaymentsRailToggles, PaymentsStripeProduct, PaymentsStripeSettings, entitlementsForProduct, grantableEntitlements, productForProviderSku, providerProductId, railEnabled, resolveProduct };
402
+ export { KIT_METERS, PaymentsAppleProduct, PaymentsConfig, PaymentsGoogleProduct, PaymentsGrants, PaymentsLedgerGrant, PaymentsLemonSqueezyProduct, PaymentsLemonSqueezySettings, PaymentsMeters, PaymentsPaddleProduct, PaymentsPaddleSettings, PaymentsProduct, PaymentsProductType, PaymentsRailToggles, PaymentsReportCadence, PaymentsReportedBilling, PaymentsStripeProduct, PaymentsStripeSettings, REPORTED_BILLING_RAILS, compOnlyEntitlements, entitlementsForProduct, grantableEntitlements, productForProviderSku, providerProductId, railEnabled, reportedBillingProblems, reportedProducts, resolveProduct };
@@ -0,0 +1,34 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { z } from "zod";
4
+ /**
5
+ * How much of one meter one subject used in one period — the row in `pithy_payments_meter_counters`, keyed
6
+ * `UNIQUE (subjectType, subjectId, meter, periodStart)`.
7
+ *
8
+ * **A counter, not a scan.** Counting a period's emails by reading the jobs table would be a range scan on
9
+ * every send, and it would count rows the email capability prunes. One row per period, incremented in the
10
+ * same statement that checks the limit, is both cheaper and the only shape a concurrent burst cannot walk
11
+ * past.
12
+ *
13
+ * **A new period starts at zero with nothing to reset it.** The period's start is half the key, so the first
14
+ * charge of a new period lands on a row that does not exist yet. There is no cron, no sweep, no reset job.
15
+ *
16
+ * **It refuses and never bills.** Nothing reads this table to report usage to a store: the kit does not sell
17
+ * overage, and a meter joined to a bill would make every counter a money path.
18
+ */
19
+ export declare const PaymentsMeterCounter: z.ZodObject<{
20
+ id: z.ZodString;
21
+ subjectType: z.ZodEnum<{
22
+ organization: "organization";
23
+ user: "user";
24
+ }>;
25
+ subjectId: z.ZodString;
26
+ meter: z.ZodString;
27
+ periodStart: z.ZodCodec<z.ZodUnion<readonly [z.ZodNumber, z.ZodString, z.ZodDate]>, z.ZodDate>;
28
+ used: z.ZodNumber;
29
+ createdAt: z.ZodCodec<z.ZodUnion<readonly [z.ZodNumber, z.ZodString, z.ZodDate]>, z.ZodDate>;
30
+ updatedAt: z.ZodCodec<z.ZodUnion<readonly [z.ZodNumber, z.ZodString, z.ZodDate]>, z.ZodDate>;
31
+ }, z.core.$strip>;
32
+ export type PaymentsMeterCounter = z.output<typeof PaymentsMeterCounter>;
33
+ export type PaymentsMeterCounterRow = z.input<typeof PaymentsMeterCounter>;
34
+ //# sourceMappingURL=meterCounter.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"meterCounter.d.ts","sourceRoot":"","sources":["../../src/data/meterCounter.ts"],"names":[],"mappings":"AAIA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAGxB;;;;;;;;;;;;;;GAcG;AACH,eAAO,MAAM,oBAAoB;;;;;;;;;;;;iBAa0E,CAAC;AAC5G,MAAM,MAAM,oBAAoB,GAAG,CAAC,CAAC,MAAM,CAAC,OAAO,oBAAoB,CAAC,CAAC;AACzE,MAAM,MAAM,uBAAuB,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,oBAAoB,CAAC,CAAC"}