@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
package/src/admin/read.ts CHANGED
@@ -2,20 +2,27 @@
2
2
  // SPDX-License-Identifier: MIT
3
3
 
4
4
  import type { D1Database } from "@cloudflare/workers-types";
5
+ import { chunkByBoundParameters } from "@pithy-sh/core/src/data/boundParameters";
5
6
  import { decodeCursor, type PageCursor, pageLimit, toPage } from "@pithy-sh/core/src/data/cursor";
6
7
  import type { z } from "zod";
7
8
  import { PaymentsEntitlement } from "../data/entitlement";
9
+ import { PaymentsOverride } from "../data/override";
8
10
  import { PaymentsPurchase, type PurchaseEnvironment } from "../data/purchase";
9
11
  import type { PaymentsRail } from "../data/rail";
10
12
  import { PaymentsReconcileRun } from "../data/reconcileRun";
11
13
  import type { PurchaseStatus } from "../data/status";
12
- import type { PaymentsSubject } from "../data/subject";
14
+ import { encodeSubjectReference, type PaymentsSubject } from "../data/subject";
13
15
  import {
14
16
  PAYMENTS_ENTITLEMENTS_TABLE,
17
+ PAYMENTS_OVERRIDES_TABLE,
15
18
  PAYMENTS_PURCHASES_TABLE,
16
19
  PAYMENTS_RECONCILE_RUNS_TABLE,
20
+ PAYMENTS_USAGE_REPORTS_TABLE,
21
+ PAYMENTS_USAGE_RUNS_TABLE,
17
22
  paymentsDatabase,
18
23
  } from "../data/tables";
24
+ import { PaymentsUsageReport } from "../data/usageReport";
25
+ import { PaymentsUsageRun } from "../data/usageRun";
19
26
 
