@pithy-sh/payments 0.3.10 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (215) hide show
  1. package/README.md +11 -3
  2. package/dist/admin/coverage.d.ts.map +1 -1
  3. package/dist/admin/coverage.js +26 -2
  4. package/dist/admin/read.d.ts +48 -1
  5. package/dist/admin/read.d.ts.map +1 -1
  6. package/dist/admin/read.js +89 -2
  7. package/dist/audit/actions.d.ts +13 -0
  8. package/dist/audit/actions.d.ts.map +1 -1
  9. package/dist/audit/actions.js +14 -1
  10. package/dist/capability.d.ts +33 -2
  11. package/dist/capability.d.ts.map +1 -1
  12. package/dist/capability.js +52 -9
  13. package/dist/client/api.d.ts +38 -0
  14. package/dist/client/api.d.ts.map +1 -1
  15. package/dist/client/api.js +59 -1
  16. package/dist/client/hooks.d.ts +63 -1
  17. package/dist/client/hooks.d.ts.map +1 -1
  18. package/dist/client/hooks.js +96 -2
  19. package/dist/client/paddleLink.d.ts +31 -0
  20. package/dist/client/paddleLink.d.ts.map +1 -0
  21. package/dist/client/paddleLink.js +37 -0
  22. package/dist/client/projection.d.ts +29 -0
  23. package/dist/client/projection.d.ts.map +1 -1
  24. package/dist/config/allowances.d.ts +71 -0
  25. package/dist/config/allowances.d.ts.map +1 -0
  26. package/dist/config/allowances.js +115 -0
  27. package/dist/config/config.d.ts +155 -9
  28. package/dist/config/config.d.ts.map +1 -1
  29. package/dist/config/config.js +164 -14
  30. package/dist/data/meterCounter.d.ts +34 -0
  31. package/dist/data/meterCounter.d.ts.map +1 -0
  32. package/dist/data/meterCounter.js +33 -0
  33. package/dist/data/override.d.ts +56 -0
  34. package/dist/data/override.d.ts.map +1 -0
  35. package/dist/data/override.js +58 -0
  36. package/dist/data/paddleIds.d.ts +28 -0
  37. package/dist/data/paddleIds.d.ts.map +1 -0
  38. package/dist/data/paddleIds.js +73 -0
  39. package/dist/data/period.d.ts +10 -0
  40. package/dist/data/period.d.ts.map +1 -0
  41. package/dist/data/period.js +37 -0
  42. package/dist/data/purchase.d.ts +1 -0
  43. package/dist/data/purchase.d.ts.map +1 -1
  44. package/dist/data/purchase.js +1 -0
  45. package/dist/data/tables.d.ts +17 -1
  46. package/dist/data/tables.d.ts.map +1 -1
  47. package/dist/data/tables.js +24 -4
  48. package/dist/data/usageReport.d.ts +68 -0
  49. package/dist/data/usageReport.d.ts.map +1 -0
  50. package/dist/data/usageReport.js +55 -0
  51. package/dist/data/usageRun.d.ts +93 -0
  52. package/dist/data/usageRun.d.ts.map +1 -0
  53. package/dist/data/usageRun.js +50 -0
  54. package/dist/entitlement/allowance.d.ts +100 -0
  55. package/dist/entitlement/allowance.d.ts.map +1 -0
  56. package/dist/entitlement/allowance.js +171 -0
  57. package/dist/entitlement/manual.d.ts +5 -5
  58. package/dist/entitlement/manual.js +3 -3
  59. package/dist/entitlement/meter.d.ts +98 -0
  60. package/dist/entitlement/meter.d.ts.map +1 -0
  61. package/dist/entitlement/meter.js +177 -0
  62. package/dist/entitlement/override.d.ts +119 -0
  63. package/dist/entitlement/override.d.ts.map +1 -0
  64. package/dist/entitlement/override.js +256 -0
  65. package/dist/entitlement/resolver.d.ts +2 -1
  66. package/dist/entitlement/resolver.d.ts.map +1 -1
  67. package/dist/entitlement/resolver.js +32 -1
  68. package/dist/entitlement/unimplementedSubject.d.ts.map +1 -1
  69. package/dist/entitlement/unimplementedSubject.js +3 -2
  70. package/dist/error/errors.d.ts +19 -0
  71. package/dist/error/errors.d.ts.map +1 -1
  72. package/dist/error/errors.js +35 -2
  73. package/dist/http/responses.d.ts +390 -5
  74. package/dist/http/responses.d.ts.map +1 -1
  75. package/dist/http/responses.js +169 -13
  76. package/dist/http/routes.d.ts +6 -2
  77. package/dist/http/routes.d.ts.map +1 -1
  78. package/dist/http/routes.js +478 -52
  79. package/dist/http/schemas.d.ts +75 -1
  80. package/dist/http/schemas.d.ts.map +1 -1
  81. package/dist/http/schemas.js +80 -3
  82. package/dist/http/scopes.d.ts +25 -0
  83. package/dist/http/scopes.d.ts.map +1 -1
  84. package/dist/http/scopes.js +60 -1
  85. package/dist/http/view.d.ts +22 -4
  86. package/dist/http/view.d.ts.map +1 -1
  87. package/dist/http/view.js +88 -7
  88. package/dist/http/webhookGuard.d.ts.map +1 -1
  89. package/dist/http/webhookGuard.js +1 -1
  90. package/dist/index.d.ts +2 -1
  91. package/dist/index.d.ts.map +1 -1
  92. package/dist/index.js +3 -2
  93. package/dist/migrations/0002_allowances.d.ts +26 -0
  94. package/dist/migrations/0002_allowances.d.ts.map +1 -0
  95. package/dist/migrations/0002_allowances.js +62 -0
  96. package/dist/peer.d.ts +1 -0
  97. package/dist/peer.d.ts.map +1 -1
  98. package/dist/projection/event.d.ts +1 -0
  99. package/dist/projection/event.d.ts.map +1 -1
  100. package/dist/projection/event.js +1 -0
  101. package/dist/projection/writer.d.ts.map +1 -1
  102. package/dist/projection/writer.js +3 -1
  103. package/dist/rails/contract.d.ts +6 -0
  104. package/dist/rails/contract.d.ts.map +1 -1
  105. package/dist/rails/google/playApi.d.ts.map +1 -1
  106. package/dist/rails/google/playApi.js +2 -0
  107. package/dist/rails/paddle/events.d.ts.map +1 -1
  108. package/dist/rails/paddle/events.js +2 -1
  109. package/dist/rails/paddle/objects.d.ts +2 -0
  110. package/dist/rails/paddle/objects.d.ts.map +1 -1
  111. package/dist/rails/paddle/objects.js +7 -2
  112. package/dist/rails/paddle/refresh.d.ts +10 -5
  113. package/dist/rails/paddle/refresh.d.ts.map +1 -1
  114. package/dist/rails/paddle/refresh.js +8 -5
  115. package/dist/rails/paddle/refund.d.ts.map +1 -1
  116. package/dist/rails/paddle/refund.js +10 -2
  117. package/dist/rails/paddle/subscription.d.ts.map +1 -1
  118. package/dist/rails/paddle/subscription.js +8 -3
  119. package/dist/rails/paddle/usage.d.ts +11 -0
  120. package/dist/rails/paddle/usage.d.ts.map +1 -0
  121. package/dist/rails/paddle/usage.js +49 -0
  122. package/dist/rails/paddle/verify.d.ts.map +1 -1
  123. package/dist/rails/paddle/verify.js +2 -3
  124. package/dist/rails/quantity.d.ts +12 -0
  125. package/dist/rails/quantity.d.ts.map +1 -0
  126. package/dist/rails/quantity.js +16 -0
  127. package/dist/rails/stripe/checkout.d.ts.map +1 -1
  128. package/dist/rails/stripe/checkout.js +1 -1
  129. package/dist/rails/stripe/objects.d.ts.map +1 -1
  130. package/dist/rails/stripe/objects.js +3 -0
  131. package/dist/rails/stripe/usage.d.ts +10 -0
  132. package/dist/rails/stripe/usage.d.ts.map +1 -0
  133. package/dist/rails/stripe/usage.js +49 -0
  134. package/dist/secret/registry.d.ts.map +1 -1
  135. package/dist/secret/registry.js +3 -2
  136. package/dist/usage/pass.d.ts +120 -0
  137. package/dist/usage/pass.d.ts.map +1 -0
  138. package/dist/usage/pass.js +363 -0
  139. package/dist/usage/reporter.d.ts +36 -0
  140. package/dist/usage/reporter.d.ts.map +1 -0
  141. package/dist/usage/reporter.js +2 -0
  142. package/dist/version.generated.d.ts +1 -1
  143. package/dist/version.generated.d.ts.map +1 -1
  144. package/dist/version.generated.js +1 -1
  145. package/dist/workflows/specs.d.ts +28 -0
  146. package/dist/workflows/specs.d.ts.map +1 -1
  147. package/dist/workflows/specs.js +26 -1
  148. package/dist/workflows/usage.d.ts +38 -0
  149. package/dist/workflows/usage.d.ts.map +1 -0
  150. package/dist/workflows/usage.js +77 -0
  151. package/dist/workflows/worker.js +2 -2
  152. package/dist/workflows/workerConfig.d.ts.map +1 -1
  153. package/dist/workflows/workerConfig.js +8 -2
  154. package/docs/entitlements.md +249 -0
  155. package/docs/lemon-squeezy.md +1 -0
  156. package/docs/paddle.md +18 -2
  157. package/package.json +7 -7
  158. package/pithy.manifest.json +3 -8
  159. package/src/admin/coverage.ts +28 -0
  160. package/src/admin/read.ts +173 -1
  161. package/src/audit/actions.ts +13 -0
  162. package/src/capability.ts +87 -9
  163. package/src/client/api.ts +79 -0
  164. package/src/client/hooks.ts +122 -0
  165. package/src/client/paddleLink.ts +41 -0
  166. package/src/client/projection.ts +31 -0
  167. package/src/config/allowances.ts +211 -0
  168. package/src/config/config.ts +283 -15
  169. package/src/data/meterCounter.ts +38 -0
  170. package/src/data/override.ts +74 -0
  171. package/src/data/paddleIds.ts +74 -0
  172. package/src/data/period.ts +53 -0
  173. package/src/data/purchase.ts +9 -0
  174. package/src/data/tables.ts +25 -1
  175. package/src/data/usageReport.ts +64 -0
  176. package/src/data/usageRun.ts +66 -0
  177. package/src/entitlement/allowance.ts +213 -0
  178. package/src/entitlement/manual.ts +6 -6
  179. package/src/entitlement/meter.ts +252 -0
  180. package/src/entitlement/override.ts +381 -0
  181. package/src/entitlement/resolver.ts +43 -2
  182. package/src/entitlement/unimplementedSubject.ts +3 -4
  183. package/src/error/errors.ts +44 -1
  184. package/src/http/responses.ts +338 -10
  185. package/src/http/routes.ts +1089 -460
  186. package/src/http/schemas.ts +171 -2
  187. package/src/http/scopes.ts +68 -0
  188. package/src/http/view.ts +112 -7
  189. package/src/http/webhookGuard.ts +3 -2
  190. package/src/index.ts +18 -0
  191. package/src/migrations/0002_allowances.ts +149 -0
  192. package/src/projection/event.ts +9 -0
  193. package/src/projection/writer.ts +4 -0
  194. package/src/rails/contract.ts +6 -0
  195. package/src/rails/google/playApi.ts +2 -0
  196. package/src/rails/paddle/events.ts +2 -1
  197. package/src/rails/paddle/fixtures/subscription-charge.json +19 -0
  198. package/src/rails/paddle/objects.ts +6 -0
  199. package/src/rails/paddle/refresh.ts +17 -10
  200. package/src/rails/paddle/refund.ts +10 -2
  201. package/src/rails/paddle/subscription.ts +8 -3
  202. package/src/rails/paddle/usage.ts +66 -0
  203. package/src/rails/paddle/verify.ts +6 -4
  204. package/src/rails/quantity.ts +14 -0
  205. package/src/rails/stripe/checkout.ts +3 -1
  206. package/src/rails/stripe/fixtures/meter-event-created.json +12 -0
  207. package/src/rails/stripe/objects.ts +4 -0
  208. package/src/rails/stripe/usage.ts +61 -0
  209. package/src/secret/registry.ts +3 -2
  210. package/src/usage/pass.ts +539 -0
  211. package/src/usage/reporter.ts +38 -0
  212. package/src/version.generated.ts +1 -1
  213. package/src/workflows/specs.ts +34 -0
  214. package/src/workflows/usage.ts +97 -0
  215. package/src/workflows/workerConfig.ts +9 -3
