mbase-sdk 0.0.2 → 0.0.4
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/README.md +58 -20
- package/dist/index.cjs +103 -33
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +108 -25
- package/dist/index.d.ts +108 -25
- package/dist/index.js +102 -33
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -19,13 +19,17 @@ import { Meterbase } from "@meterbase/sdk"
|
|
|
19
19
|
|
|
20
20
|
const meterbase = new Meterbase({ apiKey: process.env.METERBASE_API_KEY! })
|
|
21
21
|
|
|
22
|
-
const { allowed } = await meterbase.check({
|
|
22
|
+
const { allowed, reason, rate_limits } = await meterbase.check({
|
|
23
23
|
customer_id: "acct_1", // the tenant's own id, not ours
|
|
24
24
|
meter_id: "ai_tokens", // the meter's key, not ours
|
|
25
25
|
quantity: 50_000, // what you are about to spend; defaults to 1
|
|
26
26
|
})
|
|
27
27
|
|
|
28
|
-
if (!allowed) throw new Error(
|
|
28
|
+
if (!allowed) throw new Error(`Refused: ${reason}`)
|
|
29
|
+
|
|
30
|
+
// Allowed, and still worth reading: every window comes back on every call.
|
|
31
|
+
const tight = rate_limits.find((w) => w.remaining < w.max / 10)
|
|
32
|
+
if (tight) console.warn(`Slowing down until ${tight.resets_at}`)
|
|
29
33
|
|
|
30
34
|
const completion = await generate(prompt)
|
|
31
35
|
|
|
@@ -48,6 +52,16 @@ capacity is not a number. It is one figure and not a breakdown: `check` answers
|
|
|
48
52
|
from a single cached integer, and itemising where the capacity came from would
|
|
49
53
|
cost it that. For the per-grant detail, read a customer's allowances.
|
|
50
54
|
|
|
55
|
+
A check answers **two gates**, and `allowed` needs both: the capacity has to
|
|
56
|
+
cover the quantity, and every rate limit in force — _at most so much of this
|
|
57
|
+
meter per minute, hour or day_ — has to admit it. `reason` names the one that
|
|
58
|
+
said no, and is absent when the answer is yes. `rate_limits` reports every
|
|
59
|
+
window whether or not it refused, so a caller can ease off as its headroom
|
|
60
|
+
closes instead of finding the ceiling by hitting it; it is `[]` when no rule
|
|
61
|
+
applies. A limit is protective and not commercial, so it is never folded into
|
|
62
|
+
`available`: a customer well inside their plan can still be limited, and one on
|
|
63
|
+
`no_cap` is precisely the customer a runaway loop costs most.
|
|
64
|
+
|
|
51
65
|
### Recording usage
|
|
52
66
|
|
|
53
67
|
`track` counts work that already happened — the tokens were spent, the image
|
|
@@ -60,7 +74,7 @@ const { event } = await meterbase.track({
|
|
|
60
74
|
customer_id: "acct_1",
|
|
61
75
|
meter_id: "ai_tokens",
|
|
62
76
|
quantity: 250_000,
|
|
63
|
-
idempotency_key: "
|
|
77
|
+
idempotency_key: "0199e0c0-8f3a-7c21-9d44-6b2e91a0f5c3", // a UUIDv7; generated when you omit it
|
|
64
78
|
})
|
|
65
79
|
|
|
66
80
|
event.replayed // false the first time, true for a retry of the same call
|
|
@@ -75,16 +89,37 @@ bill drawn from a period is never moved by a report that arrives after it.
|
|
|
75
89
|
|
|
76
90
|
#### Idempotency
|
|
77
91
|
|
|
78
|
-
`
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
The
|
|
86
|
-
|
|
87
|
-
|
|
92
|
+
`idempotency_key` identifies one logical event, and **is** that event's id.
|
|
93
|
+
It has to be a **UUIDv7**, whose first 48 bits are the millisecond it was
|
|
94
|
+
minted. That timestamp is not decoration: the engine admits a key only while
|
|
95
|
+
it is within **one hour** of the engine's clock, and keeps the claim behind it
|
|
96
|
+
until exactly that hour is up. A retry is therefore recognised for as long as
|
|
97
|
+
it is accepted at all.
|
|
98
|
+
|
|
99
|
+
| The call sends | The engine answers |
|
|
100
|
+
| ------------------------------------- | ------------------------------------------------------ |
|
|
101
|
+
| a fresh key | the recorded event, `replayed: false` |
|
|
102
|
+
| a key it has already seen | that event with `replayed: true`, writing nothing |
|
|
103
|
+
| a key more than an hour old, or ahead | `422 too_late`, writing nothing |
|
|
104
|
+
| anything that is not a UUIDv7 | `422 invalid_idempotency_key`, writing nothing |
|
|
105
|
+
|
|
106
|
+
A key it has already seen replays **whatever the rest of the body says**:
|
|
107
|
+
there is one claim behind the key and nothing to compare a retry against, so
|
|
108
|
+
a changed quantity is a replay rather than an error. The upside is that a
|
|
109
|
+
replay costs one lookup and stores nothing.
|
|
110
|
+
|
|
111
|
+
**The hour is a retry budget.** Retry inside it and your call is recognised.
|
|
112
|
+
Past it, `too_late` — and do not then resend under a fresh key, because the
|
|
113
|
+
original may have been recorded. Nothing is written on either refusal: both
|
|
114
|
+
are checked before the engine touches anything.
|
|
115
|
+
|
|
116
|
+
**Clocks matter now.** The key is minted here, from this machine's clock, so
|
|
117
|
+
a device running more than an hour off would have every call refused. When
|
|
118
|
+
this SDK mints the key it handles that itself: `too_late` carries the engine's
|
|
119
|
+
`server_time`, the client corrects its offset and retries once, and you never
|
|
120
|
+
see the error. When **you** supply the key, you get `TooLateError` with
|
|
121
|
+
`serverTime` on it, because only you can know whether that key names work that
|
|
122
|
+
was already recorded.
|
|
88
123
|
|
|
89
124
|
**The SDK generates a key when you omit one, and reuses it across that call's
|
|
90
125
|
retries** — including its own, since `track` is the one `POST` it will replay.
|
|
@@ -368,9 +403,10 @@ try {
|
|
|
368
403
|
| `PermissionDeniedError` | 403 — the key may not use this route |
|
|
369
404
|
| `NotFoundError` | 404 |
|
|
370
405
|
| `ConflictError` | 409 — a key or external id is taken |
|
|
371
|
-
| `IdempotencyConflictError` | 409 — a `ConflictError` naming the event that key already recorded, on `existingEventId` |
|
|
372
406
|
| `InvalidRequestError` | 422 — a field failed validation |
|
|
373
407
|
| `CycleChangeRequiresResetError` | 422 — an `InvalidRequestError`: the two plans' cycles differ, so use `restart` |
|
|
408
|
+
| `InvalidIdempotencyKeyError` | 422 — an `InvalidRequestError`: the key was not a UUIDv7 |
|
|
409
|
+
| `TooLateError` | 422 — an `InvalidRequestError`: the key is over an hour from the engine's clock, which it carries on `serverTime`. Nothing was recorded |
|
|
374
410
|
| `RateLimitError` | 429 |
|
|
375
411
|
| `ServerError` | 5xx |
|
|
376
412
|
| `ConnectionError` / `TimeoutError` | the request never got an answer |
|
|
@@ -405,7 +441,8 @@ because a retried create could produce a second row.
|
|
|
405
441
|
SDK fixes that key **before** the retry loop starts: every attempt of one call
|
|
406
442
|
names the same logical event, so the engine replays it instead of counting the
|
|
407
443
|
work twice. If you retry `track` yourself, pass your own `idempotency_key` and
|
|
408
|
-
keep it the same across attempts for exactly that reason
|
|
444
|
+
keep it the same across attempts for exactly that reason — and do it inside
|
|
445
|
+
the hour the engine holds that key for.
|
|
409
446
|
|
|
410
447
|
## Types
|
|
411
448
|
|
|
@@ -481,11 +518,12 @@ It asserts the whole lifecycle of a customer, a meter and a plan; that a plan's
|
|
|
481
518
|
allowances become real entitlement a `check` can see, with the recurring cap
|
|
482
519
|
and the minted bonus summed into `available`; that tracked usage takes exactly
|
|
483
520
|
that much away, that a replay takes nothing, and that a reused key naming a
|
|
484
|
-
different event is refused; that a
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
521
|
+
different event is refused; that a rate limit set on a meter comes back on
|
|
522
|
+
every `check` as a live window, and refuses with the allowance untouched; that
|
|
523
|
+
a scheduled plan change is dated ahead and reads as `pending`, that cancelling
|
|
524
|
+
it supersedes it, that a `restart` re-anchors the customer, and that two plans
|
|
525
|
+
on different cycles refuse a scheduled change; that soft deletes and archiving
|
|
526
|
+
behave as documented; that duplicates really answer
|
|
489
527
|
`409 customer_external_id_taken` / `409 meter_key_taken`; and — via
|
|
490
528
|
`Record<keyof T, true>` field maps — that the engine's fields still match the
|
|
491
529
|
SDK's types exactly, in both directions.
|
package/dist/index.cjs
CHANGED
|
@@ -29,17 +29,18 @@ var NotFoundError = class extends APIError {
|
|
|
29
29
|
};
|
|
30
30
|
var ConflictError = class extends APIError {
|
|
31
31
|
};
|
|
32
|
-
var
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
32
|
+
var InvalidRequestError = class extends APIError {
|
|
33
|
+
};
|
|
34
|
+
var InvalidIdempotencyKeyError = class extends InvalidRequestError {
|
|
35
|
+
};
|
|
36
|
+
var TooLateError = class extends InvalidRequestError {
|
|
37
|
+
/** The engine's clock when it refused. */
|
|
38
|
+
serverTime;
|
|
36
39
|
constructor(args) {
|
|
37
40
|
super(args);
|
|
38
|
-
this.
|
|
41
|
+
this.serverTime = serverTime(args.body);
|
|
39
42
|
}
|
|
40
43
|
};
|
|
41
|
-
var InvalidRequestError = class extends APIError {
|
|
42
|
-
};
|
|
43
44
|
var CycleChangeRequiresResetError = class extends InvalidRequestError {
|
|
44
45
|
};
|
|
45
46
|
var RateLimitError = class extends APIError {
|
|
@@ -65,21 +66,32 @@ function errorFromResponse(args) {
|
|
|
65
66
|
case 404:
|
|
66
67
|
return new NotFoundError(args);
|
|
67
68
|
case 409:
|
|
68
|
-
return
|
|
69
|
+
return new ConflictError(args);
|
|
69
70
|
case 422:
|
|
70
|
-
|
|
71
|
+
switch (args.code) {
|
|
72
|
+
case "cycle_change_requires_reset":
|
|
73
|
+
return new CycleChangeRequiresResetError(args);
|
|
74
|
+
case "invalid_idempotency_key":
|
|
75
|
+
return new InvalidIdempotencyKeyError(args);
|
|
76
|
+
case "too_late":
|
|
77
|
+
return new TooLateError(args);
|
|
78
|
+
default:
|
|
79
|
+
return new InvalidRequestError(args);
|
|
80
|
+
}
|
|
71
81
|
case 429:
|
|
72
82
|
return new RateLimitError(args);
|
|
73
83
|
default:
|
|
74
84
|
return args.status >= 500 ? new ServerError(args) : new APIError(args);
|
|
75
85
|
}
|
|
76
86
|
}
|
|
77
|
-
function
|
|
87
|
+
function serverTime(body) {
|
|
78
88
|
if (typeof body !== "object" || body === null) return void 0;
|
|
79
89
|
const error = body.error;
|
|
80
90
|
if (typeof error !== "object" || error === null) return void 0;
|
|
81
|
-
const
|
|
82
|
-
|
|
91
|
+
const at = error.server_time;
|
|
92
|
+
if (typeof at !== "string") return void 0;
|
|
93
|
+
const parsed = new Date(at);
|
|
94
|
+
return Number.isNaN(parsed.getTime()) ? void 0 : parsed;
|
|
83
95
|
}
|
|
84
96
|
|
|
85
97
|
// src/client.ts
|
|
@@ -93,6 +105,21 @@ var Client = class {
|
|
|
93
105
|
#timeout;
|
|
94
106
|
#maxRetries;
|
|
95
107
|
#fetch;
|
|
108
|
+
/**
|
|
109
|
+
* How far the engine's clock is ahead of this machine's, in milliseconds.
|
|
110
|
+
* Idempotency keys are minted here and the engine refuses one dated more
|
|
111
|
+
* than an hour from its own clock, so without this a device with a wrong
|
|
112
|
+
* clock would fail every call forever.
|
|
113
|
+
*/
|
|
114
|
+
#clockOffset = 0;
|
|
115
|
+
/** The engine's clock, as well as this client knows it. */
|
|
116
|
+
now() {
|
|
117
|
+
return Date.now() + this.#clockOffset;
|
|
118
|
+
}
|
|
119
|
+
/** Off by up to one round trip, which a window in hours does not notice. */
|
|
120
|
+
observeServerTime(at) {
|
|
121
|
+
this.#clockOffset = at.getTime() - Date.now();
|
|
122
|
+
}
|
|
96
123
|
constructor(options) {
|
|
97
124
|
if (!options.apiKey) {
|
|
98
125
|
throw new MeterbaseError(
|
|
@@ -637,6 +664,12 @@ var Meterbase = class {
|
|
|
637
664
|
*
|
|
638
665
|
* This is the gate, and the only call that ever refuses. Run it before the
|
|
639
666
|
* work; record the work with `track` afterwards.
|
|
667
|
+
*
|
|
668
|
+
* Two gates answer it, and `allowed` needs both: the customer's capacity has
|
|
669
|
+
* to cover the quantity, and every rate-limit window in force has to admit
|
|
670
|
+
* it. `reason` names the one that said no. `rate_limits` reports each window
|
|
671
|
+
* whether or not it refused, so a caller can ease off as its headroom closes
|
|
672
|
+
* instead of discovering the ceiling by hitting it.
|
|
640
673
|
*/
|
|
641
674
|
check(params, options) {
|
|
642
675
|
return this.#client.request({
|
|
@@ -652,25 +685,42 @@ var Meterbase = class {
|
|
|
652
685
|
* customer's capacity is recorded, drives `available` to 0, and the next
|
|
653
686
|
* `check` says no. The answer is a receipt, not a verdict.
|
|
654
687
|
*
|
|
655
|
-
* `idempotency_key` is generated when omitted, so retrying this
|
|
656
|
-
* SDK's own retries included — replays the original rather than
|
|
657
|
-
* the same work twice.
|
|
688
|
+
* `idempotency_key` is a UUIDv7, generated when omitted, so retrying this
|
|
689
|
+
* call — the SDK's own retries included — replays the original rather than
|
|
690
|
+
* counting the same work twice. The engine keeps that claim for an hour,
|
|
691
|
+
* which is how long a retry stays recognisable.
|
|
658
692
|
*/
|
|
659
693
|
// `async` so that generating the key cannot throw synchronously out of a
|
|
660
694
|
// method that otherwise only ever rejects: one call, one way to fail.
|
|
661
695
|
async track(params, options) {
|
|
662
|
-
|
|
696
|
+
const send = (key2) => this.#client.request({
|
|
663
697
|
...options,
|
|
664
698
|
method: "POST",
|
|
665
699
|
path: "/v1/usage/track",
|
|
666
|
-
// Fixed
|
|
667
|
-
//
|
|
668
|
-
body: {
|
|
669
|
-
...params,
|
|
670
|
-
idempotency_key: params.idempotency_key ?? idempotencyKey()
|
|
671
|
-
},
|
|
700
|
+
// Fixed before the retry loop is entered: every attempt of this call
|
|
701
|
+
// carries the same key, which is what makes replaying it safe.
|
|
702
|
+
body: { ...params, idempotency_key: key2 },
|
|
672
703
|
idempotent: true
|
|
673
704
|
});
|
|
705
|
+
if (params.idempotency_key !== void 0) {
|
|
706
|
+
return send(params.idempotency_key);
|
|
707
|
+
}
|
|
708
|
+
const key = idempotencyKey(this.#client.now());
|
|
709
|
+
const startedAt = Date.now();
|
|
710
|
+
try {
|
|
711
|
+
return await send(key);
|
|
712
|
+
} catch (error) {
|
|
713
|
+
if (!(error instanceof TooLateError) || error.serverTime === void 0) {
|
|
714
|
+
throw error;
|
|
715
|
+
}
|
|
716
|
+
const elapsed = Date.now() - startedAt;
|
|
717
|
+
const serverAtStart = error.serverTime.getTime() - elapsed;
|
|
718
|
+
if (Math.abs(serverAtStart - mintedAtMs(key)) <= IDEMPOTENCY_WINDOW_MS) {
|
|
719
|
+
throw error;
|
|
720
|
+
}
|
|
721
|
+
this.#client.observeServerTime(error.serverTime);
|
|
722
|
+
return await send(idempotencyKey(this.#client.now()));
|
|
723
|
+
}
|
|
674
724
|
}
|
|
675
725
|
/** Reports which workspace this key acts for. */
|
|
676
726
|
whoami(options) {
|
|
@@ -681,18 +731,37 @@ var Meterbase = class {
|
|
|
681
731
|
});
|
|
682
732
|
}
|
|
683
733
|
};
|
|
684
|
-
|
|
734
|
+
var IDEMPOTENCY_WINDOW_MS = 60 * 60 * 1e3;
|
|
735
|
+
function mintedAtMs(key) {
|
|
736
|
+
return Number.parseInt(key.replace(/-/g, "").slice(0, 12), 16);
|
|
737
|
+
}
|
|
738
|
+
function idempotencyKey(atMs) {
|
|
685
739
|
const webcrypto = globalThis.crypto;
|
|
686
|
-
if (typeof webcrypto?.
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
const bytes = webcrypto.getRandomValues(new Uint8Array(16));
|
|
691
|
-
return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
|
|
740
|
+
if (typeof webcrypto?.getRandomValues !== "function") {
|
|
741
|
+
throw new MeterbaseError(
|
|
742
|
+
"No crypto to generate an idempotency key with: pass `idempotency_key` yourself (a UUIDv7), or run somewhere `crypto.getRandomValues` exists."
|
|
743
|
+
);
|
|
692
744
|
}
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
);
|
|
745
|
+
const bytes = webcrypto.getRandomValues(new Uint8Array(16));
|
|
746
|
+
const ms = Math.max(0, Math.trunc(atMs));
|
|
747
|
+
const high = Math.floor(ms / 4294967296);
|
|
748
|
+
const low = ms >>> 0;
|
|
749
|
+
bytes[0] = high >>> 8 & 255;
|
|
750
|
+
bytes[1] = high & 255;
|
|
751
|
+
bytes[2] = low >>> 24 & 255;
|
|
752
|
+
bytes[3] = low >>> 16 & 255;
|
|
753
|
+
bytes[4] = low >>> 8 & 255;
|
|
754
|
+
bytes[5] = low & 255;
|
|
755
|
+
bytes[6] = bytes[6] & 15 | 112;
|
|
756
|
+
bytes[8] = bytes[8] & 63 | 128;
|
|
757
|
+
const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
|
|
758
|
+
return [
|
|
759
|
+
hex.slice(0, 8),
|
|
760
|
+
hex.slice(8, 12),
|
|
761
|
+
hex.slice(12, 16),
|
|
762
|
+
hex.slice(16, 20),
|
|
763
|
+
hex.slice(20)
|
|
764
|
+
].join("-");
|
|
696
765
|
}
|
|
697
766
|
|
|
698
767
|
exports.APIError = APIError;
|
|
@@ -700,7 +769,7 @@ exports.AuthenticationError = AuthenticationError;
|
|
|
700
769
|
exports.ConflictError = ConflictError;
|
|
701
770
|
exports.ConnectionError = ConnectionError;
|
|
702
771
|
exports.CycleChangeRequiresResetError = CycleChangeRequiresResetError;
|
|
703
|
-
exports.
|
|
772
|
+
exports.InvalidIdempotencyKeyError = InvalidIdempotencyKeyError;
|
|
704
773
|
exports.InvalidRequestError = InvalidRequestError;
|
|
705
774
|
exports.Meterbase = Meterbase;
|
|
706
775
|
exports.MeterbaseError = MeterbaseError;
|
|
@@ -709,6 +778,7 @@ exports.PermissionDeniedError = PermissionDeniedError;
|
|
|
709
778
|
exports.RateLimitError = RateLimitError;
|
|
710
779
|
exports.ServerError = ServerError;
|
|
711
780
|
exports.TimeoutError = TimeoutError;
|
|
781
|
+
exports.TooLateError = TooLateError;
|
|
712
782
|
exports.errorFromResponse = errorFromResponse;
|
|
713
783
|
//# sourceMappingURL=index.cjs.map
|
|
714
784
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/errors.ts","../src/client.ts","../src/resources/customer-allowances.ts","../src/resources/customer-plan.ts","../src/resources/customers.ts","../src/resources/meters.ts","../src/resources/plans.ts","../src/index.ts"],"names":[],"mappings":";;;AAGO,IAAM,cAAA,GAAN,cAA6B,KAAA,CAAM;AAAA,EACxC,WAAA,CAAY,S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,OAAO,SAAA,EAAW,UAAA,KAAe,UAAA,EAAY;AAC/C,IAAA,OAAO,UAAU,UAAA,EAAW;AAAA,EAC9B;AAGA,EAAA,IAAI,OAAO,SAAA,EAAW,eAAA,KAAoB,UAAA,EAAY;AACpD,IAAA,MAAM,QAAQ,SAAA,CAAU,eAAA,CAAgB,IAAI,UAAA,CAAW,EAAE,CAAC,CAAA;AAC1D,IAAA,OAAO,KAAA,CAAM,IAAA,CAAK,KAAA,EAAO,CAAC,MAAM,CAAA,CAAE,QAAA,CAAS,EAAE,CAAA,CAAE,SAAS,CAAA,EAAG,GAAG,CAAC,CAAA,CAAE,KAAK,EAAE,CAAA;AAAA,EAC1E;AAEA,EAAA,MAAM,IAAI,cAAA;AAAA,IACR;AAAA,GAEF;AACF","file":"index.cjs","sourcesContent":["// Every failure is a MeterbaseError, so a caller can catch one type and still\n// switch on the specific one. `code` is stable; `message` may change.\n\nexport class MeterbaseError extends Error {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message, options)\n this.name = new.target.name\n }\n}\n\nexport class APIError extends MeterbaseError {\n readonly status: number\n readonly code: string\n /** From `X-Request-Id`, when the engine sends one. */\n readonly requestId: string | undefined\n readonly body: unknown\n\n constructor(args: {\n status: number\n code: string\n message: string\n requestId?: string | undefined\n body?: unknown\n }) {\n super(args.message)\n this.status = args.status\n this.code = args.code\n this.requestId = args.requestId\n this.body = args.body\n }\n}\n\nexport class AuthenticationError extends APIError {}\nexport class PermissionDeniedError extends APIError {}\nexport class NotFoundError extends APIError {}\nexport class ConflictError extends APIError {}\n\n/**\n * `409 idempotency_conflict`: the key is in use for a different meter or\n * quantity. A caller told their key is taken asks what it recorded next, so\n * the engine names the original and this carries it.\n *\n * A `ConflictError` still, so `catch (e) { if (e instanceof ConflictError) }`\n * keeps working.\n */\nexport class IdempotencyConflictError extends ConflictError {\n /** The event that key already recorded. Undefined only if the engine sent a\n * body this could not be read out of. */\n readonly existingEventId: string | undefined\n\n constructor(args: ConstructorParameters<typeof APIError>[0]) {\n super(args)\n this.existingEventId = existingEventId(args.body)\n }\n}\n\nexport class InvalidRequestError extends APIError {}\n\n/**\n * `422 cycle_change_requires_reset`: the two plans measure different cycles,\n * so a `next_cycle` change has no shared boundary to wait for and a `prorate`\n * no shared period to weight. The move is `customers.plan.restart`, which\n * closes the current period and opens a fresh one on the new cycle — or\n * `changeNow` with the default `reconciliation: \"none\"` to keep the period\n * that is running. The engine's `message` says as much.\n *\n * An `InvalidRequestError` still, so an existing `catch` keeps working.\n */\nexport class CycleChangeRequiresResetError extends InvalidRequestError {}\nexport class RateLimitError extends APIError {\n /** Seconds to wait, from `Retry-After`, when the engine sends one. */\n readonly retryAfter: number | undefined\n\n constructor(\n args: ConstructorParameters<typeof APIError>[0] & {\n retryAfter?: number | undefined\n },\n ) {\n super(args)\n this.retryAfter = args.retryAfter\n }\n}\nexport class ServerError extends APIError {}\n\n// The request never produced an answer: DNS, TLS, a reset, an abort.\nexport class ConnectionError extends MeterbaseError {}\nexport class TimeoutError extends ConnectionError {}\n\nexport function errorFromResponse(args: {\n status: number\n code: string\n message: string\n requestId?: string | undefined\n retryAfter?: number | undefined\n body?: unknown\n}): APIError {\n switch (args.status) {\n case 401:\n return new AuthenticationError(args)\n case 403:\n return new PermissionDeniedError(args)\n case 404:\n return new NotFoundError(args)\n case 409:\n return args.code === \"idempotency_conflict\"\n ? new IdempotencyConflictError(args)\n : new ConflictError(args)\n case 422:\n return args.code === \"cycle_change_requires_reset\"\n ? new CycleChangeRequiresResetError(args)\n : new InvalidRequestError(args)\n case 429:\n return new RateLimitError(args)\n default:\n return args.status >= 500 ? new ServerError(args) : new APIError(args)\n }\n}\n\n/** The engine carries it beside `code` and `message`, inside `error`. */\nfunction existingEventId(body: unknown): string | undefined {\n if (typeof body !== \"object\" || body === null) return undefined\n\n const error = (body as { error?: unknown }).error\n if (typeof error !== \"object\" || error === null) return undefined\n\n const id = (error as { existing_event_id?: unknown }).existing_event_id\n return typeof id === \"string\" ? id : undefined\n}\n","// Everything goes through `request`, so authentication, timeouts, retries and\n// error mapping are defined once.\n\nimport {\n ConnectionError,\n errorFromResponse,\n MeterbaseError,\n TimeoutError,\n} from \"./errors.js\"\n\nexport type MeterbaseOptions = {\n /** A secret key. It names its own workspace. */\n apiKey: string\n /** Defaults to the hosted engine. */\n baseUrl?: string\n /** Per attempt, not per call. */\n timeout?: number\n maxRetries?: number\n fetch?: typeof globalThis.fetch\n}\n\nexport type RequestOptions = {\n signal?: AbortSignal\n timeout?: number\n maxRetries?: number\n}\n\ntype HttpMethod = \"GET\" | \"POST\" | \"PATCH\" | \"DELETE\"\n\ntype Request = RequestOptions & {\n method: HttpMethod\n path: string\n query?: Record<string, string | number | boolean | undefined>\n body?: unknown\n /**\n * Replay this call even though its method is not safe. Only a route that\n * carries an idempotency key may set it, and the key has to be fixed before\n * `request` is called — the loop re-sends one body, so a key generated\n * per attempt would count the same usage twice.\n */\n idempotent?: boolean\n}\n\nconst DEFAULT_BASE_URL = \"https://api.meterbase.tech\"\nconst DEFAULT_TIMEOUT = 10_000\nconst DEFAULT_MAX_RETRIES = 2\nconst MAX_BACKOFF = 8_000\n\nexport class Client {\n readonly #apiKey: string\n readonly #baseUrl: string\n readonly #timeout: number\n readonly #maxRetries: number\n readonly #fetch: typeof globalThis.fetch\n\n constructor(options: MeterbaseOptions) {\n if (!options.apiKey) {\n throw new MeterbaseError(\n \"An API key is required: new Meterbase({ apiKey: 'mb_sk_live_…' }).\",\n )\n }\n\n this.#apiKey = options.apiKey\n this.#baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/+$/, \"\")\n this.#timeout = options.timeout ?? DEFAULT_TIMEOUT\n this.#maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES\n this.#fetch = options.fetch ?? globalThis.fetch\n\n if (typeof this.#fetch !== \"function\") {\n throw new MeterbaseError(\n \"No fetch implementation: pass one as `fetch`, or run on Node 18+.\",\n )\n }\n }\n\n async request<T>(req: Request): Promise<T> {\n const maxRetries = req.maxRetries ?? this.#maxRetries\n // Safe methods, plus the routes that carry an idempotency key and say so.\n // Any other POST or PATCH could create a second row on a replay.\n const retryable =\n req.method === \"GET\" || req.method === \"DELETE\" || req.idempotent === true\n\n let lastError: unknown\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n if (attempt > 0) await sleep(backoff(attempt, lastError))\n\n try {\n const response = await this.#send(req)\n\n if (response.ok) return (await parseBody(response)) as T\n\n const error = await errorFrom(response)\n if (retryable && attempt < maxRetries && shouldRetry(response.status)) {\n lastError = error\n continue\n }\n throw error\n } catch (cause) {\n if (\n cause instanceof MeterbaseError &&\n !(cause instanceof ConnectionError)\n ) {\n throw cause\n }\n // A connection failure proves nothing about whether the server acted,\n // so it is replayed under the same idempotency rule.\n if (!retryable || attempt >= maxRetries) throw cause\n lastError = cause\n }\n }\n\n /* c8 ignore next 2 -- the loop always returns or throws */\n throw lastError\n }\n\n async #send(req: Request): Promise<Response> {\n const url = new URL(this.#baseUrl + req.path)\n for (const [key, value] of Object.entries(req.query ?? {})) {\n if (value !== undefined) url.searchParams.set(key, String(value))\n }\n\n const headers: Record<string, string> = {\n authorization: `Bearer ${this.#apiKey}`,\n accept: \"application/json\",\n }\n if (req.body !== undefined) headers[\"content-type\"] = \"application/json\"\n\n const timeout = req.timeout ?? this.#timeout\n const controller = new AbortController()\n const onAbort = () => controller.abort(req.signal?.reason)\n req.signal?.addEventListener(\"abort\", onAbort, { once: true })\n\n let timedOut = false\n const timer = setTimeout(() => {\n timedOut = true\n controller.abort()\n }, timeout)\n\n try {\n return await this.#fetch(url, {\n method: req.method,\n headers,\n body: req.body === undefined ? undefined : JSON.stringify(req.body),\n signal: controller.signal,\n })\n } catch (cause) {\n if (timedOut) {\n throw new TimeoutError(`Request timed out after ${timeout}ms.`, {\n cause,\n })\n }\n // A caller's own abort is theirs to handle, not ours to reclassify.\n if (req.signal?.aborted) throw cause\n throw new ConnectionError(`Could not reach ${url.origin}.`, { cause })\n } finally {\n clearTimeout(timer)\n req.signal?.removeEventListener(\"abort\", onAbort)\n }\n }\n}\n\nfunction shouldRetry(status: number): boolean {\n return status === 408 || status === 429 || status >= 500\n}\n\n/** Exponential backoff with full jitter, unless the engine named a delay. */\nfunction backoff(attempt: number, lastError: unknown): number {\n const retryAfter =\n lastError && typeof lastError === \"object\" && \"retryAfter\" in lastError\n ? (lastError as { retryAfter?: number }).retryAfter\n : undefined\n if (retryAfter !== undefined) return Math.min(retryAfter * 1000, MAX_BACKOFF)\n\n const ceiling = Math.min(500 * 2 ** (attempt - 1), MAX_BACKOFF)\n return Math.random() * ceiling\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n\nasync function parseBody(response: Response): Promise<unknown> {\n if (response.status === 204) return undefined\n\n const text = await response.text()\n if (text === \"\") return undefined\n\n try {\n return JSON.parse(text)\n } catch (cause) {\n throw new MeterbaseError(\"The engine returned a body that is not JSON.\", {\n cause,\n })\n }\n}\n\nasync function errorFrom(response: Response) {\n const body = await response.text()\n const parsed = parseErrorBody(body)\n const retryAfterHeader = response.headers.get(\"retry-after\")\n const retryAfter = retryAfterHeader ? Number(retryAfterHeader) : undefined\n\n return errorFromResponse({\n status: response.status,\n code: parsed?.code ?? `http_${response.status}`,\n message: parsed?.message ?? `The engine responded ${response.status}.`,\n requestId: response.headers.get(\"x-request-id\") ?? undefined,\n retryAfter:\n retryAfter !== undefined && Number.isFinite(retryAfter)\n ? retryAfter\n : undefined,\n body: body === \"\" ? undefined : (safeParse(body) ?? body),\n })\n}\n\nfunction parseErrorBody(body: string) {\n const parsed = safeParse(body) as\n { error?: { code?: string; message?: string } } | undefined\n const error = parsed?.error\n if (!error?.code || !error.message) return undefined\n\n return { code: error.code, message: error.message }\n}\n\nfunction safeParse(body: string): unknown {\n try {\n return JSON.parse(body)\n } catch {\n return undefined\n }\n}\n","import type { Client, RequestOptions } from \"../client.js\"\nimport type {\n Allowance,\n AllowanceGrantParams,\n AllowanceListParams,\n List,\n} from \"../types.js\"\n\n/**\n * Capacity handed to one customer on top of their plan. A grant with\n * `source: \"plan\"` is the engine's own, minted when a plan is assigned, and\n * cannot be created here.\n */\nexport class CustomerAllowances {\n readonly #client: Client\n\n constructor(client: Client) {\n this.#client = client\n }\n\n grant(\n customerId: string,\n params: AllowanceGrantParams,\n options?: RequestOptions,\n ): Promise<Allowance> {\n return this.#client.request({\n ...options,\n method: \"POST\",\n path: `/v1/customers/${encodeURIComponent(customerId)}/allowances`,\n body: params,\n })\n }\n\n /** Open grants only, unless `include_closed`. */\n list(\n customerId: string,\n params: AllowanceListParams = {},\n options?: RequestOptions,\n ): Promise<List<Allowance>> {\n return this.#client.request({\n ...options,\n method: \"GET\",\n path: `/v1/customers/${encodeURIComponent(customerId)}/allowances`,\n query: {\n meter_id: params.meter_id,\n include_closed: params.include_closed,\n },\n })\n }\n\n retrieve(\n customerId: string,\n allowanceId: string,\n options?: RequestOptions,\n ): Promise<Allowance> {\n return this.#client.request({\n ...options,\n method: \"GET\",\n path: `/v1/customers/${encodeURIComponent(customerId)}/allowances/${encodeURIComponent(allowanceId)}`,\n })\n }\n\n /** Withdraws what is left without erasing what was consumed. Idempotent. */\n revoke(\n customerId: string,\n allowanceId: string,\n options?: RequestOptions,\n ): Promise<Allowance> {\n return this.#client.request({\n ...options,\n method: \"DELETE\",\n path: `/v1/customers/${encodeURIComponent(customerId)}/allowances/${encodeURIComponent(allowanceId)}`,\n })\n }\n}\n","import type { Client, RequestOptions } from \"../client.js\"\nimport type {\n AssignPlanParams,\n Assignment,\n List,\n PlanChangeNowParams,\n PlanChangeParams,\n PlanMoveParams,\n} from \"../types.js\"\nimport { NotFoundError } from \"../errors.js\"\n\n/**\n * Which plan a customer holds. The history is append-only: there is no patch\n * and no delete, and moving a customer to a different plan is the same call as\n * their first.\n *\n * `assign` is that call, mirroring the wire. The rest name the four moves a\n * caller actually makes — later, now, now-and-start-over, and never mind — so\n * that picking one does not mean knowing what `effective` and `reconciliation`\n * do to a half-used period.\n */\nexport class CustomerPlan {\n readonly #client: Client\n\n constructor(client: Client) {\n this.#client = client\n }\n\n /**\n * Put a customer on a plan. This is the wire call, and the only one that\n * takes `cycle_anchor` — a first assignment's one chance to put their\n * periods on a date they already have.\n *\n * Returns the instruction as recorded, which is not always as asked: a first\n * plan is recorded `immediate` whatever `effective` said.\n */\n assign(\n customerId: string,\n params: AssignPlanParams,\n options?: RequestOptions,\n ): Promise<Assignment> {\n return this.#client.request({\n ...options,\n method: \"POST\",\n path: `/v1/customers/${encodeURIComponent(customerId)}/plan`,\n body: params,\n })\n }\n\n /**\n * Move a customer to a different plan, with both knobs in the open.\n * `effective` defaults to `next_cycle`; `reconciliation` applies only to an\n * `immediate` change and defaults to `none`.\n *\n * Reach for `changeAtNextCycle`, `changeNow` or `restart` when one of them\n * says what you mean — this is the form to fall back to when the two are\n * chosen at runtime.\n */\n change(\n customerId: string,\n params: PlanChangeParams,\n options?: RequestOptions,\n ): Promise<Assignment> {\n const { plan, ...rest } = params\n\n return this.assign(customerId, { plan_id: plan, ...rest }, options)\n }\n\n /**\n * Schedule the move for the end of the period they are in: they keep the\n * plan they are paying for until it runs out, and the new one starts at\n * their next boundary. Nothing is pro-rated, because nothing is split.\n *\n * Two plans on different cycles share no boundary, and this answers\n * `CycleChangeRequiresResetError` — use `restart` for that move.\n */\n changeAtNextCycle(\n customerId: string,\n params: PlanMoveParams,\n options?: RequestOptions,\n ): Promise<Assignment> {\n return this.change(\n customerId,\n { plan: params.plan, effective: \"next_cycle\" },\n options,\n )\n }\n\n /**\n * Move them now, inside the period already running. Their renewal day does\n * not move; what changes is this period's cap, and `reconciliation` says\n * how:\n *\n * - `none` (the default) — the new plan's amount governs the whole period.\n * Usage already spent still counts, so a downgrade can deny until the\n * period ends.\n * - `prorate` — each plan's amount weighted by the fraction of the period it\n * was held for. Refused between plans on different cycles, which share no\n * period to weight.\n *\n * To have the period itself start over instead, use `restart`.\n */\n changeNow(\n customerId: string,\n params: PlanChangeNowParams,\n options?: RequestOptions,\n ): Promise<Assignment> {\n return this.change(\n customerId,\n { ...params, effective: \"immediate\" },\n options,\n )\n }\n\n /**\n * Move them now and start a fresh period today: the period they were in\n * closes where the change lands, keeping the usage it had, and the new\n * plan's full amount opens immediately.\n *\n * This moves the customer's anchor, so their renewal day becomes today. It\n * is the move for a customer starting over — a new contract, a re-signup —\n * and the only one that can take a customer between plans whose cycles\n * differ.\n */\n restart(\n customerId: string,\n params: PlanMoveParams,\n options?: RequestOptions,\n ): Promise<Assignment> {\n return this.change(\n customerId,\n { plan: params.plan, effective: \"immediate\", reconciliation: \"reset\" },\n options,\n )\n }\n\n /**\n * Call off a change that has not landed yet, leaving the customer on the\n * plan they hold. Naming the plan already held is what supersedes a pending\n * instruction, so this reads the plan in force and names it back.\n *\n * Returns the assignment still in force, or `null` for a customer holding no\n * plan — who can have nothing pending, since a first assignment always lands\n * at once.\n */\n async cancelScheduledChange(\n customerId: string,\n options?: RequestOptions,\n ): Promise<Assignment | null> {\n const current = await this.retrieve(customerId, options)\n if (current === null) return null\n\n return this.assign(customerId, { plan_id: current.plan_id }, options)\n }\n\n /**\n * The plan in force now, which is not always the newest instruction: a\n * change dated ahead does not govern yet.\n *\n * `null` when the customer holds no plan. That is a default deny rather than\n * a failure — they are entitled to nothing — so it is an answer here and not\n * a thrown `NotFoundError`. A customer who does not exist at all still\n * throws one.\n */\n async retrieve(\n customerId: string,\n options?: RequestOptions,\n ): Promise<Assignment | null> {\n try {\n return await this.#client.request<Assignment>({\n ...options,\n method: \"GET\",\n path: `/v1/customers/${encodeURIComponent(customerId)}/plan`,\n })\n } catch (error) {\n if (error instanceof NotFoundError && error.code === \"no_plan_assigned\") {\n return null\n }\n throw error\n }\n }\n\n /**\n * The change waiting to land, or `null` when none is. At most one is ever\n * live: a newer instruction supersedes the one before it.\n *\n * Read against the assignment in force rather than against the local clock,\n * so a change landing seconds from now is not reported as already governing.\n */\n async pending(\n customerId: string,\n options?: RequestOptions,\n ): Promise<Assignment | null> {\n const [current, { data }] = await Promise.all([\n this.retrieve(customerId, options),\n this.history(customerId, options),\n ])\n\n const inForce =\n current === null ? -Infinity : Date.parse(current.effective_at)\n\n return (\n data.find(\n (a) => a.superseded_at === null && Date.parse(a.effective_at) > inForce,\n ) ?? null\n )\n }\n\n /** Every instruction, superseded ones included: it is the whole trail. */\n history(\n customerId: string,\n options?: RequestOptions,\n ): Promise<List<Assignment>> {\n return this.#client.request({\n ...options,\n method: \"GET\",\n path: `/v1/customers/${encodeURIComponent(customerId)}/plan/history`,\n })\n }\n}\n","import type { Client, RequestOptions } from \"../client.js\"\nimport type {\n Customer,\n CustomerCreateParams,\n CustomerListParams,\n CustomerUpdateParams,\n CustomerWithPlan,\n List,\n} from \"../types.js\"\nimport { CustomerAllowances } from \"./customer-allowances.js\"\nimport { CustomerPlan } from \"./customer-plan.js\"\n\nexport class Customers {\n /** The plan they hold, and the trail of instructions that got them there. */\n readonly plan: CustomerPlan\n /** Grants, which sit on top of whatever the plan gives. */\n readonly allowances: CustomerAllowances\n\n readonly #client: Client\n\n constructor(client: Client) {\n this.#client = client\n this.plan = new CustomerPlan(client)\n this.allowances = new CustomerAllowances(client)\n }\n\n create(\n params: CustomerCreateParams,\n options?: RequestOptions,\n ): Promise<Customer> {\n return this.#client.request({\n ...options,\n method: \"POST\",\n path: \"/v1/customers\",\n body: params,\n })\n }\n\n /** Lean: a listing does not embed the plan. Read one customer for that. */\n list(\n params: CustomerListParams = {},\n options?: RequestOptions,\n ): Promise<List<Customer>> {\n return this.#client.request({\n ...options,\n method: \"GET\",\n path: \"/v1/customers\",\n query: { include_deleted: params.include_deleted },\n })\n }\n\n /**\n * One customer, with the plan they hold. `plan` is the one in force now and\n * `pending_plan` the change waiting to land, each `null` when there is\n * none — so knowing what a customer is on costs no second request.\n */\n retrieve(id: string, options?: RequestOptions): Promise<CustomerWithPlan> {\n return this.#client.request({\n ...options,\n method: \"GET\",\n path: `/v1/customers/${encodeURIComponent(id)}`,\n })\n }\n\n /**\n * Resolves the tenant's own identifier, or null, embedding the plan the way\n * `retrieve` does. The engine answers this as a filtered list, so a miss is\n * an empty collection rather than a 404.\n */\n async retrieveByExternalId(\n externalId: string,\n options?: RequestOptions,\n ): Promise<CustomerWithPlan | null> {\n const { data } = await this.#client.request<List<CustomerWithPlan>>({\n ...options,\n method: \"GET\",\n path: \"/v1/customers\",\n query: { external_id: externalId },\n })\n\n return data[0] ?? null\n }\n\n update(\n id: string,\n params: CustomerUpdateParams,\n options?: RequestOptions,\n ): Promise<Customer> {\n return this.#client.request({\n ...options,\n method: \"PATCH\",\n path: `/v1/customers/${encodeURIComponent(id)}`,\n body: params,\n })\n }\n\n /** Soft delete: usage and assignments keep referencing the customer. */\n delete(id: string, options?: RequestOptions): Promise<Customer> {\n return this.#client.request({\n ...options,\n method: \"DELETE\",\n path: `/v1/customers/${encodeURIComponent(id)}`,\n })\n }\n}\n","import type { Client, RequestOptions } from \"../client.js\"\nimport type {\n List,\n Meter,\n MeterCreateParams,\n MeterListParams,\n MeterUpdateParams,\n} from \"../types.js\"\n\nexport class Meters {\n readonly #client: Client\n\n constructor(client: Client) {\n this.#client = client\n }\n\n create(params: MeterCreateParams, options?: RequestOptions): Promise<Meter> {\n return this.#client.request({\n ...options,\n method: \"POST\",\n path: \"/v1/meters\",\n body: params,\n })\n }\n\n list(\n params: MeterListParams = {},\n options?: RequestOptions,\n ): Promise<List<Meter>> {\n return this.#client.request({\n ...options,\n method: \"GET\",\n path: \"/v1/meters\",\n query: { include_archived: params.include_archived },\n })\n }\n\n retrieve(id: string, options?: RequestOptions): Promise<Meter> {\n return this.#client.request({\n ...options,\n method: \"GET\",\n path: `/v1/meters/${encodeURIComponent(id)}`,\n })\n }\n\n update(\n id: string,\n params: MeterUpdateParams,\n options?: RequestOptions,\n ): Promise<Meter> {\n return this.#client.request({\n ...options,\n method: \"PATCH\",\n path: `/v1/meters/${encodeURIComponent(id)}`,\n body: params,\n })\n }\n\n /** Soft delete: plans and usage keep referencing the meter. Idempotent. */\n archive(id: string, options?: RequestOptions): Promise<Meter> {\n return this.#client.request({\n ...options,\n method: \"DELETE\",\n path: `/v1/meters/${encodeURIComponent(id)}`,\n })\n }\n}\n","import type { Client, RequestOptions } from \"../client.js\"\nimport type {\n List,\n Plan,\n PlanAllowance,\n PlanAllowanceListParams,\n PlanAllowanceSetParams,\n PlanCreateParams,\n PlanListParams,\n PlanUpdateParams,\n} from \"../types.js\"\n\n/**\n * A plan's entitlement, versioned. There is no update and no delete: an edit\n * appends the next version, so which amount applied when stays derivable.\n */\nexport class PlanAllowances {\n readonly #client: Client\n\n constructor(client: Client) {\n this.#client = client\n }\n\n set(\n planId: string,\n params: PlanAllowanceSetParams,\n options?: RequestOptions,\n ): Promise<PlanAllowance> {\n return this.#client.request({\n ...options,\n method: \"POST\",\n path: `/v1/plans/${encodeURIComponent(planId)}/allowances`,\n body: params,\n })\n }\n\n /** Every version of every meter, newest first — history, not just current. */\n list(\n planId: string,\n params: PlanAllowanceListParams = {},\n options?: RequestOptions,\n ): Promise<List<PlanAllowance>> {\n return this.#client.request({\n ...options,\n method: \"GET\",\n path: `/v1/plans/${encodeURIComponent(planId)}/allowances`,\n query: { meter_id: params.meter_id },\n })\n }\n}\n\nexport class Plans {\n readonly allowances: PlanAllowances\n\n readonly #client: Client\n\n constructor(client: Client) {\n this.#client = client\n this.allowances = new PlanAllowances(client)\n }\n\n /** A new plan grants nothing; attach entitlement with `allowances.set`. */\n create(params: PlanCreateParams, options?: RequestOptions): Promise<Plan> {\n return this.#client.request({\n ...options,\n method: \"POST\",\n path: \"/v1/plans\",\n body: params,\n })\n }\n\n list(\n params: PlanListParams = {},\n options?: RequestOptions,\n ): Promise<List<Plan>> {\n return this.#client.request({\n ...options,\n method: \"GET\",\n path: \"/v1/plans\",\n query: { include_archived: params.include_archived },\n })\n }\n\n retrieve(id: string, options?: RequestOptions): Promise<Plan> {\n return this.#client.request({\n ...options,\n method: \"GET\",\n path: `/v1/plans/${encodeURIComponent(id)}`,\n })\n }\n\n update(\n id: string,\n params: PlanUpdateParams,\n options?: RequestOptions,\n ): Promise<Plan> {\n return this.#client.request({\n ...options,\n method: \"PATCH\",\n path: `/v1/plans/${encodeURIComponent(id)}`,\n body: params,\n })\n }\n\n /**\n * Stops new assignments without withdrawing capacity from anyone already on\n * the plan, which is why an archived plan still resolves by id. Idempotent.\n */\n archive(id: string, options?: RequestOptions): Promise<Plan> {\n return this.#client.request({\n ...options,\n method: \"DELETE\",\n path: `/v1/plans/${encodeURIComponent(id)}`,\n })\n }\n}\n","import { Client, type MeterbaseOptions, type RequestOptions } from \"./client.js\"\nimport { MeterbaseError } from \"./errors.js\"\nimport type { CustomerAllowances } from \"./resources/customer-allowances.js\"\nimport type { CustomerPlan } from \"./resources/customer-plan.js\"\nimport { Customers } from \"./resources/customers.js\"\nimport { Meters } from \"./resources/meters.js\"\nimport { Plans, type PlanAllowances } from \"./resources/plans.js\"\nimport type {\n CheckParams,\n CheckResult,\n TrackParams,\n TrackResult,\n WhoAmI,\n} from \"./types.js\"\n\nexport class Meterbase {\n readonly customers: Customers\n readonly meters: Meters\n readonly plans: Plans\n\n readonly #client: Client\n\n constructor(options: MeterbaseOptions) {\n this.#client = new Client(options)\n this.customers = new Customers(this.#client)\n this.meters = new Meters(this.#client)\n this.plans = new Plans(this.#client)\n }\n\n /**\n * Asks whether a customer may consume `quantity` of a meter, named by the\n * tenant's own external id and the meter's key. Absence of entitlement is\n * not permission: a customer with no plan and no grant is denied.\n *\n * This is the gate, and the only call that ever refuses. Run it before the\n * work; record the work with `track` afterwards.\n */\n check(params: CheckParams, options?: RequestOptions): Promise<CheckResult> {\n return this.#client.request({\n ...options,\n method: \"POST\",\n path: \"/v1/check\",\n body: params,\n })\n }\n\n /**\n * Records usage that already happened — the tokens were spent, the image\n * was generated — so it never refuses on capacity. A quantity beyond the\n * customer's capacity is recorded, drives `available` to 0, and the next\n * `check` says no. The answer is a receipt, not a verdict.\n *\n * `idempotency_key` is generated when omitted, so retrying this call — the\n * SDK's own retries included — replays the original rather than counting\n * the same work twice.\n */\n // `async` so that generating the key cannot throw synchronously out of a\n // method that otherwise only ever rejects: one call, one way to fail.\n async track(\n params: TrackParams,\n options?: RequestOptions,\n ): Promise<TrackResult> {\n return this.#client.request({\n ...options,\n method: \"POST\",\n path: \"/v1/usage/track\",\n // Fixed here, once, before the retry loop is entered: every attempt of\n // this call carries the same key, which is what makes replaying it safe.\n body: {\n ...params,\n idempotency_key: params.idempotency_key ?? idempotencyKey(),\n },\n idempotent: true,\n })\n }\n\n /** Reports which workspace this key acts for. */\n whoami(options?: RequestOptions): Promise<WhoAmI> {\n return this.#client.request({\n ...options,\n method: \"GET\",\n path: \"/v1/whoami\",\n })\n }\n}\n\n// Type-only: none of them is constructible without the unexported Client.\nexport type {\n CustomerAllowances,\n CustomerPlan,\n Customers,\n MeterbaseOptions,\n Meters,\n PlanAllowances,\n Plans,\n RequestOptions,\n}\nexport * from \"./errors.js\"\nexport type * from \"./types.js\"\n\n/**\n * The engine requires a key, and a caller made to invent one on every call\n * eventually will not — which is the moment a retry counts twice.\n */\nfunction idempotencyKey(): string {\n // Structurally, not as `Crypto`: that lib type is the DOM's, and this\n // compiles without it so the SDK stays as portable as `fetch` is.\n const webcrypto = globalThis.crypto as\n | {\n randomUUID?: () => string\n getRandomValues?: (array: Uint8Array) => Uint8Array\n }\n | undefined\n\n if (typeof webcrypto?.randomUUID === \"function\") {\n return webcrypto.randomUUID()\n }\n // `randomUUID` needs a secure context; `getRandomValues` does not, so a\n // page served over plain http still gets 128 random bits.\n if (typeof webcrypto?.getRandomValues === \"function\") {\n const bytes = webcrypto.getRandomValues(new Uint8Array(16))\n return Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\")\n }\n\n throw new MeterbaseError(\n \"No crypto to generate an idempotency key with: pass `idempotency_key` \" +\n \"yourself, or run somewhere `crypto.getRandomValues` exists.\",\n )\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/errors.ts","../src/client.ts","../src/resources/customer-allowances.ts","../src/resources/customer-plan.ts","../src/resources/customers.ts","../src/resources/meters.ts","../src/resources/plans.ts","../src/index.ts"],"names":["key"],"mappings":";;;AAGO,IAAM,cAAA,GAAN,cAA6B,KAAA,CAAM;AAAA,EACxC,WAAA,CAAY,SAAiB,OAAA,EAA+B;AAC1D,IAAA,KAAA,CAAM,SAAS,OAAO,CAAA;AACtB,IAAA,IAAA,CAAK,OAAO,GAAA,CAAA,MAAA,CAAW,IAAA;AAAA,EACzB;AACF;AAEO,IAAM,QAAA,GAAN,cAAuB,cAAA,CAAe;AAAA,EAClC,MAAA;AAAA,EACA,IAAA;AAAA;AAAA,EAEA,SAAA;AAAA,EACA,IAAA;AAAA,EAET,YAAY,IAAA,EAMT;AACD,IAAA,KAAA,CAAM,KAAK,OAAO,CAAA;AAClB,IAAA,IAAA,CAAK,SAAS,IAAA,CAAK,MAAA;AACnB,IAAA,IAAA,CAAK,OAAO,IAAA,CAAK,IAAA;AACjB,IAAA,IAAA,CAAK,YAAY,IAAA,CAAK,SAAA;AACtB,IAAA,IAAA,CAAK,OAAO,IAAA,CAAK,IAAA;AAAA,EACnB;AACF;AAEO,IAAM,mBAAA,GAAN,cAAkC,QAAA,CAAS;AAAC;AAC5C,IAAM,qBAAA,GAAN,cAAoC,QAAA,CAAS;AAAC;AAC9C,IAAM,aAAA,GAAN,cAA4B,QAAA,CAAS;AAAC;AACtC,IAAM,aAAA,GAAN,cAA4B,QAAA,CAAS;AAAC;AAEtC,IAAM,mBAAA,GAAN,cAAkC,QAAA,CAAS;AAAC;AAO5C,IAAM,0BAAA,GAAN,cAAyC,mBAAA,CAAoB;AAAC;AAY9D,IAAM,YAAA,GAAN,cAA2B,mBAAA,CAAoB;AAAA;AAAA,EAE3C,UAAA;AAAA,EAET,YAAY,IAAA,EAAiD;AAC3D,IAAA,KAAA,CAAM,IAAI,CAAA;AACV,IAAA,IAAA,CAAK,UAAA,GAAa,UAAA,CAAW,IAAA,CAAK,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AAA;AAC1B,EAAA,KAAA,CAAM,CAAC,IAAI,IAAA,GAAO,GAAA;AAClB,EAAA,KAAA,CAAM,CAAC,CAAA,GAAK,GAAA,KAAQ,EAAA,GAAM,GAAA;AAC1B,EAAA,KAAA,CAAM,CAAC,CAAA,GAAK,GAAA,KAAQ,EAAA,GAAM,GAAA;AAC1B,EAAA,KAAA,CAAM,CAAC,CAAA,GAAK,GAAA,KAAQ,CAAA,GAAK,GAAA;AACzB,EAAA,KAAA,CAAM,CAAC,IAAI,GAAA,GAAM,GAAA;AAEjB,EAAA,KAAA,CAAM,CAAC,CAAA,GAAK,KAAA,CAAM,CAAC,IAAK,EAAA,GAAQ,GAAA;AAChC,EAAA,KAAA,CAAM,CAAC,CAAA,GAAK,KAAA,CAAM,CAAC,IAAK,EAAA,GAAQ,GAAA;AAEhC,EAAA,MAAM,MAAM,KAAA,CAAM,IAAA,CAAK,KAAA,EAAO,CAAC,MAAM,CAAA,CAAE,QAAA,CAAS,EAAE,CAAA,CAAE,SAAS,CAAA,EAAG,GAAG,CAAC,CAAA,CAAE,KAAK,EAAE,CAAA;AAE7E,EAAA,OAAO;AAAA,IACL,GAAA,CAAI,KAAA,CAAM,CAAA,EAAG,CAAC,CAAA;AAAA,IACd,GAAA,CAAI,KAAA,CAAM,CAAA,EAAG,EAAE,CAAA;AAAA,IACf,GAAA,CAAI,KAAA,CAAM,EAAA,EAAI,EAAE,CAAA;AAAA,IAChB,GAAA,CAAI,KAAA,CAAM,EAAA,EAAI,EAAE,CAAA;AAAA,IAChB,GAAA,CAAI,MAAM,EAAE;AAAA,GACd,CAAE,KAAK,GAAG,CAAA;AACZ","file":"index.cjs","sourcesContent":["// Every failure is a MeterbaseError, so a caller can catch one type and still\n// switch on the specific one. `code` is stable; `message` may change.\n\nexport class MeterbaseError extends Error {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message, options)\n this.name = new.target.name\n }\n}\n\nexport class APIError extends MeterbaseError {\n readonly status: number\n readonly code: string\n /** From `X-Request-Id`, when the engine sends one. */\n readonly requestId: string | undefined\n readonly body: unknown\n\n constructor(args: {\n status: number\n code: string\n message: string\n requestId?: string | undefined\n body?: unknown\n }) {\n super(args.message)\n this.status = args.status\n this.code = args.code\n this.requestId = args.requestId\n this.body = args.body\n }\n}\n\nexport class AuthenticationError extends APIError {}\nexport class PermissionDeniedError extends APIError {}\nexport class NotFoundError extends APIError {}\nexport class ConflictError extends APIError {}\n\nexport class InvalidRequestError extends APIError {}\n\n/**\n * `422 invalid_idempotency_key`: the key was not a UUID version 7.\n * `crypto.randomUUID()` mints a v4, so omit `idempotency_key` and let this\n * SDK mint the right thing.\n */\nexport class InvalidIdempotencyKeyError extends InvalidRequestError {}\n\n/**\n * `422 too_late`: the key's timestamp is more than an hour from the engine's\n * clock, so a retry can no longer be told from a new event. **Nothing was\n * recorded** — the check runs before any write.\n *\n * The usual cause is this machine's clock. When this SDK minted the key it\n * corrects the offset from `serverTime` and retries once, so you only see\n * this for a key you supplied. If that key is a retry of a call made over an\n * hour ago, do not resend it under a new one: it may already be recorded.\n */\nexport class TooLateError extends InvalidRequestError {\n /** The engine's clock when it refused. */\n readonly serverTime: Date | undefined\n\n constructor(args: ConstructorParameters<typeof APIError>[0]) {\n super(args)\n this.serverTime = serverTime(args.body)\n }\n}\n\n/**\n * `422 cycle_change_requires_reset`: the two plans measure different cycles,\n * so a `next_cycle` change has no shared boundary to wait for and a `prorate`\n * no shared period to weight. The move is `customers.plan.restart`, which\n * closes the current period and opens a fresh one on the new cycle — or\n * `changeNow` with the default `reconciliation: \"none\"` to keep the period\n * that is running. The engine's `message` says as much.\n *\n * An `InvalidRequestError` still, so an existing `catch` keeps working.\n */\nexport class CycleChangeRequiresResetError extends InvalidRequestError {}\nexport class RateLimitError extends APIError {\n /** Seconds to wait, from `Retry-After`, when the engine sends one. */\n readonly retryAfter: number | undefined\n\n constructor(\n args: ConstructorParameters<typeof APIError>[0] & {\n retryAfter?: number | undefined\n },\n ) {\n super(args)\n this.retryAfter = args.retryAfter\n }\n}\nexport class ServerError extends APIError {}\n\n// The request never produced an answer: DNS, TLS, a reset, an abort.\nexport class ConnectionError extends MeterbaseError {}\nexport class TimeoutError extends ConnectionError {}\n\nexport function errorFromResponse(args: {\n status: number\n code: string\n message: string\n requestId?: string | undefined\n retryAfter?: number | undefined\n body?: unknown\n}): APIError {\n switch (args.status) {\n case 401:\n return new AuthenticationError(args)\n case 403:\n return new PermissionDeniedError(args)\n case 404:\n return new NotFoundError(args)\n case 409:\n return new ConflictError(args)\n case 422:\n switch (args.code) {\n case \"cycle_change_requires_reset\":\n return new CycleChangeRequiresResetError(args)\n case \"invalid_idempotency_key\":\n return new InvalidIdempotencyKeyError(args)\n case \"too_late\":\n return new TooLateError(args)\n default:\n return new InvalidRequestError(args)\n }\n case 429:\n return new RateLimitError(args)\n default:\n return args.status >= 500 ? new ServerError(args) : new APIError(args)\n }\n}\n\n/** The engine carries it beside `code` and `message`, inside `error`. */\nfunction serverTime(body: unknown): Date | undefined {\n if (typeof body !== \"object\" || body === null) return undefined\n\n const error = (body as { error?: unknown }).error\n if (typeof error !== \"object\" || error === null) return undefined\n\n const at = (error as { server_time?: unknown }).server_time\n if (typeof at !== \"string\") return undefined\n\n const parsed = new Date(at)\n return Number.isNaN(parsed.getTime()) ? undefined : parsed\n}\n","// Everything goes through `request`, so authentication, timeouts, retries and\n// error mapping are defined once.\n\nimport {\n ConnectionError,\n errorFromResponse,\n MeterbaseError,\n TimeoutError,\n} from \"./errors.js\"\n\nexport type MeterbaseOptions = {\n /** A secret key. It names its own workspace. */\n apiKey: string\n /** Defaults to the hosted engine. */\n baseUrl?: string\n /** Per attempt, not per call. */\n timeout?: number\n maxRetries?: number\n fetch?: typeof globalThis.fetch\n}\n\nexport type RequestOptions = {\n signal?: AbortSignal\n timeout?: number\n maxRetries?: number\n}\n\ntype HttpMethod = \"GET\" | \"POST\" | \"PATCH\" | \"DELETE\"\n\ntype Request = RequestOptions & {\n method: HttpMethod\n path: string\n query?: Record<string, string | number | boolean | undefined>\n body?: unknown\n /**\n * Replay this call even though its method is not safe. Only a route that\n * carries an idempotency key may set it, and the key has to be fixed before\n * `request` is called — the loop re-sends one body, so a key generated\n * per attempt would count the same usage twice.\n */\n idempotent?: boolean\n}\n\nconst DEFAULT_BASE_URL = \"https://api.meterbase.tech\"\nconst DEFAULT_TIMEOUT = 10_000\nconst DEFAULT_MAX_RETRIES = 2\nconst MAX_BACKOFF = 8_000\n\nexport class Client {\n readonly #apiKey: string\n readonly #baseUrl: string\n readonly #timeout: number\n readonly #maxRetries: number\n readonly #fetch: typeof globalThis.fetch\n\n /**\n * How far the engine's clock is ahead of this machine's, in milliseconds.\n * Idempotency keys are minted here and the engine refuses one dated more\n * than an hour from its own clock, so without this a device with a wrong\n * clock would fail every call forever.\n */\n #clockOffset = 0\n\n /** The engine's clock, as well as this client knows it. */\n now(): number {\n return Date.now() + this.#clockOffset\n }\n\n /** Off by up to one round trip, which a window in hours does not notice. */\n observeServerTime(at: Date): void {\n this.#clockOffset = at.getTime() - Date.now()\n }\n\n constructor(options: MeterbaseOptions) {\n if (!options.apiKey) {\n throw new MeterbaseError(\n \"An API key is required: new Meterbase({ apiKey: 'mb_sk_live_…' }).\",\n )\n }\n\n this.#apiKey = options.apiKey\n this.#baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\\/+$/, \"\")\n this.#timeout = options.timeout ?? DEFAULT_TIMEOUT\n this.#maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES\n this.#fetch = options.fetch ?? globalThis.fetch\n\n if (typeof this.#fetch !== \"function\") {\n throw new MeterbaseError(\n \"No fetch implementation: pass one as `fetch`, or run on Node 18+.\",\n )\n }\n }\n\n async request<T>(req: Request): Promise<T> {\n const maxRetries = req.maxRetries ?? this.#maxRetries\n // Safe methods, plus the routes that carry an idempotency key and say so.\n // Any other POST or PATCH could create a second row on a replay.\n const retryable =\n req.method === \"GET\" || req.method === \"DELETE\" || req.idempotent === true\n\n let lastError: unknown\n for (let attempt = 0; attempt <= maxRetries; attempt++) {\n if (attempt > 0) await sleep(backoff(attempt, lastError))\n\n try {\n const response = await this.#send(req)\n\n if (response.ok) return (await parseBody(response)) as T\n\n const error = await errorFrom(response)\n if (retryable && attempt < maxRetries && shouldRetry(response.status)) {\n lastError = error\n continue\n }\n throw error\n } catch (cause) {\n if (\n cause instanceof MeterbaseError &&\n !(cause instanceof ConnectionError)\n ) {\n throw cause\n }\n // A connection failure proves nothing about whether the server acted,\n // so it is replayed under the same idempotency rule.\n if (!retryable || attempt >= maxRetries) throw cause\n lastError = cause\n }\n }\n\n /* c8 ignore next 2 -- the loop always returns or throws */\n throw lastError\n }\n\n async #send(req: Request): Promise<Response> {\n const url = new URL(this.#baseUrl + req.path)\n for (const [key, value] of Object.entries(req.query ?? {})) {\n if (value !== undefined) url.searchParams.set(key, String(value))\n }\n\n const headers: Record<string, string> = {\n authorization: `Bearer ${this.#apiKey}`,\n accept: \"application/json\",\n }\n if (req.body !== undefined) headers[\"content-type\"] = \"application/json\"\n\n const timeout = req.timeout ?? this.#timeout\n const controller = new AbortController()\n const onAbort = () => controller.abort(req.signal?.reason)\n req.signal?.addEventListener(\"abort\", onAbort, { once: true })\n\n let timedOut = false\n const timer = setTimeout(() => {\n timedOut = true\n controller.abort()\n }, timeout)\n\n try {\n return await this.#fetch(url, {\n method: req.method,\n headers,\n body: req.body === undefined ? undefined : JSON.stringify(req.body),\n signal: controller.signal,\n })\n } catch (cause) {\n if (timedOut) {\n throw new TimeoutError(`Request timed out after ${timeout}ms.`, {\n cause,\n })\n }\n // A caller's own abort is theirs to handle, not ours to reclassify.\n if (req.signal?.aborted) throw cause\n throw new ConnectionError(`Could not reach ${url.origin}.`, { cause })\n } finally {\n clearTimeout(timer)\n req.signal?.removeEventListener(\"abort\", onAbort)\n }\n }\n}\n\nfunction shouldRetry(status: number): boolean {\n return status === 408 || status === 429 || status >= 500\n}\n\n/** Exponential backoff with full jitter, unless the engine named a delay. */\nfunction backoff(attempt: number, lastError: unknown): number {\n const retryAfter =\n lastError && typeof lastError === \"object\" && \"retryAfter\" in lastError\n ? (lastError as { retryAfter?: number }).retryAfter\n : undefined\n if (retryAfter !== undefined) return Math.min(retryAfter * 1000, MAX_BACKOFF)\n\n const ceiling = Math.min(500 * 2 ** (attempt - 1), MAX_BACKOFF)\n return Math.random() * ceiling\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n\nasync function parseBody(response: Response): Promise<unknown> {\n if (response.status === 204) return undefined\n\n const text = await response.text()\n if (text === \"\") return undefined\n\n try {\n return JSON.parse(text)\n } catch (cause) {\n throw new MeterbaseError(\"The engine returned a body that is not JSON.\", {\n cause,\n })\n }\n}\n\nasync function errorFrom(response: Response) {\n const body = await response.text()\n const parsed = parseErrorBody(body)\n const retryAfterHeader = response.headers.get(\"retry-after\")\n const retryAfter = retryAfterHeader ? Number(retryAfterHeader) : undefined\n\n return errorFromResponse({\n status: response.status,\n code: parsed?.code ?? `http_${response.status}`,\n message: parsed?.message ?? `The engine responded ${response.status}.`,\n requestId: response.headers.get(\"x-request-id\") ?? undefined,\n retryAfter:\n retryAfter !== undefined && Number.isFinite(retryAfter)\n ? retryAfter\n : undefined,\n body: body === \"\" ? undefined : (safeParse(body) ?? body),\n })\n}\n\nfunction parseErrorBody(body: string) {\n const parsed = safeParse(body) as\n { error?: { code?: string; message?: string } } | undefined\n const error = parsed?.error\n if (!error?.code || !error.message) return undefined\n\n return { code: error.code, message: error.message }\n}\n\nfunction safeParse(body: string): unknown {\n try {\n return JSON.parse(body)\n } catch {\n return undefined\n }\n}\n","import type { Client, RequestOptions } from \"../client.js\"\nimport type {\n Allowance,\n AllowanceGrantParams,\n AllowanceListParams,\n List,\n} from \"../types.js\"\n\n/**\n * Capacity handed to one customer on top of their plan. A grant with\n * `source: \"plan\"` is the engine's own, minted when a plan is assigned, and\n * cannot be created here.\n */\nexport class CustomerAllowances {\n readonly #client: Client\n\n constructor(client: Client) {\n this.#client = client\n }\n\n grant(\n customerId: string,\n params: AllowanceGrantParams,\n options?: RequestOptions,\n ): Promise<Allowance> {\n return this.#client.request({\n ...options,\n method: \"POST\",\n path: `/v1/customers/${encodeURIComponent(customerId)}/allowances`,\n body: params,\n })\n }\n\n /** Open grants only, unless `include_closed`. */\n list(\n customerId: string,\n params: AllowanceListParams = {},\n options?: RequestOptions,\n ): Promise<List<Allowance>> {\n return this.#client.request({\n ...options,\n method: \"GET\",\n path: `/v1/customers/${encodeURIComponent(customerId)}/allowances`,\n query: {\n meter_id: params.meter_id,\n include_closed: params.include_closed,\n },\n })\n }\n\n retrieve(\n customerId: string,\n allowanceId: string,\n options?: RequestOptions,\n ): Promise<Allowance> {\n return this.#client.request({\n ...options,\n method: \"GET\",\n path: `/v1/customers/${encodeURIComponent(customerId)}/allowances/${encodeURIComponent(allowanceId)}`,\n })\n }\n\n /** Withdraws what is left without erasing what was consumed. Idempotent. */\n revoke(\n customerId: string,\n allowanceId: string,\n options?: RequestOptions,\n ): Promise<Allowance> {\n return this.#client.request({\n ...options,\n method: \"DELETE\",\n path: `/v1/customers/${encodeURIComponent(customerId)}/allowances/${encodeURIComponent(allowanceId)}`,\n })\n }\n}\n","import type { Client, RequestOptions } from \"../client.js\"\nimport type {\n AssignPlanParams,\n Assignment,\n List,\n PlanChangeNowParams,\n PlanChangeParams,\n PlanMoveParams,\n} from \"../types.js\"\nimport { NotFoundError } from \"../errors.js\"\n\n/**\n * Which plan a customer holds. The history is append-only: there is no patch\n * and no delete, and moving a customer to a different plan is the same call as\n * their first.\n *\n * `assign` is that call, mirroring the wire. The rest name the four moves a\n * caller actually makes — later, now, now-and-start-over, and never mind — so\n * that picking one does not mean knowing what `effective` and `reconciliation`\n * do to a half-used period.\n */\nexport class CustomerPlan {\n readonly #client: Client\n\n constructor(client: Client) {\n this.#client = client\n }\n\n /**\n * Put a customer on a plan. This is the wire call, and the only one that\n * takes `cycle_anchor` — a first assignment's one chance to put their\n * periods on a date they already have.\n *\n * Returns the instruction as recorded, which is not always as asked: a first\n * plan is recorded `immediate` whatever `effective` said.\n */\n assign(\n customerId: string,\n params: AssignPlanParams,\n options?: RequestOptions,\n ): Promise<Assignment> {\n return this.#client.request({\n ...options,\n method: \"POST\",\n path: `/v1/customers/${encodeURIComponent(customerId)}/plan`,\n body: params,\n })\n }\n\n /**\n * Move a customer to a different plan, with both knobs in the open.\n * `effective` defaults to `next_cycle`; `reconciliation` applies only to an\n * `immediate` change and defaults to `none`.\n *\n * Reach for `changeAtNextCycle`, `changeNow` or `restart` when one of them\n * says what you mean — this is the form to fall back to when the two are\n * chosen at runtime.\n */\n change(\n customerId: string,\n params: PlanChangeParams,\n options?: RequestOptions,\n ): Promise<Assignment> {\n const { plan, ...rest } = params\n\n return this.assign(customerId, { plan_id: plan, ...rest }, options)\n }\n\n /**\n * Schedule the move for the end of the period they are in: they keep the\n * plan they are paying for until it runs out, and the new one starts at\n * their next boundary. Nothing is pro-rated, because nothing is split.\n *\n * Two plans on different cycles share no boundary, and this answers\n * `CycleChangeRequiresResetError` — use `restart` for that move.\n */\n changeAtNextCycle(\n customerId: string,\n params: PlanMoveParams,\n options?: RequestOptions,\n ): Promise<Assignment> {\n return this.change(\n customerId,\n { plan: params.plan, effective: \"next_cycle\" },\n options,\n )\n }\n\n /**\n * Move them now, inside the period already running. Their renewal day does\n * not move; what changes is this period's cap, and `reconciliation` says\n * how:\n *\n * - `none` (the default) — the new plan's amount governs the whole period.\n * Usage already spent still counts, so a downgrade can deny until the\n * period ends.\n * - `prorate` — each plan's amount weighted by the fraction of the period it\n * was held for. Refused between plans on different cycles, which share no\n * period to weight.\n *\n * To have the period itself start over instead, use `restart`.\n */\n changeNow(\n customerId: string,\n params: PlanChangeNowParams,\n options?: RequestOptions,\n ): Promise<Assignment> {\n return this.change(\n customerId,\n { ...params, effective: \"immediate\" },\n options,\n )\n }\n\n /**\n * Move them now and start a fresh period today: the period they were in\n * closes where the change lands, keeping the usage it had, and the new\n * plan's full amount opens immediately.\n *\n * This moves the customer's anchor, so their renewal day becomes today. It\n * is the move for a customer starting over — a new contract, a re-signup —\n * and the only one that can take a customer between plans whose cycles\n * differ.\n */\n restart(\n customerId: string,\n params: PlanMoveParams,\n options?: RequestOptions,\n ): Promise<Assignment> {\n return this.change(\n customerId,\n { plan: params.plan, effective: \"immediate\", reconciliation: \"reset\" },\n options,\n )\n }\n\n /**\n * Call off a change that has not landed yet, leaving the customer on the\n * plan they hold. Naming the plan already held is what supersedes a pending\n * instruction, so this reads the plan in force and names it back.\n *\n * Returns the assignment still in force, or `null` for a customer holding no\n * plan — who can have nothing pending, since a first assignment always lands\n * at once.\n */\n async cancelScheduledChange(\n customerId: string,\n options?: RequestOptions,\n ): Promise<Assignment | null> {\n const current = await this.retrieve(customerId, options)\n if (current === null) return null\n\n return this.assign(customerId, { plan_id: current.plan_id }, options)\n }\n\n /**\n * The plan in force now, which is not always the newest instruction: a\n * change dated ahead does not govern yet.\n *\n * `null` when the customer holds no plan. That is a default deny rather than\n * a failure — they are entitled to nothing — so it is an answer here and not\n * a thrown `NotFoundError`. A customer who does not exist at all still\n * throws one.\n */\n async retrieve(\n customerId: string,\n options?: RequestOptions,\n ): Promise<Assignment | null> {\n try {\n return await this.#client.request<Assignment>({\n ...options,\n method: \"GET\",\n path: `/v1/customers/${encodeURIComponent(customerId)}/plan`,\n })\n } catch (error) {\n if (error instanceof NotFoundError && error.code === \"no_plan_assigned\") {\n return null\n }\n throw error\n }\n }\n\n /**\n * The change waiting to land, or `null` when none is. At most one is ever\n * live: a newer instruction supersedes the one before it.\n *\n * Read against the assignment in force rather than against the local clock,\n * so a change landing seconds from now is not reported as already governing.\n */\n async pending(\n customerId: string,\n options?: RequestOptions,\n ): Promise<Assignment | null> {\n const [current, { data }] = await Promise.all([\n this.retrieve(customerId, options),\n this.history(customerId, options),\n ])\n\n const inForce =\n current === null ? -Infinity : Date.parse(current.effective_at)\n\n return (\n data.find(\n (a) => a.superseded_at === null && Date.parse(a.effective_at) > inForce,\n ) ?? null\n )\n }\n\n /** Every instruction, superseded ones included: it is the whole trail. */\n history(\n customerId: string,\n options?: RequestOptions,\n ): Promise<List<Assignment>> {\n return this.#client.request({\n ...options,\n method: \"GET\",\n path: `/v1/customers/${encodeURIComponent(customerId)}/plan/history`,\n })\n }\n}\n","import type { Client, RequestOptions } from \"../client.js\"\nimport type {\n Customer,\n CustomerCreateParams,\n CustomerListParams,\n CustomerUpdateParams,\n CustomerWithPlan,\n List,\n} from \"../types.js\"\nimport { CustomerAllowances } from \"./customer-allowances.js\"\nimport { CustomerPlan } from \"./customer-plan.js\"\n\nexport class Customers {\n /** The plan they hold, and the trail of instructions that got them there. */\n readonly plan: CustomerPlan\n /** Grants, which sit on top of whatever the plan gives. */\n readonly allowances: CustomerAllowances\n\n readonly #client: Client\n\n constructor(client: Client) {\n this.#client = client\n this.plan = new CustomerPlan(client)\n this.allowances = new CustomerAllowances(client)\n }\n\n create(\n params: CustomerCreateParams,\n options?: RequestOptions,\n ): Promise<Customer> {\n return this.#client.request({\n ...options,\n method: \"POST\",\n path: \"/v1/customers\",\n body: params,\n })\n }\n\n /** Lean: a listing does not embed the plan. Read one customer for that. */\n list(\n params: CustomerListParams = {},\n options?: RequestOptions,\n ): Promise<List<Customer>> {\n return this.#client.request({\n ...options,\n method: \"GET\",\n path: \"/v1/customers\",\n query: { include_deleted: params.include_deleted },\n })\n }\n\n /**\n * One customer, with the plan they hold. `plan` is the one in force now and\n * `pending_plan` the change waiting to land, each `null` when there is\n * none — so knowing what a customer is on costs no second request.\n */\n retrieve(id: string, options?: RequestOptions): Promise<CustomerWithPlan> {\n return this.#client.request({\n ...options,\n method: \"GET\",\n path: `/v1/customers/${encodeURIComponent(id)}`,\n })\n }\n\n /**\n * Resolves the tenant's own identifier, or null, embedding the plan the way\n * `retrieve` does. The engine answers this as a filtered list, so a miss is\n * an empty collection rather than a 404.\n */\n async retrieveByExternalId(\n externalId: string,\n options?: RequestOptions,\n ): Promise<CustomerWithPlan | null> {\n const { data } = await this.#client.request<List<CustomerWithPlan>>({\n ...options,\n method: \"GET\",\n path: \"/v1/customers\",\n query: { external_id: externalId },\n })\n\n return data[0] ?? null\n }\n\n update(\n id: string,\n params: CustomerUpdateParams,\n options?: RequestOptions,\n ): Promise<Customer> {\n return this.#client.request({\n ...options,\n method: \"PATCH\",\n path: `/v1/customers/${encodeURIComponent(id)}`,\n body: params,\n })\n }\n\n /** Soft delete: usage and assignments keep referencing the customer. */\n delete(id: string, options?: RequestOptions): Promise<Customer> {\n return this.#client.request({\n ...options,\n method: \"DELETE\",\n path: `/v1/customers/${encodeURIComponent(id)}`,\n })\n }\n}\n","import type { Client, RequestOptions } from \"../client.js\"\nimport type {\n List,\n Meter,\n MeterCreateParams,\n MeterListParams,\n MeterUpdateParams,\n} from \"../types.js\"\n\nexport class Meters {\n readonly #client: Client\n\n constructor(client: Client) {\n this.#client = client\n }\n\n create(params: MeterCreateParams, options?: RequestOptions): Promise<Meter> {\n return this.#client.request({\n ...options,\n method: \"POST\",\n path: \"/v1/meters\",\n body: params,\n })\n }\n\n list(\n params: MeterListParams = {},\n options?: RequestOptions,\n ): Promise<List<Meter>> {\n return this.#client.request({\n ...options,\n method: \"GET\",\n path: \"/v1/meters\",\n query: { include_archived: params.include_archived },\n })\n }\n\n retrieve(id: string, options?: RequestOptions): Promise<Meter> {\n return this.#client.request({\n ...options,\n method: \"GET\",\n path: `/v1/meters/${encodeURIComponent(id)}`,\n })\n }\n\n update(\n id: string,\n params: MeterUpdateParams,\n options?: RequestOptions,\n ): Promise<Meter> {\n return this.#client.request({\n ...options,\n method: \"PATCH\",\n path: `/v1/meters/${encodeURIComponent(id)}`,\n body: params,\n })\n }\n\n /** Soft delete: plans and usage keep referencing the meter. Idempotent. */\n archive(id: string, options?: RequestOptions): Promise<Meter> {\n return this.#client.request({\n ...options,\n method: \"DELETE\",\n path: `/v1/meters/${encodeURIComponent(id)}`,\n })\n }\n}\n","import type { Client, RequestOptions } from \"../client.js\"\nimport type {\n List,\n Plan,\n PlanAllowance,\n PlanAllowanceListParams,\n PlanAllowanceSetParams,\n PlanCreateParams,\n PlanListParams,\n PlanUpdateParams,\n} from \"../types.js\"\n\n/**\n * A plan's entitlement, versioned. There is no update and no delete: an edit\n * appends the next version, so which amount applied when stays derivable.\n */\nexport class PlanAllowances {\n readonly #client: Client\n\n constructor(client: Client) {\n this.#client = client\n }\n\n set(\n planId: string,\n params: PlanAllowanceSetParams,\n options?: RequestOptions,\n ): Promise<PlanAllowance> {\n return this.#client.request({\n ...options,\n method: \"POST\",\n path: `/v1/plans/${encodeURIComponent(planId)}/allowances`,\n body: params,\n })\n }\n\n /** Every version of every meter, newest first — history, not just current. */\n list(\n planId: string,\n params: PlanAllowanceListParams = {},\n options?: RequestOptions,\n ): Promise<List<PlanAllowance>> {\n return this.#client.request({\n ...options,\n method: \"GET\",\n path: `/v1/plans/${encodeURIComponent(planId)}/allowances`,\n query: { meter_id: params.meter_id },\n })\n }\n}\n\nexport class Plans {\n readonly allowances: PlanAllowances\n\n readonly #client: Client\n\n constructor(client: Client) {\n this.#client = client\n this.allowances = new PlanAllowances(client)\n }\n\n /** A new plan grants nothing; attach entitlement with `allowances.set`. */\n create(params: PlanCreateParams, options?: RequestOptions): Promise<Plan> {\n return this.#client.request({\n ...options,\n method: \"POST\",\n path: \"/v1/plans\",\n body: params,\n })\n }\n\n list(\n params: PlanListParams = {},\n options?: RequestOptions,\n ): Promise<List<Plan>> {\n return this.#client.request({\n ...options,\n method: \"GET\",\n path: \"/v1/plans\",\n query: { include_archived: params.include_archived },\n })\n }\n\n retrieve(id: string, options?: RequestOptions): Promise<Plan> {\n return this.#client.request({\n ...options,\n method: \"GET\",\n path: `/v1/plans/${encodeURIComponent(id)}`,\n })\n }\n\n update(\n id: string,\n params: PlanUpdateParams,\n options?: RequestOptions,\n ): Promise<Plan> {\n return this.#client.request({\n ...options,\n method: \"PATCH\",\n path: `/v1/plans/${encodeURIComponent(id)}`,\n body: params,\n })\n }\n\n /**\n * Stops new assignments without withdrawing capacity from anyone already on\n * the plan, which is why an archived plan still resolves by id. Idempotent.\n */\n archive(id: string, options?: RequestOptions): Promise<Plan> {\n return this.#client.request({\n ...options,\n method: \"DELETE\",\n path: `/v1/plans/${encodeURIComponent(id)}`,\n })\n }\n}\n","import { Client, type MeterbaseOptions, type RequestOptions } from \"./client.js\"\nimport { MeterbaseError, TooLateError } from \"./errors.js\"\nimport type { CustomerAllowances as CustomerAllowancesResource } from \"./resources/customer-allowances.js\"\nimport type { CustomerPlan as CustomerPlanResource } from \"./resources/customer-plan.js\"\nimport { Customers as CustomersResource } from \"./resources/customers.js\"\nimport { Meters as MetersResource } from \"./resources/meters.js\"\nimport {\n Plans as PlansResource,\n type PlanAllowances as PlanAllowancesResource,\n} from \"./resources/plans.js\"\nimport type {\n CheckParams,\n CheckResult,\n TrackParams,\n TrackResult,\n WhoAmI,\n} from \"./types.js\"\n\nexport class Meterbase {\n readonly customers: Customers\n readonly meters: Meters\n readonly plans: Plans\n\n readonly #client: Client\n\n constructor(options: MeterbaseOptions) {\n this.#client = new Client(options)\n this.customers = new CustomersResource(this.#client)\n this.meters = new MetersResource(this.#client)\n this.plans = new PlansResource(this.#client)\n }\n\n /**\n * Asks whether a customer may consume `quantity` of a meter, named by the\n * tenant's own external id and the meter's key. Absence of entitlement is\n * not permission: a customer with no plan and no grant is denied.\n *\n * This is the gate, and the only call that ever refuses. Run it before the\n * work; record the work with `track` afterwards.\n *\n * Two gates answer it, and `allowed` needs both: the customer's capacity has\n * to cover the quantity, and every rate-limit window in force has to admit\n * it. `reason` names the one that said no. `rate_limits` reports each window\n * whether or not it refused, so a caller can ease off as its headroom closes\n * instead of discovering the ceiling by hitting it.\n */\n check(params: CheckParams, options?: RequestOptions): Promise<CheckResult> {\n return this.#client.request({\n ...options,\n method: \"POST\",\n path: \"/v1/check\",\n body: params,\n })\n }\n\n /**\n * Records usage that already happened — the tokens were spent, the image\n * was generated — so it never refuses on capacity. A quantity beyond the\n * customer's capacity is recorded, drives `available` to 0, and the next\n * `check` says no. The answer is a receipt, not a verdict.\n *\n * `idempotency_key` is a UUIDv7, generated when omitted, so retrying this\n * call — the SDK's own retries included — replays the original rather than\n * counting the same work twice. The engine keeps that claim for an hour,\n * which is how long a retry stays recognisable.\n */\n // `async` so that generating the key cannot throw synchronously out of a\n // method that otherwise only ever rejects: one call, one way to fail.\n async track(\n params: TrackParams,\n options?: RequestOptions,\n ): Promise<TrackResult> {\n const send = (key: string) =>\n this.#client.request<TrackResult>({\n ...options,\n method: \"POST\",\n path: \"/v1/usage/track\",\n // Fixed before the retry loop is entered: every attempt of this call\n // carries the same key, which is what makes replaying it safe.\n body: { ...params, idempotency_key: key },\n idempotent: true,\n })\n\n if (params.idempotency_key !== undefined) {\n // The caller's key, so the caller's problem if it is out of the window:\n // this cannot know whether it names work already recorded, and minting\n // a replacement could count that work twice.\n return send(params.idempotency_key)\n }\n\n const key = idempotencyKey(this.#client.now())\n const startedAt = Date.now()\n\n try {\n return await send(key)\n } catch (error) {\n // The only failure this can fix by itself: a clock that disagrees with\n // the engine's.\n if (!(error instanceof TooLateError) || error.serverTime === undefined) {\n throw error\n }\n\n // Re-minting is safe only if no attempt under the old key can have\n // landed. `send` retries internally, so this 422 may have come from a\n // later attempt while an earlier one succeeded. If the key was already\n // outside the window when the call began, every attempt was refused.\n const elapsed = Date.now() - startedAt\n const serverAtStart = error.serverTime.getTime() - elapsed\n if (Math.abs(serverAtStart - mintedAtMs(key)) <= IDEMPOTENCY_WINDOW_MS) {\n throw error\n }\n\n this.#client.observeServerTime(error.serverTime)\n\n return await send(idempotencyKey(this.#client.now()))\n }\n }\n\n /** Reports which workspace this key acts for. */\n whoami(options?: RequestOptions): Promise<WhoAmI> {\n return this.#client.request({\n ...options,\n method: \"GET\",\n path: \"/v1/whoami\",\n })\n }\n}\n\n/**\n * The resource namespaces, type-only: none is constructible without the\n * unexported Client. Instance types rather than `export type { Customers }`,\n * which the declaration bundler re-emits as a value export — promising a\n * runtime binding the bundle never has.\n */\nexport type CustomerAllowances = InstanceType<typeof CustomerAllowancesResource>\nexport type CustomerPlan = InstanceType<typeof CustomerPlanResource>\nexport type Customers = InstanceType<typeof CustomersResource>\nexport type Meters = InstanceType<typeof MetersResource>\nexport type PlanAllowances = InstanceType<typeof PlanAllowancesResource>\nexport type Plans = InstanceType<typeof PlansResource>\nexport type { MeterbaseOptions, RequestOptions }\nexport * from \"./errors.js\"\nexport type * from \"./types.js\"\n\n/**\n * A UUIDv7: 48 bits of Unix milliseconds, then the version and variant, then\n * 74 random bits. `crypto.randomUUID()` mints a v4, which carries no time, so\n * this builds one from random bytes.\n *\n * `atMs` is the engine's clock as the client knows it, not this machine's: a\n * device an hour out would otherwise mint keys the engine refuses.\n */\n/** How far the engine lets a key's timestamp sit from its own clock. */\nconst IDEMPOTENCY_WINDOW_MS = 60 * 60 * 1000\n\n/** The millisecond a v7 carries in its first 48 bits. */\nfunction mintedAtMs(key: string): number {\n return Number.parseInt(key.replace(/-/g, \"\").slice(0, 12), 16)\n}\n\nfunction idempotencyKey(atMs: number): string {\n // Structurally, not as `Crypto`: that lib type is the DOM's, and this\n // compiles without it so the SDK stays as portable as `fetch` is.\n const webcrypto = globalThis.crypto as\n | { getRandomValues?: (array: Uint8Array) => Uint8Array }\n | undefined\n\n if (typeof webcrypto?.getRandomValues !== \"function\") {\n throw new MeterbaseError(\n \"No crypto to generate an idempotency key with: pass `idempotency_key` \" +\n \"yourself (a UUIDv7), or run somewhere `crypto.getRandomValues` exists.\",\n )\n }\n\n const bytes = webcrypto.getRandomValues(new Uint8Array(16))\n\n // Big-endian ms in the first six bytes, split in two so the arithmetic\n // stays 32-bit safe without BigInt.\n const ms = Math.max(0, Math.trunc(atMs))\n const high = Math.floor(ms / 0x1_0000_0000) // the top 16 bits of 48\n const low = ms >>> 0 // the bottom 32\n bytes[0] = (high >>> 8) & 0xff\n bytes[1] = high & 0xff\n bytes[2] = (low >>> 24) & 0xff\n bytes[3] = (low >>> 16) & 0xff\n bytes[4] = (low >>> 8) & 0xff\n bytes[5] = low & 0xff\n\n bytes[6] = (bytes[6]! & 0x0f) | 0x70 // version 7\n bytes[8] = (bytes[8]! & 0x3f) | 0x80 // variant 10\n\n const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, \"0\")).join(\"\")\n\n return [\n hex.slice(0, 8),\n hex.slice(8, 12),\n hex.slice(12, 16),\n hex.slice(16, 20),\n hex.slice(20),\n ].join(\"-\")\n}\n"]}
|