mbase-sdk 0.0.2

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/dist/index.cjs ADDED
@@ -0,0 +1,714 @@
1
+ 'use strict';
2
+
3
+ // src/errors.ts
4
+ var MeterbaseError = class extends Error {
5
+ constructor(message, options) {
6
+ super(message, options);
7
+ this.name = new.target.name;
8
+ }
9
+ };
10
+ var APIError = class extends MeterbaseError {
11
+ status;
12
+ code;
13
+ /** From `X-Request-Id`, when the engine sends one. */
14
+ requestId;
15
+ body;
16
+ constructor(args) {
17
+ super(args.message);
18
+ this.status = args.status;
19
+ this.code = args.code;
20
+ this.requestId = args.requestId;
21
+ this.body = args.body;
22
+ }
23
+ };
24
+ var AuthenticationError = class extends APIError {
25
+ };
26
+ var PermissionDeniedError = class extends APIError {
27
+ };
28
+ var NotFoundError = class extends APIError {
29
+ };
30
+ var ConflictError = class extends APIError {
31
+ };
32
+ var IdempotencyConflictError = class extends ConflictError {
33
+ /** The event that key already recorded. Undefined only if the engine sent a
34
+ * body this could not be read out of. */
35
+ existingEventId;
36
+ constructor(args) {
37
+ super(args);
38
+ this.existingEventId = existingEventId(args.body);
39
+ }
40
+ };
41
+ var InvalidRequestError = class extends APIError {
42
+ };
43
+ var CycleChangeRequiresResetError = class extends InvalidRequestError {
44
+ };
45
+ var RateLimitError = class extends APIError {
46
+ /** Seconds to wait, from `Retry-After`, when the engine sends one. */
47
+ retryAfter;
48
+ constructor(args) {
49
+ super(args);
50
+ this.retryAfter = args.retryAfter;
51
+ }
52
+ };
53
+ var ServerError = class extends APIError {
54
+ };
55
+ var ConnectionError = class extends MeterbaseError {
56
+ };
57
+ var TimeoutError = class extends ConnectionError {
58
+ };
59
+ function errorFromResponse(args) {
60
+ switch (args.status) {
61
+ case 401:
62
+ return new AuthenticationError(args);
63
+ case 403:
64
+ return new PermissionDeniedError(args);
65
+ case 404:
66
+ return new NotFoundError(args);
67
+ case 409:
68
+ return args.code === "idempotency_conflict" ? new IdempotencyConflictError(args) : new ConflictError(args);
69
+ case 422:
70
+ return args.code === "cycle_change_requires_reset" ? new CycleChangeRequiresResetError(args) : new InvalidRequestError(args);
71
+ case 429:
72
+ return new RateLimitError(args);
73
+ default:
74
+ return args.status >= 500 ? new ServerError(args) : new APIError(args);
75
+ }
76
+ }
77
+ function existingEventId(body) {
78
+ if (typeof body !== "object" || body === null) return void 0;
79
+ const error = body.error;
80
+ if (typeof error !== "object" || error === null) return void 0;
81
+ const id = error.existing_event_id;
82
+ return typeof id === "string" ? id : void 0;
83
+ }
84
+
85
+ // src/client.ts
86
+ var DEFAULT_BASE_URL = "https://api.meterbase.tech";
87
+ var DEFAULT_TIMEOUT = 1e4;
88
+ var DEFAULT_MAX_RETRIES = 2;
89
+ var MAX_BACKOFF = 8e3;
90
+ var Client = class {
91
+ #apiKey;
92
+ #baseUrl;
93
+ #timeout;
94
+ #maxRetries;
95
+ #fetch;
96
+ constructor(options) {
97
+ if (!options.apiKey) {
98
+ throw new MeterbaseError(
99
+ "An API key is required: new Meterbase({ apiKey: 'mb_sk_live_\u2026' })."
100
+ );
101
+ }
102
+ this.#apiKey = options.apiKey;
103
+ this.#baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
104
+ this.#timeout = options.timeout ?? DEFAULT_TIMEOUT;
105
+ this.#maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES;
106
+ this.#fetch = options.fetch ?? globalThis.fetch;
107
+ if (typeof this.#fetch !== "function") {
108
+ throw new MeterbaseError(
109
+ "No fetch implementation: pass one as `fetch`, or run on Node 18+."
110
+ );
111
+ }
112
+ }
113
+ async request(req) {
114
+ const maxRetries = req.maxRetries ?? this.#maxRetries;
115
+ const retryable = req.method === "GET" || req.method === "DELETE" || req.idempotent === true;
116
+ let lastError;
117
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
118
+ if (attempt > 0) await sleep(backoff(attempt, lastError));
119
+ try {
120
+ const response = await this.#send(req);
121
+ if (response.ok) return await parseBody(response);
122
+ const error = await errorFrom(response);
123
+ if (retryable && attempt < maxRetries && shouldRetry(response.status)) {
124
+ lastError = error;
125
+ continue;
126
+ }
127
+ throw error;
128
+ } catch (cause) {
129
+ if (cause instanceof MeterbaseError && !(cause instanceof ConnectionError)) {
130
+ throw cause;
131
+ }
132
+ if (!retryable || attempt >= maxRetries) throw cause;
133
+ lastError = cause;
134
+ }
135
+ }
136
+ throw lastError;
137
+ }
138
+ async #send(req) {
139
+ const url = new URL(this.#baseUrl + req.path);
140
+ for (const [key, value] of Object.entries(req.query ?? {})) {
141
+ if (value !== void 0) url.searchParams.set(key, String(value));
142
+ }
143
+ const headers = {
144
+ authorization: `Bearer ${this.#apiKey}`,
145
+ accept: "application/json"
146
+ };
147
+ if (req.body !== void 0) headers["content-type"] = "application/json";
148
+ const timeout = req.timeout ?? this.#timeout;
149
+ const controller = new AbortController();
150
+ const onAbort = () => controller.abort(req.signal?.reason);
151
+ req.signal?.addEventListener("abort", onAbort, { once: true });
152
+ let timedOut = false;
153
+ const timer = setTimeout(() => {
154
+ timedOut = true;
155
+ controller.abort();
156
+ }, timeout);
157
+ try {
158
+ return await this.#fetch(url, {
159
+ method: req.method,
160
+ headers,
161
+ body: req.body === void 0 ? void 0 : JSON.stringify(req.body),
162
+ signal: controller.signal
163
+ });
164
+ } catch (cause) {
165
+ if (timedOut) {
166
+ throw new TimeoutError(`Request timed out after ${timeout}ms.`, {
167
+ cause
168
+ });
169
+ }
170
+ if (req.signal?.aborted) throw cause;
171
+ throw new ConnectionError(`Could not reach ${url.origin}.`, { cause });
172
+ } finally {
173
+ clearTimeout(timer);
174
+ req.signal?.removeEventListener("abort", onAbort);
175
+ }
176
+ }
177
+ };
178
+ function shouldRetry(status) {
179
+ return status === 408 || status === 429 || status >= 500;
180
+ }
181
+ function backoff(attempt, lastError) {
182
+ const retryAfter = lastError && typeof lastError === "object" && "retryAfter" in lastError ? lastError.retryAfter : void 0;
183
+ if (retryAfter !== void 0) return Math.min(retryAfter * 1e3, MAX_BACKOFF);
184
+ const ceiling = Math.min(500 * 2 ** (attempt - 1), MAX_BACKOFF);
185
+ return Math.random() * ceiling;
186
+ }
187
+ function sleep(ms) {
188
+ return new Promise((resolve) => setTimeout(resolve, ms));
189
+ }
190
+ async function parseBody(response) {
191
+ if (response.status === 204) return void 0;
192
+ const text = await response.text();
193
+ if (text === "") return void 0;
194
+ try {
195
+ return JSON.parse(text);
196
+ } catch (cause) {
197
+ throw new MeterbaseError("The engine returned a body that is not JSON.", {
198
+ cause
199
+ });
200
+ }
201
+ }
202
+ async function errorFrom(response) {
203
+ const body = await response.text();
204
+ const parsed = parseErrorBody(body);
205
+ const retryAfterHeader = response.headers.get("retry-after");
206
+ const retryAfter = retryAfterHeader ? Number(retryAfterHeader) : void 0;
207
+ return errorFromResponse({
208
+ status: response.status,
209
+ code: parsed?.code ?? `http_${response.status}`,
210
+ message: parsed?.message ?? `The engine responded ${response.status}.`,
211
+ requestId: response.headers.get("x-request-id") ?? void 0,
212
+ retryAfter: retryAfter !== void 0 && Number.isFinite(retryAfter) ? retryAfter : void 0,
213
+ body: body === "" ? void 0 : safeParse(body) ?? body
214
+ });
215
+ }
216
+ function parseErrorBody(body) {
217
+ const parsed = safeParse(body);
218
+ const error = parsed?.error;
219
+ if (!error?.code || !error.message) return void 0;
220
+ return { code: error.code, message: error.message };
221
+ }
222
+ function safeParse(body) {
223
+ try {
224
+ return JSON.parse(body);
225
+ } catch {
226
+ return void 0;
227
+ }
228
+ }
229
+
230
+ // src/resources/customer-allowances.ts
231
+ var CustomerAllowances = class {
232
+ #client;
233
+ constructor(client) {
234
+ this.#client = client;
235
+ }
236
+ grant(customerId, params, options) {
237
+ return this.#client.request({
238
+ ...options,
239
+ method: "POST",
240
+ path: `/v1/customers/${encodeURIComponent(customerId)}/allowances`,
241
+ body: params
242
+ });
243
+ }
244
+ /** Open grants only, unless `include_closed`. */
245
+ list(customerId, params = {}, options) {
246
+ return this.#client.request({
247
+ ...options,
248
+ method: "GET",
249
+ path: `/v1/customers/${encodeURIComponent(customerId)}/allowances`,
250
+ query: {
251
+ meter_id: params.meter_id,
252
+ include_closed: params.include_closed
253
+ }
254
+ });
255
+ }
256
+ retrieve(customerId, allowanceId, options) {
257
+ return this.#client.request({
258
+ ...options,
259
+ method: "GET",
260
+ path: `/v1/customers/${encodeURIComponent(customerId)}/allowances/${encodeURIComponent(allowanceId)}`
261
+ });
262
+ }
263
+ /** Withdraws what is left without erasing what was consumed. Idempotent. */
264
+ revoke(customerId, allowanceId, options) {
265
+ return this.#client.request({
266
+ ...options,
267
+ method: "DELETE",
268
+ path: `/v1/customers/${encodeURIComponent(customerId)}/allowances/${encodeURIComponent(allowanceId)}`
269
+ });
270
+ }
271
+ };
272
+
273
+ // src/resources/customer-plan.ts
274
+ var CustomerPlan = class {
275
+ #client;
276
+ constructor(client) {
277
+ this.#client = client;
278
+ }
279
+ /**
280
+ * Put a customer on a plan. This is the wire call, and the only one that
281
+ * takes `cycle_anchor` — a first assignment's one chance to put their
282
+ * periods on a date they already have.
283
+ *
284
+ * Returns the instruction as recorded, which is not always as asked: a first
285
+ * plan is recorded `immediate` whatever `effective` said.
286
+ */
287
+ assign(customerId, params, options) {
288
+ return this.#client.request({
289
+ ...options,
290
+ method: "POST",
291
+ path: `/v1/customers/${encodeURIComponent(customerId)}/plan`,
292
+ body: params
293
+ });
294
+ }
295
+ /**
296
+ * Move a customer to a different plan, with both knobs in the open.
297
+ * `effective` defaults to `next_cycle`; `reconciliation` applies only to an
298
+ * `immediate` change and defaults to `none`.
299
+ *
300
+ * Reach for `changeAtNextCycle`, `changeNow` or `restart` when one of them
301
+ * says what you mean — this is the form to fall back to when the two are
302
+ * chosen at runtime.
303
+ */
304
+ change(customerId, params, options) {
305
+ const { plan, ...rest } = params;
306
+ return this.assign(customerId, { plan_id: plan, ...rest }, options);
307
+ }
308
+ /**
309
+ * Schedule the move for the end of the period they are in: they keep the
310
+ * plan they are paying for until it runs out, and the new one starts at
311
+ * their next boundary. Nothing is pro-rated, because nothing is split.
312
+ *
313
+ * Two plans on different cycles share no boundary, and this answers
314
+ * `CycleChangeRequiresResetError` — use `restart` for that move.
315
+ */
316
+ changeAtNextCycle(customerId, params, options) {
317
+ return this.change(
318
+ customerId,
319
+ { plan: params.plan, effective: "next_cycle" },
320
+ options
321
+ );
322
+ }
323
+ /**
324
+ * Move them now, inside the period already running. Their renewal day does
325
+ * not move; what changes is this period's cap, and `reconciliation` says
326
+ * how:
327
+ *
328
+ * - `none` (the default) — the new plan's amount governs the whole period.
329
+ * Usage already spent still counts, so a downgrade can deny until the
330
+ * period ends.
331
+ * - `prorate` — each plan's amount weighted by the fraction of the period it
332
+ * was held for. Refused between plans on different cycles, which share no
333
+ * period to weight.
334
+ *
335
+ * To have the period itself start over instead, use `restart`.
336
+ */
337
+ changeNow(customerId, params, options) {
338
+ return this.change(
339
+ customerId,
340
+ { ...params, effective: "immediate" },
341
+ options
342
+ );
343
+ }
344
+ /**
345
+ * Move them now and start a fresh period today: the period they were in
346
+ * closes where the change lands, keeping the usage it had, and the new
347
+ * plan's full amount opens immediately.
348
+ *
349
+ * This moves the customer's anchor, so their renewal day becomes today. It
350
+ * is the move for a customer starting over — a new contract, a re-signup —
351
+ * and the only one that can take a customer between plans whose cycles
352
+ * differ.
353
+ */
354
+ restart(customerId, params, options) {
355
+ return this.change(
356
+ customerId,
357
+ { plan: params.plan, effective: "immediate", reconciliation: "reset" },
358
+ options
359
+ );
360
+ }
361
+ /**
362
+ * Call off a change that has not landed yet, leaving the customer on the
363
+ * plan they hold. Naming the plan already held is what supersedes a pending
364
+ * instruction, so this reads the plan in force and names it back.
365
+ *
366
+ * Returns the assignment still in force, or `null` for a customer holding no
367
+ * plan — who can have nothing pending, since a first assignment always lands
368
+ * at once.
369
+ */
370
+ async cancelScheduledChange(customerId, options) {
371
+ const current = await this.retrieve(customerId, options);
372
+ if (current === null) return null;
373
+ return this.assign(customerId, { plan_id: current.plan_id }, options);
374
+ }
375
+ /**
376
+ * The plan in force now, which is not always the newest instruction: a
377
+ * change dated ahead does not govern yet.
378
+ *
379
+ * `null` when the customer holds no plan. That is a default deny rather than
380
+ * a failure — they are entitled to nothing — so it is an answer here and not
381
+ * a thrown `NotFoundError`. A customer who does not exist at all still
382
+ * throws one.
383
+ */
384
+ async retrieve(customerId, options) {
385
+ try {
386
+ return await this.#client.request({
387
+ ...options,
388
+ method: "GET",
389
+ path: `/v1/customers/${encodeURIComponent(customerId)}/plan`
390
+ });
391
+ } catch (error) {
392
+ if (error instanceof NotFoundError && error.code === "no_plan_assigned") {
393
+ return null;
394
+ }
395
+ throw error;
396
+ }
397
+ }
398
+ /**
399
+ * The change waiting to land, or `null` when none is. At most one is ever
400
+ * live: a newer instruction supersedes the one before it.
401
+ *
402
+ * Read against the assignment in force rather than against the local clock,
403
+ * so a change landing seconds from now is not reported as already governing.
404
+ */
405
+ async pending(customerId, options) {
406
+ const [current, { data }] = await Promise.all([
407
+ this.retrieve(customerId, options),
408
+ this.history(customerId, options)
409
+ ]);
410
+ const inForce = current === null ? -Infinity : Date.parse(current.effective_at);
411
+ return data.find(
412
+ (a) => a.superseded_at === null && Date.parse(a.effective_at) > inForce
413
+ ) ?? null;
414
+ }
415
+ /** Every instruction, superseded ones included: it is the whole trail. */
416
+ history(customerId, options) {
417
+ return this.#client.request({
418
+ ...options,
419
+ method: "GET",
420
+ path: `/v1/customers/${encodeURIComponent(customerId)}/plan/history`
421
+ });
422
+ }
423
+ };
424
+
425
+ // src/resources/customers.ts
426
+ var Customers = class {
427
+ /** The plan they hold, and the trail of instructions that got them there. */
428
+ plan;
429
+ /** Grants, which sit on top of whatever the plan gives. */
430
+ allowances;
431
+ #client;
432
+ constructor(client) {
433
+ this.#client = client;
434
+ this.plan = new CustomerPlan(client);
435
+ this.allowances = new CustomerAllowances(client);
436
+ }
437
+ create(params, options) {
438
+ return this.#client.request({
439
+ ...options,
440
+ method: "POST",
441
+ path: "/v1/customers",
442
+ body: params
443
+ });
444
+ }
445
+ /** Lean: a listing does not embed the plan. Read one customer for that. */
446
+ list(params = {}, options) {
447
+ return this.#client.request({
448
+ ...options,
449
+ method: "GET",
450
+ path: "/v1/customers",
451
+ query: { include_deleted: params.include_deleted }
452
+ });
453
+ }
454
+ /**
455
+ * One customer, with the plan they hold. `plan` is the one in force now and
456
+ * `pending_plan` the change waiting to land, each `null` when there is
457
+ * none — so knowing what a customer is on costs no second request.
458
+ */
459
+ retrieve(id, options) {
460
+ return this.#client.request({
461
+ ...options,
462
+ method: "GET",
463
+ path: `/v1/customers/${encodeURIComponent(id)}`
464
+ });
465
+ }
466
+ /**
467
+ * Resolves the tenant's own identifier, or null, embedding the plan the way
468
+ * `retrieve` does. The engine answers this as a filtered list, so a miss is
469
+ * an empty collection rather than a 404.
470
+ */
471
+ async retrieveByExternalId(externalId, options) {
472
+ const { data } = await this.#client.request({
473
+ ...options,
474
+ method: "GET",
475
+ path: "/v1/customers",
476
+ query: { external_id: externalId }
477
+ });
478
+ return data[0] ?? null;
479
+ }
480
+ update(id, params, options) {
481
+ return this.#client.request({
482
+ ...options,
483
+ method: "PATCH",
484
+ path: `/v1/customers/${encodeURIComponent(id)}`,
485
+ body: params
486
+ });
487
+ }
488
+ /** Soft delete: usage and assignments keep referencing the customer. */
489
+ delete(id, options) {
490
+ return this.#client.request({
491
+ ...options,
492
+ method: "DELETE",
493
+ path: `/v1/customers/${encodeURIComponent(id)}`
494
+ });
495
+ }
496
+ };
497
+
498
+ // src/resources/meters.ts
499
+ var Meters = class {
500
+ #client;
501
+ constructor(client) {
502
+ this.#client = client;
503
+ }
504
+ create(params, options) {
505
+ return this.#client.request({
506
+ ...options,
507
+ method: "POST",
508
+ path: "/v1/meters",
509
+ body: params
510
+ });
511
+ }
512
+ list(params = {}, options) {
513
+ return this.#client.request({
514
+ ...options,
515
+ method: "GET",
516
+ path: "/v1/meters",
517
+ query: { include_archived: params.include_archived }
518
+ });
519
+ }
520
+ retrieve(id, options) {
521
+ return this.#client.request({
522
+ ...options,
523
+ method: "GET",
524
+ path: `/v1/meters/${encodeURIComponent(id)}`
525
+ });
526
+ }
527
+ update(id, params, options) {
528
+ return this.#client.request({
529
+ ...options,
530
+ method: "PATCH",
531
+ path: `/v1/meters/${encodeURIComponent(id)}`,
532
+ body: params
533
+ });
534
+ }
535
+ /** Soft delete: plans and usage keep referencing the meter. Idempotent. */
536
+ archive(id, options) {
537
+ return this.#client.request({
538
+ ...options,
539
+ method: "DELETE",
540
+ path: `/v1/meters/${encodeURIComponent(id)}`
541
+ });
542
+ }
543
+ };
544
+
545
+ // src/resources/plans.ts
546
+ var PlanAllowances = class {
547
+ #client;
548
+ constructor(client) {
549
+ this.#client = client;
550
+ }
551
+ set(planId, params, options) {
552
+ return this.#client.request({
553
+ ...options,
554
+ method: "POST",
555
+ path: `/v1/plans/${encodeURIComponent(planId)}/allowances`,
556
+ body: params
557
+ });
558
+ }
559
+ /** Every version of every meter, newest first — history, not just current. */
560
+ list(planId, params = {}, options) {
561
+ return this.#client.request({
562
+ ...options,
563
+ method: "GET",
564
+ path: `/v1/plans/${encodeURIComponent(planId)}/allowances`,
565
+ query: { meter_id: params.meter_id }
566
+ });
567
+ }
568
+ };
569
+ var Plans = class {
570
+ allowances;
571
+ #client;
572
+ constructor(client) {
573
+ this.#client = client;
574
+ this.allowances = new PlanAllowances(client);
575
+ }
576
+ /** A new plan grants nothing; attach entitlement with `allowances.set`. */
577
+ create(params, options) {
578
+ return this.#client.request({
579
+ ...options,
580
+ method: "POST",
581
+ path: "/v1/plans",
582
+ body: params
583
+ });
584
+ }
585
+ list(params = {}, options) {
586
+ return this.#client.request({
587
+ ...options,
588
+ method: "GET",
589
+ path: "/v1/plans",
590
+ query: { include_archived: params.include_archived }
591
+ });
592
+ }
593
+ retrieve(id, options) {
594
+ return this.#client.request({
595
+ ...options,
596
+ method: "GET",
597
+ path: `/v1/plans/${encodeURIComponent(id)}`
598
+ });
599
+ }
600
+ update(id, params, options) {
601
+ return this.#client.request({
602
+ ...options,
603
+ method: "PATCH",
604
+ path: `/v1/plans/${encodeURIComponent(id)}`,
605
+ body: params
606
+ });
607
+ }
608
+ /**
609
+ * Stops new assignments without withdrawing capacity from anyone already on
610
+ * the plan, which is why an archived plan still resolves by id. Idempotent.
611
+ */
612
+ archive(id, options) {
613
+ return this.#client.request({
614
+ ...options,
615
+ method: "DELETE",
616
+ path: `/v1/plans/${encodeURIComponent(id)}`
617
+ });
618
+ }
619
+ };
620
+
621
+ // src/index.ts
622
+ var Meterbase = class {
623
+ customers;
624
+ meters;
625
+ plans;
626
+ #client;
627
+ constructor(options) {
628
+ this.#client = new Client(options);
629
+ this.customers = new Customers(this.#client);
630
+ this.meters = new Meters(this.#client);
631
+ this.plans = new Plans(this.#client);
632
+ }
633
+ /**
634
+ * Asks whether a customer may consume `quantity` of a meter, named by the
635
+ * tenant's own external id and the meter's key. Absence of entitlement is
636
+ * not permission: a customer with no plan and no grant is denied.
637
+ *
638
+ * This is the gate, and the only call that ever refuses. Run it before the
639
+ * work; record the work with `track` afterwards.
640
+ */
641
+ check(params, options) {
642
+ return this.#client.request({
643
+ ...options,
644
+ method: "POST",
645
+ path: "/v1/check",
646
+ body: params
647
+ });
648
+ }
649
+ /**
650
+ * Records usage that already happened — the tokens were spent, the image
651
+ * was generated — so it never refuses on capacity. A quantity beyond the
652
+ * customer's capacity is recorded, drives `available` to 0, and the next
653
+ * `check` says no. The answer is a receipt, not a verdict.
654
+ *
655
+ * `idempotency_key` is generated when omitted, so retrying this call — the
656
+ * SDK's own retries included — replays the original rather than counting
657
+ * the same work twice.
658
+ */
659
+ // `async` so that generating the key cannot throw synchronously out of a
660
+ // method that otherwise only ever rejects: one call, one way to fail.
661
+ async track(params, options) {
662
+ return this.#client.request({
663
+ ...options,
664
+ method: "POST",
665
+ path: "/v1/usage/track",
666
+ // Fixed here, once, before the retry loop is entered: every attempt of
667
+ // this call carries the same key, which is what makes replaying it safe.
668
+ body: {
669
+ ...params,
670
+ idempotency_key: params.idempotency_key ?? idempotencyKey()
671
+ },
672
+ idempotent: true
673
+ });
674
+ }
675
+ /** Reports which workspace this key acts for. */
676
+ whoami(options) {
677
+ return this.#client.request({
678
+ ...options,
679
+ method: "GET",
680
+ path: "/v1/whoami"
681
+ });
682
+ }
683
+ };
684
+ function idempotencyKey() {
685
+ const webcrypto = globalThis.crypto;
686
+ if (typeof webcrypto?.randomUUID === "function") {
687
+ return webcrypto.randomUUID();
688
+ }
689
+ if (typeof webcrypto?.getRandomValues === "function") {
690
+ const bytes = webcrypto.getRandomValues(new Uint8Array(16));
691
+ return Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
692
+ }
693
+ throw new MeterbaseError(
694
+ "No crypto to generate an idempotency key with: pass `idempotency_key` yourself, or run somewhere `crypto.getRandomValues` exists."
695
+ );
696
+ }
697
+
698
+ exports.APIError = APIError;
699
+ exports.AuthenticationError = AuthenticationError;
700
+ exports.ConflictError = ConflictError;
701
+ exports.ConnectionError = ConnectionError;
702
+ exports.CycleChangeRequiresResetError = CycleChangeRequiresResetError;
703
+ exports.IdempotencyConflictError = IdempotencyConflictError;
704
+ exports.InvalidRequestError = InvalidRequestError;
705
+ exports.Meterbase = Meterbase;
706
+ exports.MeterbaseError = MeterbaseError;
707
+ exports.NotFoundError = NotFoundError;
708
+ exports.PermissionDeniedError = PermissionDeniedError;
709
+ exports.RateLimitError = RateLimitError;
710
+ exports.ServerError = ServerError;
711
+ exports.TimeoutError = TimeoutError;
712
+ exports.errorFromResponse = errorFromResponse;
713
+ //# sourceMappingURL=index.cjs.map
714
+ //# sourceMappingURL=index.cjs.map