@@ -0,0 +1,177 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { PaymentsSubject, encodeSubjectReference } from "../data/subject.js";
4
+ import { PaymentsMeterCounter } from "../data/meterCounter.js";
5
+ import { grantingStatuses } from "../data/status.js";
6
+ import { PaymentsPurchase } from "../data/purchase.js";
7
+ import { PAYMENTS_PURCHASES_TABLE, paymentsDatabase } from "../data/tables.js";
8
+ import { knownPeriodStart } from "../data/period.js";
9
+ import { PaymentsQuotaExceededError } from "../error/errors.js";
10
+ import { resolveEntitlements } from "../projection/resolve.js";
11
+ import { resolveQuota } from "./allowance.js";
12
+ import { allowanceOverride, readOverride } from "./override.js";
13
+ import { InternalError, PithyError, ValidationError, messageOf } from "@pithy-sh/core/src/error/pithyError";
14
+ import { grantedEntitlementKeys } from "@pithy-sh/core/src/entitlement/entitlement";
15
+ import { createWorkerLogger } from "@pithy-sh/core/src/logger/worker";
16
+ import { sql } from "kysely";
17
+ //#region src/entitlement/meter.ts
18
+ /** Whether a kit meter is enforced in this config. Anything not a kit meter is not. */
19
+ function meterEnforced(meters, meter) {
20
+ return meters[meter]?.enforce === true;
21
+ }
22
+ /**
23
+ * Everything resolution needs for one subject, read now: the keys granting access and the override row. A
24
+ * caller acting for nobody holds nothing and has no override, and resolves to the floor.
25
+ */
26
+ async function allowanceInputFor(db, declarations, subject, now) {
27
+ if (subject === void 0 || db === void 0) return {
28
+ declarations,
29
+ held: /* @__PURE__ */ new Set(),
30
+ override: null
31
+ };
32
+ const [entitlements, override] = await Promise.all([resolveEntitlements(db, subject, now), readOverride(db, subject)]);
33
+ return {
34
+ declarations,
35
+ held: grantedEntitlementKeys(entitlements, now),
36
+ override: allowanceOverride(override)
37
+ };
38
+ }
39
+ /** The first instant of `now`'s calendar month, in UTC. The period of a subject payments knows no billing period for. */
40
+ function calendarMonthStart(now) {
41
+ return new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1));
42
+ }
43
+ /**
44
+ * When the subject's current period began: the start of its current billing period where payments knows one,
45
+ * the calendar month where it does not — a free-floor account still has a month.
46
+ *
47
+ * The current period is a granting subscription row whose window holds `now`; `data/period.ts` says which
48
+ * rails' rows state where that period began. Two at once — an upgrade overlapping an old subscription's tail —
49
+ * is answered by the newest, which is the one the customer is now paying for.
50
+ */
51
+ async function meterPeriodStart(db, subject, now) {
52
+ const at = now.getTime();
53
+ const row = await db.selectFrom(PAYMENTS_PURCHASES_TABLE).select([
54
+ "rail",
55
+ "purchasedAt",
56
+ "payload"
57
+ ]).where("subjectType", "=", subject.subjectType).where("subjectId", "=", subject.subjectId).where("type", "=", "subscription").where("status", "in", grantingStatuses(true)).where("purchasedAt", "<=", at).where("expiresAt", ">", at).orderBy("purchasedAt", "desc").limit(1).executeTakeFirst();
58
+ if (row === void 0) return calendarMonthStart(now);
59
+ const purchase = PaymentsPurchase.pick({
60
+ rail: true,
61
+ purchasedAt: true,
62
+ payload: true
63
+ }).parse(row);
64
+ return knownPeriodStart(purchase) ?? calendarMonthStart(now);
65
+ }
66
+ /**
67
+ * Charge `amount` of `meter` against `subject` — or refuse, and write nothing.
68
+ *
69
+ * **The check and the write are one statement.** An upsert on `(subject, meter, periodStart)` whose update
70
+ * is conditioned on `used + amount <= limit`, with `RETURNING` to read back whether it landed. SQLite
71
+ * evaluates the condition under its write lock, so a burst of concurrent sends is serialized by the database
72
+ * and the first that would pass the limit changes nothing — the guarantee `@pithy-sh/storage`'s conditional
73
+ * insert makes, for the same reason: D1 has no interactive transaction to make two statements one.
74
+ *
75
+ * An unlimited subject — `null`, from a plan or from `unrestricted` — is counted and never refused.
76
+ */
77
+ async function chargeMeter(db, allowances, charge) {
78
+ if (!meterEnforced(allowances.meters, charge.meter)) return;
79
+ const input = await allowanceInputFor(db, allowances.declarations, charge.subject, charge.now);
80
+ const limit = resolveQuota(input, charge.meter).effective.value;
81
+ const periodStart = await meterPeriodStart(db, charge.subject, charge.now);
82
+ const refused = () => new PaymentsQuotaExceededError({
83
+ params: {
84
+ meter: charge.meter,
85
+ limit: limit ?? 0
86
+ },
87
+ detail: `${encodeSubjectReference(charge.subject)} is at its ${charge.meter} quota of ${limit} for the period from ${periodStart.toISOString()}.`
88
+ });
89
+ if (limit !== null && charge.amount > limit) throw refused();
90
+ const at = charge.now.getTime();
91
+ const record = PaymentsMeterCounter.encode({
92
+ id: crypto.randomUUID(),
93
+ subjectType: charge.subject.subjectType,
94
+ subjectId: charge.subject.subjectId,
95
+ meter: charge.meter,
96
+ periodStart,
97
+ used: charge.amount,
98
+ createdAt: charge.now,
99
+ updatedAt: charge.now
100
+ });
101
+ if (await db.insertInto("pithyPaymentsMeterCounters").values(record).onConflict((oc) => {
102
+ const update = oc.columns([
103
+ "subjectType",
104
+ "subjectId",
105
+ "meter",
106
+ "periodStart"
107
+ ]).doUpdateSet({
108
+ used: sql`${sql.ref(`pithyPaymentsMeterCounters.used`)} + excluded.used`,
109
+ updatedAt: at
110
+ });
111
+ return limit === null ? update : update.where(sql`${sql.ref(`pithyPaymentsMeterCounters.used`)} + excluded.used <= ${limit}`);
112
+ }).returning("used").executeTakeFirst() === void 0) throw refused();
113
+ }
114
+ /**
115
+ * The ceiling a capability enforces on a level it counts itself — `storageBytes`, `mediaItems` — for a
116
+ * subject, or `{ enforced: false }` where the meter is advisory and the capability keeps its own.
117
+ *
118
+ * **The ceiling names the organization it covers.** An organization's plan is the organization's, so the
119
+ * capability must sum every member's rows against it, not the caller's alone — `tenant` says so, the same
120
+ * value the holder's `tenant` carries. A user subject, or nobody, is `null`: the caller's own rows.
121
+ */
122
+ async function meterLimitFor(db, allowances, subject, meter, now) {
123
+ if (!meterEnforced(allowances.meters, meter)) return { enforced: false };
124
+ const input = await allowanceInputFor(db, allowances.declarations, subject, now);
125
+ return {
126
+ enforced: true,
127
+ limit: resolveQuota(input, meter).effective.value,
128
+ tenant: subject?.subjectType === "organization" ? subject.subjectId : null
129
+ };
130
+ }
131
+ /**
132
+ * The meter `@pithy-sh/email` finds among the composed capabilities and charges at enqueue — the env-side
133
+ * half of the seam, for the callers with no request. See `@pithy-sh/core/src/entitlement/meter.ts`.
134
+ *
135
+ * A refusal is the provider's own `payments/quota_exceeded`. Anything else that goes wrong — a malformed
136
+ * holder, a D1 read that throws — is logged and refused as `core/internal`, never let through: see this
137
+ * module's note on which way round to err.
138
+ */
139
+ function paymentsUsageMeter(allowances, database = "DB") {
140
+ return {
141
+ provider: "payments",
142
+ async charge(env, charge) {
143
+ if (!meterEnforced(allowances.meters, charge.meter)) return;
144
+ const log = charge.log ?? createWorkerLogger({ name: "payments" });
145
+ const subject = PaymentsSubject.safeParse(charge.subject);
146
+ if (!subject.success || !Number.isInteger(charge.amount) || charge.amount < 1) throw new ValidationError({
147
+ message: "That usage charge names no valid holder or amount.",
148
+ action: "Charge a whole amount from 1 against a subject the payments subject schema accepts.",
149
+ detail: `meter ${charge.meter}, amount ${charge.amount}`
150
+ });
151
+ try {
152
+ const d1 = env[database];
153
+ if (!d1) throw new InternalError({ detail: `No \`${database}\` binding on env; the ${charge.meter} meter cannot count.` });
154
+ await chargeMeter(paymentsDatabase(d1), allowances, {
155
+ subject: subject.data,
156
+ meter: charge.meter,
157
+ amount: charge.amount,
158
+ now: charge.now ?? /* @__PURE__ */ new Date()
159
+ });
160
+ } catch (error) {
161
+ if (error instanceof PaymentsQuotaExceededError) throw error;
162
+ log.error("usage meter charge failed", {
163
+ meter: charge.meter,
164
+ cause: messageOf(error)
165
+ });
166
+ if (error instanceof PithyError && error.payload.code !== "core/internal") throw error;
167
+ throw new InternalError({
168
+ message: "Usage could not be checked, so nothing was written.",
169
+ action: "Read the preceding log line for why the meter read failed.",
170
+ detail: `the ${charge.meter} meter could not be charged; refusing rather than serving unbounded.`
171
+ });
172
+ }
173
+ }
174
+ };
175
+ }
176
+ //#endregion
177
+ export { allowanceInputFor, calendarMonthStart, chargeMeter, meterEnforced, meterLimitFor, meterPeriodStart, paymentsUsageMeter };
@@ -0,0 +1,119 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import type { D1Database } from "@cloudflare/workers-types";
4
+ import { type AllowanceDeclarations, type FeatureMap, type QuotaMap } from "../config/allowances";
5
+ import { PaymentsOverride } from "../data/override";
6
+ import { type PaymentsSubject } from "../data/subject";
7
+ import { type PaymentsDatabase } from "../data/tables";
8
+ import type { AllowanceOverride } from "./allowance";
9
+ /**
10
+ * Per-subject overrides — the writes behind the control plane's set and clear, and the read every resolver
11
+ * shares.
12
+ *
13
+ * **The first runtime-writable input to an entitlement decision in the kit**, so each rule below is one of the
14
+ * things that keeps it narrow:
15
+ *
16
+ * - **A name must be declared.** A patch naming `emals` is refused naming it and listing what is declared,
17
+ * the shape a grant of an unknown key already gets. `unrestricted` names nothing, so it is exempt.
18
+ * - **A ceiling is a ceiling.** Where a declaration states `overrideMax`, a set past it is refused naming the
19
+ * limit — never clamped, because a clamped number is a wrong number nobody chose.
20
+ * - **A write is a merge by name.** A set changes only the names it carries, so coming back months later to
21
+ * add 100 to one allowance is a request naming one allowance — and one operator's stale pane cannot erase
22
+ * another's pin by omission.
23
+ * - **A write names the version it read.** A version behind the row is `payments/override_stale`, and nothing
24
+ * is written. The compare is inside the write's own `WHERE`, so two writers racing on one row cannot both
25
+ * pass a check made a statement earlier.
26
+ * - **A version never repeats.** A clear keeps the row, empty, at the next version rather than deleting it,
27
+ * so a pane still holding a cleared row's version is behind, not current again.
28
+ * - **A clear only moves a subject back toward its plan.** Unpinning a name on an `unrestricted` subject
29
+ * would lift it to unlimited, which is the unrestricted scope's grant, so a clear naming such a pin is
30
+ * refused. A whole clear takes `unrestricted` with it, which narrows, and is allowed.
31
+ * - **A reason is required on every set**, and the audit event carries it. Six months later, the question
32
+ * anybody asks about an override is why.
33
+ */
34
+ /** A subject's override row, or undefined when it has none. */
35
+ export declare function readOverride(db: PaymentsDatabase, subject: PaymentsSubject): Promise<PaymentsOverride | undefined>;
36
+ /** The resolver's view of a row: the three facts resolution reads, or null for no override — a cleared row included. */
37
+ export declare function allowanceOverride(row: PaymentsOverride | undefined): AllowanceOverride | null;
38
+ /** The version a write must name: the row's — a cleared row's included — or 0 when there has never been one. */
39
+ export declare function overrideVersion(row: PaymentsOverride | undefined): number;
40
+ /** What a set or a clear changed, for the audit event and the response. */
41
+ export interface OverrideChange {
42
+ /** The row before the write, or undefined when there was none. */
43
+ before: PaymentsOverride | undefined;
44
+ /**
45
+ * The row after the write, or undefined when the subject has never had one. A clear leaves an empty row
46
+ * ({@link isEmptyOverride}), which carries the version the next write must name.
47
+ */
48
+ after: PaymentsOverride | undefined;
49
+ }
50
+ /** The clock and the id minter. */
51
+ export interface OverrideWriteOptions {
52
+ /** The write timestamp. Defaults to now. */
53
+ now?: Date;
54
+ /** The id minter for a row that does not exist yet. Defaults to `crypto.randomUUID`. */
55
+ newId?: () => string;
56
+ }
57
+ /** A sparse patch: the names to pin, and nothing about the names it omits. */
58
+ export interface OverridePatch {
59
+ /** Quotas to pin, by name. */
60
+ quotas?: QuotaMap;
61
+ /** Features to pin, by name. */
62
+ features?: FeatureMap;
63
+ }
64
+ /**
65
+ * The ceiling an override of `name` is bounded by for a subject holding `held`, or undefined for none.
66
+ *
67
+ * **The keys the subject holds decide, because the ceiling belongs to the tier.** `growth` states that its
68
+ * customers' email allowance may be shaded up to 100,000. Among the held keys that declare the quota, the
69
+ * most permissive applies — and a held key declaring the quota with *no* ceiling leaves it unbounded, since a
70
+ * ceiling that gets in the way of a genuine deal is worse than none. A subject holding no key that declares
71
+ * the quota is bounded the same way by every declaration of it.
72
+ */
73
+ export declare function overrideCeiling(declarations: AllowanceDeclarations, held: ReadonlySet<string>, name: string): number | undefined;
74
+ /** What a set carries besides the change itself. */
75
+ interface OverrideWrite {
76
+ /** Who. */
77
+ subject: PaymentsSubject;
78
+ /** The version the caller read. 0 when it read no override. */
79
+ version: number;
80
+ /** Why. */
81
+ reason: string;
82
+ }
83
+ /**
84
+ * Pin numbers and switches for one subject. A merge: the names the patch carries change, every other pin
85
+ * stands, and every name never pinned keeps tracking the plan.
86
+ */
87
+ export declare function setOverride(d1: D1Database, declarations: AllowanceDeclarations, input: OverrideWrite & OverridePatch, options?: OverrideWriteOptions): Promise<OverrideChange>;
88
+ /**
89
+ * Turn `unrestricted` on or off for one subject. Its own write, behind its own scope: it is the largest grant
90
+ * the kit has, and the only one whose reach grows by itself as names are declared. Pins stand either way.
91
+ * Never bounded by `overrideMax` — being unbounded is what it is for.
92
+ */
93
+ export declare function setUnrestricted(d1: D1Database, input: OverrideWrite & {
94
+ unrestricted: boolean;
95
+ }, options?: OverrideWriteOptions): Promise<OverrideChange>;
96
+ /** What a clear names: some pins, or — with neither list — the whole override. */
97
+ export interface OverrideClear {
98
+ /** Who. */
99
+ subject: PaymentsSubject;
100
+ /** The version the caller read. Optional: a clear that names none is not checked. */
101
+ version?: number;
102
+ /** Quota pins to remove. */
103
+ quotas?: readonly string[];
104
+ /** Feature pins to remove. */
105
+ features?: readonly string[];
106
+ /** Why, when the caller says. A clear keeps the last set's reason otherwise. */
107
+ reason?: string;
108
+ }
109
+ /**
110
+ * Remove pins, or the whole override. **Idempotent**: clearing an override that does not exist — or that a
111
+ * clear already emptied — is the state the caller asked for, and answers with nothing changed rather than a
112
+ * 404. A name unpinned resolves from the plan again on the next read.
113
+ *
114
+ * **A whole clear keeps the row**, empty, at the next version — see {@link isEmptyOverride} for why a version
115
+ * must never repeat. Every read treats that row as no override.
116
+ */
117
+ export declare function clearOverride(d1: D1Database, input: OverrideClear, options?: OverrideWriteOptions): Promise<OverrideChange>;
118
+ export {};
119
+ //# sourceMappingURL=override.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"override.d.ts","sourceRoot":"","sources":["../../src/entitlement/override.ts"],"names":[],"mappings":"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"}
@@ -0,0 +1,256 @@
1
+ // SPDX-FileCopyrightText: 2026 Pithy
2
+ // SPDX-License-Identifier: MIT
3
+ import { encodeSubjectReference } from "../data/subject.js";
4
+ import { declaredFeatureNames, declaredQuotaNames } from "../config/allowances.js";
5
+ import { PaymentsOverride, isEmptyOverride } from "../data/override.js";
6
+ import { PAYMENTS_OVERRIDES_TABLE, paymentsDatabase } from "../data/tables.js";
7
+ import { PaymentsOverrideStaleError } from "../error/errors.js";
8
+ import { resolveEntitlements } from "../projection/resolve.js";
9
+ import { InternalError, ValidationError } from "@pithy-sh/core/src/error/pithyError";
10
+ import { grantedEntitlementKeys } from "@pithy-sh/core/src/entitlement/entitlement";
11
+ import { withD1Retry } from "@pithy-sh/core/src/data/withD1Retry";
12
+ //#region src/entitlement/override.ts
13
+ /**
14
+ * Per-subject overrides — the writes behind the control plane's set and clear, and the read every resolver
15
+ * shares.
16
+ *
17
+ * **The first runtime-writable input to an entitlement decision in the kit**, so each rule below is one of the
18
+ * things that keeps it narrow:
19
+ *
20
+ * - **A name must be declared.** A patch naming `emals` is refused naming it and listing what is declared,
21
+ * the shape a grant of an unknown key already gets. `unrestricted` names nothing, so it is exempt.
22
+ * - **A ceiling is a ceiling.** Where a declaration states `overrideMax`, a set past it is refused naming the
23
+ * limit — never clamped, because a clamped number is a wrong number nobody chose.
24
+ * - **A write is a merge by name.** A set changes only the names it carries, so coming back months later to
25
+ * add 100 to one allowance is a request naming one allowance — and one operator's stale pane cannot erase
26
+ * another's pin by omission.
27
+ * - **A write names the version it read.** A version behind the row is `payments/override_stale`, and nothing
28
+ * is written. The compare is inside the write's own `WHERE`, so two writers racing on one row cannot both
29
+ * pass a check made a statement earlier.
30
+ * - **A version never repeats.** A clear keeps the row, empty, at the next version rather than deleting it,
31
+ * so a pane still holding a cleared row's version is behind, not current again.
32
+ * - **A clear only moves a subject back toward its plan.** Unpinning a name on an `unrestricted` subject
33
+ * would lift it to unlimited, which is the unrestricted scope's grant, so a clear naming such a pin is
34
+ * refused. A whole clear takes `unrestricted` with it, which narrows, and is allowed.
35
+ * - **A reason is required on every set**, and the audit event carries it. Six months later, the question
36
+ * anybody asks about an override is why.
37
+ */
38
+ /** A subject's override row, or undefined when it has none. */
39
+ async function readOverride(db, subject) {
40
+ const row = await db.selectFrom(PAYMENTS_OVERRIDES_TABLE).selectAll().where("subjectType", "=", subject.subjectType).where("subjectId", "=", subject.subjectId).executeTakeFirst();
41
+ return row === void 0 ? void 0 : PaymentsOverride.parse(row);
42
+ }
43
+ /** The resolver's view of a row: the three facts resolution reads, or null for no override — a cleared row included. */
44
+ function allowanceOverride(row) {
45
+ if (row === void 0 || isEmptyOverride(row)) return null;
46
+ return {
47
+ unrestricted: row.unrestricted,
48
+ quotas: row.quotas,
49
+ features: row.features
50
+ };
51
+ }
52
+ /** The version a write must name: the row's — a cleared row's included — or 0 when there has never been one. */
53
+ function overrideVersion(row) {
54
+ return row?.version ?? 0;
55
+ }
56
+ /** Refuse a patch naming anything the declarations do not mention, naming it and listing what is declared. */
57
+ function requireDeclaredNames(declarations, patch) {
58
+ const quotas = declaredQuotaNames(declarations);
59
+ for (const name of Object.keys(patch.quotas ?? {})) {
60
+ if (quotas.includes(name)) continue;
61
+ throw new ValidationError({
62
+ message: `No quota "${name}" is declared. Declared quotas: ${quotas.join(", ") || "none"}.`,
63
+ action: "Override a quota this project declares, or declare it in pithy.config.ts first."
64
+ });
65
+ }
66
+ const features = declaredFeatureNames(declarations);
67
+ for (const name of Object.keys(patch.features ?? {})) {
68
+ if (features.includes(name)) continue;
69
+ throw new ValidationError({
70
+ message: `No feature "${name}" is declared. Declared features: ${features.join(", ") || "none"}.`,
71
+ action: "Override a feature this project declares, or declare it in pithy.config.ts first."
72
+ });
73
+ }
74
+ }
75
+ /**
76
+ * The ceiling an override of `name` is bounded by for a subject holding `held`, or undefined for none.
77
+ *
78
+ * **The keys the subject holds decide, because the ceiling belongs to the tier.** `growth` states that its
79
+ * customers' email allowance may be shaded up to 100,000. Among the held keys that declare the quota, the
80
+ * most permissive applies — and a held key declaring the quota with *no* ceiling leaves it unbounded, since a
81
+ * ceiling that gets in the way of a genuine deal is worse than none. A subject holding no key that declares
82
+ * the quota is bounded the same way by every declaration of it.
83
+ */
84
+ function overrideCeiling(declarations, held, name) {
85
+ const speaking = Object.entries(declarations.entitlements).filter(([, declaration]) => name in declaration.quotas);
86
+ const heldSpeaking = speaking.filter(([key]) => held.has(key));
87
+ const deciding = heldSpeaking.length > 0 ? heldSpeaking : speaking;
88
+ let ceiling;
89
+ for (const [, declaration] of deciding) {
90
+ const stated = declaration.overrideMax?.[name];
91
+ if (stated === void 0) return void 0;
92
+ ceiling = ceiling === void 0 ? stated : Math.max(ceiling, stated);
93
+ }
94
+ return ceiling;
95
+ }
96
+ /** Refuse a quota pin past its ceiling, naming the limit. Unlimited (`null`) is past every ceiling. */
97
+ function requireWithinCeilings(declarations, held, quotas) {
98
+ for (const [name, value] of Object.entries(quotas)) {
99
+ const ceiling = overrideCeiling(declarations, held, name);
100
+ if (ceiling === void 0) continue;
101
+ if (value !== null && value <= ceiling) continue;
102
+ throw new ValidationError({
103
+ message: `"${name}" may be overridden up to ${ceiling}, and ${value === null ? "unlimited" : value} is past it.`,
104
+ action: `Send a number no larger than ${ceiling}, or raise \`overrideMax.${name}\` in pithy.config.ts. Unlimited for every name is \`unrestricted\`.`
105
+ });
106
+ }
107
+ }
108
+ /** The stale refusal, with the two versions in `detail`. */
109
+ function stale(subject, sent, current) {
110
+ return new PaymentsOverrideStaleError({ detail: `The override for ${encodeSubjectReference(subject)} is at version ${current}; the write named ${sent}.` });
111
+ }
112
+ /**
113
+ * Write `next` over the subject's row, but only if the row is still at `write.version`.
114
+ *
115
+ * The compare is the statement's own: an update `WHERE version = ?` on an existing row, and an insert that
116
+ * does nothing on conflict for a row that did not exist. Zero rows written is the stale answer either way,
117
+ * because the two writers it protects were never going to be serialized by anything else.
118
+ */
119
+ async function writeVersioned(d1, write, change, options) {
120
+ const db = paymentsDatabase(d1);
121
+ const now = options.now ?? /* @__PURE__ */ new Date();
122
+ const before = await readOverride(db, write.subject);
123
+ const current = overrideVersion(before);
124
+ if (write.version !== current) throw stale(write.subject, write.version, current);
125
+ const next = change(before);
126
+ const record = PaymentsOverride.encode({
127
+ id: before?.id ?? (options.newId ?? (() => crypto.randomUUID()))(),
128
+ subjectType: write.subject.subjectType,
129
+ subjectId: write.subject.subjectId,
130
+ unrestricted: next.unrestricted,
131
+ quotas: next.quotas,
132
+ features: next.features,
133
+ version: current + 1,
134
+ reason: write.reason,
135
+ createdAt: before?.createdAt ?? now,
136
+ updatedAt: now
137
+ });
138
+ const changes = {
139
+ unrestricted: record.unrestricted,
140
+ quotas: record.quotas,
141
+ features: record.features,
142
+ version: record.version,
143
+ reason: record.reason,
144
+ updatedAt: record.updatedAt
145
+ };
146
+ if (await withD1Retry(async () => before === void 0 ? db.insertInto("pithyPaymentsOverrides").values(record).onConflict((oc) => oc.columns(["subjectType", "subjectId"]).doNothing()).returning("id").executeTakeFirst() : db.updateTable("pithyPaymentsOverrides").set(changes).where("subjectType", "=", write.subject.subjectType).where("subjectId", "=", write.subject.subjectId).where("version", "=", current).returning("id").executeTakeFirst()) === void 0) {
147
+ const moved = await readOverride(db, write.subject);
148
+ throw stale(write.subject, write.version, overrideVersion(moved));
149
+ }
150
+ const after = await readOverride(db, write.subject);
151
+ if (after === void 0) throw new InternalError({
152
+ message: "The override could not be recorded.",
153
+ detail: `Wrote the override for ${encodeSubjectReference(write.subject)} but could not read it back.`
154
+ });
155
+ return {
156
+ before,
157
+ after
158
+ };
159
+ }
160
+ /** The keys a subject holds that grant access now — what a ceiling is decided by. */
161
+ async function heldNow(db, subject, now) {
162
+ return grantedEntitlementKeys(await resolveEntitlements(db, subject, now), now);
163
+ }
164
+ /**
165
+ * Pin numbers and switches for one subject. A merge: the names the patch carries change, every other pin
166
+ * stands, and every name never pinned keeps tracking the plan.
167
+ */
168
+ async function setOverride(d1, declarations, input, options = {}) {
169
+ requireDeclaredNames(declarations, input);
170
+ const now = options.now ?? /* @__PURE__ */ new Date();
171
+ requireWithinCeilings(declarations, await heldNow(paymentsDatabase(d1), input.subject, now), input.quotas ?? {});
172
+ return writeVersioned(d1, input, (before) => ({
173
+ unrestricted: before?.unrestricted ?? false,
174
+ quotas: {
175
+ ...before?.quotas ?? {},
176
+ ...input.quotas ?? {}
177
+ },
178
+ features: {
179
+ ...before?.features ?? {},
180
+ ...input.features ?? {}
181
+ }
182
+ }), {
183
+ ...options,
184
+ now
185
+ });
186
+ }
187
+ /**
188
+ * Turn `unrestricted` on or off for one subject. Its own write, behind its own scope: it is the largest grant
189
+ * the kit has, and the only one whose reach grows by itself as names are declared. Pins stand either way.
190
+ * Never bounded by `overrideMax` — being unbounded is what it is for.
191
+ */
192
+ async function setUnrestricted(d1, input, options = {}) {
193
+ return writeVersioned(d1, input, (before) => ({
194
+ unrestricted: input.unrestricted,
195
+ quotas: before?.quotas ?? {},
196
+ features: before?.features ?? {}
197
+ }), options);
198
+ }
199
+ /**
200
+ * Refuse a partial clear that would lift a pin on an `unrestricted` subject to unlimited.
201
+ *
202
+ * On an unrestricted row a pin is the one thing holding a name below unlimited, so removing it is not a move
203
+ * back toward the plan — it is the largest grant the kit has, made one name at a time, by a credential that
204
+ * holds only the clear scope. Turning `unrestricted` off first, behind its own scope, or clearing the whole
205
+ * override, are the two ways that narrow.
206
+ */
207
+ function requireNarrowingClear(row, input) {
208
+ if (!row.unrestricted) return;
209
+ const lifted = [...(input.quotas ?? []).filter((name) => name in row.quotas), ...(input.features ?? []).filter((name) => name in row.features)];
210
+ if (lifted.length === 0) return;
211
+ throw new ValidationError({
212
+ message: `This subject is unrestricted, so unpinning ${lifted.map((name) => `"${name}"`).join(", ")} would make it unlimited.`,
213
+ action: "Turn unrestricted off first through its own route, or clear the whole override — both move the subject back toward its plan.",
214
+ detail: `A clear only narrows. On an unrestricted override a pin is all that holds a name below unlimited, and lifting that is the unrestricted scope's grant.`
215
+ });
216
+ }
217
+ /**
218
+ * Remove pins, or the whole override. **Idempotent**: clearing an override that does not exist — or that a
219
+ * clear already emptied — is the state the caller asked for, and answers with nothing changed rather than a
220
+ * 404. A name unpinned resolves from the plan again on the next read.
221
+ *
222
+ * **A whole clear keeps the row**, empty, at the next version — see {@link isEmptyOverride} for why a version
223
+ * must never repeat. Every read treats that row as no override.
224
+ */
225
+ async function clearOverride(d1, input, options = {}) {
226
+ const before = await readOverride(paymentsDatabase(d1), input.subject);
227
+ if (before === void 0 || isEmptyOverride(before)) return {
228
+ before: void 0,
229
+ after: before
230
+ };
231
+ if (input.version !== void 0 && input.version !== before.version) throw stale(input.subject, input.version, before.version);
232
+ const whole = input.quotas === void 0 && input.features === void 0;
233
+ if (!whole) requireNarrowingClear(before, input);
234
+ return writeVersioned(d1, {
235
+ subject: input.subject,
236
+ version: before.version,
237
+ reason: input.reason ?? before.reason
238
+ }, (current) => {
239
+ if (whole) return {
240
+ unrestricted: false,
241
+ quotas: {},
242
+ features: {}
243
+ };
244
+ const quotas = { ...current?.quotas ?? {} };
245
+ for (const name of input.quotas ?? []) delete quotas[name];
246
+ const features = { ...current?.features ?? {} };
247
+ for (const name of input.features ?? []) delete features[name];
248
+ return {
249
+ unrestricted: current?.unrestricted ?? false,
250
+ quotas,
251
+ features
252
+ };
253
+ }, options);
254
+ }
255
+ //#endregion
256
+ export { allowanceOverride, clearOverride, overrideCeiling, overrideVersion, readOverride, setOverride, setUnrestricted };
@@ -4,6 +4,7 @@ import type { PithyMiddleware } from "@pithy-sh/core/src/capability/capability";
4
4
  import type { EntitlementHolder, EntitlementResolver } from "@pithy-sh/core/src/entitlement/entitlement";
