@krizaka/credits 0.0.0-stage → 0.1.1
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.
- package/LICENSE +201 -0
- package/README.md +49 -2
- package/dist/chunk-34Y2HXOB.js +109 -0
- package/dist/chunk-34Y2HXOB.js.map +1 -0
- package/dist/chunk-WDHQ7QHY.js +56 -0
- package/dist/chunk-WDHQ7QHY.js.map +1 -0
- package/dist/credits-Do0guD2C.d.ts +258 -0
- package/dist/index.d.ts +35 -0
- package/dist/index.js +524 -0
- package/dist/index.js.map +1 -0
- package/dist/port-C0Qw77Bp.d.ts +163 -0
- package/dist/settings.d.ts +18 -0
- package/dist/settings.js +23 -0
- package/dist/settings.js.map +1 -0
- package/dist/testkit.d.ts +30 -0
- package/dist/testkit.js +284 -0
- package/dist/testkit.js.map +1 -0
- package/package.json +83 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,50 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @krizaka/credits
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
**One credits ledger for every Krizaka product.** It replaces three models: Yomizaka's `audit_credits` and `free_audit_used_at` columns on `accounts` (`reserveAudit` / `releaseAudit` / `refundFailedAudit`), Orochia's `wallet_ledger` with holds, and the Java kit's `credit_wallet` / `credit_ledger_entry` / `credit_hold` (`krizaka-billing`, whose names and events it follows). The coupons module (#46) grants capped credits through it.
|
|
4
|
+
|
|
5
|
+
> **The ledger is append-only and the balance is derived.** Nothing stores a balance that could drift: what is left of a pot is the sum of its lines. A database trigger refuses any `UPDATE` or `DELETE` of a line. Credits are integers, never floats.
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
import { emitMigration, transaction } from "@krizaka/db";
|
|
9
|
+
import { createCredits, creditsSchema } from "@krizaka/credits";
|
|
10
|
+
import { creditsSettings, readCreditsSettings } from "@krizaka/credits/settings";
|
|
11
|
+
|
|
12
|
+
emitMigration(creditsSchema, 1, { tables: { owner: "accounts" } }); // commit the SQL once, in your migrations
|
|
13
|
+
|
|
14
|
+
const credits = createCredits({ clock, settings: () => readCreditsSettings((key) => settings.get(key)), outbox });
|
|
15
|
+
|
|
16
|
+
await transaction(connect, async (tx) => {
|
|
17
|
+
// a coupon's free credits: 20 audits, at most 5 a day, then stop; they lapse in 30 days
|
|
18
|
+
await credits.grant(tx, { accountId, amount: 20, capPerDay: 5, expiresAt, onExhausted: "stop", source: `coupon:${redemptionId}`, idempotencyKey: `redeem-${redemptionId}` });
|
|
19
|
+
// credits bought (the payment webhook, in the event's transaction)
|
|
20
|
+
await credits.purchase(tx, { accountId, amount: 10, source: `purchase:${paymentRef}`, idempotencyKey: `pay-${paymentRef}` });
|
|
21
|
+
});
|
|
22
|
+
|
|
23
|
+
// spending: it refuses with a typed code, writes nothing when it refuses, and a replay of the key spends nothing more
|
|
24
|
+
const { draws } = await credits.consume(tx, { accountId, amount: 1, reason: `audit:${auditId}`, idempotencyKey: `audit-${auditId}` });
|
|
25
|
+
await credits.refund(tx, { accountId, consumed: `audit-${auditId}`, reason: "the run failed" }); // back to the same pots, once
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
## The model
|
|
29
|
+
|
|
30
|
+
- **Two kinds of pot.** A **granted** pot is free usage (a coupon, an allowance, a demo): it always **expires**, may be capped **per day** and **per month**, and says what happens when it runs out: `stop` or `fallback_paid`. A **purchased** pot does not expire and is never capped.
|
|
31
|
+
- **`consume(tx, { accountId, amount, reason, idempotencyKey })`** draws from the granted pots that **expire first**, each within its caps, then from purchased credits. Nothing is partial: it covers the whole amount or refuses.
|
|
32
|
+
- past a pot's cap: `CREDITS_CAP_DAY` / `CREDITS_CAP_MONTH` (a fair-use limit: purchased credits do not bypass it; another granted pot still can serve);
|
|
33
|
+
- a `stop` pot that is empty: `CREDITS_EXHAUSTED`, even if purchased credits exist;
|
|
34
|
+
- a `fallback_paid` pot that is empty: it moves on to purchased credits, then answers `PAYWALL`;
|
|
35
|
+
- no credits at all: `PAYWALL`.
|
|
36
|
+
Refusals are `CreditsError`s with a `code` and the HTTP `status` a route may answer (402 / 429).
|
|
37
|
+
- **Holds.** `hold` keeps credits back for work in progress (it counts against the caps and the balance, and expires after `credits.holdTtlSeconds`); `settle(holdId, { amount? })` spends what the work cost (at most the hold) and frees the rest; `release` frees it all. Once each; a replay answers the first result.
|
|
38
|
+
- **`refund`** gives back what a consume (or a settled hold) spent, to the same pots, once. **`expire(grantId)`** writes off what is left of a pot (a revoked coupon: credits already spent are never taken back); **`expireDue`** sweeps the lapsed pots in a job. **`adjust`** is an administrator's signed correction, never below zero.
|
|
39
|
+
- **`balance`** is `{ total, granted, purchased, held, available, grants[] }`, derived; **`history`** pages the lines newest first.
|
|
40
|
+
- **Idempotency.** Every writing call takes a key; the lines of an operation are `<kind>.<key>:<n>` (unique in the database). Keys are unique per ledger, not per account: use an id (a payment ref, a job id). A key already used by **another account** is refused (`CREDITS_KEY_REUSED`). Keys carry no colon.
|
|
41
|
+
- **Concurrency.** Every writer takes `pg_advisory_xact_lock` on the account first, then reads and decides: concurrent consumption of the last credit never goes negative, a cap holds under load, and one key sent many times spends once (all proved on PostgreSQL, in loops).
|
|
42
|
+
- **Days and months** are cut by PostgreSQL in the admin's IANA zone (`credits.timeZone`, default `America/Toronto`), so daylight-saving shifts are the database's own tz data; « today » comes from the injected clock.
|
|
43
|
+
- **Events** (through `@krizaka/outbox`, in the caller's transaction, ids derived from the fact so each is announced once): `evt.credit.granted.v1` and `evt.credit.exhausted.v1`, the names of `krizaka-billing-api`, with a JSON Schema each (`CREDIT_EVENT_SCHEMAS`).
|
|
44
|
+
- **Settings** (`@krizaka/credits/settings`): `credits.timeZone` (a choice among the runtime's IANA zones) and `credits.holdTtlSeconds` (900, 30–86400).
|
|
45
|
+
- **Tables** (`creditsSchema`, Postgres schema `credits`): `grant`, `entry`, `hold`. The one product table it references is the owner (`owner`, the account table). An account that has credits is **anonymised, never deleted**: it is an accounting record, like an invoice.
|
|
46
|
+
- `creditsLedgerContract` (`@krizaka/credits/testkit`) is the contract every store runs; `memoryCreditStore()` is for unit tests (it has no transaction, so `lock` does nothing: concurrency is proved on PostgreSQL).
|
|
47
|
+
|
|
48
|
+
## Adopting it (Yomizaka)
|
|
49
|
+
|
|
50
|
+
`audit_credits` becomes a purchased pot (`purchase` once per account for the balance it has, key `import-<accountId>`), the free audit a granted pot with `onExhausted: "fallback_paid"`, `reserveAudit` a `consume` (a `PAYWALL` is already Yomizaka's 402), `releaseAudit` and `refundFailedAudit` a `refund` of the consume key.
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import {
|
|
2
|
+
BUCKET,
|
|
3
|
+
CREDITS_CODE,
|
|
4
|
+
CreditsError,
|
|
5
|
+
ON_EXHAUSTED
|
|
6
|
+
} from "./chunk-WDHQ7QHY.js";
|
|
7
|
+
|
|
8
|
+
// src/rules.ts
|
|
9
|
+
import { isAfter } from "@krizaka/time";
|
|
10
|
+
var CREDITS_DEFAULTS = { timeZone: "America/Toronto", holdTtlSeconds: 900 };
|
|
11
|
+
var HOLD_TTL_BOUNDS = [30, 86400];
|
|
12
|
+
var alive = (s, now) => !s.closed && (s.grant.expiresAt === null || isAfter(s.grant.expiresAt, now));
|
|
13
|
+
var byExpiry = (a, b) => (a.grant.expiresAt?.valueOf() ?? Infinity) - (b.grant.expiresAt?.valueOf() ?? Infinity) || a.grant.createdAt.valueOf() - b.grant.createdAt.valueOf() || a.grant.id.localeCompare(b.grant.id);
|
|
14
|
+
function drawGranted(granted, need) {
|
|
15
|
+
const draws = [];
|
|
16
|
+
let left = need;
|
|
17
|
+
let capped = null;
|
|
18
|
+
for (const s of granted) {
|
|
19
|
+
if (left === 0) break;
|
|
20
|
+
const dayLeft = s.grant.capPerDay === null ? Infinity : Math.max(0, s.grant.capPerDay - s.usedToday);
|
|
21
|
+
const monthLeft = s.grant.capPerMonth === null ? Infinity : Math.max(0, s.grant.capPerMonth - s.usedThisMonth);
|
|
22
|
+
const take = Math.min(left, s.remaining, dayLeft, monthLeft);
|
|
23
|
+
if (take < Math.min(left, s.remaining)) capped ??= dayLeft <= monthLeft ? CREDITS_CODE.capDay : CREDITS_CODE.capMonth;
|
|
24
|
+
if (take > 0) {
|
|
25
|
+
draws.push({ grantId: s.grant.id, amount: take });
|
|
26
|
+
left -= take;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
return { draws, left, capped };
|
|
30
|
+
}
|
|
31
|
+
function drawPurchased(purchased, need) {
|
|
32
|
+
const draws = [];
|
|
33
|
+
let left = need;
|
|
34
|
+
const oldestFirst = [...purchased].sort((a, b) => a.grant.createdAt.valueOf() - b.grant.createdAt.valueOf() || a.grant.id.localeCompare(b.grant.id));
|
|
35
|
+
for (const s of oldestFirst) {
|
|
36
|
+
if (left === 0) break;
|
|
37
|
+
const take = Math.min(left, s.remaining);
|
|
38
|
+
draws.push({ grantId: s.grant.id, amount: take });
|
|
39
|
+
left -= take;
|
|
40
|
+
}
|
|
41
|
+
return { draws, left };
|
|
42
|
+
}
|
|
43
|
+
function planDraws(states, need, now) {
|
|
44
|
+
const live = states.filter((s) => alive(s, now));
|
|
45
|
+
const granted = live.filter((s) => s.grant.bucket === BUCKET.granted && s.remaining > 0).sort(byExpiry);
|
|
46
|
+
const first = drawGranted(granted, need);
|
|
47
|
+
if (first.left === 0) return { ok: true, draws: first.draws };
|
|
48
|
+
if (first.capped) return { ok: false, code: first.capped };
|
|
49
|
+
const taken = new Map(first.draws.map((d) => [d.grantId, d.amount]));
|
|
50
|
+
const stopped = live.some((s) => s.grant.bucket === BUCKET.granted && s.grant.onExhausted === ON_EXHAUSTED.stop && s.remaining - (taken.get(s.grant.id) ?? 0) <= 0);
|
|
51
|
+
if (stopped) return { ok: false, code: CREDITS_CODE.exhausted };
|
|
52
|
+
const rest = drawPurchased(live.filter((s) => s.grant.bucket === BUCKET.purchased && s.remaining > 0), first.left);
|
|
53
|
+
return rest.left === 0 ? { ok: true, draws: [...first.draws, ...rest.draws] } : { ok: false, code: CREDITS_CODE.paywall };
|
|
54
|
+
}
|
|
55
|
+
function skipFirst(draws, skip) {
|
|
56
|
+
let toSkip = skip;
|
|
57
|
+
const out = [];
|
|
58
|
+
for (const d of draws) {
|
|
59
|
+
const dropped = Math.min(toSkip, d.amount);
|
|
60
|
+
toSkip -= dropped;
|
|
61
|
+
if (d.amount > dropped) out.push({ grantId: d.grantId, amount: d.amount - dropped });
|
|
62
|
+
}
|
|
63
|
+
return out;
|
|
64
|
+
}
|
|
65
|
+
function checkAmount(n, what = "an amount") {
|
|
66
|
+
if (!Number.isSafeInteger(n) || n <= 0) throw new CreditsError(CREDITS_CODE.badAmount, `${what} of credits is a positive integer, got ${n}`);
|
|
67
|
+
return n;
|
|
68
|
+
}
|
|
69
|
+
var KEY = /^[\x21-\x7e]{1,150}$/;
|
|
70
|
+
function checkKey(key) {
|
|
71
|
+
if (!KEY.test(key) || key.includes(":")) throw new CreditsError(CREDITS_CODE.badKey, "An idempotency key is 1 to 150 printable characters, without spaces or a colon");
|
|
72
|
+
return key;
|
|
73
|
+
}
|
|
74
|
+
function checkSettings(s) {
|
|
75
|
+
try {
|
|
76
|
+
new Intl.DateTimeFormat("en", { timeZone: s.timeZone });
|
|
77
|
+
} catch {
|
|
78
|
+
throw new CreditsError(CREDITS_CODE.badSettings, `Not an IANA time zone: ${s.timeZone}`);
|
|
79
|
+
}
|
|
80
|
+
if (!Number.isSafeInteger(s.holdTtlSeconds) || s.holdTtlSeconds < HOLD_TTL_BOUNDS[0] || s.holdTtlSeconds > HOLD_TTL_BOUNDS[1]) {
|
|
81
|
+
throw new CreditsError(CREDITS_CODE.badSettings, `holdTtlSeconds is ${HOLD_TTL_BOUNDS[0]} to ${HOLD_TTL_BOUNDS[1]}`);
|
|
82
|
+
}
|
|
83
|
+
return s;
|
|
84
|
+
}
|
|
85
|
+
var MAX_SOURCE = 200;
|
|
86
|
+
function checkGrantedTerms(input, now) {
|
|
87
|
+
if (!(input.expiresAt instanceof Date) || Number.isNaN(input.expiresAt.valueOf()) || input.expiresAt <= now) throw new CreditsError(CREDITS_CODE.badGrant, "A granted pot lapses in the future");
|
|
88
|
+
for (const cap of [input.capPerDay, input.capPerMonth]) if (cap !== void 0 && cap !== null) checkAmount(cap, "a cap");
|
|
89
|
+
if (input.onExhausted !== ON_EXHAUSTED.stop && input.onExhausted !== ON_EXHAUSTED.fallbackPaid) throw new CreditsError(CREDITS_CODE.badGrant, "onExhausted is stop or fallback_paid");
|
|
90
|
+
}
|
|
91
|
+
function checkNewGrant(kind, input, now) {
|
|
92
|
+
checkAmount(input.amount, "a grant");
|
|
93
|
+
checkKey(input.idempotencyKey);
|
|
94
|
+
if (!input.accountId) throw new CreditsError(CREDITS_CODE.badGrant, "A grant has an account");
|
|
95
|
+
if (!input.source || input.source.length > MAX_SOURCE) throw new CreditsError(CREDITS_CODE.badGrant, `A source is 1 to ${MAX_SOURCE} characters`);
|
|
96
|
+
if (kind === "grant") checkGrantedTerms(input, now);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export {
|
|
100
|
+
CREDITS_DEFAULTS,
|
|
101
|
+
HOLD_TTL_BOUNDS,
|
|
102
|
+
planDraws,
|
|
103
|
+
skipFirst,
|
|
104
|
+
checkAmount,
|
|
105
|
+
checkKey,
|
|
106
|
+
checkSettings,
|
|
107
|
+
checkNewGrant
|
|
108
|
+
};
|
|
109
|
+
//# sourceMappingURL=chunk-34Y2HXOB.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/rules.ts"],"sourcesContent":["import { isAfter } from \"@krizaka/time\";\n\nimport { BUCKET, CREDITS_CODE, type CreditsCode, CreditsError, type CreditsSettings, type GrantState, ON_EXHAUSTED } from \"./port\";\n\n/** How much of one grant a consumption takes. */\nexport interface Draw {\n grantId: string;\n amount: number;\n}\n\nexport type Plan = { ok: true; draws: Draw[] } | { ok: false; code: CreditsCode };\n\n/** The defaults and bounds of the settings (the admin changes them without a redeploy). */\nexport const CREDITS_DEFAULTS: CreditsSettings = { timeZone: \"America/Toronto\", holdTtlSeconds: 900 };\n// @fixed: bounds on the lifetime of a hold, in seconds: 30 seconds to a day (a sanity range, not a business parameter)\nexport const HOLD_TTL_BOUNDS = [30, 86_400] as const;\n\nconst alive = (s: GrantState, now: Date) => !s.closed && (s.grant.expiresAt === null || isAfter(s.grant.expiresAt, now));\nconst byExpiry = (a: GrantState, b: GrantState) =>\n (a.grant.expiresAt?.valueOf() ?? Infinity) - (b.grant.expiresAt?.valueOf() ?? Infinity) || a.grant.createdAt.valueOf() - b.grant.createdAt.valueOf() || a.grant.id.localeCompare(b.grant.id);\n\n/** What the granted pots can give, each within its caps, and the first cap that held one back. */\nfunction drawGranted(granted: readonly GrantState[], need: number): { draws: Draw[]; left: number; capped: CreditsCode | null } {\n const draws: Draw[] = [];\n let left = need;\n let capped: CreditsCode | null = null;\n for (const s of granted) {\n if (left === 0) break;\n const dayLeft = s.grant.capPerDay === null ? Infinity : Math.max(0, s.grant.capPerDay - s.usedToday);\n const monthLeft = s.grant.capPerMonth === null ? Infinity : Math.max(0, s.grant.capPerMonth - s.usedThisMonth);\n const take = Math.min(left, s.remaining, dayLeft, monthLeft);\n if (take < Math.min(left, s.remaining)) capped ??= dayLeft <= monthLeft ? CREDITS_CODE.capDay : CREDITS_CODE.capMonth;\n if (take > 0) {\n draws.push({ grantId: s.grant.id, amount: take });\n left -= take;\n }\n }\n return { draws, left, capped };\n}\n\n/** What the purchased pots can give, the oldest first. */\nfunction drawPurchased(purchased: readonly GrantState[], need: number): { draws: Draw[]; left: number } {\n const draws: Draw[] = [];\n let left = need;\n const oldestFirst = [...purchased].sort((a, b) => a.grant.createdAt.valueOf() - b.grant.createdAt.valueOf() || a.grant.id.localeCompare(b.grant.id));\n for (const s of oldestFirst) {\n if (left === 0) break;\n const take = Math.min(left, s.remaining);\n draws.push({ grantId: s.grant.id, amount: take });\n left -= take;\n }\n return { draws, left };\n}\n\n/**\n * Plans where `need` credits come from, or says why they cannot. Pure: the same states give the same plan.\n *\n * Granted credits go first, the pot that lapses first first, each within its caps of the day and the month. If the granted pots cannot\n * give it all: a pot held back by a cap answers `CREDITS_CAP_DAY` / `CREDITS_CAP_MONTH` (the cap is a fair-use limit: purchased\n * credits do not bypass it); else a `stop` pot that is empty answers `CREDITS_EXHAUSTED`; else the purchased credits give the rest, and\n * when they cannot, `PAYWALL`. Nothing is partial: the plan covers the whole amount or refuses.\n * @param states every grant of the account with what is left (`CreditStore.grantStates`)\n * @param need credits wanted, a positive integer\n * @param now the injected clock's instant\n */\nexport function planDraws(states: readonly GrantState[], need: number, now: Date): Plan {\n const live = states.filter((s) => alive(s, now));\n const granted = live.filter((s) => s.grant.bucket === BUCKET.granted && s.remaining > 0).sort(byExpiry);\n const first = drawGranted(granted, need);\n if (first.left === 0) return { ok: true, draws: first.draws };\n if (first.capped) return { ok: false, code: first.capped };\n const taken = new Map(first.draws.map((d) => [d.grantId, d.amount]));\n const stopped = live.some((s) => s.grant.bucket === BUCKET.granted && s.grant.onExhausted === ON_EXHAUSTED.stop && s.remaining - (taken.get(s.grant.id) ?? 0) <= 0);\n if (stopped) return { ok: false, code: CREDITS_CODE.exhausted };\n const rest = drawPurchased(live.filter((s) => s.grant.bucket === BUCKET.purchased && s.remaining > 0), first.left);\n return rest.left === 0 ? { ok: true, draws: [...first.draws, ...rest.draws] } : { ok: false, code: CREDITS_CODE.paywall };\n}\n\n/** Drops the first `skip` credits of a plan (the ones already held back by active holds), keeping the order. */\nexport function skipFirst(draws: readonly Draw[], skip: number): Draw[] {\n let toSkip = skip;\n const out: Draw[] = [];\n for (const d of draws) {\n const dropped = Math.min(toSkip, d.amount);\n toSkip -= dropped;\n if (d.amount > dropped) out.push({ grantId: d.grantId, amount: d.amount - dropped });\n }\n return out;\n}\n\n/** Whether `n` is an amount of credits: a positive safe integer. @throws CreditsError `CREDITS_BAD_AMOUNT` */\nexport function checkAmount(n: number, what = \"an amount\"): number {\n if (!Number.isSafeInteger(n) || n <= 0) throw new CreditsError(CREDITS_CODE.badAmount, `${what} of credits is a positive integer, got ${n}`);\n return n;\n}\n\nconst KEY = /^[\\x21-\\x7e]{1,150}$/;\n/** An idempotency key: printable ASCII without spaces, 1 to 150 characters. @throws CreditsError `CREDITS_BAD_KEY` */\nexport function checkKey(key: string): string {\n if (!KEY.test(key) || key.includes(\":\")) throw new CreditsError(CREDITS_CODE.badKey, \"An idempotency key is 1 to 150 printable characters, without spaces or a colon\");\n return key;\n}\n\n/** Checks the settings the service was given. @throws CreditsError `CREDITS_BAD_SETTINGS` */\nexport function checkSettings(s: CreditsSettings): CreditsSettings {\n try {\n new Intl.DateTimeFormat(\"en\", { timeZone: s.timeZone });\n } catch {\n throw new CreditsError(CREDITS_CODE.badSettings, `Not an IANA time zone: ${s.timeZone}`);\n }\n if (!Number.isSafeInteger(s.holdTtlSeconds) || s.holdTtlSeconds < HOLD_TTL_BOUNDS[0] || s.holdTtlSeconds > HOLD_TTL_BOUNDS[1]) {\n throw new CreditsError(CREDITS_CODE.badSettings, `holdTtlSeconds is ${HOLD_TTL_BOUNDS[0]} to ${HOLD_TTL_BOUNDS[1]}`);\n }\n return s;\n}\n\n// @fixed: the longest source a line of the ledger carries (its CHECK)\nconst MAX_SOURCE = 200;\n\n/** The shape of what `grant` and `purchase` take, for the checks. */\ninterface NewGrantInput {\n accountId: string;\n amount: number;\n source: string;\n idempotencyKey: string;\n expiresAt?: Date;\n capPerDay?: number | null;\n capPerMonth?: number | null;\n onExhausted?: string;\n}\n\n/** The checks of a granted pot's own terms: it lapses in the future, its caps are whole numbers, it says what happens when it runs out. */\nfunction checkGrantedTerms(input: NewGrantInput, now: Date): void {\n if (!(input.expiresAt instanceof Date) || Number.isNaN(input.expiresAt.valueOf()) || input.expiresAt <= now) throw new CreditsError(CREDITS_CODE.badGrant, \"A granted pot lapses in the future\");\n for (const cap of [input.capPerDay, input.capPerMonth]) if (cap !== undefined && cap !== null) checkAmount(cap, \"a cap\");\n if (input.onExhausted !== ON_EXHAUSTED.stop && input.onExhausted !== ON_EXHAUSTED.fallbackPaid) throw new CreditsError(CREDITS_CODE.badGrant, \"onExhausted is stop or fallback_paid\");\n}\n\n/**\n * Checks what `grant` or `purchase` was given, before any store call.\n * @throws CreditsError `CREDITS_BAD_AMOUNT`, `CREDITS_BAD_KEY` or `CREDITS_BAD_GRANT`\n */\nexport function checkNewGrant(kind: \"grant\" | \"purchase\", input: NewGrantInput, now: Date): void {\n checkAmount(input.amount, \"a grant\");\n checkKey(input.idempotencyKey);\n if (!input.accountId) throw new CreditsError(CREDITS_CODE.badGrant, \"A grant has an account\");\n if (!input.source || input.source.length > MAX_SOURCE) throw new CreditsError(CREDITS_CODE.badGrant, `A source is 1 to ${MAX_SOURCE} characters`);\n if (kind === \"grant\") checkGrantedTerms(input, now);\n}\n"],"mappings":";;;;;;;;AAAA,SAAS,eAAe;AAajB,IAAM,mBAAoC,EAAE,UAAU,mBAAmB,gBAAgB,IAAI;AAE7F,IAAM,kBAAkB,CAAC,IAAI,KAAM;AAE1C,IAAM,QAAQ,CAAC,GAAe,QAAc,CAAC,EAAE,WAAW,EAAE,MAAM,cAAc,QAAQ,QAAQ,EAAE,MAAM,WAAW,GAAG;AACtH,IAAM,WAAW,CAAC,GAAe,OAC9B,EAAE,MAAM,WAAW,QAAQ,KAAK,aAAa,EAAE,MAAM,WAAW,QAAQ,KAAK,aAAa,EAAE,MAAM,UAAU,QAAQ,IAAI,EAAE,MAAM,UAAU,QAAQ,KAAK,EAAE,MAAM,GAAG,cAA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S,MAAM,cAAc;AAC7B,MAAI,CAAC,MAAM,UAAW,OAAM,IAAI,aAAa,aAAa,UAAU,wBAAwB;AAC5F,MAAI,CAAC,MAAM,UAAU,MAAM,OAAO,SAAS,WAAY,OAAM,IAAI,aAAa,aAAa,UAAU,oBAAoB,UAAU,aAAa;AAChJ,MAAI,SAAS,QAAS,mBAAkB,OAAO,GAAG;AACpD;","names":[]}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
// src/port.ts
|
|
2
|
+
var BUCKET = { granted: "granted", purchased: "purchased" };
|
|
3
|
+
var ON_EXHAUSTED = { stop: "stop", fallbackPaid: "fallback_paid" };
|
|
4
|
+
var ENTRY_TYPE = { grant: "GRANT", purchase: "PURCHASE", debit: "DEBIT", refund: "REFUND", expiry: "EXPIRY", adjustment: "ADJUSTMENT" };
|
|
5
|
+
var HOLD_STATUS = { active: "active", settled: "settled", released: "released" };
|
|
6
|
+
var CREDITS_CODE = {
|
|
7
|
+
capDay: "CREDITS_CAP_DAY",
|
|
8
|
+
capMonth: "CREDITS_CAP_MONTH",
|
|
9
|
+
exhausted: "CREDITS_EXHAUSTED",
|
|
10
|
+
paywall: "PAYWALL",
|
|
11
|
+
badAmount: "CREDITS_BAD_AMOUNT",
|
|
12
|
+
badGrant: "CREDITS_BAD_GRANT",
|
|
13
|
+
badKey: "CREDITS_BAD_KEY",
|
|
14
|
+
badSettings: "CREDITS_BAD_SETTINGS",
|
|
15
|
+
unknownGrant: "CREDITS_UNKNOWN_GRANT",
|
|
16
|
+
unknownHold: "CREDITS_UNKNOWN_HOLD",
|
|
17
|
+
holdClosed: "CREDITS_HOLD_CLOSED",
|
|
18
|
+
keyReused: "CREDITS_KEY_REUSED",
|
|
19
|
+
nothingToRefund: "CREDITS_NOTHING_TO_REFUND"
|
|
20
|
+
};
|
|
21
|
+
var CREDITS_STATUS = {
|
|
22
|
+
CREDITS_CAP_DAY: 429,
|
|
23
|
+
CREDITS_CAP_MONTH: 429,
|
|
24
|
+
CREDITS_EXHAUSTED: 402,
|
|
25
|
+
PAYWALL: 402,
|
|
26
|
+
CREDITS_BAD_AMOUNT: 400,
|
|
27
|
+
CREDITS_BAD_GRANT: 400,
|
|
28
|
+
CREDITS_BAD_KEY: 400,
|
|
29
|
+
CREDITS_BAD_SETTINGS: 500,
|
|
30
|
+
CREDITS_UNKNOWN_GRANT: 404,
|
|
31
|
+
CREDITS_UNKNOWN_HOLD: 404,
|
|
32
|
+
CREDITS_HOLD_CLOSED: 409,
|
|
33
|
+
CREDITS_KEY_REUSED: 409,
|
|
34
|
+
CREDITS_NOTHING_TO_REFUND: 404
|
|
35
|
+
};
|
|
36
|
+
var CreditsError = class extends Error {
|
|
37
|
+
constructor(code, message) {
|
|
38
|
+
super(message);
|
|
39
|
+
this.code = code;
|
|
40
|
+
this.name = "CreditsError";
|
|
41
|
+
this.status = CREDITS_STATUS[code];
|
|
42
|
+
}
|
|
43
|
+
code;
|
|
44
|
+
status;
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
export {
|
|
48
|
+
BUCKET,
|
|
49
|
+
ON_EXHAUSTED,
|
|
50
|
+
ENTRY_TYPE,
|
|
51
|
+
HOLD_STATUS,
|
|
52
|
+
CREDITS_CODE,
|
|
53
|
+
CREDITS_STATUS,
|
|
54
|
+
CreditsError
|
|
55
|
+
};
|
|
56
|
+
//# sourceMappingURL=chunk-WDHQ7QHY.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/port.ts"],"sourcesContent":["/**\n * The ports of « credits »: ONE ledger of usage credits per account. Generic: no product import, no database client (a `Query`\n * comes in), no wall clock (a `Clock` comes in). Credits are integers (never floats). The ledger is append-only and the balance is\n * DERIVED from it: nothing stores a balance that could drift.\n *\n * Two kinds of credit live in it. A GRANT is free usage (a coupon, a monthly allowance, a demo): it expires, may be capped per day or\n * month, and says what happens when it runs out (`stop`, or `fallback_paid`: go on with what the person bought). A PURCHASE is paid\n * usage: it does not expire and is never capped.\n */\nexport type { Clock, Query } from \"@krizaka/db\";\n\nexport const BUCKET = { granted: \"granted\", purchased: \"purchased\" } as const;\nexport type Bucket = (typeof BUCKET)[keyof typeof BUCKET];\n\n/** What happens when a grant has run out: refuse (`stop`), or move on to purchased credits (`fallback_paid`). */\nexport const ON_EXHAUSTED = { stop: \"stop\", fallbackPaid: \"fallback_paid\" } as const;\nexport type OnExhausted = (typeof ON_EXHAUSTED)[keyof typeof ON_EXHAUSTED];\n\n/** The kinds of line of the ledger. Amounts are signed: credits in are positive, credits out negative. */\nexport const ENTRY_TYPE = { grant: \"GRANT\", purchase: \"PURCHASE\", debit: \"DEBIT\", refund: \"REFUND\", expiry: \"EXPIRY\", adjustment: \"ADJUSTMENT\" } as const;\nexport type EntryType = (typeof ENTRY_TYPE)[keyof typeof ENTRY_TYPE];\n\nexport const HOLD_STATUS = { active: \"active\", settled: \"settled\", released: \"released\" } as const;\nexport type HoldStatus = (typeof HOLD_STATUS)[keyof typeof HOLD_STATUS];\n\n/** A pot of credits. Immutable: what is left of it is derived from the ledger. */\nexport interface Grant {\n id: string;\n accountId: string;\n bucket: Bucket;\n /** What it started with. */\n amount: number;\n /** The most it gives in a calendar day (in the settings' time zone), or none. Granted only. */\n capPerDay: number | null;\n /** The most it gives in a calendar month, or none. Granted only. */\n capPerMonth: number | null;\n /** When it lapses. Required for a granted pot, none for a purchased one. */\n expiresAt: Date | null;\n onExhausted: OnExhausted;\n /** Where it comes from (`coupon:<redemptionId>`, `plan:monthly`, `purchase:<paymentRef>`). */\n source: string;\n createdAt: Date;\n}\n\n/** One line of the ledger. */\nexport interface Entry {\n id: string;\n accountId: string;\n grantId: string | null;\n type: EntryType;\n /** Signed. */\n amount: number;\n reason: string;\n /** The caller's key for the whole operation: a replay finds its lines. */\n operation: string;\n /** Unique: `<operation>:<n>`. */\n idempotencyKey: string;\n /** For a REFUND: the operation it gives back. */\n reverses: string | null;\n holdId: string | null;\n at: Date;\n}\n\nexport interface Hold {\n id: string;\n accountId: string;\n amount: number;\n expiresAt: Date;\n status: HoldStatus;\n /** What it settled for, when settled. */\n settledAmount: number | null;\n createdAt: Date;\n closedAt: Date | null;\n operation: string;\n}\n\n/** A grant as the planner sees it: what is left, what it gave today and this month, and whether it was closed by an expiry line. */\nexport interface GrantState {\n grant: Grant;\n remaining: number;\n usedToday: number;\n usedThisMonth: number;\n /** An EXPIRY line closed it (revoked, or swept after its date). */\n closed: boolean;\n}\n\n/** The calendar the caps are counted in: the zone, and the local day and month of « now » in it (`2026-10-26`, `2026-10`). */\nexport interface Calendar {\n timeZone: string;\n day: string;\n month: string;\n}\n\n/** Where the ledger lives. Every adapter runs `creditStoreContract` (`@krizaka/credits/testkit`). Times come from the caller. */\nexport interface CreditStore {\n /** Serialises the writers of one account until the transaction ends (an advisory lock). Call it before reading to decide. */\n lock(accountId: string): Promise<void>;\n insertGrant(grant: Grant): Promise<void>;\n grantById(grantId: string): Promise<Grant | null>;\n /** The account's grants, with what is left and what each gave in the calendar's day and month. Includes lapsed and closed ones. */\n grantStates(accountId: string, calendar: Calendar): Promise<GrantState[]>;\n /** Writes lines. A duplicate `idempotencyKey` is a bug of the caller (it checked `entriesOf` first, under the lock) and throws. */\n insertEntries(entries: Entry[]): Promise<void>;\n /** The lines of one operation, in order. */\n entriesOf(operation: string): Promise<Entry[]>;\n /** The lines of the account, newest first. */\n history(accountId: string, options: { limit: number; before?: Date }): Promise<Entry[]>;\n insertHold(hold: Hold): Promise<void>;\n holdById(holdId: string): Promise<Hold | null>;\n holdByOperation(operation: string): Promise<Hold | null>;\n /** What the account's active holds that have not expired at `now` keep back, except `exceptHoldId`. */\n heldAmount(accountId: string, now: Date, exceptHoldId?: string): Promise<number>;\n closeHold(holdId: string, status: typeof HOLD_STATUS.settled | typeof HOLD_STATUS.released, settledAmount: number | null, at: Date): Promise<void>;\n /** Granted pots past their date that still hold credits and no EXPIRY line, oldest first. */\n lapsedWithCredits(now: Date, limit: number): Promise<{ grantId: string; accountId: string }[]>;\n}\n\n/** The knobs of the ledger, read from the admin's settings (`@krizaka/credits/settings`). */\nexport interface CreditsSettings {\n /** The IANA zone that days and months are counted in. */\n timeZone: string;\n /** Seconds a hold keeps credits back when the caller names no lifetime. */\n holdTtlSeconds: number;\n}\n\n/** Stable codes of the refusals of this package. */\nexport const CREDITS_CODE = {\n capDay: \"CREDITS_CAP_DAY\",\n capMonth: \"CREDITS_CAP_MONTH\",\n exhausted: \"CREDITS_EXHAUSTED\",\n paywall: \"PAYWALL\",\n badAmount: \"CREDITS_BAD_AMOUNT\",\n badGrant: \"CREDITS_BAD_GRANT\",\n badKey: \"CREDITS_BAD_KEY\",\n badSettings: \"CREDITS_BAD_SETTINGS\",\n unknownGrant: \"CREDITS_UNKNOWN_GRANT\",\n unknownHold: \"CREDITS_UNKNOWN_HOLD\",\n holdClosed: \"CREDITS_HOLD_CLOSED\",\n keyReused: \"CREDITS_KEY_REUSED\",\n nothingToRefund: \"CREDITS_NOTHING_TO_REFUND\",\n} as const;\nexport type CreditsCode = (typeof CREDITS_CODE)[keyof typeof CREDITS_CODE];\n\n/** The HTTP status a route may answer for each refusal. */\nexport const CREDITS_STATUS: Record<CreditsCode, number> = {\n CREDITS_CAP_DAY: 429,\n CREDITS_CAP_MONTH: 429,\n CREDITS_EXHAUSTED: 402,\n PAYWALL: 402,\n CREDITS_BAD_AMOUNT: 400,\n CREDITS_BAD_GRANT: 400,\n CREDITS_BAD_KEY: 400,\n CREDITS_BAD_SETTINGS: 500,\n CREDITS_UNKNOWN_GRANT: 404,\n CREDITS_UNKNOWN_HOLD: 404,\n CREDITS_HOLD_CLOSED: 409,\n CREDITS_KEY_REUSED: 409,\n CREDITS_NOTHING_TO_REFUND: 404,\n};\n\n/** A refusal: a stable `code`, the HTTP `status` a route may answer, and a message. */\nexport class CreditsError extends Error {\n readonly status: number;\n constructor(\n readonly code: CreditsCode,\n message: string,\n ) {\n super(message);\n this.name = \"CreditsError\";\n this.status = CREDITS_STATUS[code];\n }\n}\n"],"mappings":";AAWO,IAAM,SAAS,EAAE,SAAS,WAAW,WAAW,YAAY;AAI5D,IAAM,eAAe,EAAE,MAAM,QAAQ,cAAc,gBAAgB;AAInE,IAAM,aAAa,EAAE,OAAO,SAAS,UAAU,YAAY,OAAO,SAAS,QAAQ,UAAU,QAAQ,UAAU,YAAY,aAAa;AAGxI,IAAM,cAAc,EAAE,QAAQ,UAAU,SAAS,WAAW,UAAU,WAAW;AAwGjF,IAAM,eAAe;AAAA,EAC1B,QAAQ;AAAA,EACR,UAAU;AAAA,EACV,WAAW;AAAA,EACX,SAAS;AAAA,EACT,WAAW;AAAA,EACX,UAAU;AAAA,EACV,QAAQ;AAAA,EACR,aAAa;AAAA,EACb,cAAc;AAAA,EACd,aAAa;AAAA,EACb,YAAY;AAAA,EACZ,WAAW;AAAA,EACX,iBAAiB;AACnB;AAIO,IAAM,iBAA8C;AAAA,EACzD,iBAAiB;AAAA,EACjB,mBAAmB;AAAA,EACnB,mBAAmB;AAAA,EACnB,SAAS;AAAA,EACT,oBAAoB;AAAA,EACpB,mBAAmB;AAAA,EACnB,iBAAiB;AAAA,EACjB,sBAAsB;AAAA,EACtB,uBAAuB;AAAA,EACvB,sBAAsB;AAAA,EACtB,qBAAqB;AAAA,EACrB,oBAAoB;AAAA,EACpB,2BAA2B;AAC7B;AAGO,IAAM,eAAN,cAA2B,MAAM;AAAA,EAEtC,YACW,MACT,SACA;AACA,UAAM,OAAO;AAHJ;AAIT,SAAK,OAAO;AACZ,SAAK,SAAS,eAAe,IAAI;AAAA,EACnC;AAAA,EANW;AAAA,EAFF;AASX;","names":[]}
|