@klappay/types 2.0.2 → 2.0.3

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.js CHANGED
@@ -240,27 +240,50 @@ var TOKEN_ADDRESSES = {
240
240
  };
241
241
 
242
242
  // src/charges.ts
243
+ var import_zod8 = require("zod");
244
+
245
+ // src/checkout-metadata.ts
243
246
  var import_zod7 = require("zod");
244
- var ChargeStatusSchema = import_zod7.z.enum(["pending", "partially_paid", "confirmed", "expired", "underpaid"]).describe(
247
+ var CHECKOUT_PRODUCTS_MAX = 20;
248
+ var CheckoutProductSchema = import_zod7.z.object({
249
+ name: import_zod7.z.string().min(1).max(200).describe("What the payer is buying, shown as-is on the hosted checkout page."),
250
+ quantity: import_zod7.z.number().int().positive().max(9999).optional().describe("How many of this item. Omit for a single, unquantified item."),
251
+ imageUrl: import_zod7.z.string().url().max(2048).refine((value) => /^https?:\/\//.test(value), "must use http or https").optional().describe(
252
+ "Product image, fetched only by the payer's own browser \u2014 Klappay never fetches it server-side. Must be `http(s)`."
253
+ )
254
+ });
255
+ var KlappayCheckoutMetadataSchema = import_zod7.z.object({
256
+ products: import_zod7.z.array(CheckoutProductSchema).max(CHECKOUT_PRODUCTS_MAX).optional().describe(
257
+ `What the payer is buying, shown on the hosted checkout page \u2014 up to ${CHECKOUT_PRODUCTS_MAX} items. Purely informational: never validated against \`amount\`, never used by any payment or distribution logic.`
258
+ )
259
+ }).describe(
260
+ "Reserved for Klappay \u2014 the one namespace inside `metadata` whose format is defined and enforced by Klappay, not by you. A `metadata.klappay` that does not match this shape is rejected outright (`400 validation_error`), unlike every other key in `metadata`, which accepts absolutely anything and never fails validation."
261
+ );
262
+ var MetadataWithKlappaySchema = import_zod7.z.object({ klappay: KlappayCheckoutMetadataSchema.optional() }).catchall(import_zod7.z.unknown()).describe(
263
+ "Arbitrary key/value data, returned as-is on every read. Put whatever you want in here \u2014 none of it is validated, except the `klappay` key, which is reserved for Klappay: if present, it must match `KlappayCheckoutMetadataSchema` exactly, or the whole request is rejected with `400 validation_error`."
264
+ );
265
+
266
+ // src/charges.ts
267
+ var ChargeStatusSchema = import_zod8.z.enum(["pending", "partially_paid", "confirmed", "expired", "underpaid"]).describe(
245
268
  "Payment progress, from the payer side. `pending`: created, nothing received yet. `partially_paid`: some funds received, less than `amount`. `confirmed`: full amount received (or more \u2014 see `isOverpaid`). `expired`: `expiresAt` passed with zero funds received. `underpaid`: `expiresAt` passed while `partially_paid`. Every status is reached automatically, on its own timeline \u2014 there is no merchant-initiated cancellation. This never reflects whether funds actually reached the merchant \u2014 see `settlementStatus` for that."
246
269
  );
247
- var SettlementStatusSchema = import_zod7.z.enum(["pending", "completed", "failed"]).describe(
270
+ var SettlementStatusSchema = import_zod8.z.enum(["pending", "completed", "failed"]).describe(
248
271
  "Progress of the payout to the merchant's wallet, a separate step from `status` \u2014 `status: confirmed` only means the payment was detected on-chain, not that the merchant has been paid yet. `pending`: payment detected, payout not yet attempted. `completed`: the merchant's wallet has the funds. `failed`: the payout attempt failed and retries were exhausted (rare; contact support). `null` on the parent `Charge` means no payout has been attempted yet \u2014 nothing has been received, or the charge is still in progress."
249
272
  );
250
273
  var CHARGE_EXPIRES_IN_MIN_SECONDS = 60;
251
274
  var CHARGE_EXPIRES_IN_MAX_SECONDS = 3600;
252
275
  var CHARGE_ACCEPTED_PAYMENTS_MAX = 14;
253
- var AcceptedPaymentSchema = import_zod7.z.object({
276
+ var AcceptedPaymentSchema = import_zod8.z.object({
254
277
  token: TokenSchema,
255
278
  network: NetworkSchema
256
279
  });
257
- var AcceptedPaymentsSchema = import_zod7.z.array(AcceptedPaymentSchema).min(1, "At least one accepted payment is required.").max(CHARGE_ACCEPTED_PAYMENTS_MAX).superRefine((pairs, ctx) => {
280
+ var AcceptedPaymentsSchema = import_zod8.z.array(AcceptedPaymentSchema).min(1, "At least one accepted payment is required.").max(CHARGE_ACCEPTED_PAYMENTS_MAX).superRefine((pairs, ctx) => {
258
281
  const seen = /* @__PURE__ */ new Set();
259
282
  pairs.forEach((pair, index) => {
260
283
  const key = `${pair.token}:${pair.network}`;
261
284
  if (seen.has(key)) {
262
285
  ctx.addIssue({
263
- code: import_zod7.z.ZodIssueCode.custom,
286
+ code: import_zod8.z.ZodIssueCode.custom,
264
287
  message: `Duplicate accepted payment: ${pair.token} on ${pair.network}.`,
265
288
  path: [index]
266
289
  });
@@ -268,7 +291,7 @@ var AcceptedPaymentsSchema = import_zod7.z.array(AcceptedPaymentSchema).min(1, "
268
291
  seen.add(key);
269
292
  if (!OPERATIONAL_NETWORKS.includes(pair.network)) {
270
293
  ctx.addIssue({
271
- code: import_zod7.z.ZodIssueCode.custom,
294
+ code: import_zod8.z.ZodIssueCode.custom,
272
295
  message: `Network "${pair.network}" isn't live yet \u2014 only ${OPERATIONAL_NETWORKS.join(", ")} today.`,
273
296
  path: [index, "network"]
274
297
  });
@@ -278,22 +301,22 @@ var AcceptedPaymentsSchema = import_zod7.z.array(AcceptedPaymentSchema).min(1, "
278
301
  `Every \`(token, network)\` pair the payer is allowed to pay with \u2014 at least one, up to ${CHARGE_ACCEPTED_PAYMENTS_MAX}. This list is also the only restriction knob: the payer can use any combination of the pairs listed here, and every transfer on one of them is credited and sums toward the charge total (see \`paidWith\`) \u2014 e.g. a charge accepting USDC and USDT can be confirmed by $9 in USDC plus $1 in USDT, or by USDC arriving on two different accepted networks. To require payment in one specific token on one specific network, list only that single pair \u2014 a transfer on any pair not in this list is still recorded (for audit) but never credited. Each network must be live (see \`GET /v1/networks\` for the current matrix) \u2014 an unconfigured \`(token, network)\` combination for your environment is rejected with \`422 token_not_supported\`.`
279
302
  );
280
303
  var CHARGE_SPLIT_RECIPIENTS_MAX = 5;
281
- var SplitRecipientSchema = import_zod7.z.object({
282
- address: import_zod7.z.string().regex(/^0x[0-9a-fA-F]{40}$/, "must be a 20-byte hex address").describe("EVM address to send a slice of this charge to."),
283
- percent: import_zod7.z.number().positive().max(100).describe(
304
+ var SplitRecipientSchema = import_zod8.z.object({
305
+ address: import_zod8.z.string().regex(/^0x[0-9a-fA-F]{40}$/, "must be a 20-byte hex address").describe("EVM address to send a slice of this charge to."),
306
+ percent: import_zod8.z.number().positive().max(100).describe(
284
307
  "Percent of *your own* net share (i.e. of `100 - feePercent`, not of the charge's gross `amount`) to route to this address instead of your own payout wallet. Klappay's fee is computed on the gross amount first and is never diluted by how you choose to split what's left \u2014 see `docs/payments.md`'s \"Settling the payout\" section for the exact math."
285
308
  ),
286
- label: import_zod7.z.string().min(1).max(64).optional().describe(
309
+ label: import_zod8.z.string().min(1).max(64).optional().describe(
287
310
  'Free-form label for your own bookkeeping (e.g. `"supplier"`, `"sales rep"`) \u2014 echoed back unchanged, never interpreted by Klappay.'
288
311
  )
289
312
  });
290
- var SplitRecipientsSchema = import_zod7.z.array(SplitRecipientSchema).max(CHARGE_SPLIT_RECIPIENTS_MAX).superRefine((recipients, ctx) => {
313
+ var SplitRecipientsSchema = import_zod8.z.array(SplitRecipientSchema).max(CHARGE_SPLIT_RECIPIENTS_MAX).superRefine((recipients, ctx) => {
291
314
  const seen = /* @__PURE__ */ new Set();
292
315
  recipients.forEach((recipient, index) => {
293
316
  const key = recipient.address.toLowerCase();
294
317
  if (seen.has(key)) {
295
318
  ctx.addIssue({
296
- code: import_zod7.z.ZodIssueCode.custom,
319
+ code: import_zod8.z.ZodIssueCode.custom,
297
320
  message: `Duplicate split recipient address: ${recipient.address}.`,
298
321
  path: [index, "address"]
299
322
  });
@@ -304,79 +327,79 @@ var SplitRecipientsSchema = import_zod7.z.array(SplitRecipientSchema).max(CHARGE
304
327
  `Optional extra recipients for this charge's split \u2014 e.g. a supplier or the sales rep who closed the deal \u2014 up to ${CHARGE_SPLIT_RECIPIENTS_MAX}. Frozen at creation exactly like everything else that shapes the split address; cannot be changed afterward. The sum of every \`percent\` here must fit within \`100 - feePercent\` (your own net share) \u2014 a request that doesn't is rejected with \`422 split_recipients_exceed_available_percent\`.`
305
328
  );
306
329
  var CHARGE_AMOUNT_MAX = 999999999999;
307
- var CreateChargeSchema = import_zod7.z.object({
308
- amount: import_zod7.z.number().positive().max(CHARGE_AMOUNT_MAX).describe(
330
+ var CreateChargeSchema = import_zod8.z.object({
331
+ amount: import_zod8.z.number().positive().max(CHARGE_AMOUNT_MAX).describe(
309
332
  "Amount to charge, in `currency` units (e.g. `49.9` = $49.90) \u2014 up to 6 decimal places; anything more precise is silently truncated. Required \u2014 every charge has a target amount, the first credited transfer that reaches it confirms the charge."
310
333
  ),
311
- currency: import_zod7.z.literal("USD").default("USD").describe("Always `USD` today \u2014 the only supported currency."),
334
+ currency: import_zod8.z.literal("USD").default("USD").describe("Always `USD` today \u2014 the only supported currency."),
312
335
  acceptedPayments: AcceptedPaymentsSchema,
313
- expiresIn: import_zod7.z.number().int().min(CHARGE_EXPIRES_IN_MIN_SECONDS).max(CHARGE_EXPIRES_IN_MAX_SECONDS).describe(
336
+ expiresIn: import_zod8.z.number().int().min(CHARGE_EXPIRES_IN_MIN_SECONDS).max(CHARGE_EXPIRES_IN_MAX_SECONDS).describe(
314
337
  "Seconds, not minutes or milliseconds \u2014 how long the charge stays open before it expires. Required, min 60, max 3600 (60 minutes) \u2014 sized off the slowest chain Klappay supports today (Ethereum mainnet, where a safely-confirmed transfer takes up to ~15 minutes), leaving real margin for payer-side delay (gas spikes, wallet friction) on top of that. Cannot be extended or shortened after creation."
315
338
  ),
316
- idempotencyKey: import_zod7.z.string().min(1).max(255).optional().describe(
339
+ idempotencyKey: import_zod8.z.string().min(1).max(255).optional().describe(
317
340
  "Scoped to your tenant. Replaying the same key returns the original charge unchanged instead of creating a duplicate \u2014 safe to retry a request after a timeout without double-charging."
318
341
  ),
319
- externalRef: import_zod7.z.string().min(1).max(255).optional().describe(
342
+ externalRef: import_zod8.z.string().min(1).max(255).optional().describe(
320
343
  "An opaque correlation id from your own system (e.g. an order id) \u2014 echoed back on the charge and in every webhook payload. Not interpreted or validated by Klappay."
321
344
  ),
322
- source: import_zod7.z.string().min(1).max(64).optional().describe(
345
+ source: import_zod8.z.string().min(1).max(64).optional().describe(
323
346
  'Free-form label for what created this charge (e.g. `"checkout"`, `"invoice"`) \u2014 useful if you create charges from more than one flow and want to tell them apart later. Not a fixed enum; use whatever values make sense to you.'
324
347
  ),
325
- metadata: import_zod7.z.record(import_zod7.z.string(), import_zod7.z.unknown()).optional().describe("Arbitrary key/value data to attach to the charge, returned as-is on every read."),
326
- redirectUrl: import_zod7.z.string().url().refine((value) => /^https?:\/\//.test(value), "must use http or https").optional().describe(
348
+ metadata: MetadataWithKlappaySchema.optional(),
349
+ redirectUrl: import_zod8.z.string().url().refine((value) => /^https?:\/\//.test(value), "must use http or https").optional().describe(
327
350
  "Where to send the payer once this charge resolves, if you use Klappay's hosted checkout page (see `checkoutUrl` on the read shape) \u2014 ignored otherwise. Must be `http(s)` \u2014 a browser will navigate here, so `javascript:`/`data:` and other non-navigational schemes are rejected. Otherwise not validated beyond being well-formed; what happens at that destination is yours to build."
328
351
  ),
329
352
  splitRecipients: SplitRecipientsSchema.optional()
330
353
  });
331
- var ChargeSchema = import_zod7.z.object({
332
- id: import_zod7.z.string().describe("Klappay-generated id, e.g. `ch_...`. Use this to look up the charge later."),
333
- amount: import_zod7.z.number().describe("The amount originally requested, in `currency` units (up to 6 decimal places)."),
334
- amountReceived: import_zod7.z.number().nullable().describe(
354
+ var ChargeSchema = import_zod8.z.object({
355
+ id: import_zod8.z.string().describe("Klappay-generated id, e.g. `ch_...`. Use this to look up the charge later."),
356
+ amount: import_zod8.z.number().describe("The amount originally requested, in `currency` units (up to 6 decimal places)."),
357
+ amountReceived: import_zod8.z.number().nullable().describe(
335
358
  "Cumulative amount actually received on-chain so far, in `currency` units (up to 6 decimal places). `null` until the first transfer arrives. Can exceed `amount` \u2014 see `isOverpaid`."
336
359
  ),
337
- isOverpaid: import_zod7.z.boolean().describe(
360
+ isOverpaid: import_zod8.z.boolean().describe(
338
361
  "`true` if `amountReceived` ended up greater than `amount`. Klappay never refunds the difference automatically \u2014 see the docs for why."
339
362
  ),
340
- currency: import_zod7.z.string().describe("Always `USD` today \u2014 the only supported currency."),
341
- acceptedPayments: import_zod7.z.array(AcceptedPaymentSchema).describe(
363
+ currency: import_zod8.z.string().describe("Always `USD` today \u2014 the only supported currency."),
364
+ acceptedPayments: import_zod8.z.array(AcceptedPaymentSchema).describe(
342
365
  "Every `(token, network)` pair this charge was configured to accept, unchanged after creation."
343
366
  ),
344
- paidWith: import_zod7.z.array(AcceptedPaymentSchema).describe(
367
+ paidWith: import_zod8.z.array(AcceptedPaymentSchema).describe(
345
368
  "Every distinct `(token, network)` pair that has actually contributed a credited transfer so far \u2014 empty until the first one arrives. Can hold more than one entry: a charge accepting several pairs can be paid across a combination of them, and every entry here sums toward `amountReceived`."
346
369
  ),
347
- address: import_zod7.z.string().describe(
370
+ address: import_zod8.z.string().describe(
348
371
  "The on-chain address the payer must send funds to \u2014 identical across every accepted network (0xSplits addresses are chain-agnostic). Unique per charge, predicted at creation time \u2014 funds sent here go directly to the merchant, Klappay never custodies them."
349
372
  ),
350
373
  status: ChargeStatusSchema,
351
374
  settlementStatus: SettlementStatusSchema.nullable(),
352
375
  environment: EnvironmentSchema,
353
- apiKeyId: import_zod7.z.string().nullable().describe(
376
+ apiKeyId: import_zod8.z.string().nullable().describe(
354
377
  "Which of your API keys created this charge. `null` for a charge created before this field existed."
355
378
  ),
356
- txHash: import_zod7.z.string().nullable().describe(
379
+ txHash: import_zod8.z.string().nullable().describe(
357
380
  "Transaction hash of the most recent transfer detected for this charge. `null` until a payment is detected."
358
381
  ),
359
- externalRef: import_zod7.z.string().nullable(),
360
- source: import_zod7.z.string().nullable(),
361
- metadata: import_zod7.z.record(import_zod7.z.string(), import_zod7.z.unknown()).nullable(),
362
- redirectUrl: import_zod7.z.string().nullable().describe("Echoes the `redirectUrl` set at creation, if any. `null` if none was set."),
363
- checkoutUrl: import_zod7.z.string().nullable().describe(
382
+ externalRef: import_zod8.z.string().nullable(),
383
+ source: import_zod8.z.string().nullable(),
384
+ metadata: MetadataWithKlappaySchema.nullable(),
385
+ redirectUrl: import_zod8.z.string().nullable().describe("Echoes the `redirectUrl` set at creation, if any. `null` if none was set."),
386
+ checkoutUrl: import_zod8.z.string().nullable().describe(
364
387
  "Link to Klappay's hosted checkout page for this charge. `null` if this deployment has no hosted checkout configured \u2014 build your own payment UI from `address`/`acceptedPayments` instead."
365
388
  ),
366
- splitRecipients: import_zod7.z.array(SplitRecipientSchema).describe("Echoes whatever extra split recipients were set at creation \u2014 empty array if none."),
367
- createdAt: import_zod7.z.string().datetime(),
368
- expiresAt: import_zod7.z.string().datetime().describe(
389
+ splitRecipients: import_zod8.z.array(SplitRecipientSchema).describe("Echoes whatever extra split recipients were set at creation \u2014 empty array if none."),
390
+ createdAt: import_zod8.z.string().datetime(),
391
+ expiresAt: import_zod8.z.string().datetime().describe(
369
392
  "When this charge stops accepting payment, if still `pending`/`partially_paid` by then."
370
393
  ),
371
- confirmedAt: import_zod7.z.string().datetime().nullable().describe("When `status` first reached `confirmed`. `null` until then."),
372
- settledAt: import_zod7.z.string().datetime().nullable().describe(
394
+ confirmedAt: import_zod8.z.string().datetime().nullable().describe("When `status` first reached `confirmed`. `null` until then."),
395
+ settledAt: import_zod8.z.string().datetime().nullable().describe(
373
396
  "When `settlementStatus` first reached `completed` \u2014 the merchant's wallet actually has the funds. `null` until then, including while `settlementStatus` is `pending`/`failed`."
374
397
  ),
375
- lastActivityAt: import_zod7.z.string().datetime().describe(
398
+ lastActivityAt: import_zod8.z.string().datetime().describe(
376
399
  "When a transfer was last credited toward this charge, or `createdAt` if none has arrived yet."
377
400
  )
378
401
  });
379
- var ListChargesSchema = import_zod7.z.object({
402
+ var ListChargesSchema = import_zod8.z.object({
380
403
  status: ChargeStatusSchema.optional(),
381
404
  token: TokenSchema.optional().describe(
382
405
  "Filters on `paidWith.token` \u2014 the pair actually paid, not accepted."
@@ -385,13 +408,13 @@ var ListChargesSchema = import_zod7.z.object({
385
408
  "Filters on `paidWith.network` \u2014 the pair actually paid, not accepted."
386
409
  ),
387
410
  environment: EnvironmentSchema.optional(),
388
- since: import_zod7.z.string().datetime().optional().describe(
411
+ since: import_zod8.z.string().datetime().optional().describe(
389
412
  "Only return charges created at or after this timestamp (filters on `createdAt`, not on when the status last changed). If polling as a fallback for missed webhooks, use a window at least as wide as the longest `expiresIn` your charges use, or you can miss a long-lived charge that changed status outside a narrower window."
390
413
  ),
391
- isOverpaid: import_zod7.z.enum(["true", "false"]).transform((v) => v === "true").optional()
414
+ isOverpaid: import_zod8.z.enum(["true", "false"]).transform((v) => v === "true").optional()
392
415
  }).extend(PaginationQuerySchema.shape);
393
416
  var PaginatedChargesSchema = paginatedSchema(ChargeSchema);
394
- var GetChargeQrCodeQuerySchema = import_zod7.z.object({
417
+ var GetChargeQrCodeQuerySchema = import_zod8.z.object({
395
418
  token: TokenSchema.optional().describe(
396
419
  "Which accepted `(token, network)` pair to encode in the QR \u2014 required if `acceptedPayments` has more than one pair, since there is no single unambiguous default to fall back to. Ignored (and unnecessary) when the charge accepts exactly one pair."
397
420
  ),
@@ -399,61 +422,61 @@ var GetChargeQrCodeQuerySchema = import_zod7.z.object({
399
422
  });
400
423
 
401
424
  // src/distributions.ts
402
- var import_zod8 = require("zod");
403
- var SplitDistributionStatusSchema = import_zod8.z.enum(["pending", "processing", "completed", "failed"]).describe(
425
+ var import_zod9 = require("zod");
426
+ var SplitDistributionStatusSchema = import_zod9.z.enum(["pending", "processing", "completed", "failed"]).describe(
404
427
  "Status of one payout attempt to the merchant, for a single `(token, network)` pair \u2014 a charge that settles across more than one pair has one of these per pair. `pending`: queued, not yet claimed by a distributor. `processing`: a distributor (Klappay's own worker, or anyone racing to call `distribute()` first, see `PendingDistributionSchema`) has claimed it and is submitting the on-chain transaction. `completed`: the merchant's wallet has the funds. `failed`: every automatic retry was exhausted."
405
428
  );
406
- var PendingDistributionRecipientSchema = import_zod8.z.object({
407
- address: import_zod8.z.string().describe("On-chain recipient address."),
408
- percentAllocation: import_zod8.z.number().describe("This recipient's share of the split, as a percentage (e.g. `99.0991` = 99.0991%).")
429
+ var PendingDistributionRecipientSchema = import_zod9.z.object({
430
+ address: import_zod9.z.string().describe("On-chain recipient address."),
431
+ percentAllocation: import_zod9.z.number().describe("This recipient's share of the split, as a percentage (e.g. `99.0991` = 99.0991%).")
409
432
  });
410
- var PendingDistributionSchema = import_zod8.z.object({
411
- splitAddress: import_zod8.z.string().describe("The on-chain 0xSplits address to call `distribute()` on."),
433
+ var PendingDistributionSchema = import_zod9.z.object({
434
+ splitAddress: import_zod9.z.string().describe("The on-chain 0xSplits address to call `distribute()` on."),
412
435
  network: NetworkSchema,
413
436
  token: TokenSchema,
414
- recipients: import_zod8.z.array(PendingDistributionRecipientSchema).describe(
437
+ recipients: import_zod9.z.array(PendingDistributionRecipientSchema).describe(
415
438
  "The exact recipient list to pass to `distribute()` \u2014 the split contract only stores a hash of this config, so the caller must supply the identical array to prove it matches. Always present, never reconstructed from partial data."
416
439
  ),
417
- distributorFeePercent: import_zod8.z.number().describe(
440
+ distributorFeePercent: import_zod9.z.number().describe(
418
441
  "Percentage of the split balance paid to whoever calls `distribute()` first (e.g. `0.1` = 0.1%). Frozen at charge creation, same for every distribution today."
419
442
  ),
420
- estimatedRewardAmount: import_zod8.z.number().describe(
443
+ estimatedRewardAmount: import_zod9.z.number().describe(
421
444
  "Estimate only, in the charge's `currency` units, based on the amount Klappay detected on-chain \u2014 not a live read of the split's current balance. Read the balance yourself before submitting a transaction; a stale estimate is harmless (see the docs), never a reason to skip that check."
422
445
  ),
423
- availableSince: import_zod8.z.string().datetime().describe("When this distribution entered its grace period."),
424
- graceEndsAt: import_zod8.z.string().datetime().describe(
446
+ availableSince: import_zod9.z.string().datetime().describe("When this distribution entered its grace period."),
447
+ graceEndsAt: import_zod9.z.string().datetime().describe(
425
448
  "When Klappay's own worker may claim this distribution. Racing to call `distribute()` after this timestamp is possible but increasingly likely to lose to the worker."
426
449
  )
427
450
  });
428
451
  var PaginatedPendingDistributionsSchema = paginatedSchema(PendingDistributionSchema);
429
- var ListenPendingDistributionsQuerySchema = import_zod8.z.object({
430
- limit: import_zod8.z.coerce.number().int().min(0).max(PAGINATION_LIMIT_MAX).default(0).describe(
452
+ var ListenPendingDistributionsQuerySchema = import_zod9.z.object({
453
+ limit: import_zod9.z.coerce.number().int().min(0).max(PAGINATION_LIMIT_MAX).default(0).describe(
431
454
  "How many currently-claimable distributions to emit as an initial snapshot right after connecting \u2014 each as a synthetic `distribution.available` event \u2014 before continuing with real-time deltas. `0` (the default, same as omitting it) sends no snapshot at all, matching this endpoint's original behavior: connect first, then call `GET /v1/distributions/pending` yourself to bootstrap. Not a page \u2014 there is no cursor for this snapshot, so if more than `limit` are claimable at connect time, the excess is simply not sent; call `GET /v1/distributions/pending` directly for a complete, paginated listing."
432
455
  )
433
456
  });
434
- var PendingDistributionEventSchema = import_zod8.z.discriminatedUnion("type", [
435
- import_zod8.z.object({
436
- type: import_zod8.z.literal("distribution.available"),
457
+ var PendingDistributionEventSchema = import_zod9.z.discriminatedUnion("type", [
458
+ import_zod9.z.object({
459
+ type: import_zod9.z.literal("distribution.available"),
437
460
  distribution: PendingDistributionSchema
438
461
  }),
439
- import_zod8.z.object({
440
- type: import_zod8.z.literal("distribution.claimed"),
441
- splitAddress: import_zod8.z.string().describe("No longer claimable \u2014 either settled by someone, or picked up by the worker.")
462
+ import_zod9.z.object({
463
+ type: import_zod9.z.literal("distribution.claimed"),
464
+ splitAddress: import_zod9.z.string().describe("No longer claimable \u2014 either settled by someone, or picked up by the worker.")
442
465
  })
443
466
  ]);
444
467
 
445
468
  // src/metrics.ts
446
- var import_zod9 = require("zod");
447
- var MetricsResourceSchema = import_zod9.z.enum(["charges", "transactions", "distributions"]).describe(
469
+ var import_zod10 = require("zod");
470
+ var MetricsResourceSchema = import_zod10.z.enum(["charges", "transactions", "distributions"]).describe(
448
471
  "Which underlying dataset to query. `charges`: one row per charge. `transactions`: one row per detected on-chain transfer \u2014 a charge paid in installments has more than one. `distributions`: one row per payout attempt to the merchant, one per `(token, network)` pair a charge settled across."
449
472
  );
450
- var MetricsAggregationSchema = import_zod9.z.enum(["count", "sum", "avg", "min", "max"]).describe(
473
+ var MetricsAggregationSchema = import_zod10.z.enum(["count", "sum", "avg", "min", "max"]).describe(
451
474
  "`count` counts matching rows and never takes `field`. `sum`/`avg`/`min`/`max` require `field` to be set to one of the resource\u2019s numeric fields."
452
475
  );
453
- var MetricsFilterOperatorSchema = import_zod9.z.enum(["eq", "neq", "in", "gt", "gte", "lt", "lte"]).describe(
476
+ var MetricsFilterOperatorSchema = import_zod10.z.enum(["eq", "neq", "in", "gt", "gte", "lt", "lte"]).describe(
454
477
  "`in` expects an array value (max 50 entries); every other operator expects a single scalar."
455
478
  );
456
- var MetricsDateGranularitySchema = import_zod9.z.enum(["day", "week", "month", "year"]).describe(
479
+ var MetricsDateGranularitySchema = import_zod10.z.enum(["day", "week", "month", "year"]).describe(
457
480
  "Bucket width for a `date_bucket` `groupBy` entry \u2014 Postgres `date_trunc` semantics (UTC)."
458
481
  );
459
482
  var metricsQueryEnvironmentSchema = EnvironmentSchema.describe(
@@ -466,151 +489,151 @@ var METRICS_QUERY_MAX_GROUP_BY = 3;
466
489
  var METRICS_QUERY_MAX_FILTERS = 20;
467
490
  var METRICS_QUERY_MAX_METRICS = 10;
468
491
  var METRIC_ALIAS_PATTERN = /^[a-zA-Z_][a-zA-Z0-9_]*$/;
469
- var metricAliasSchema = import_zod9.z.string().min(1).max(64).regex(
492
+ var metricAliasSchema = import_zod10.z.string().min(1).max(64).regex(
470
493
  METRIC_ALIAS_PATTERN,
471
494
  "Must start with a letter or underscore, and contain only letters, digits, and underscores \u2014 this becomes a SQL column alias."
472
495
  ).optional();
473
- var MetricsFilterValueSchema = import_zod9.z.union([
474
- import_zod9.z.string().max(255),
475
- import_zod9.z.number(),
476
- import_zod9.z.boolean(),
477
- import_zod9.z.array(import_zod9.z.union([import_zod9.z.string().max(255), import_zod9.z.number()])).min(1).max(50)
496
+ var MetricsFilterValueSchema = import_zod10.z.union([
497
+ import_zod10.z.string().max(255),
498
+ import_zod10.z.number(),
499
+ import_zod10.z.boolean(),
500
+ import_zod10.z.array(import_zod10.z.union([import_zod10.z.string().max(255), import_zod10.z.number()])).min(1).max(50)
478
501
  ]);
479
- var orderBySchema = import_zod9.z.object({
480
- key: import_zod9.z.string().min(1).max(64).regex(
502
+ var orderBySchema = import_zod10.z.object({
503
+ key: import_zod10.z.string().min(1).max(64).regex(
481
504
  METRIC_ALIAS_PATTERN,
482
505
  "Must start with a letter or underscore, and contain only letters, digits, and underscores \u2014 every valid output column name already looks like this."
483
506
  ).describe(
484
507
  "An output column name from this same query \u2014 either a `groupBy` field name, or a metric\u2019s `alias` (or its default name: `${aggregation}` for `count`, `${aggregation}_${field}` otherwise, e.g. `sum_amount`). Must match `^[a-zA-Z_][a-zA-Z0-9_]*$` \u2014 every real output column name already does, so this only ever rejects a value that could never have been one."
485
508
  ),
486
- direction: import_zod9.z.enum(["asc", "desc"])
509
+ direction: import_zod10.z.enum(["asc", "desc"])
487
510
  }).describe(
488
511
  "Sort the result rows by any output column \u2014 including the bucket field itself for a `date_bucket` query (e.g. `createdAt`). Omit to get ascending-by-bucket order for a date-bucketed query, or implementation-defined (not guaranteed stable) order otherwise."
489
512
  );
490
- var limitSchema = import_zod9.z.number().int().min(1).max(METRICS_QUERY_MAX_ROW_LIMIT).default(METRICS_QUERY_DEFAULT_ROW_LIMIT).describe(
513
+ var limitSchema = import_zod10.z.number().int().min(1).max(METRICS_QUERY_MAX_ROW_LIMIT).default(METRICS_QUERY_DEFAULT_ROW_LIMIT).describe(
491
514
  `Max rows to return, ${1}\u2013${METRICS_QUERY_MAX_ROW_LIMIT}, default ${METRICS_QUERY_DEFAULT_ROW_LIMIT}. If more rows matched, \`meta.truncated\` is \`true\` on the response \u2014 narrow the query instead of just raising this.`
492
515
  );
493
- var ChargesQueryFieldSchema = import_zod9.z.enum(["status", "source", "apiKeyId", "currency", "isOverpaid", "externalRef"]).describe(
516
+ var ChargesQueryFieldSchema = import_zod10.z.enum(["status", "source", "apiKeyId", "currency", "isOverpaid", "externalRef"]).describe(
494
517
  "A `Charge` field to filter or group by \u2014 see `ChargeStatusSchema` for `status`'s own possible values (charges.md). `source`/`externalRef` are free-form strings your own integration set at creation, not a fixed enum."
495
518
  );
496
- var ChargesMetricFieldSchema = import_zod9.z.enum(["amount", "amountReceived", "feePercent"]).describe(
519
+ var ChargesMetricFieldSchema = import_zod10.z.enum(["amount", "amountReceived", "feePercent"]).describe(
497
520
  "A `Charge` numeric field to aggregate. `amount`/`amountReceived` are decimal currency amounts (requested vs. actually received \u2014 see `charges.md`). `feePercent` is the platform fee frozen on the charge at creation, e.g. `1.5` means 1.5%."
498
521
  );
499
- var ChargesDateFieldSchema = import_zod9.z.enum(["createdAt", "confirmedAt", "lastActivityAt", "expiresAt"]).describe(
522
+ var ChargesDateFieldSchema = import_zod10.z.enum(["createdAt", "confirmedAt", "lastActivityAt", "expiresAt"]).describe(
500
523
  "A `Charge` timestamp to filter/bucket by. `confirmedAt` is `null` until the charge reaches `confirmed` \u2014 a `dateRange`/`date_bucket` on it implicitly excludes every charge that never confirmed. `expiresAt` is always present (set at creation), useful for e.g. finding charges expiring soon or measuring how close to expiry charges typically resolve."
501
524
  );
502
- var ChargesFilterSchema = import_zod9.z.object({
525
+ var ChargesFilterSchema = import_zod10.z.object({
503
526
  field: ChargesQueryFieldSchema,
504
527
  operator: MetricsFilterOperatorSchema,
505
528
  value: MetricsFilterValueSchema
506
529
  });
507
- var ChargesGroupBySchema = import_zod9.z.union([
508
- import_zod9.z.object({ type: import_zod9.z.literal("field"), field: ChargesQueryFieldSchema }),
509
- import_zod9.z.object({
510
- type: import_zod9.z.literal("date_bucket"),
530
+ var ChargesGroupBySchema = import_zod10.z.union([
531
+ import_zod10.z.object({ type: import_zod10.z.literal("field"), field: ChargesQueryFieldSchema }),
532
+ import_zod10.z.object({
533
+ type: import_zod10.z.literal("date_bucket"),
511
534
  field: ChargesDateFieldSchema,
512
535
  granularity: MetricsDateGranularitySchema
513
536
  })
514
537
  ]);
515
- var ChargesMetricSchema = import_zod9.z.object({
538
+ var ChargesMetricSchema = import_zod10.z.object({
516
539
  aggregation: MetricsAggregationSchema,
517
540
  field: ChargesMetricFieldSchema.optional(),
518
541
  alias: metricAliasSchema
519
542
  });
520
- var ChargesMetricsQuerySchema = import_zod9.z.object({
521
- resource: import_zod9.z.literal("charges"),
543
+ var ChargesMetricsQuerySchema = import_zod10.z.object({
544
+ resource: import_zod10.z.literal("charges"),
522
545
  environment: metricsQueryEnvironmentSchema,
523
- dateRange: import_zod9.z.object({
546
+ dateRange: import_zod10.z.object({
524
547
  field: ChargesDateFieldSchema,
525
- from: import_zod9.z.string().max(64).datetime(),
526
- to: import_zod9.z.string().max(64).datetime()
548
+ from: import_zod10.z.string().max(64).datetime(),
549
+ to: import_zod10.z.string().max(64).datetime()
527
550
  }),
528
- groupBy: import_zod9.z.array(ChargesGroupBySchema).max(METRICS_QUERY_MAX_GROUP_BY).default([]),
529
- metrics: import_zod9.z.array(ChargesMetricSchema).min(1).max(METRICS_QUERY_MAX_METRICS),
530
- filters: import_zod9.z.array(ChargesFilterSchema).max(METRICS_QUERY_MAX_FILTERS).default([]),
551
+ groupBy: import_zod10.z.array(ChargesGroupBySchema).max(METRICS_QUERY_MAX_GROUP_BY).default([]),
552
+ metrics: import_zod10.z.array(ChargesMetricSchema).min(1).max(METRICS_QUERY_MAX_METRICS),
553
+ filters: import_zod10.z.array(ChargesFilterSchema).max(METRICS_QUERY_MAX_FILTERS).default([]),
531
554
  orderBy: orderBySchema.optional(),
532
555
  limit: limitSchema
533
556
  });
534
- var TransactionsQueryFieldSchema = import_zod9.z.enum(["network", "token", "source", "causedTransition"]).describe(
557
+ var TransactionsQueryFieldSchema = import_zod10.z.enum(["network", "token", "source", "causedTransition"]).describe(
535
558
  "A `Transaction` field to filter or group by \u2014 see `NetworkSchema`/`TokenSchema`/`TransactionSourceSchema` for their possible values. `causedTransition` is `true` only for the transfer(s) that actually flipped the charge's `status` \u2014 a charge paid in installments can have more than one; filtering/grouping on it excludes no-op duplicate transfers (see `TimelineEvent.causedTransition` in charges.md for the full explanation)."
536
559
  );
537
- var TransactionsMetricFieldSchema = import_zod9.z.enum(["amount"]).describe("The transfer amount, in the charge's `currency` units.");
538
- var TransactionsDateFieldSchema = import_zod9.z.enum(["detectedAt"]).describe("When Klappay detected this transfer on-chain (not when it was mined).");
539
- var TransactionsFilterSchema = import_zod9.z.object({
560
+ var TransactionsMetricFieldSchema = import_zod10.z.enum(["amount"]).describe("The transfer amount, in the charge's `currency` units.");
561
+ var TransactionsDateFieldSchema = import_zod10.z.enum(["detectedAt"]).describe("When Klappay detected this transfer on-chain (not when it was mined).");
562
+ var TransactionsFilterSchema = import_zod10.z.object({
540
563
  field: TransactionsQueryFieldSchema,
541
564
  operator: MetricsFilterOperatorSchema,
542
565
  value: MetricsFilterValueSchema
543
566
  });
544
- var TransactionsGroupBySchema = import_zod9.z.union([
545
- import_zod9.z.object({ type: import_zod9.z.literal("field"), field: TransactionsQueryFieldSchema }),
546
- import_zod9.z.object({
547
- type: import_zod9.z.literal("date_bucket"),
567
+ var TransactionsGroupBySchema = import_zod10.z.union([
568
+ import_zod10.z.object({ type: import_zod10.z.literal("field"), field: TransactionsQueryFieldSchema }),
569
+ import_zod10.z.object({
570
+ type: import_zod10.z.literal("date_bucket"),
548
571
  field: TransactionsDateFieldSchema,
549
572
  granularity: MetricsDateGranularitySchema
550
573
  })
551
574
  ]);
552
- var TransactionsMetricSchema = import_zod9.z.object({
575
+ var TransactionsMetricSchema = import_zod10.z.object({
553
576
  aggregation: MetricsAggregationSchema,
554
577
  field: TransactionsMetricFieldSchema.optional(),
555
578
  alias: metricAliasSchema
556
579
  });
557
- var TransactionsMetricsQuerySchema = import_zod9.z.object({
558
- resource: import_zod9.z.literal("transactions"),
580
+ var TransactionsMetricsQuerySchema = import_zod10.z.object({
581
+ resource: import_zod10.z.literal("transactions"),
559
582
  environment: metricsQueryEnvironmentSchema,
560
- dateRange: import_zod9.z.object({
583
+ dateRange: import_zod10.z.object({
561
584
  field: TransactionsDateFieldSchema,
562
- from: import_zod9.z.string().max(64).datetime(),
563
- to: import_zod9.z.string().max(64).datetime()
585
+ from: import_zod10.z.string().max(64).datetime(),
586
+ to: import_zod10.z.string().max(64).datetime()
564
587
  }),
565
- groupBy: import_zod9.z.array(TransactionsGroupBySchema).max(METRICS_QUERY_MAX_GROUP_BY).default([]),
566
- metrics: import_zod9.z.array(TransactionsMetricSchema).min(1).max(METRICS_QUERY_MAX_METRICS),
567
- filters: import_zod9.z.array(TransactionsFilterSchema).max(METRICS_QUERY_MAX_FILTERS).default([]),
588
+ groupBy: import_zod10.z.array(TransactionsGroupBySchema).max(METRICS_QUERY_MAX_GROUP_BY).default([]),
589
+ metrics: import_zod10.z.array(TransactionsMetricSchema).min(1).max(METRICS_QUERY_MAX_METRICS),
590
+ filters: import_zod10.z.array(TransactionsFilterSchema).max(METRICS_QUERY_MAX_FILTERS).default([]),
568
591
  orderBy: orderBySchema.optional(),
569
592
  limit: limitSchema
570
593
  });
571
- var DistributionsQueryFieldSchema = import_zod9.z.enum(["status", "network", "token", "distributorAddress"]).describe(
594
+ var DistributionsQueryFieldSchema = import_zod10.z.enum(["status", "network", "token", "distributorAddress"]).describe(
572
595
  "A `SplitDistribution` field to filter or group by \u2014 see `SplitDistributionStatusSchema`/`NetworkSchema`/`TokenSchema` for their possible values. `distributorAddress` is the public on-chain address that actually called `distribute()` for a `completed` distribution \u2014 Klappay's own operator address if settled by Klappay's own worker, a community keeper's address if settled externally (or `null` on the rare case that lookup failed), `null` for every non-`completed` status."
573
596
  );
574
- var DistributionsMetricFieldSchema = import_zod9.z.enum(["attempts"]).describe(
597
+ var DistributionsMetricFieldSchema = import_zod10.z.enum(["attempts"]).describe(
575
598
  "How many times a payout was attempted for this settlement so far \u2014 incremented on every attempt, whether it succeeded or is being retried after failing. A high `attempts` alongside `status: 'failed'` means every automatic retry was exhausted."
576
599
  );
577
- var DistributionsDateFieldSchema = import_zod9.z.enum(["createdAt", "processingStartedAt", "completedAt"]).describe(
600
+ var DistributionsDateFieldSchema = import_zod10.z.enum(["createdAt", "processingStartedAt", "completedAt"]).describe(
578
601
  "`createdAt`: when this settlement was queued. `processingStartedAt`: when a worker began its most recent attempt at the payout \u2014 `null` until the first attempt, then overwritten on every subsequent retry, so it reflects the *latest* attempt's start, not the first. `completedAt`: when it actually paid out \u2014 `null` until `status` reaches `completed`, so a `dateRange`/`date_bucket` on it implicitly excludes every distribution still pending/processing/failed."
579
602
  );
580
- var DistributionsFilterSchema = import_zod9.z.object({
603
+ var DistributionsFilterSchema = import_zod10.z.object({
581
604
  field: DistributionsQueryFieldSchema,
582
605
  operator: MetricsFilterOperatorSchema,
583
606
  value: MetricsFilterValueSchema
584
607
  });
585
- var DistributionsGroupBySchema = import_zod9.z.union([
586
- import_zod9.z.object({ type: import_zod9.z.literal("field"), field: DistributionsQueryFieldSchema }),
587
- import_zod9.z.object({
588
- type: import_zod9.z.literal("date_bucket"),
608
+ var DistributionsGroupBySchema = import_zod10.z.union([
609
+ import_zod10.z.object({ type: import_zod10.z.literal("field"), field: DistributionsQueryFieldSchema }),
610
+ import_zod10.z.object({
611
+ type: import_zod10.z.literal("date_bucket"),
589
612
  field: DistributionsDateFieldSchema,
590
613
  granularity: MetricsDateGranularitySchema
591
614
  })
592
615
  ]);
593
- var DistributionsMetricSchema = import_zod9.z.object({
616
+ var DistributionsMetricSchema = import_zod10.z.object({
594
617
  aggregation: MetricsAggregationSchema,
595
618
  field: DistributionsMetricFieldSchema.optional(),
596
619
  alias: metricAliasSchema
597
620
  });
598
- var DistributionsMetricsQuerySchema = import_zod9.z.object({
599
- resource: import_zod9.z.literal("distributions"),
621
+ var DistributionsMetricsQuerySchema = import_zod10.z.object({
622
+ resource: import_zod10.z.literal("distributions"),
600
623
  environment: metricsQueryEnvironmentSchema,
601
- dateRange: import_zod9.z.object({
624
+ dateRange: import_zod10.z.object({
602
625
  field: DistributionsDateFieldSchema,
603
- from: import_zod9.z.string().max(64).datetime(),
604
- to: import_zod9.z.string().max(64).datetime()
626
+ from: import_zod10.z.string().max(64).datetime(),
627
+ to: import_zod10.z.string().max(64).datetime()
605
628
  }),
606
- groupBy: import_zod9.z.array(DistributionsGroupBySchema).max(METRICS_QUERY_MAX_GROUP_BY).default([]),
607
- metrics: import_zod9.z.array(DistributionsMetricSchema).min(1).max(METRICS_QUERY_MAX_METRICS),
608
- filters: import_zod9.z.array(DistributionsFilterSchema).max(METRICS_QUERY_MAX_FILTERS).default([]),
629
+ groupBy: import_zod10.z.array(DistributionsGroupBySchema).max(METRICS_QUERY_MAX_GROUP_BY).default([]),
630
+ metrics: import_zod10.z.array(DistributionsMetricSchema).min(1).max(METRICS_QUERY_MAX_METRICS),
631
+ filters: import_zod10.z.array(DistributionsFilterSchema).max(METRICS_QUERY_MAX_FILTERS).default([]),
609
632
  orderBy: orderBySchema.optional(),
610
633
  limit: limitSchema
611
634
  });
612
635
  var ONE_DAY_MS = 24 * 60 * 60 * 1e3;
613
- var MetricsQuerySchema = import_zod9.z.discriminatedUnion("resource", [
636
+ var MetricsQuerySchema = import_zod10.z.discriminatedUnion("resource", [
614
637
  ChargesMetricsQuerySchema,
615
638
  TransactionsMetricsQuerySchema,
616
639
  DistributionsMetricsQuerySchema
@@ -619,7 +642,7 @@ var MetricsQuerySchema = import_zod9.z.discriminatedUnion("resource", [
619
642
  const to = new Date(input.dateRange.to);
620
643
  if (from >= to) {
621
644
  ctx.addIssue({
622
- code: import_zod9.z.ZodIssueCode.custom,
645
+ code: import_zod10.z.ZodIssueCode.custom,
623
646
  message: "`dateRange.from` must be before `dateRange.to`.",
624
647
  path: ["dateRange", "from"]
625
648
  });
@@ -627,7 +650,7 @@ var MetricsQuerySchema = import_zod9.z.discriminatedUnion("resource", [
627
650
  const spanDays = (to.getTime() - from.getTime()) / ONE_DAY_MS;
628
651
  if (spanDays > MAX_METRICS_QUERY_DATE_RANGE_DAYS) {
629
652
  ctx.addIssue({
630
- code: import_zod9.z.ZodIssueCode.custom,
653
+ code: import_zod10.z.ZodIssueCode.custom,
631
654
  message: `\`dateRange\` cannot span more than ${MAX_METRICS_QUERY_DATE_RANGE_DAYS} days.`,
632
655
  path: ["dateRange", "to"]
633
656
  });
@@ -635,7 +658,7 @@ var MetricsQuerySchema = import_zod9.z.discriminatedUnion("resource", [
635
658
  const dateBucketCount = input.groupBy.filter((entry) => entry.type === "date_bucket").length;
636
659
  if (dateBucketCount > 1) {
637
660
  ctx.addIssue({
638
- code: import_zod9.z.ZodIssueCode.custom,
661
+ code: import_zod10.z.ZodIssueCode.custom,
639
662
  message: "At most one `date_bucket` entry is allowed in `groupBy`.",
640
663
  path: ["groupBy"]
641
664
  });
@@ -643,7 +666,7 @@ var MetricsQuerySchema = import_zod9.z.discriminatedUnion("resource", [
643
666
  input.metrics.forEach((metric, index) => {
644
667
  if (metric.aggregation !== "count" && metric.field === void 0) {
645
668
  ctx.addIssue({
646
- code: import_zod9.z.ZodIssueCode.custom,
669
+ code: import_zod10.z.ZodIssueCode.custom,
647
670
  message: "`field` is required unless `aggregation` is `count`.",
648
671
  path: ["metrics", index, "field"]
649
672
  });
@@ -652,7 +675,7 @@ var MetricsQuerySchema = import_zod9.z.discriminatedUnion("resource", [
652
675
  const aliases = input.metrics.map((metric) => metric.alias).filter((alias) => alias !== void 0);
653
676
  if (new Set(aliases).size !== aliases.length) {
654
677
  ctx.addIssue({
655
- code: import_zod9.z.ZodIssueCode.custom,
678
+ code: import_zod10.z.ZodIssueCode.custom,
656
679
  message: "Every `metrics[].alias` must be unique.",
657
680
  path: ["metrics"]
658
681
  });
@@ -661,32 +684,32 @@ var MetricsQuerySchema = import_zod9.z.discriminatedUnion("resource", [
661
684
  input.metrics.forEach((metric, index) => {
662
685
  if (metric.alias !== void 0 && reservedNames.has(metric.alias)) {
663
686
  ctx.addIssue({
664
- code: import_zod9.z.ZodIssueCode.custom,
687
+ code: import_zod10.z.ZodIssueCode.custom,
665
688
  message: `\`alias\` "${metric.alias}" collides with a \`groupBy\` field name (or the reserved word "bucket") \u2014 choose a different alias.`,
666
689
  path: ["metrics", index, "alias"]
667
690
  });
668
691
  }
669
692
  });
670
693
  });
671
- var MetricsQueryResultRowSchema = import_zod9.z.record(
672
- import_zod9.z.string(),
673
- import_zod9.z.union([import_zod9.z.string(), import_zod9.z.number(), import_zod9.z.boolean(), import_zod9.z.null()])
694
+ var MetricsQueryResultRowSchema = import_zod10.z.record(
695
+ import_zod10.z.string(),
696
+ import_zod10.z.union([import_zod10.z.string(), import_zod10.z.number(), import_zod10.z.boolean(), import_zod10.z.null()])
674
697
  );
675
- var MetricsQueryResultSchema = import_zod9.z.object({
676
- data: import_zod9.z.array(MetricsQueryResultRowSchema),
677
- meta: import_zod9.z.object({
698
+ var MetricsQueryResultSchema = import_zod10.z.object({
699
+ data: import_zod10.z.array(MetricsQueryResultRowSchema),
700
+ meta: import_zod10.z.object({
678
701
  resource: MetricsResourceSchema,
679
702
  environment: EnvironmentSchema,
680
- rowCount: import_zod9.z.number().int().describe("Number of rows in `data`."),
681
- truncated: import_zod9.z.boolean().describe(
703
+ rowCount: import_zod10.z.number().int().describe("Number of rows in `data`."),
704
+ truncated: import_zod10.z.boolean().describe(
682
705
  "`true` if more rows matched than `limit` allowed \u2014 `data` holds only the first `limit`."
683
706
  )
684
707
  })
685
708
  });
686
709
 
687
710
  // src/webhook-events.ts
688
- var import_zod10 = require("zod");
689
- var ChargeWebhookEventTypeSchema = import_zod10.z.enum([
711
+ var import_zod11 = require("zod");
712
+ var ChargeWebhookEventTypeSchema = import_zod11.z.enum([
690
713
  "charge.created",
691
714
  "charge.partially_paid",
692
715
  "charge.confirmed",
@@ -698,14 +721,14 @@ var ChargeWebhookEventTypeSchema = import_zod10.z.enum([
698
721
  ]).describe(
699
722
  'Note the distinction between `charge.confirmed` and `charge.settled`: `confirmed` means the payment was detected on-chain; `settled` means the merchant\'s wallet actually received the funds \u2014 a separate, later step. Subscribe to `confirmed` if you only need "will I get paid," or `settled` if you need "has the money actually arrived." `charge.overpaid` fires alongside `charge.confirmed`/`charge.partially_paid` whenever the cumulative amount received ends up above `amount` (see `Charge.isOverpaid`). Every event in this category carries the full `Charge` object as `data`.'
700
723
  );
701
- var WebhookDeliveryEventTypeSchema = import_zod10.z.enum(["webhook.delivery_failed", "webhook.delivery_recovered", "webhook.endpoint_unhealthy"]).describe(
724
+ var WebhookDeliveryEventTypeSchema = import_zod11.z.enum(["webhook.delivery_failed", "webhook.delivery_recovered", "webhook.endpoint_unhealthy"]).describe(
702
725
  "Meta-events about the health of your own webhook endpoints \u2014 useful for monitoring without polling `GET /v1/webhooks/{id}/deliveries`. `webhook.endpoint_unhealthy` fires once when a webhook's failure rate over the trailing 24h crosses 20%, and `webhook.delivery_recovered` fires once when a delivery to that webhook next succeeds. `data` for every event in this category: `{ webhookId, url, failureRatio? }` (`failureRatio` only present on `webhook.endpoint_unhealthy`)."
703
726
  );
704
- var WebhookEventTypeSchema = import_zod10.z.union([
727
+ var WebhookEventTypeSchema = import_zod11.z.union([
705
728
  ChargeWebhookEventTypeSchema,
706
729
  WebhookDeliveryEventTypeSchema
707
730
  ]);
708
- var WebhookCategorySchema = import_zod10.z.enum(["payments", "webhooks"]).describe(
731
+ var WebhookCategorySchema = import_zod11.z.enum(["payments", "webhooks"]).describe(
709
732
  "Subscribe to every event in a category via `eventCategories` instead of listing events one by one \u2014 new events added to a category later arrive automatically, no subscription update needed."
710
733
  );
711
734
  function buildCategoryMap() {
@@ -733,78 +756,78 @@ var TriggerableChargeEventSchema = ChargeWebhookEventTypeSchema.exclude([
733
756
  );
734
757
 
735
758
  // src/webhooks.ts
736
- var import_zod11 = require("zod");
759
+ var import_zod12 = require("zod");
737
760
  var WEBHOOK_EVENTS_WILDCARD = "*";
738
- var CreateWebhookSchema = import_zod11.z.object({
739
- url: import_zod11.z.string().max(2048).url().describe(
761
+ var CreateWebhookSchema = import_zod12.z.object({
762
+ url: import_zod12.z.string().max(2048).url().describe(
740
763
  "Must be HTTPS and resolve to a public address \u2014 private/internal IPs are rejected."
741
764
  ),
742
- events: import_zod11.z.array(import_zod11.z.union([WebhookEventTypeSchema, import_zod11.z.literal(WEBHOOK_EVENTS_WILDCARD)])).max(Object.keys(EVENT_CATEGORY_MAP).length + 1).default([]).describe(
765
+ events: import_zod12.z.array(import_zod12.z.union([WebhookEventTypeSchema, import_zod12.z.literal(WEBHOOK_EVENTS_WILDCARD)])).max(Object.keys(EVENT_CATEGORY_MAP).length + 1).default([]).describe(
743
766
  'Individual event types to receive, or `"*"` for every event (combine with `excludeEvents` to opt back out of specific ones). Omit in favor of `eventCategories` if you want whole categories instead.'
744
767
  ),
745
- eventCategories: import_zod11.z.array(WebhookCategorySchema).max(WebhookCategorySchema.options.length).default([]).describe(
768
+ eventCategories: import_zod12.z.array(WebhookCategorySchema).max(WebhookCategorySchema.options.length).default([]).describe(
746
769
  "Subscribe to every event in these categories. At least one of `events` or `eventCategories` is required."
747
770
  ),
748
- excludeEvents: import_zod11.z.array(WebhookEventTypeSchema).max(Object.keys(EVENT_CATEGORY_MAP).length).default([]).describe(
771
+ excludeEvents: import_zod12.z.array(WebhookEventTypeSchema).max(Object.keys(EVENT_CATEGORY_MAP).length).default([]).describe(
749
772
  'Event types to exclude even if selected via `events: ["*"]` or `eventCategories`.'
750
773
  )
751
774
  }).refine((v) => v.events.length > 0 || v.eventCategories.length > 0, {
752
775
  message: "must select at least one event via `events` or `eventCategories`",
753
776
  path: ["events"]
754
777
  });
755
- var WebhookSchema = import_zod11.z.object({
756
- id: import_zod11.z.string(),
778
+ var WebhookSchema = import_zod12.z.object({
779
+ id: import_zod12.z.string(),
757
780
  environment: EnvironmentSchema.nullable().describe(
758
781
  "Which environment's API key created this webhook \u2014 `live` or `test`. Every event is only ever delivered to a webhook whose `environment` matches the event's own (or to a webhook with `environment: null`, which receives every environment \u2014 the case for every webhook created before this field existed)."
759
782
  ),
760
- url: import_zod11.z.string(),
761
- events: import_zod11.z.array(WebhookEventTypeSchema),
762
- eventCategories: import_zod11.z.array(WebhookCategorySchema),
763
- excludeEvents: import_zod11.z.array(WebhookEventTypeSchema),
764
- isWildcard: import_zod11.z.boolean(),
765
- secret: import_zod11.z.string().describe(
783
+ url: import_zod12.z.string(),
784
+ events: import_zod12.z.array(WebhookEventTypeSchema),
785
+ eventCategories: import_zod12.z.array(WebhookCategorySchema),
786
+ excludeEvents: import_zod12.z.array(WebhookEventTypeSchema),
787
+ isWildcard: import_zod12.z.boolean(),
788
+ secret: import_zod12.z.string().describe(
766
789
  "The signing secret, used to verify the `X-Klappay-Signature` header on every delivery. Returned in full only this once \u2014 store it now, it is not recoverable afterward. Header format: `t=<unix-seconds>,v1=<hex-encoded HMAC-SHA256>`. Compute the expected signature as `HMAC-SHA256(secret, \"${t}.${raw request body}\")` (hex-encoded) and compare it to `v1` using a constant-time comparison; as a replay-protection measure, also reject if `t` is too far from the current time \u2014 Klappay does not enforce or check any particular tolerance server-side, so the exact threshold is entirely the receiver's own policy call. An official SDK's `constructEvent()`/`verifySignature()` do this for you, defaulting to a 300-second tolerance, overridable via `constructEvent`'s `toleranceSeconds` option \u2014 see github.com/klappay for available SDKs."
767
790
  ),
768
- createdAt: import_zod11.z.string().datetime()
791
+ createdAt: import_zod12.z.string().datetime()
769
792
  });
770
793
  var WebhookListItemSchema = WebhookSchema.omit({ secret: true }).extend({
771
- hint: import_zod11.z.string().describe("A truncated, safe-to-display form of the secret (e.g. `whsec_...ab12`).")
794
+ hint: import_zod12.z.string().describe("A truncated, safe-to-display form of the secret (e.g. `whsec_...ab12`).")
772
795
  });
773
- var WebhookPayloadSchema = import_zod11.z.object({
774
- id: import_zod11.z.string().describe(
796
+ var WebhookPayloadSchema = import_zod12.z.object({
797
+ id: import_zod12.z.string().describe(
775
798
  "Unique id for this specific delivery \u2014 also sent as the `X-Klappay-Delivery` header."
776
799
  ),
777
800
  event: WebhookEventTypeSchema,
778
- createdAt: import_zod11.z.string().datetime(),
779
- data: import_zod11.z.unknown().describe(
801
+ createdAt: import_zod12.z.string().datetime(),
802
+ data: import_zod12.z.unknown().describe(
780
803
  "Event-specific data. Charge events (`charge.*`) carry the full `Charge` object; webhook-delivery events carry a smaller, event-specific object \u2014 see `WebhookEventDataMap`/`TypedWebhookPayload` for the exact shape per event, or docs/webhooks.md."
781
804
  )
782
805
  });
783
- var WebhookDeliveryStatusSchema = import_zod11.z.enum(["pending", "delivered", "failed"]);
784
- var WebhookDeliverySchema = import_zod11.z.object({
785
- id: import_zod11.z.string(),
786
- webhookId: import_zod11.z.string(),
806
+ var WebhookDeliveryStatusSchema = import_zod12.z.enum(["pending", "delivered", "failed"]);
807
+ var WebhookDeliverySchema = import_zod12.z.object({
808
+ id: import_zod12.z.string(),
809
+ webhookId: import_zod12.z.string(),
787
810
  event: WebhookEventTypeSchema,
788
811
  status: WebhookDeliveryStatusSchema.describe(
789
812
  "`pending`: still retrying. `delivered`: got a 2xx response. `failed`: retries exhausted (5 attempts over ~24h) \u2014 use `POST /v1/webhooks/{id}/deliveries/{deliveryId}/retry` to try again manually."
790
813
  ),
791
- attempts: import_zod11.z.number(),
792
- responseCode: import_zod11.z.number().nullable().describe(
814
+ attempts: import_zod12.z.number(),
815
+ responseCode: import_zod12.z.number().nullable().describe(
793
816
  "HTTP status your endpoint returned on the most recent attempt. `null` if every attempt failed to connect at all."
794
817
  ),
795
- nextRetryAt: import_zod11.z.string().datetime().nullable(),
796
- deliveredAt: import_zod11.z.string().datetime().nullable(),
797
- createdAt: import_zod11.z.string().datetime()
818
+ nextRetryAt: import_zod12.z.string().datetime().nullable(),
819
+ deliveredAt: import_zod12.z.string().datetime().nullable(),
820
+ createdAt: import_zod12.z.string().datetime()
798
821
  });
799
822
  var ListWebhookDeliveriesSchema = PaginationQuerySchema;
800
823
  var PaginatedWebhookDeliveriesSchema = paginatedSchema(WebhookDeliverySchema);
801
824
 
802
825
  // src/timeline.ts
803
- var import_zod12 = require("zod");
804
- var TransactionSourceSchema = import_zod12.z.enum(["moralis_webhook", "reconciliation_job", "sandbox"]).describe(
826
+ var import_zod13 = require("zod");
827
+ var TransactionSourceSchema = import_zod13.z.enum(["moralis_webhook", "reconciliation_job", "sandbox"]).describe(
805
828
  "How this transfer was detected: `moralis_webhook` (the normal path), `reconciliation_job` (a fallback poller caught it after the webhook was missed or delayed), or `sandbox` (simulated via `POST /v1/sandbox/charges/{id}/trigger`, no real on-chain transfer)."
806
829
  );
807
- var TimelineEventTypeSchema = import_zod12.z.enum([
830
+ var TimelineEventTypeSchema = import_zod13.z.enum([
808
831
  "charge.created",
809
832
  "charge.expired",
810
833
  "transaction.detected",
@@ -815,11 +838,11 @@ var TimelineEventTypeSchema = import_zod12.z.enum([
815
838
  ]).describe(
816
839
  "`charge.created`: the charge was created. `charge.expired`: `expiresAt` passed with no full payment. `transaction.detected`: a raw on-chain transfer was seen (see the `event`-shaped fields below for details \u2014 a charge can have more than one, e.g. a partial payment followed by the rest). `split.distributed`: a payout to the merchant completed on-chain, for one contributing `(token, network)` pair \u2014 a charge settled across more than one pair emits one of these per pair (see the `token`/`network` fields below). `webhook.dispatched`/`webhook.delivered`/`webhook.failed`: one specific delivery *attempt* for one webhook subscription \u2014 `failed` here means this single attempt failed, not that all retries were exhausted (see `WebhookDeliveryStatusSchema` for the exhausted-all-retries state)."
817
840
  );
818
- var TimelineEventSchema = import_zod12.z.object({
841
+ var TimelineEventSchema = import_zod13.z.object({
819
842
  type: TimelineEventTypeSchema,
820
- at: import_zod12.z.string().datetime(),
821
- txHash: import_zod12.z.string().optional().describe("Present for `transaction.detected` and `split.distributed` events only."),
822
- amount: import_zod12.z.number().optional().describe(
843
+ at: import_zod13.z.string().datetime(),
844
+ txHash: import_zod13.z.string().optional().describe("Present for `transaction.detected` and `split.distributed` events only."),
845
+ amount: import_zod13.z.number().optional().describe(
823
846
  "Present for `transaction.detected` events only \u2014 the amount that specific transfer carried."
824
847
  ),
825
848
  source: TransactionSourceSchema.optional().describe(
@@ -831,49 +854,49 @@ var TimelineEventSchema = import_zod12.z.object({
831
854
  network: NetworkSchema.optional().describe(
832
855
  "Present for `transaction.detected` and `split.distributed` events \u2014 which network this specific transfer, or settlement, used."
833
856
  ),
834
- causedTransition: import_zod12.z.boolean().optional().describe(
857
+ causedTransition: import_zod13.z.boolean().optional().describe(
835
858
  "Present for `transaction.detected` events only. `true` if this specific transfer changed the charge's status (e.g. PENDING\u2192CONFIRMED) \u2014 a charge paid in installments can have more than one such event."
836
859
  ),
837
860
  event: WebhookEventTypeSchema.optional().describe(
838
861
  "Present for `webhook.*` events only \u2014 which event type this delivery was for."
839
862
  ),
840
- responseCode: import_zod12.z.number().nullable().optional().describe(
863
+ responseCode: import_zod13.z.number().nullable().optional().describe(
841
864
  "Present for `webhook.*` events only \u2014 HTTP status your endpoint returned, or `null` if the request never connected."
842
865
  ),
843
- attempts: import_zod12.z.number().optional().describe(
866
+ attempts: import_zod13.z.number().optional().describe(
844
867
  "Present for `webhook.*` events only \u2014 how many delivery attempts have been made so far."
845
868
  )
846
869
  });
847
870
 
848
871
  // src/health.ts
849
- var import_zod13 = require("zod");
850
- var HealthSchema = import_zod13.z.object({
851
- status: import_zod13.z.enum(["ok", "error"]).describe(
872
+ var import_zod14 = require("zod");
873
+ var HealthSchema = import_zod14.z.object({
874
+ status: import_zod14.z.enum(["ok", "error"]).describe(
852
875
  "`error` when the database connectivity check fails \u2014 the HTTP status code mirrors this (503 instead of 200), so a plain uptime check (not just a JSON-aware one) still catches a DB outage."
853
876
  ),
854
- version: import_zod13.z.string(),
855
- timestamp: import_zod13.z.string().datetime(),
856
- db: import_zod13.z.enum(["ok", "error"]).describe("Result of a real database connectivity check, not just a process-alive check."),
857
- pendingWebhooks: import_zod13.z.number().describe("Count of webhook deliveries still awaiting a successful attempt."),
858
- oldestPendingChargeAgeSeconds: import_zod13.z.number().nullable().describe("Age of the oldest still-unpaid charge, in seconds. `null` if there are none."),
859
- lastMoralisEventAgeSeconds: import_zod13.z.number().nullable().describe(
877
+ version: import_zod14.z.string(),
878
+ timestamp: import_zod14.z.string().datetime(),
879
+ db: import_zod14.z.enum(["ok", "error"]).describe("Result of a real database connectivity check, not just a process-alive check."),
880
+ pendingWebhooks: import_zod14.z.number().describe("Count of webhook deliveries still awaiting a successful attempt."),
881
+ oldestPendingChargeAgeSeconds: import_zod14.z.number().nullable().describe("Age of the oldest still-unpaid charge, in seconds. `null` if there are none."),
882
+ lastMoralisEventAgeSeconds: import_zod14.z.number().nullable().describe(
860
883
  "Seconds since the last on-chain payment notification was received \u2014 a cheap signal for whether payment detection is currently working. `null` if none have ever been received."
861
884
  )
862
885
  });
863
886
 
864
887
  // src/sandbox.ts
865
- var import_zod14 = require("zod");
866
- var SandboxTriggerSchema = import_zod14.z.object({
888
+ var import_zod15 = require("zod");
889
+ var SandboxTriggerSchema = import_zod15.z.object({
867
890
  event: TriggerableChargeEventSchema,
868
- amount: import_zod14.z.number().positive().max(CHARGE_AMOUNT_MAX).optional().describe(
891
+ amount: import_zod15.z.number().positive().max(CHARGE_AMOUNT_MAX).optional().describe(
869
892
  "Used with `charge.partially_paid` (amount to simulate as received so far \u2014 must be less than the charge amount, defaults to half of it if omitted) and with `charge.overpaid` (amount received \u2014 must be greater than the charge amount, defaults to 1.5x it if omitted). Ignored for every other event."
870
893
  )
871
894
  });
872
895
 
873
896
  // src/capabilities.ts
874
- var import_zod15 = require("zod");
875
- var CapabilitiesSchema = import_zod15.z.object({
876
- acceptedPayments: import_zod15.z.array(AcceptedPaymentSchema).describe(
897
+ var import_zod16 = require("zod");
898
+ var CapabilitiesSchema = import_zod16.z.object({
899
+ acceptedPayments: import_zod16.z.array(AcceptedPaymentSchema).describe(
877
900
  "Every `(token, network)` pair actually configured for your environment right now \u2014 read straight from the same lookup `POST /v1/charges` validates `acceptedPayments` against, so it can never list a pair that charge creation would then reject. Use this to build a picker UI instead of hardcoding the matrix client-side."
878
901
  )
879
902
  });