@pithy-sh/payments 0.4.0 → 0.6.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 (180) 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 +2 -1
  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 +77 -0
  46. package/dist/data/usageRun.d.ts.map +1 -0
  47. package/dist/data/usageRun.js +50 -0
  48. package/dist/data/webhookEvent.d.ts +1 -1
  49. package/dist/entitlement/allowance.d.ts +100 -0
  50. package/dist/entitlement/allowance.d.ts.map +1 -0
  51. package/dist/entitlement/allowance.js +171 -0
  52. package/dist/entitlement/manual.d.ts +5 -5
  53. package/dist/entitlement/manual.js +3 -3
  54. package/dist/entitlement/meter.d.ts +98 -0
  55. package/dist/entitlement/meter.d.ts.map +1 -0
  56. package/dist/entitlement/meter.js +177 -0
  57. package/dist/entitlement/override.d.ts +119 -0
  58. package/dist/entitlement/override.d.ts.map +1 -0
  59. package/dist/entitlement/override.js +256 -0
  60. package/dist/entitlement/resolver.d.ts +2 -1
  61. package/dist/entitlement/resolver.d.ts.map +1 -1
  62. package/dist/entitlement/resolver.js +32 -1
  63. package/dist/error/errors.d.ts +23 -3
  64. package/dist/error/errors.d.ts.map +1 -1
  65. package/dist/error/errors.js +35 -2
  66. package/dist/http/responses.d.ts +367 -0
  67. package/dist/http/responses.d.ts.map +1 -1
  68. package/dist/http/responses.js +146 -7
  69. package/dist/http/routes.d.ts.map +1 -1
  70. package/dist/http/routes.js +270 -16
  71. package/dist/http/schemas.d.ts +54 -0
  72. package/dist/http/schemas.d.ts.map +1 -1
  73. package/dist/http/schemas.js +61 -2
  74. package/dist/http/scopes.d.ts +25 -0
  75. package/dist/http/scopes.d.ts.map +1 -1
  76. package/dist/http/scopes.js +60 -1
  77. package/dist/http/view.d.ts +22 -4
  78. package/dist/http/view.d.ts.map +1 -1
  79. package/dist/http/view.js +88 -7
  80. package/dist/index.d.ts +2 -1
  81. package/dist/index.d.ts.map +1 -1
  82. package/dist/index.js +3 -2
  83. package/dist/migrations/0002_allowances.d.ts +26 -0
  84. package/dist/migrations/0002_allowances.d.ts.map +1 -0
  85. package/dist/migrations/0002_allowances.js +62 -0
  86. package/dist/peer.d.ts +2 -1
  87. package/dist/peer.d.ts.map +1 -1
  88. package/dist/projection/event.d.ts +1 -0
  89. package/dist/projection/event.d.ts.map +1 -1
  90. package/dist/projection/event.js +1 -0
  91. package/dist/projection/writer.d.ts.map +1 -1
  92. package/dist/projection/writer.js +3 -1
  93. package/dist/rails/contract.d.ts +6 -0
  94. package/dist/rails/contract.d.ts.map +1 -1
  95. package/dist/rails/google/playApi.d.ts.map +1 -1
  96. package/dist/rails/google/playApi.js +2 -0
  97. package/dist/rails/paddle/objects.d.ts +2 -0
  98. package/dist/rails/paddle/objects.d.ts.map +1 -1
  99. package/dist/rails/paddle/objects.js +7 -2
  100. package/dist/rails/paddle/usage.d.ts +11 -0
  101. package/dist/rails/paddle/usage.d.ts.map +1 -0
  102. package/dist/rails/paddle/usage.js +49 -0
  103. package/dist/rails/quantity.d.ts +12 -0
  104. package/dist/rails/quantity.d.ts.map +1 -0
  105. package/dist/rails/quantity.js +16 -0
  106. package/dist/rails/stripe/checkout.d.ts.map +1 -1
  107. package/dist/rails/stripe/checkout.js +1 -1
  108. package/dist/rails/stripe/objects.d.ts.map +1 -1
  109. package/dist/rails/stripe/objects.js +3 -0
  110. package/dist/rails/stripe/usage.d.ts +10 -0
  111. package/dist/rails/stripe/usage.d.ts.map +1 -0
  112. package/dist/rails/stripe/usage.js +49 -0
  113. package/dist/usage/pass.d.ts +120 -0
  114. package/dist/usage/pass.d.ts.map +1 -0
  115. package/dist/usage/pass.js +363 -0
  116. package/dist/usage/reporter.d.ts +36 -0
  117. package/dist/usage/reporter.d.ts.map +1 -0
  118. package/dist/usage/reporter.js +2 -0
  119. package/dist/version.generated.d.ts +1 -1
  120. package/dist/version.generated.js +1 -1
  121. package/dist/workflows/report.d.ts.map +1 -1
  122. package/dist/workflows/specs.d.ts +28 -0
  123. package/dist/workflows/specs.d.ts.map +1 -1
  124. package/dist/workflows/specs.js +26 -1
  125. package/dist/workflows/usage.d.ts +38 -0
  126. package/dist/workflows/usage.d.ts.map +1 -0
  127. package/dist/workflows/usage.js +77 -0
  128. package/dist/workflows/worker.js +2 -2
  129. package/docs/entitlements.md +249 -0
  130. package/docs/lemon-squeezy.md +1 -0
  131. package/docs/paddle.md +1 -0
  132. package/package.json +5 -5
  133. package/pithy.manifest.json +3 -8
  134. package/src/admin/coverage.ts +28 -0
  135. package/src/admin/read.ts +173 -1
  136. package/src/audit/actions.ts +13 -0
  137. package/src/capability.ts +87 -9
  138. package/src/client/api.ts +44 -0
  139. package/src/client/hooks.ts +44 -0
  140. package/src/client/projection.ts +31 -0
  141. package/src/config/allowances.ts +211 -0
  142. package/src/config/config.ts +283 -15
  143. package/src/data/meterCounter.ts +38 -0
  144. package/src/data/override.ts +74 -0
  145. package/src/data/period.ts +53 -0
  146. package/src/data/purchase.ts +9 -0
  147. package/src/data/tables.ts +25 -1
  148. package/src/data/usageReport.ts +64 -0
  149. package/src/data/usageRun.ts +66 -0
  150. package/src/entitlement/allowance.ts +213 -0
  151. package/src/entitlement/manual.ts +6 -6
  152. package/src/entitlement/meter.ts +252 -0
  153. package/src/entitlement/override.ts +381 -0
  154. package/src/entitlement/resolver.ts +43 -2
  155. package/src/error/errors.ts +48 -4
  156. package/src/http/responses.ts +305 -4
  157. package/src/http/routes.ts +365 -11
  158. package/src/http/schemas.ts +139 -1
  159. package/src/http/scopes.ts +68 -0
  160. package/src/http/view.ts +112 -7
  161. package/src/index.ts +18 -0
  162. package/src/migrations/0002_allowances.ts +149 -0
  163. package/src/projection/event.ts +9 -0
  164. package/src/projection/writer.ts +4 -0
  165. package/src/rails/contract.ts +6 -0
  166. package/src/rails/google/playApi.ts +2 -0
  167. package/src/rails/paddle/fixtures/subscription-charge.json +19 -0
  168. package/src/rails/paddle/objects.ts +6 -0
  169. package/src/rails/paddle/usage.ts +66 -0
  170. package/src/rails/quantity.ts +14 -0
  171. package/src/rails/stripe/checkout.ts +3 -1
  172. package/src/rails/stripe/fixtures/meter-event-created.json +12 -0
  173. package/src/rails/stripe/objects.ts +4 -0
  174. package/src/rails/stripe/usage.ts +61 -0
  175. package/src/usage/pass.ts +539 -0
  176. package/src/usage/reporter.ts +38 -0
  177. package/src/version.generated.ts +1 -1
  178. package/src/workflows/report.ts +4 -2
  179. package/src/workflows/specs.ts +34 -0
  180. package/src/workflows/usage.ts +97 -0
