@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
@@ -0,0 +1,211 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { z } from "zod";
5
+
6
+ /**
7
+ * What an entitlement buys: a display name, numbered allowances, and switches. Declared once per key.
8
+ *
9
+ * A key is the thing gating code names and the thing a product mentions — `growth` — and until this
10
+ * existed it was declared nowhere. It was only ever *mentioned*, in the array a product grants and in a
11
+ * second list of comp-only keys, and those two could disagree about the same key with no answer for which
12
+ * won. There was also nowhere to write what a key buys: "up to 25 students" could gate on the key and
13
+ * could not tell 25 from 26.
14
+ *
15
+ * **The declaration hangs on the key, not on the product, because a tier is sold by more than one
16
+ * product.** `growth_monthly` and `growth_annual` are two SKUs on two rails for one tier. Writing the
17
+ * numbers on the product writes them twice and reconciles them forever.
18
+ *
19
+ * **Two maps, not one.** A single `limits: { emails: 5000, sso: true }` reads well and answers
20
+ * `number | boolean | null`, and from there no caller can tell `0` from `false` from *nothing was
21
+ * declared* without writing the same narrowing every time. `quotas` holds integers and `null`, and
22
+ * `features` holds booleans, so each reader answers one type.
23
+ *
24
+ * **`null` is unlimited, and it is written, never inferred.** A quota a key does not mention is not
25
+ * unlimited for that key — it falls to `defaults`, then to `0`. Unlimited is a decision somebody wrote
26
+ * down, because a paywall that silently does not exist is invisible until the invoice.
27
+ */
28
+
29
+ /** The longest an allowance name may be. Long enough to read, short enough to sit in an audit row. */
30
+ const MAX_ALLOWANCE_NAME_LENGTH = 64;
31
+
32
+ /** The longest a declared tier name may be — the same bound a product's display name carries. */
33
+ const MAX_TIER_NAME_LENGTH = 120;
34
+
35
+ /**
36
+ * A quota or feature name — `emails`, `seats`, `auditExport`. camelCase or snake_case, starting with a
37
+ * lowercase letter, because it is an identifier code names and never copy a screen renders.
38
+ */
39
+ export const AllowanceName = z
40
+ .string()
41
+ .min(1)
42
+ .max(MAX_ALLOWANCE_NAME_LENGTH)
43
+ .regex(
44
+ /^[a-z][A-Za-z0-9_]*$/,
45
+ "An allowance name starts with a lowercase letter and holds only letters, digits, and underscores.",
46
+ )
47
+ .describe(
48
+ "A quota or feature name — `emails`, `seats`, `auditExport`. An identifier gating code reads, never display copy, and never translated.",
49
+ );
50
+ export type AllowanceName = z.infer<typeof AllowanceName>;
51
+
52
+ /**
53
+ * One quota's value: a whole number of things, or `null` for unlimited. Never a float, never negative,
54
+ * never a string — a number that costs money to serve is not something to coerce.
55
+ */
56
+ export const QuotaValue = z
57
+ .number()
58
+ .int("A quota is a whole number, or null for unlimited.")
59
+ .min(0, "A quota is never negative. Use 0 for none and null for unlimited.")
60
+ .nullable()
61
+ .describe("How many of a thing this grants: a whole number from 0, or null for unlimited.");
62
+ export type QuotaValue = z.infer<typeof QuotaValue>;
63
+
64
+ /** A ceiling an operator's override may not pass. A whole number, and never unlimited — that is not a ceiling. */
65
+ export const OverrideCeiling = z
66
+ .number()
67
+ .int("An override ceiling is a whole number.")
68
+ .min(0, "An override ceiling is never negative.")
69
+ .describe(
70
+ "The largest number an operator's override may set for this quota. A set past it is refused naming it, never clamped.",
71
+ );
72
+ export type OverrideCeiling = z.infer<typeof OverrideCeiling>;
73
+
74
+ /** A quota map: name → whole number or unlimited. */
75
+ export const QuotaMap = z
76
+ .record(AllowanceName, QuotaValue)
77
+ .describe("Numbered allowances by name. A whole number from 0, or null for unlimited.");
78
+ export type QuotaMap = z.infer<typeof QuotaMap>;
79
+
80
+ /** A feature map: name → on or off. */
81
+ export const FeatureMap = z
82
+ .record(AllowanceName, z.boolean().describe("Whether this switch is on."))
83
+ .describe("Switches by name. A feature is read, never enforced: `false` denies nothing on its own.");
84
+ export type FeatureMap = z.infer<typeof FeatureMap>;
85
+
86
+ export const PaymentsEntitlementDeclaration = z
87
+ .object({
88
+ name: z
89
+ .string()
90
+ .min(1)
91
+ .max(MAX_TIER_NAME_LENGTH)
92
+ .describe(
93
+ "The tier's display name — `Growth`. A product name, so it is not translated, the way a product's own name is not.",
94
+ ),
95
+ quotas: QuotaMap.default({}).describe(
96
+ "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.",
97
+ ),
98
+ features: FeatureMap.default({}).describe(
99
+ "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.",
100
+ ),
101
+ overrideMax: z
102
+ .record(AllowanceName, OverrideCeiling)
103
+ .optional()
104
+ .describe(
105
+ "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.",
106
+ ),
107
+ })
108
+ .describe(
109
+ "What one entitlement key buys: its display name, its numbered quotas, and its switches. Declared once, however many products sell it.",
110
+ );
111
+ export type PaymentsEntitlementDeclaration = z.output<typeof PaymentsEntitlementDeclaration>;
112
+ export type PaymentsEntitlementDeclarationInput = z.input<typeof PaymentsEntitlementDeclaration>;
113
+
114
+ export const PaymentsAllowanceDefaults = z
115
+ .object({
116
+ quotas: QuotaMap.default({}).describe(
117
+ "What a subject holding no key that speaks to a quota gets — the free floor. A name absent here resolves to 0.",
118
+ ),
119
+ features: FeatureMap.default({}).describe(
120
+ "The switches a subject holding no key that speaks to them gets. A name absent here resolves to false.",
121
+ ),
122
+ })
123
+ .describe(
124
+ "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.",
125
+ );
126
+ export type PaymentsAllowanceDefaults = z.output<typeof PaymentsAllowanceDefaults>;
127
+
128
+ /** The slice of a parsed config the derivations below read. Structural, so a test needs no full catalog. */
129
+ export interface AllowanceDeclarations {
130
+ /** Every declared entitlement key and what it buys. */
131
+ entitlements: Readonly<Record<string, PaymentsEntitlementDeclaration>>;
132
+ /** The free floor, when declared. */
133
+ defaults?: PaymentsAllowanceDefaults | undefined;
134
+ }
135
+
136
+ /**
137
+ * Every quota name this project declares, on any key or on the floor, sorted.
138
+ *
139
+ * Derived, never written down, the way the set of grantable keys is derived from the products — a second
140
+ * list of names would be a list that disagrees with the declarations the first time one is added.
141
+ */
142
+ export function declaredQuotaNames(declarations: AllowanceDeclarations): string[] {
143
+ const names = new Set<string>(Object.keys(declarations.defaults?.quotas ?? {}));
144
+ for (const declaration of Object.values(declarations.entitlements)) {
145
+ for (const name of Object.keys(declaration.quotas)) names.add(name);
146
+ }
147
+ return [...names].sort();
148
+ }
149
+
150
+ /** Every feature name this project declares, on any key or on the floor, sorted. */
151
+ export function declaredFeatureNames(declarations: AllowanceDeclarations): string[] {
152
+ const names = new Set<string>(Object.keys(declarations.defaults?.features ?? {}));
153
+ for (const declaration of Object.values(declarations.entitlements)) {
154
+ for (const name of Object.keys(declaration.features)) names.add(name);
155
+ }
156
+ return [...names].sort();
157
+ }
158
+
159
+ /**
160
+ * The problems with a set of declarations, as sentences, each with the path it belongs at.
161
+ *
162
+ * Separate from the schema so `PaymentsConfig`'s check can report every one at once, beside the catalog
163
+ * problems it already reports, and so each rule is testable on its own.
164
+ */
165
+ export interface DeclarationProblem {
166
+ /** Where in the config the problem is. */
167
+ path: (string | number)[];
168
+ /** The sentence. Names the key and the name. */
169
+ message: string;
170
+ }
171
+
172
+ /**
173
+ * Check the rules a schema cannot state field by field: a name that is a quota on one key and a feature on
174
+ * another, and an `overrideMax` that names an undeclared quota or sits below the quota it bounds.
175
+ */
176
+ export function declarationProblems(declarations: AllowanceDeclarations): DeclarationProblem[] {
177
+ const problems: DeclarationProblem[] = [];
178
+
179
+ // A name is a number or a switch, everywhere. `quota(c, "sso")` and `feature(c, "sso")` both answering
180
+ // would give one name two meanings, and an override editor could not say which input to draw.
181
+ const quotas = new Set(declaredQuotaNames(declarations));
182
+ for (const name of declaredFeatureNames(declarations)) {
183
+ if (!quotas.has(name)) continue;
184
+ problems.push({
185
+ path: ["entitlements"],
186
+ message: `"${name}" is declared as both a quota and a feature. A name is a number or a switch, never both. Rename one.`,
187
+ });
188
+ }
189
+
190
+ for (const [key, declaration] of Object.entries(declarations.entitlements)) {
191
+ for (const [name, ceiling] of Object.entries(declaration.overrideMax ?? {})) {
192
+ if (!(name in declaration.quotas)) {
193
+ problems.push({
194
+ path: ["entitlements", key, "overrideMax", name],
195
+ 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"}.`,
196
+ });
197
+ continue;
198
+ }
199
+ const value = declaration.quotas[name];
200
+ // A ceiling under the plan's own number would refuse an override the plan already grants. Unlimited
201
+ // is above every ceiling, so a ceiling on an unlimited quota is always under it.
202
+ if (value === null || (value !== undefined && ceiling < value)) {
203
+ problems.push({
204
+ path: ["entitlements", key, "overrideMax", name],
205
+ 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.`,
206
+ });
207
+ }
208
+ }
209
+ }
210
+ return problems;
211
+ }
@@ -4,8 +4,15 @@
4
4
  import { EntitlementKey } from "@pithy-sh/core/src/entitlement/entitlement";
5
5
  import { SIGNED_WEBHOOK_MAX_TOLERANCE_SECONDS } from "@pithy-sh/core/src/http/webhookWindow";
6
6
  import { z } from "zod";
7
- import { PAYMENTS_RAILS, type PaymentsRail } from "../data/rail";
7
+ import { PAYMENTS_RAILS, PaymentsRail } from "../data/rail";
8
8
  import { PaymentsSubjectType } from "../data/subject";
9
+ import {
10
+ type DeclarationProblem,
11
+ declarationProblems,
12
+ declaredQuotaNames,
13
+ PaymentsAllowanceDefaults,
14
+ PaymentsEntitlementDeclaration,
15
+ } from "./allowances";
9
16
 
10
17
  /**
11
18
  * The payments capability's config — the catalog, and the thin surface an adopter owns in
@@ -250,6 +257,92 @@ export const PaymentsGrants = z
250
257
  .describe("What a purchase fulfills beyond its entitlements. Absent for the products that only unlock a feature.");
251
258
  export type PaymentsGrants = z.infer<typeof PaymentsGrants>;
252
259
 
260
+ /**
261
+ * The rails a reported quantity can be billed on. Stripe takes a meter event; Paddle takes a one-time charge
262
+ * against the subscription. **Apple and Google cannot**: in-app purchase has no concept of a seat, so a
263
+ * quantity-billed product is web-rails-only and says so at boot.
264
+ *
265
+ * **Lemon Squeezy is deferred, with the reason recorded on pithy-sh/pithy#561.** Its usage records are
266
+ * written against a subscription *item*, which the projection does not store, so the same call shape does
267
+ * not fit without a new column and a refresh of every Lemon Squeezy subscription. Named here so the refusal
268
+ * can say so, rather than reading as an oversight.
269
+ */
270
+ export const REPORTED_BILLING_RAILS = ["stripe", "paddle"] as const satisfies readonly PaymentsRail[];
271
+
272
+ /** How often a reported quantity goes to the store. */
273
+ export const PaymentsReportCadence = z
274
+ .enum(["period-end", "daily-peak"])
275
+ .describe(
276
+ "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.",
277
+ );
278
+ export type PaymentsReportCadence = z.infer<typeof PaymentsReportCadence>;
279
+
280
+ export const PaymentsReportedBilling = z
281
+ .strictObject({
282
+ kind: z
283
+ .literal("reported")
284
+ .describe(
285
+ "The quantity is reported by payments, from a count the adopter's `resolveQuantity` computes. The only kind there is.",
286
+ ),
287
+ unit: z
288
+ .string()
289
+ .min(1)
290
+ .max(MAX_NAME_LENGTH)
291
+ .describe("What one unit is — `student`, `coach`, `seat`. For people reading the catalog and the run log."),
292
+ cadence: PaymentsReportCadence.default("period-end").describe(
293
+ "How often the count is reported. Defaults to `period-end`. Per product, because a project can sell two things metered differently.",
294
+ ),
295
+ min: z
296
+ .number()
297
+ .int()
298
+ .min(0)
299
+ .default(0)
300
+ .describe(
301
+ "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.",
302
+ ),
303
+ max: z
304
+ .number()
305
+ .int()
306
+ .positive()
307
+ .describe(
308
+ "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.",
309
+ ),
310
+ rails: z
311
+ .array(PaymentsRail)
312
+ .min(1)
313
+ .describe(
314
+ "Which rails report this product's count. Stripe and Paddle only — in-app purchase has no seats, and Lemon Squeezy is deferred.",
315
+ ),
316
+ stripe: z
317
+ .strictObject({
318
+ meterEventName: z
319
+ .string()
320
+ .min(1)
321
+ .max(100)
322
+ .describe(
323
+ "The `event_name` of the Stripe Billing Meter this product's metered price reads — what each report is sent as.",
324
+ ),
325
+ })
326
+ .optional()
327
+ .describe("How Stripe hears the count: the meter it is reported to. Required when `rails` lists stripe."),
328
+ paddle: z
329
+ .strictObject({
330
+ priceId: z
331
+ .string()
332
+ .min(1)
333
+ .max(MAX_SKU_LENGTH)
334
+ .describe(
335
+ "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.",
336
+ ),
337
+ })
338
+ .optional()
339
+ .describe("How Paddle hears the count: the one-time price it is charged at. Required when `rails` lists paddle."),
340
+ })
341
+ .describe(
342
+ "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.",
343
+ );
344
+ export type PaymentsReportedBilling = z.output<typeof PaymentsReportedBilling>;
345
+
253
346
  export const PaymentsProduct = z
254
347
  .object({
255
348
  type: PaymentsProductType.describe("What kind of product this is. Decides how a renewal and a restore behave."),
@@ -264,7 +357,7 @@ export const PaymentsProduct = z
264
357
  .array(EntitlementKey)
265
358
  .default([])
266
359
  .describe(
267
- "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.",
360
+ "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.",
268
361
  ),
269
362
  apple: PaymentsAppleProduct.optional().describe("The Apple listing, if this product ships on the App Store."),
270
363
  google: PaymentsGoogleProduct.optional().describe("The Google listing, if this product ships on Google Play."),
@@ -276,6 +369,9 @@ export const PaymentsProduct = z
276
369
  grants: PaymentsGrants.optional().describe(
277
370
  "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.",
278
371
  ),
372
+ billing: PaymentsReportedBilling.optional().describe(
373
+ "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.",
374
+ ),
279
375
  clawback: z
280
376
  .boolean()
281
377
  .default(false)
@@ -286,6 +382,42 @@ export const PaymentsProduct = z
286
382
  .describe("One logical catalog product — what it is, what it grants, and how each store lists it.");
287
383
  export type PaymentsProduct = z.infer<typeof PaymentsProduct>;
288
384
 
385
+ /**
386
+ * The meters the kit counts itself, because the kit writes the rows they count. Everything the kit cannot
387
+ * see — seats, students, projects — is the adopter's count, read through `quota()`. Payments never counts
388
+ * members. Forever.
389
+ */
390
+ export const KIT_METERS = ["emails", "storageBytes", "mediaItems"] as const;
391
+ export type KitMeter = (typeof KIT_METERS)[number];
392
+
393
+ const MeterPolicy = z
394
+ .strictObject({
395
+ enforce: z
396
+ .boolean()
397
+ .default(false)
398
+ .describe(
399
+ "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.",
400
+ ),
401
+ })
402
+ .describe("Whether one kit meter is enforced.");
403
+
404
+ export const PaymentsMeters = z
405
+ .strictObject({
406
+ emails: MeterPolicy.optional().describe(
407
+ "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.",
408
+ ),
409
+ storageBytes: MeterPolicy.optional().describe(
410
+ "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`.",
411
+ ),
412
+ mediaItems: MeterPolicy.optional().describe(
413
+ "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`.",
414
+ ),
415
+ })
416
+ .describe(
417
+ "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.",
418
+ );
419
+ export type PaymentsMeters = z.output<typeof PaymentsMeters>;
420
+
289
421
  export const PaymentsConfig = z
290
422
  .object({
291
423
  billingSubject: PaymentsSubjectType.describe(
@@ -304,11 +436,26 @@ export const PaymentsConfig = z
304
436
  .describe(
305
437
  "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.",
306
438
  ),
439
+ entitlements: z
440
+ .record(EntitlementKey, PaymentsEntitlementDeclaration)
441
+ .default({})
442
+ .describe(
443
+ "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.",
444
+ ),
445
+ defaults: PaymentsAllowanceDefaults.optional().describe(
446
+ "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.",
447
+ ),
448
+ meters: PaymentsMeters.default({}).describe(
449
+ "Which kit meters — `emails`, `storageBytes`, `mediaItems` — enforce the quota of the same name. All advisory until named.",
450
+ ),
307
451
  manualEntitlements: z
308
- .array(EntitlementKey)
309
- .default([])
452
+ .never({
453
+ error:
454
+ "`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.",
455
+ })
456
+ .optional()
310
457
  .describe(
311
- "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.",
458
+ "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.",
312
459
  ),
313
460
  stripe: PaymentsStripeSettings.optional().describe(
314
461
  "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.",
@@ -401,6 +548,43 @@ export const PaymentsConfig = z
401
548
  });
402
549
  }
403
550
 
551
+ // A key is declared once and mentioned by products. A mention with no declaration is a key whose
552
+ // quotas, features and name exist nowhere, and a comp of it would be refused while a checkout sold it.
553
+ for (const [id, product] of entries) {
554
+ for (const key of product.entitlements) {
555
+ if (key in config.entitlements) continue;
556
+ ctx.issues.push({
557
+ code: "custom",
558
+ input: ctx.value,
559
+ path: ["products", id, "entitlements"],
560
+ message: `Product "${id}" grants "${key}", which \`entitlements\` does not declare. Declare it — \`entitlements: { ${key}: { name: "…" } }\` — or correct the product.`,
561
+ });
562
+ }
563
+ }
564
+
565
+ for (const problem of declarationProblems(config)) {
566
+ ctx.issues.push({ code: "custom", input: ctx.value, path: problem.path, message: problem.message });
567
+ }
568
+
569
+ // An enforced meter with no quota of its name would resolve every subject to the hard floor of zero and
570
+ // refuse every send. That is fail-closed and it is also an outage, caught here rather than in production.
571
+ const quotaNames = new Set(declaredQuotaNames(config));
572
+ for (const meter of KIT_METERS) {
573
+ if (config.meters[meter]?.enforce !== true || quotaNames.has(meter)) continue;
574
+ ctx.issues.push({
575
+ code: "custom",
576
+ input: ctx.value,
577
+ path: ["meters", meter],
578
+ 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.`,
579
+ });
580
+ }
581
+
582
+ for (const [id, product] of entries) {
583
+ for (const problem of reportedBillingProblems(id, product, config)) {
584
+ ctx.issues.push({ code: "custom", input: ctx.value, path: problem.path, message: problem.message });
585
+ }
586
+ }
587
+
404
588
  for (const [id, product] of entries) {
405
589
  // A SKU for a rail the project turned off can never be bought, and the webhook that would carry it
406
590
  // is refused. Silently ignoring the block would leave a catalog that reads as selling something it
@@ -521,6 +705,81 @@ export function providerProductId(product: PaymentsProduct, rail: PaymentsRail):
521
705
  }
522
706
  }
523
707
 
708
+ /**
709
+ * What is wrong with one product's reported billing, as sentences naming the product — empty for a product
710
+ * that has none, or one that is sound.
711
+ *
712
+ * Every refusal here is at boot, because a reported product that cannot be reported is a subscription that
713
+ * bills nothing for a quantity the customer is using — invisible until somebody reads an invoice.
714
+ */
715
+ export function reportedBillingProblems(
716
+ id: string,
717
+ product: PaymentsProduct,
718
+ config: Pick<PaymentsConfig, "rails">,
719
+ ): DeclarationProblem[] {
720
+ const billing = product.billing;
721
+ if (billing === undefined) return [];
722
+ const problems: DeclarationProblem[] = [];
723
+ const at = (...rest: (string | number)[]) => ["products", id, "billing", ...rest];
724
+
725
+ if (product.type !== "subscription") {
726
+ problems.push({
727
+ path: at(),
728
+ 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.`,
729
+ });
730
+ }
731
+ if (billing.min > billing.max) {
732
+ problems.push({
733
+ path: at("min"),
734
+ message: `Product "${id}" reports between ${billing.min} and ${billing.max}. The minimum must not exceed the maximum.`,
735
+ });
736
+ }
737
+ for (const rail of billing.rails) {
738
+ if (rail === "apple" || rail === "google") {
739
+ problems.push({
740
+ path: at("rails"),
741
+ 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\`.`,
742
+ });
743
+ continue;
744
+ }
745
+ if (rail === "lemonSqueezy") {
746
+ problems.push({
747
+ path: at("rails"),
748
+ 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.`,
749
+ });
750
+ continue;
751
+ }
752
+ if (!config.rails[rail] || product[rail] === undefined) {
753
+ problems.push({
754
+ path: at("rails"),
755
+ 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\`.`,
756
+ });
757
+ }
758
+ }
759
+ if (billing.rails.includes("stripe") && billing.stripe === undefined) {
760
+ problems.push({
761
+ path: at("stripe"),
762
+ 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.`,
763
+ });
764
+ }
765
+ if (billing.rails.includes("paddle") && billing.paddle === undefined) {
766
+ problems.push({
767
+ path: at("paddle"),
768
+ 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.`,
769
+ });
770
+ }
771
+ return problems;
772
+ }
773
+
774
+ /** Every product billed by a reported quantity, with its id. */
775
+ export function reportedProducts(
776
+ config: PaymentsConfig,
777
+ ): (PaymentsCatalogEntry & { billing: PaymentsReportedBilling })[] {
778
+ return Object.entries(config.products).flatMap(([id, product]) =>
779
+ product.billing === undefined ? [] : [{ id, product, billing: product.billing }],
780
+ );
781
+ }
782
+
524
783
  /** The product with this logical id, or undefined. Ids come from config, so an unknown one is a 404. */
525
784
  export function resolveProduct(config: PaymentsConfig, id: string): PaymentsCatalogEntry | undefined {
526
785
  const product = config.products[id];
@@ -545,20 +804,29 @@ export function productForProviderSku(
545
804
  }
546
805
 
547
806
  /**
548
- * Every entitlement key this project defines — what the catalog's products grant, plus what the adopter
549
- * declared grantable with no sale behind it.
807
+ * Every entitlement key this project defines — the keys `entitlements` declares. Every key a product
808
+ * mentions is among them, because the config refuses a mention with no declaration.
550
809
  *
551
- * The set a manual grant is checked against, and the set the control-plane catalog read publishes the first
552
- * half of. Computed once per composition: the catalog is config, so it cannot change under a running Worker.
810
+ * The set a manual grant is checked against, and the set the control-plane catalog read publishes.
811
+ * Computed once per composition: the catalog is config, so it cannot change under a running Worker.
553
812
  *
554
- * **Empty is a real answer.** A project composing payments with nothing to sell and nothing declared defines
555
- * no keys, and every grant against it is refused — which is correct, because there is no vocabulary to grant
556
- * in. It is the same statement `clientProjection` makes as `{ enabled: false }`.
813
+ * **Empty is a real answer.** A project composing payments with nothing declared defines no keys, and every
814
+ * grant against it is refused — which is correct, because there is no vocabulary to grant in. It is the same
815
+ * statement `clientProjection` makes as `{ enabled: false }`.
557
816
  */
558
817
  export function grantableEntitlements(config: PaymentsConfig): ReadonlySet<string> {
559
- const keys = new Set<string>(config.manualEntitlements);
560
- for (const product of Object.values(config.products)) for (const key of product.entitlements) keys.add(key);
561
- return keys;
818
+ return new Set<string>(Object.keys(config.entitlements));
819
+ }
820
+
821
+ /**
822
+ * The declared keys no product sells — comp-only. Granted by hand through the control plane, sold by no
823
+ * checkout. What `manualEntitlements` used to list, said by the shape of the config rather than by a
824
+ * second list that could disagree with the first.
825
+ */
826
+ export function compOnlyEntitlements(config: PaymentsConfig): string[] {
827
+ const sold = new Set<string>();
828
+ for (const product of Object.values(config.products)) for (const key of product.entitlements) sold.add(key);
829
+ return Object.keys(config.entitlements).filter((key) => !sold.has(key));
562
830
  }
563
831
 
564
832
  /** The entitlement keys a product grants, or an empty list for an unknown product or one that grants none. */
@@ -0,0 +1,38 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+
4
+ import { SQLiteDate } from "@pithy-sh/core/src/data/codecs";
5
+ import { z } from "zod";
6
+ import { PaymentsSubject } from "./subject";
7
+
8
+ /**
9
+ * How much of one meter one subject used in one period — the row in `pithy_payments_meter_counters`, keyed
10
+ * `UNIQUE (subjectType, subjectId, meter, periodStart)`.
11
+ *
12
+ * **A counter, not a scan.** Counting a period's emails by reading the jobs table would be a range scan on
13
+ * every send, and it would count rows the email capability prunes. One row per period, incremented in the
14
+ * same statement that checks the limit, is both cheaper and the only shape a concurrent burst cannot walk
15
+ * past.
16
+ *
17
+ * **A new period starts at zero with nothing to reset it.** The period's start is half the key, so the first
18
+ * charge of a new period lands on a row that does not exist yet. There is no cron, no sweep, no reset job.
19
+ *
20
+ * **It refuses and never bills.** Nothing reads this table to report usage to a store: the kit does not sell
21
+ * overage, and a meter joined to a bill would make every counter a money path.
22
+ */
23
+ export const PaymentsMeterCounter = z
24
+ .object({
25
+ id: z.string().describe("The row's UUID."),
26
+ subjectType: PaymentsSubject.shape.subjectType.describe("Whether `subjectId` names a user or an organization."),
27
+ subjectId: PaymentsSubject.shape.subjectId.describe("The subject whose usage this counts."),
28
+ meter: z.string().describe("The meter counted — `emails`."),
29
+ periodStart: SQLiteDate.describe(
30
+ "When the period this row counts began: the subscription's billing period where payments knows one, the calendar month (UTC) where it does not.",
31
+ ),
32
+ used: z.number().int().nonnegative().describe("How many were charged against the meter in this period."),
33
+ createdAt: SQLiteDate.describe("When the period's first charge landed."),
34
+ updatedAt: SQLiteDate.describe("When the period's last charge landed."),
35
+ })
36
+ .describe("One subject's usage of one meter in one period — the row in `pithy_payments_meter_counters`.");
37
+ export type PaymentsMeterCounter = z.output<typeof PaymentsMeterCounter>;
38
+ export type PaymentsMeterCounterRow = z.input<typeof PaymentsMeterCounter>;