20
27
  /**
21
28
  * The management read model — the queries behind the control-plane reads, and nothing else.
@@ -94,6 +101,7 @@ export const PaymentsPurchaseRecord = PaymentsPurchase.pick({
94
101
  environment: true,
95
102
  amountMinor: true,
96
103
  currency: true,
104
+ quantity: true,
97
105
  purchasedAt: true,
98
106
  expiresAt: true,
99
107
  revokedAt: true,
@@ -306,6 +314,170 @@ export async function readEntitlements(d1: D1Database, subject: PaymentsSubject)
306
314
  return rows.map((row) => PaymentsEntitlement.parse(row));
307
315
  }
308
316
 
317
+ /**
318
+ * Which of `subjects` are `unrestricted` — what the entitlement listing marks on each row. One query for the
319
+ * page rather than one per row, on the override index that leads on `unrestricted`.
320
+ */
321
+ export async function unrestrictedSubjects(d1: D1Database, subjects: readonly PaymentsSubject[]): Promise<Set<string>> {
322
+ if (subjects.length === 0) return new Set();
323
+ const db = paymentsDatabase(d1);
324
+ const found = new Set<string>();
325
+ // One fixed parameter beside the list — `unrestricted` — so a full page of 100 ids is two statements.
326
+ for (const ids of chunkByBoundParameters([...new Set(subjects.map((subject) => subject.subjectId))], 1)) {
327
+ const rows = await db
328
+ .selectFrom(PAYMENTS_OVERRIDES_TABLE)
329
+ .select(["subjectType", "subjectId"])
330
+ // biome-ignore lint/suspicious/noExplicitAny: the encoded 0/1 the codec writes.
331
+ .where("unrestricted", "=", 1 as any)
332
+ .where("subjectId", "in", ids)
333
+ .execute();
334
+ for (const row of rows) found.add(encodeSubjectReference(row as PaymentsSubject));
335
+ }
336
+ return found;
337
+ }
338
+
339
+ /** What {@link listOverrides} accepts. */
340
+ export interface OverridesQuery {
341
+ /** Narrow to one subject. */
342
+ subject?: PaymentsSubject;
343
+ /** Narrow to the subjects that are `unrestricted`. */
344
+ unrestricted?: boolean;
345
+ /** Where to resume. */
346
+ cursor?: string;
347
+ /** How many rows to return, clamped by `pageLimit`. */
348
+ limit?: number;
349
+ }
350
+
351
+ /**
352
+ * Every subject's override, most recently changed first. A row a clear emptied is kept only so its version
353
+ * never repeats, and overrides nothing, so it is not listed.
354
+ */
355
+ export async function listOverrides(
356
+ d1: D1Database,
357
+ query: OverridesQuery = {},
358
+ ): Promise<PaymentsPage<PaymentsOverride>> {
359
+ const limit = pageLimit(query.limit);
360
+ const after = resume(query.cursor);
361
+ let selection = paymentsDatabase(d1)
362
+ .selectFrom(PAYMENTS_OVERRIDES_TABLE)
363
+ .selectAll()
364
+ // The SQL side of `isEmptyOverride`: the encoded 0/1 and the encoded empty JSON objects the codec writes.
365
+ .where((eb) =>
366
+ eb.or([
367
+ // biome-ignore lint/suspicious/noExplicitAny: the encoded 0/1 the codec writes.
368
+ eb("unrestricted", "=", 1 as any),
369
+ // biome-ignore lint/suspicious/noExplicitAny: the encoded JSON text the codec writes.
370
+ eb("quotas", "!=", "{}" as any),
371
+ // biome-ignore lint/suspicious/noExplicitAny: as above.
372
+ eb("features", "!=", "{}" as any),
373
+ ]),
374
+ )
375
+ .orderBy("updatedAt", "desc")
376
+ .orderBy("id", "desc")
377
+ .limit(limit + 1);
378
+ if (query.subject !== undefined) {
379
+ selection = selection
380
+ .where("subjectType", "=", query.subject.subjectType)
381
+ .where("subjectId", "=", query.subject.subjectId);
382
+ }
383
+ if (query.unrestricted !== undefined) {
384
+ const flag = query.unrestricted ? 1 : 0;
385
+ // biome-ignore lint/suspicious/noExplicitAny: the encoded 0/1 the codec writes.
386
+ selection = selection.where("unrestricted", "=", flag as any);
387
+ }
388
+ if (after) {
389
+ selection = selection.where((eb) =>
390
+ eb.or([eb("updatedAt", "<", after.sort), eb.and([eb("updatedAt", "=", after.sort), eb("id", "<", after.id)])]),
391
+ );
392
+ }
393
+ const rows = await selection.execute();
394
+ return toPage(
395
+ rows.map((row) => PaymentsOverride.parse(row)),
396
+ limit,
397
+ (override) => ({ sort: override.updatedAt.getTime(), id: override.id }),
398
+ );
399
+ }
400
+
401
+ /** Every `unrestricted` subject this deployment holds — what `pithy doctor` names. */
402
+ export async function listUnrestrictedSubjects(d1: D1Database): Promise<PaymentsSubject[]> {
403
+ const rows = await paymentsDatabase(d1)
404
+ .selectFrom(PAYMENTS_OVERRIDES_TABLE)
405
+ .select(["subjectType", "subjectId"])
406
+ // biome-ignore lint/suspicious/noExplicitAny: the encoded 0/1 the codec writes.
407
+ .where("unrestricted", "=", 1 as any)
408
+ .orderBy("subjectType")
409
+ .orderBy("subjectId")
410
+ .execute();
411
+ return rows.map((row) => ({ subjectType: row.subjectType, subjectId: row.subjectId }) as PaymentsSubject);
412
+ }
413
+
414
+ /** What {@link listUsageRuns} accepts. */
415
+ export interface UsageRunsQuery {
416
+ /** Where to resume, from a previous page's `nextCursor`. A malformed one is a first page. */
417
+ cursor?: string;
418
+ /** How many rows to return, clamped by `pageLimit`. */
419
+ limit?: number;
420
+ }
421
+
422
+ /** The usage-reporting passes this deployment has run, newest first — the same keyset the reconcile log uses. */
423
+ export async function listUsageRuns(
424
+ d1: D1Database,
425
+ query: UsageRunsQuery = {},
426
+ ): Promise<PaymentsPage<PaymentsUsageRun>> {
427
+ const limit = pageLimit(query.limit);
428
+ const after = resume(query.cursor);
429
+ let selection = paymentsDatabase(d1)
430
+ .selectFrom(PAYMENTS_USAGE_RUNS_TABLE)
431
+ .selectAll()
432
+ .orderBy("startedAt", "desc")
433
+ .orderBy("id", "desc")
434
+ .limit(limit + 1);
435
+ if (after) {
436
+ selection = selection.where((eb) =>
437
+ eb.or([eb("startedAt", "<", after.sort), eb.and([eb("startedAt", "=", after.sort), eb("id", "<", after.id)])]),
438
+ );
439
+ }
440
+ const rows = await selection.execute();
441
+ return toPage(
442
+ rows.map((row) => PaymentsUsageRun.parse(row)),
443
+ limit,
444
+ (run) => ({ sort: run.startedAt.getTime(), id: run.id }),
445
+ );
446
+ }
447
+
448
+ /**
449
+ * The newest accepted report of each subscription, by its store id — what the subscription reads show as the
450
+ * last reported count. Keyed on the subscription rather than on one period's purchase row, because the report
451
+ * for a period lands at that period's end and the current row has none until then.
452
+ */
453
+ export async function lastReports(
454
+ d1: D1Database,
455
+ subscriptions: readonly { rail: PaymentsRail; providerSubscriptionId: string }[],
456
+ ): Promise<Map<string, { quantity: number; reportedAt: Date }>> {
457
+ const latest = new Map<string, { quantity: number; reportedAt: Date }>();
458
+ if (subscriptions.length === 0) return latest;
459
+ const db = paymentsDatabase(d1);
460
+ const ids = [...new Set(subscriptions.map((entry) => entry.providerSubscriptionId))];
461
+ // One fixed parameter beside the list — `status` — so a full page is two statements. A subscription's rows
462
+ // all fall in the chunk that carries its id, so newest-first within a chunk is newest-first for it.
463
+ for (const chunk of chunkByBoundParameters(ids, 1)) {
464
+ const rows = await db
465
+ .selectFrom(PAYMENTS_USAGE_REPORTS_TABLE)
466
+ .selectAll()
467
+ .where("providerSubscriptionId", "in", chunk)
468
+ .where("status", "=", "reported")
469
+ .orderBy("reportedAt", "desc")
470
+ .execute();
471
+ for (const row of rows) {
472
+ const report = PaymentsUsageReport.parse(row);
473
+ const key = `${report.rail}:${report.providerSubscriptionId}`;
474
+ if (report.reportedAt === null || latest.has(key)) continue;
475
+ latest.set(key, { quantity: report.quantity, reportedAt: report.reportedAt });
476
+ }
477
+ }
478
+ return latest;
479
+ }
480
+
309
481
  /** What {@link listReconcileRuns} accepts. */
310
482
  export interface ReconcileRunsQuery {
311
483
  /** Restrict to the passes narrowed to one store. Never matches a pass that ran against every rail. */
@@ -208,6 +208,19 @@ export const PaymentsAuditActions = {
208
208
  * indistinguishable from the 04:00 cron, which is exactly the question somebody reading the trail is asking.
209
209
  */
210
210
  reconcileRunStarted: "payments/reconcile_run_started",
211
+ /**
212
+ * A management client pinned allowances for one subject, or turned `unrestricted` on or off. The first
213
+ * runtime-writable input to an entitlement decision, so every write is recorded with the subject, the
214
+ * mode, the before and the after — and the **reason**, verbatim, because six months later the only
215
+ * question anybody asks about an override is why.
216
+ */
217
+ overrideSet: "payments/override_set",
218
+ /** A management client unpinned allowances for one subject, or cleared its override. */
219
+ overrideCleared: "payments/override_cleared",
220
+ /**
221
+ * A management client read the usage-reporting run log. Counts and filters only, as every management read.
222
+ */
223
+ usageRunsRead: "payments/usage_runs_read",
211
224
  } as const;
212
225
 
213
226
  /** One of the payments audit action codes. */
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
  };