package/src/capability.ts CHANGED
@@ -8,13 +8,15 @@ import {
8
8
  defineCapability,
9
9
  } from "@pithy-sh/core/src/capability/capability";
10
10
  import type { DatabaseSpecMap } from "@pithy-sh/core/src/data/databases";
11
+ import type { UsageMeter } from "@pithy-sh/core/src/entitlement/meter";
11
12
  import { ValidationError } from "@pithy-sh/core/src/error/pithyError";
12
13
  import type { KvNamespaceSpecMap } from "@pithy-sh/core/src/kv/namespaces";
13
14
  import { workflowBindings } from "@pithy-sh/core/src/workflow/bindings";
14
15
  import type { Migration } from "kysely/migration";
15
- import type { PaymentsClientProduct, PaymentsClientProjection } from "./client/projection";
16
- import { PaymentsConfig, type PaymentsConfigInput } from "./config/config";
16
+ import type { PaymentsClientEntitlement, PaymentsClientProduct, PaymentsClientProjection } from "./client/projection";
17
+ import { PaymentsConfig, type PaymentsConfigInput, reportedProducts } from "./config/config";
17
18
  import { paymentsTables } from "./data/tables";
19
+ import { type PaymentsAllowances, paymentsUsageMeter } from "./entitlement/meter";
18
20
  import { installEntitlementResolver } from "./entitlement/resolver";