5
5
  import { type PaymentsSubject } from "../data/subject";
6
6
  import type { PaymentsDatabase } from "../data/tables";
7
+ import { type PaymentsAllowances } from "./meter";
7
8
  import { type PaymentsSubjectSeam } from "./subjectSeam";
8
9
  /**
9
10
  * Payments filling the entitlement seam. Core's default (`noEntitlementProvider`) holds nothing so that an
@@ -58,5 +59,5 @@ export declare function createPaymentsEntitlementResolver(db: PaymentsDatabase,
58
59
  * neither is a composition problem, and reporting `null` here would send an operator looking for a missing
59
60
  * capability.
60
61
  */
61
- export declare function installEntitlementResolver(database: string, seam: PaymentsSubjectSeam): PithyMiddleware;
62
+ export declare function installEntitlementResolver(database: string, seam: PaymentsSubjectSeam, allowances?: PaymentsAllowances): PithyMiddleware;
62
63
  //# sourceMappingURL=resolver.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"resolver.d.ts","sourceRoot":"","sources":["../../src/entitlement/resolver.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,0CAA0C,CAAC;AAChF,OAAO,KAAK,EAAe,iBAAiB,EAAE,mBAAmB,EAAE,MAAM,4CAA4C,CAAC;AAEtH,OAAO,EAA0B,KAAK,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAC/E,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AAEvD,OAAO,EAAE,KAAK,mBAAmB,EAA0B,MAAM,eAAe,CAAC;AAEjF;;;;;;GAMG;AACH,eAAO,MAAM,6BAA6B,aAAa,CAAC;AAExD;;;;;;;;;;;;;GAaG;AACH,wBAAgB,yBAAyB,CAAC,OAAO,EAAE,eAAe,GAAG,iBAAiB,CAKrF;AAED;;;;;;GAMG;AACH,wBAAgB,iCAAiC,CAC/C,EAAE,EAAE,gBAAgB,EACpB,OAAO,EAAE,eAAe,EACxB,GAAG,GAAE,MAAM,IAAuB,GACjC,mBAAmB,CAOrB;AAED;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAgB,0BAA0B,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,mBAAmB,GAAG,eAAe,CAyCvG"}