19
21
  import type { PaymentsSubjectResolver, PaymentsSubjectSeam } from "./entitlement/subjectSeam";
20
22
  import { requireImplementedSubject } from "./entitlement/unimplementedSubject";
@@ -23,12 +25,14 @@ import { paymentsManifestConfig } from "./http/manifestConfig";
23
25
  import { registerPaymentsRoutes } from "./http/routes";
24
26
  import { paymentsAdminRoutes } from "./http/scopes";
25
27
  import { payments_0001_purchases } from "./migrations/0001_purchases";
28
+ import { payments_0002_allowances } from "./migrations/0002_allowances";
26
29
  import { type PaymentsPeer, paymentsPeer } from "./peer";
27
30
  import { paymentsInapplicableSecrets, paymentsSecretBranches } from "./secret/branches";
28
31
  import { paymentsSecretsRegistry } from "./secret/registry";
29
32
  import { paymentsExampleSeed } from "./seeds/example";
33
+ import type { PaymentsQuantityResolver } from "./usage/pass";
30
34
  import { PACKAGE_NAME, PACKAGE_VERSION } from "./version.generated";
31
- import { paymentsWorkflows } from "./workflows/specs";
35
+ import { paymentsUsageWorkflows, paymentsWorkflows } from "./workflows/specs";
32
36
 
33
37
  /**
34
38
  * Where payments' migrations sort in the app database. Unique per database; the registry composes keys
@@ -66,6 +70,14 @@ export type PaymentsOptions = PaymentsConfigInput & {
66
70
  * it is optional and the authenticated caller is the answer.
67
71
  */
68
72
  resolveSubject?: PaymentsSubjectResolver;
73
+ /**
74
+ * How many of a quantity-billed product's units one subject has — students, coaches, seats. Required
75
+ * when any product declares `billing: { kind: "reported" }`, and refused at boot without one. Called by the
76
+ * usage-reporting pass on a schedule, with the env and no request; never by payments for anything else, and
77
+ * payments never counts members itself. Rides here rather than in config for the reason `resolveSubject`
78
+ * does: a function does not survive the config's round trip through JSON. See `usage/pass.ts`.
79
+ */
80
+ resolveQuantity?: PaymentsQuantityResolver;
69
81
  };
70
82
 
71
83
  /**
@@ -208,6 +220,26 @@ function requireResolvableSubject(config: PaymentsConfig, resolveSubject: Paymen
208
220
  });
209
221
  }
210
222
 
223
+ /**
224
+ * Refuse a catalog that bills by a reported quantity and gives payments nothing to ask.
225
+ *
226
+ * The same shape as {@link requireResolvableSubject}, and the same reasoning: the fault is total and the
227
+ * evidence is in hand. A quantity-billed subscription with no resolver is a subscription that bills nothing
228
+ * for what the customer is using, every period, and nothing anywhere fails — the store simply never hears a
229
+ * number. So it is refused here, naming every product it would happen to.
230
+ */
231
+ function requireQuantityResolver(config: PaymentsConfig, resolveQuantity: PaymentsQuantityResolver | undefined): void {
232
+ if (resolveQuantity !== undefined) return;
233
+ const reported = reportedProducts(config);
234
+ if (reported.length === 0) return;
235
+ throw new ValidationError({
236
+ message: `This catalog bills ${products(reported)} by a reported quantity, and nothing can say how many.`,
237
+ action:
238
+ "Pass `resolveQuantity` to `payments(...)` in this Worker's pithy.config.ts, or drop `billing` from those products.",
239
+ detail: `Products with \`billing.kind: "reported"\`: ${reported.map((entry) => entry.id).join(", ")}. Payments never counts members itself, so without a resolver no count is ever reported and the store bills nothing.`,
240
+ });
241
+ }
242
+
211
243
  /**
212
244
  * What a browser may know about this project's payments — the `virtual:pithy/payments` module.
213
245
  *
@@ -288,12 +320,30 @@ function clientProjection(config: PaymentsConfig, environment: string): Payments
288
320
  // Catalog order, not sorted: the order an adopter wrote their products in is the order a paywall
289
321
  // should list them, and it is stable for a given config either way.
290
322
  products,
323
+ // What each tier buys, so a paywall can compare them. The names, the numbers and the switches — and
324
+ // not `overrideMax`, which bounds an operator and tells a buyer nothing.
325
+ entitlements: Object.fromEntries(
326
+ Object.entries(config.entitlements).map(([key, declaration]): [string, PaymentsClientEntitlement] => [
327
+ key,
328
+ { name: declaration.name, quotas: { ...declaration.quotas }, features: { ...declaration.features } },
329
+ ]),
330
+ ),
331
+ defaults:
332
+ config.defaults === undefined
333
+ ? null
334
+ : { quotas: { ...config.defaults.quotas }, features: { ...config.defaults.features } },
291
335
  };
292
336
  }
293
337
 
338
+ /**
339
+ * The Workflows payments contributes: reconciliation always, usage reporting when the catalog sells a reported
340
+ * product.
341
+ */
342
+ type PaymentsWorkflowSpecs = typeof paymentsWorkflows & Partial<typeof paymentsUsageWorkflows>;
343
+
294
344
  /** The payments capability, with its resolved catalog attached for other tooling to read. */
295
345
  export interface PaymentsCapability