1
+ {"version":3,"file":"resolver.d.ts","sourceRoot":"","sources":["../../src/entitlement/resolver.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,0CAA0C,CAAC;AAChF,OAAO,KAAK,EAEV,iBAAiB,EACjB,mBAAmB,EAEpB,MAAM,4CAA4C,CAAC;AAEpD,OAAO,EAA0B,KAAK,eAAe,EAAE,MAAM,iBAAiB,CAAC;AAC/E,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,gBAAgB,CAAC;AAGvD,OAAO,EAAoC,KAAK,kBAAkB,EAAE,MAAM,SAAS,CAAC;AACpF,OAAO,EAAE,KAAK,mBAAmB,EAA0B,MAAM,eAAe,CAAC;AAEjF;;;;;;GAMG;AACH,eAAO,MAAM,6BAA6B,aAAa,CAAC;AAExD;;;;;;;;;;;;;GAaG;AACH,wBAAgB,yBAAyB,CAAC,OAAO,EAAE,eAAe,GAAG,iBAAiB,CAKrF;AAED;;;;;;GAMG;AACH,wBAAgB,iCAAiC,CAC/C,EAAE,EAAE,gBAAgB,EACpB,OAAO,EAAE,eAAe,EACxB,GAAG,GAAE,MAAM,IAAuB,GACjC,mBAAmB,CAOrB;AAED;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAgB,0BAA0B,CACxC,QAAQ,EAAE,MAAM,EAChB,IAAI,EAAE,mBAAmB,EACzB,UAAU,GAAE,kBAAuE,GAClF,eAAe,CAuEjB"}
@@ -2,6 +2,8 @@
2
2
  // SPDX-License-Identifier: MIT
3
3
  import { encodeSubjectReference } from "../data/subject.js";
4
4
  import { resolveEntitlements } from "../projection/resolve.js";
5
+ import { requireDeclaredFeature, requireDeclaredQuota, resolveFeature, resolveQuota } from "./allowance.js";
6
+ import { allowanceInputFor, meterLimitFor } from "./meter.js";
5
7
  import { resolvePaymentsSubject } from "./subjectSeam.js";
6
8
  import { InternalError } from "@pithy-sh/core/src/error/pithyError";
7
9
  //#region src/entitlement/resolver.ts
@@ -69,7 +71,10 @@ function createPaymentsEntitlementResolver(db, subject, now = () => /* @__PURE__
69
71
  * neither is a composition problem, and reporting `null` here would send an operator looking for a missing
70
72
  * capability.
71
73
  */
72
- function installEntitlementResolver(database, seam) {
74
+ function installEntitlementResolver(database, seam, allowances = {
75
+ declarations: { entitlements: {} },
76
+ meters: {}
77
+ }) {
73
78
  return (app) => {
74
79
  app.use("*", async (c, next) => {
75
80
  let resolving;
@@ -77,8 +82,34 @@ function installEntitlementResolver(database, seam) {
77
82
  resolving ??= resolvePaymentsSubject(c, seam);
78
83
  return resolving;
79
84
  };
85
+ /** The database, or the wiring fault — checked only once a read actually needs one. */
86
+ const appDatabase = () => {
87
+ const db = c.var.db[database];
88
+ if (!db) throw new InternalError({
89
+ message: "Payments is not configured.",
90
+ action: "Bind a D1 database named DB in wrangler.jsonc.",
91
+ detail: `No \`${database}\` database on c.var.db; payments cannot resolve allowances.`
92
+ });
93
+ return db;
94
+ };
80
95
  c.set("entitlements", {
81
96
  provider: PAYMENTS_ENTITLEMENT_PROVIDER,
97
+ quota: async (name) => {
98
+ requireDeclaredQuota(allowances.declarations, name);
99
+ const subject = await subjectOnce();
100
+ const input = await allowanceInputFor(subject && appDatabase(), allowances.declarations, subject, /* @__PURE__ */ new Date());
101
+ return resolveQuota(input, name).effective.value;
102
+ },
103
+ feature: async (name) => {
104
+ requireDeclaredFeature(allowances.declarations, name);
105
+ const subject = await subjectOnce();
106
+ const input = await allowanceInputFor(subject && appDatabase(), allowances.declarations, subject, /* @__PURE__ */ new Date());
107
+ return resolveFeature(input, name).effective.value;
108
+ },
109
+ meterLimit: async (meter) => {
110
+ const subject = await subjectOnce();
111
+ return meterLimitFor(appDatabase(), allowances, subject, meter, /* @__PURE__ */ new Date());
112
+ },
82
113
  holder: async () => {
83
114
  const subject = await subjectOnce();
84
115
  return subject ? paymentsEntitlementHolder(subject) : void 0;
@@ -1 +1 @@
1
- {"version":3,"file":"unimplementedSubject.d.ts","sourceRoot":"","sources":["../../src/entitlement/unimplementedSubject.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,eAAe,CAAC;AAwC7D;;;;;;;;;GASG;AACH,eAAO,MAAM,oBAAoB,EAAE,uBAWP,CAAC;AAE7B,mGAAmG;AACnG,wBAAgB,sBAAsB,CAAC,QAAQ,EAAE,uBAAuB,GAAG,SAAS,GAAG,OAAO,CAE7F;AAED;;;;;;GAMG;AACH,wBAAgB,yBAAyB,CAAC,QAAQ,EAAE,uBAAuB,GAAG,SAAS,GAAG,IAAI,CAS7F"}
1
+ {"version":3,"file":"unimplementedSubject.d.ts","sourceRoot":"","sources":["../../src/entitlement/unimplementedSubject.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,eAAe,CAAC;AAwC7D;;;;;;;;;GASG;AACH,eAAO,MAAM,oBAAoB,EAAE,uBAUP,CAAC;AAE7B,mGAAmG;AACnG,wBAAgB,sBAAsB,CAAC,QAAQ,EAAE,uBAAuB,GAAG,SAAS,GAAG,OAAO,CAE7F;AAED;;;;;;GAMG;AACH,wBAAgB,yBAAyB,CAAC,QAAQ,EAAE,uBAAuB,GAAG,SAAS,GAAG,IAAI,CAQ7F"}