296
- extends Capability<DatabaseSpecMap, KvNamespaceSpecMap, "payments", typeof paymentsWorkflows> {
346
+ extends Capability<DatabaseSpecMap, KvNamespaceSpecMap, "payments", PaymentsWorkflowSpecs> {
297
347
  /** The resolved catalog. */
298
348
  paymentsConfig: PaymentsConfig;
299
349
  /**
@@ -302,6 +352,19 @@ export interface PaymentsCapability
302
352
  * payments bundles it (#645). See `peer.ts`.
303
353
  */
304
354
  paymentsPeer: PaymentsPeer;
355
+ /**
356
+ * The meter `@pithy-sh/email` charges at enqueue — found structurally through core's
357
+ * `composedUsageMeter`, so email imports nothing from this package. Charges nothing for a meter this
358
+ * config leaves advisory. See `entitlement/meter.ts`.
359
+ */
360
+ usageMeter: UsageMeter;
361
+ /**
362
+ * What the usage-reporting Workflow reads off the composition: the adopter's `resolveQuantity`, when the
363
+ * catalog bills by a reported quantity, and undefined otherwise. On the capability rather than in the
364
+ * config, so it is never serialized and never reaches a browser. `reportPaymentsUsage` in
365
+ * `workflows/usage.ts` reads it.
366
+ */
367
+ paymentsUsage: { resolveQuantity: PaymentsQuantityResolver } | undefined;
305
368
  }
306
369
 
307
370
  /**
@@ -335,13 +398,14 @@ export function payments(options: PaymentsOptions): PaymentsCapability {
335
398
  // whose whole hazard is being serialized by accident. Separated here, the config that reaches
336
399
  // `JSON.stringify` in `provision/resolvePaymentsConfig.ts` provably holds no function, because no function
337
400
  // was ever in it.
338
- const { resolveSubject, ...catalog } = options;
401
+ const { resolveSubject, resolveQuantity, ...catalog } = options;
339
402
 
340
403
  // Parse the catalog at assembly — a product naming a disabled rail, a duplicate provider SKU, or a
341
404
  // ledger grant on a non-consumable fails on deploy, not on the first webhook. `billingSubject` is required
342
405
  // and has no default: what a project bills is a decision, and a default would make it an accident.
343
406
  const resolved = PaymentsConfig.parse(catalog);
344
407
  requireResolvableSubject(resolved, resolveSubject);
408
+ requireQuantityResolver(resolved, resolveQuantity);
345
409
 
346
410
  // The one seam, built once. Both halves come from different places by construction (see
347
411
  // {@link PaymentsOptions}), and every asker — the entitlement gate through the middleware, the routes
@@ -357,13 +421,22 @@ export function payments(options: PaymentsOptions): PaymentsCapability {
357
421
  ...(resolveSubject ? { resolveSubject } : {}),
358
422
  };
359
423
 
424
+ // The declarations and the meters, once — the gate's readers, the routes, and the meter `@pithy-sh/email`
425
+ // charges all read this object, so they cannot disagree about what a name means.
426
+ const allowances: PaymentsAllowances = { declarations: resolved, meters: resolved.meters };
427
+
360
428
  // The optional peers, filled once by `compose` — which runs after this factory, so the routes are handed
361
429
  // the slot and read it per request rather than being handed a value that does not exist yet.
362
430
  const peers: { ledger: PaymentsLedgerPeer | undefined } = { ledger: undefined };
363
431
 
364
432
  const migrations: Record<string, Migration> = {
365
433
  "0001_purchases": payments_0001_purchases,
434
+ "0002_allowances": payments_0002_allowances,
366
435
  };
436
+ // Usage reporting only where something is billed by a reported quantity: a project that sells none binds
437
+ // nothing for it, and its `pithy doctor` has nothing to report about a Workflow it does not have.
438
+ const workflows: PaymentsWorkflowSpecs =
439
+ reportedProducts(resolved).length > 0 ? { ...paymentsWorkflows, ...paymentsUsageWorkflows } : paymentsWorkflows;
367
440
  const requiredBindings: BindingSpecInput[] = [
368
441
  // The app database — all four pithy_payments_* tables live here.
369
442
  { type: "d1", name: "DB" },
@@ -371,7 +444,7 @@ export function payments(options: PaymentsOptions): PaymentsCapability {
371
444
  // declaration, so a binding rename cannot leave the two disagreeing. `optional` because the binding
372
445
  // exists only once `pithy payments provision` has deployed the host, and an unprovisioned project must
373
446
  // still verify receipts, accept webhooks, and resolve entitlements.
374
- ...workflowBindings(paymentsWorkflows),
447
+ ...workflowBindings(workflows),
375
448
  ];
376
449
 
377
450
  const capability = defineCapability({
@@ -395,7 +468,7 @@ export function payments(options: PaymentsOptions): PaymentsCapability {
395
468
  inapplicableSecrets: paymentsInapplicableSecrets(resolved.rails),
396
469
  // The one durable job: the nightly reconciliation pass. Declared here so `createBackend` derives its
397
470
  // binding and types `c.var.workflows.trigger("payments/reconcile", …)` precisely.
398
- workflows: paymentsWorkflows,
471
+ workflows,
399
472
  // The one thing this capability cannot check on its own: whether the ledger it credits agrees the
400
473
  // currency exists. See `checkLedgerGrants` for why the failure is otherwise invisible. And the one place
401
474
  // the ledger reaches payments at all: found among the composed capabilities, never imported (#645).
@@ -422,7 +495,7 @@ export function payments(options: PaymentsOptions): PaymentsCapability {
422
495
  },
423
496
  // Replaces core's fail-closed `noEntitlementProvider` with the D1-backed resolver, over the seam that
424
497
  // says who to resolve for.
425
- middleware: [installEntitlementResolver(PAYMENTS_DATABASE_NAME, subject)],
498
+ middleware: [installEntitlementResolver(PAYMENTS_DATABASE_NAME, subject, allowances)],
426
499
  // The management surface, described for `GET /control-plane/manifest`. Built from the resolved
427
500
  // `basePath` rather than the default, so an adopter who mounted payments at `/billing` gets a
428
501
  // manifest naming `/billing/entitlements/grant` — the whole point of describing rather than
@@ -438,7 +511,12 @@ export function payments(options: PaymentsOptions): PaymentsCapability {
438
511
  seeds: [paymentsExampleSeed],
439
512
  });
440
513
 
441
- return Object.assign(capability, { paymentsConfig: resolved, paymentsPeer });
514
+ return Object.assign(capability, {
515
+ paymentsConfig: resolved,
516
+ paymentsPeer,
517
+ usageMeter: paymentsUsageMeter(allowances, "DB"),
518
+ paymentsUsage: resolveQuantity === undefined ? undefined : { resolveQuantity },
519
+ });
442
520
  }
443
521
 
444
522
  /** Whether a capability is the payments capability — carries its resolved catalog. */
package/src/client/api.ts CHANGED
@@ -542,6 +542,50 @@ function isEntitlementsBody(value: unknown): value is { entitlements: Entitlemen
542
542
  return isRecord(value) && isArrayOf(value.entitlements, isEntitlementView);
543
543
  }
544
544
 
545
+ /**
546
+ * What the caller's holder may have, as `GET /payments/entitlements` resolves it: every declared quota (a
547
+ * whole number, or null for unlimited) and every declared feature. **A UX affordance, never a security
548
+ * boundary** — a paywall shows "3 of 10 seats", and the server is what refuses the eleventh.
549
+ */
550
+ export interface AllowancesView {
551
+ /** Quotas by name. `null` is unlimited. */
552
+ quotas: Readonly<Record<string, number | null>>;
553
+ /** Features by name. */
554
+ features: Readonly<Record<string, boolean>>;
555
+ }
556
+
557
+ /** Whether a value is a map whose every value passes `guard`. */
558
+ function isMapOf<T>(value: unknown, guard: (item: unknown) => item is T): value is Record<string, T> {
559
+ return isRecord(value) && Object.values(value).every(guard);
560
+ }
561
+
562
+ /** A quota on the wire: a whole number from 0, or null. */
563
+ function isQuota(value: unknown): value is number | null {
564
+ return value === null || (typeof value === "number" && Number.isInteger(value) && value >= 0);
565
+ }
566
+
567
+ /** A feature on the wire. */
568
+ function isSwitch(value: unknown): value is boolean {
569
+ return typeof value === "boolean";
570
+ }
571
+
572
+ /** Whether a value is the entitlements envelope from a Worker that resolves allowances. */
573
+ function isAllowancesBody(value: unknown): value is AllowancesView {
574
+ return isRecord(value) && isMapOf(value.quotas, isQuota) && isMapOf(value.features, isSwitch);
575
+ }
576
+
577
+ /**
578
+ * The caller's resolved allowances. The client-side reading of `quota(c, name)` and `feature(c, name)`, for a
579
+ * paywall screen — never the enforcement, which the server does.
580
+ *
581
+ * A Worker that predates declarations answers no allowances, and that is a failure here rather than an empty
582
+ * map: an empty map reads as *zero of everything*, and a screen would tell a paying customer they have none.
583
+ */
584
+ export async function getAllowances(options?: PaymentsClientOptions): Promise<PaymentsResult<AllowancesView>> {
585
+ const result = await callPayments("/entitlements", {}, options, isAllowancesBody);
586
+ return result.ok ? { ok: true, value: { quotas: result.value.quotas, features: result.value.features } } : result;
587
+ }
588
+
545
589
  /** Whether a value is the purchase envelope both write routes' single-purchase form returns. */
546
590
  function isPurchaseBody(value: unknown): value is { purchase: PurchaseView; entitlements: EntitlementView[] } {
547
591
  return isRecord(value) && isPurchaseView(value.purchase) && isArrayOf(value.entitlements, isEntitlementView);
@@ -3,7 +3,9 @@
3
3
 
4
4
  import { useCallback, useEffect, useRef, useState } from "react";
5
5
  import {
6
+ type AllowancesView,
6
7
  type EntitlementView,
8
+ getAllowances,
7
9
  getEntitlements,
8
10
  openBillingPortal,
9
11
  openStoreSubscriptions,
@@ -143,6 +145,48 @@ export function useEntitlement(key: string, options?: PaymentsClientOptions): Us
143
145
  return { entitled, loading, readFailure, refresh };
144
146
  }
145
147
 
148
+ /** What {@link useAllowances} gives a paywall screen. */
149
+ export interface UseAllowances {
150
+ /** The caller's resolved quotas and features, or null until a read has landed. Never guessed. */
151
+ allowances: AllowancesView | null;
152
+ /** Whether a read is in flight. */
153
+ loading: boolean;
154
+ /** Why the last read could not be made, or null. `allowances` keeps its last answer while this is set. */
155
+ readFailure: PaymentsFailure | null;
156
+ /** Re-read. Call it after a purchase or an upgrade completes. */
157
+ refresh: () => void;
158
+ }
159
+
160
+ /**
161
+ * What the caller's holder may have — "3 of 10 seats", "SSO included" — for a screen to show.
162
+ *
163
+ * **Null until it knows, never zero.** A paywall that rendered `0 of 0` from a read still in flight would tell
164
+ * a paying customer they have nothing. And it is a UX affordance, never a boundary: the server's `quota()` and
165
+ * the kit's meters are what refuse.
166
+ */
167
+ export function useAllowances(options?: PaymentsClientOptions): UseAllowances {
168
+ const [allowances, setAllowances] = useState<AllowancesView | null>(null);
169
+ const [loading, setLoading] = useState(true);
170
+ const [readFailure, setReadFailure] = useState<PaymentsFailure | null>(null);
171
+ const latest = useLatest(options);
172
+ const live = useLive();
173
+ const basePath = options?.basePath;
174
+
175
+ const refresh = useCallback(() => {
176
+ setLoading(true);
177
+ void getAllowances({ ...latest.current, basePath }).then((result) => {
178
+ if (!live.current) return;
179
+ if (result.ok) setAllowances(result.value);
180
+ setReadFailure(result.ok ? null : result.failure);
181
+ setLoading(false);
182
+ });
183
+ }, [basePath, latest, live]);
184
+
185
+ useEffect(refresh, [refresh]);
186
+
187
+ return { allowances, loading, readFailure, refresh };
188
+ }
189
+
146
190
  /** What {@link useSubscription} gives a subscription screen. */
147
191
  export interface UseSubscription {
148
192
  /** Every entitlement the caller holds, as the server resolved it. */
@@ -40,6 +40,24 @@ export type PaymentsClientProduct = {
40
40
  };
41
41
  };
42
42
 
43
+ /** Numbered allowances and switches, as a browser reads them. */
44
+ export type PaymentsClientAllowances = {
45
+ /** Quotas by name: a whole number, or null for unlimited. */
46
+ quotas: Record<string, number | null>;
47
+ /** Features by name. */
48
+ features: Record<string, boolean>;
49
+ };
50
+
51
+ /** One declared entitlement key, browser-safe: what it is called and what it buys. */
52
+ export type PaymentsClientEntitlement = {
53
+ /** The tier's display name — `Growth`. Not translated: it is a product name. */
54
+ name: string;
55
+ /** Quotas by name: a whole number, or null for unlimited. */
56
+ quotas: Record<string, number | null>;
57
+ /** Features by name. */
58
+ features: Record<string, boolean>;
59
+ };
60
+
43
61
  /**
44
62
  * What a browser may know about this project's payments — the shape of `virtual:pithy/payments`.
45
63
  *
@@ -130,4 +148,17 @@ export type PaymentsClientProjection =
130
148
  * purchase fulfills beyond its entitlements, stay server-side.
131
149
  */
132
150
  products: PaymentsClientProduct[];
151
+ /**
152
+ * What each entitlement key buys, keyed by the key — its display name, its quotas (a whole number,
153
+ * or null for unlimited) and its features — so a paywall can lay tiers side by side. What the
154
+ * caller's own holder resolves to is `GET {basePath}/entitlements`. A UX affordance, never a
155
+ * security boundary: the server enforces every number here. The ceilings an operator's override is
156
+ * bounded by stay server-side.
157
+ */
158
+ entitlements: {
159
+ /** One declared key, by the key. */
160
+ [key: string]: PaymentsClientEntitlement;
161
+ };
162
+ /** What a caller holding no key gets — the free floor — or null when none is declared. */
163
+ defaults: PaymentsClientAllowances | null;
133
164
  };
@@ -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
+ }