@solvapay/server 2.4.1 → 2.5.0-preview-4dcf60c628500a6210ba69edbf7ae56ee47fbb3a

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.
@@ -154,6 +154,32 @@ async function getAuthenticatedUserCore(request, options = {}) {
154
154
 
155
155
  // src/client.ts
156
156
  import { SolvaPayError as SolvaPayError2 } from "@solvapay/core";
157
+ var API_ERROR_BODY_MAX = 240;
158
+ function apiDebugLog(...args) {
159
+ if (process.env.SOLVAPAY_DEBUG === "true") {
160
+ console.log(...args);
161
+ }
162
+ }
163
+ function isNonJsonResponseBody(body, contentType) {
164
+ const ct = contentType?.split(";")[0]?.trim().toLowerCase() ?? "";
165
+ if (ct.includes("json")) return false;
166
+ const trimmed = body.trimStart();
167
+ if (trimmed.startsWith("<")) return true;
168
+ if (ct && !ct.includes("json")) return true;
169
+ return false;
170
+ }
171
+ async function throwApiError(operation, res) {
172
+ const body = await res.text();
173
+ const contentType = res.headers.get("content-type");
174
+ const nonJson = isNonJsonResponseBody(body, contentType);
175
+ const snippet = body.length > API_ERROR_BODY_MAX ? `${body.slice(0, API_ERROR_BODY_MAX)}\u2026` : body;
176
+ const detail = nonJson ? `non-JSON response (${contentType ?? "unknown content-type"}) \u2014 the API may not have been reached. Body: ${snippet}` : snippet;
177
+ apiDebugLog(`\u274C API Error: ${res.status} - ${detail}`);
178
+ throw new SolvaPayError2(`${operation} failed (${res.status}): ${detail}`, {
179
+ status: res.status,
180
+ code: nonJson ? "non_json_response" : void 0
181
+ });
182
+ }
157
183
  function createSolvaPayClient(opts) {
158
184
  const base = opts.apiBaseUrl ?? "https://api.solvapay.com";
159
185
  if (!opts.apiKey) throw new SolvaPayError2("Missing apiKey");
@@ -161,12 +187,6 @@ function createSolvaPayClient(opts) {
161
187
  "Content-Type": "application/json",
162
188
  Authorization: `Bearer ${opts.apiKey}`
163
189
  };
164
- const debug = process.env.SOLVAPAY_DEBUG === "true";
165
- const log = (...args) => {
166
- if (debug) {
167
- console.log(...args);
168
- }
169
- };
170
190
  return {
171
191
  // POST: /v1/sdk/limits
172
192
  async checkLimits(params) {
@@ -177,11 +197,7 @@ function createSolvaPayClient(opts) {
177
197
  body: JSON.stringify(params)
178
198
  });
179
199
  if (!res.ok) {
180
- const error = await res.text();
181
- log(`\u274C API Error: ${res.status} - ${error}`);
182
- throw new SolvaPayError2(`Check limits failed (${res.status}): ${error}`, {
183
- status: res.status
184
- });
200
+ await throwApiError("Check limits", res);
185
201
  }
186
202
  const result = await res.json();
187
203
  return result;
@@ -195,11 +211,7 @@ function createSolvaPayClient(opts) {
195
211
  body: JSON.stringify(params)
196
212
  });
197
213
  if (!res.ok) {
198
- const error = await res.text();
199
- log(`\u274C API Error: ${res.status} - ${error}`);
200
- throw new SolvaPayError2(`Track usage failed (${res.status}): ${error}`, {
201
- status: res.status
202
- });
214
+ await throwApiError("Track usage", res);
203
215
  }
204
216
  return await res.json();
205
217
  },
@@ -212,11 +224,7 @@ function createSolvaPayClient(opts) {
212
224
  body: JSON.stringify(params)
213
225
  });
214
226
  if (!res.ok) {
215
- const error = await res.text();
216
- log(`\u274C API Error: ${res.status} - ${error}`);
217
- throw new SolvaPayError2(`Track usage bulk failed (${res.status}): ${error}`, {
218
- status: res.status
219
- });
227
+ await throwApiError("Track usage bulk", res);
220
228
  }
221
229
  return await res.json();
222
230
  },
@@ -229,11 +237,7 @@ function createSolvaPayClient(opts) {
229
237
  body: JSON.stringify(params)
230
238
  });
231
239
  if (!res.ok) {
232
- const error = await res.text();
233
- log(`\u274C API Error: ${res.status} - ${error}`);
234
- throw new SolvaPayError2(`Create customer failed (${res.status}): ${error}`, {
235
- status: res.status
236
- });
240
+ await throwApiError("Create customer", res);
237
241
  }
238
242
  const result = await res.json();
239
243
  return {
@@ -249,11 +253,7 @@ function createSolvaPayClient(opts) {
249
253
  body: JSON.stringify(params)
250
254
  });
251
255
  if (!res.ok) {
252
- const error = await res.text();
253
- log(`\u274C API Error: ${res.status} - ${error}`);
254
- throw new SolvaPayError2(`Update customer failed (${res.status}): ${error}`, {
255
- status: res.status
256
- });
256
+ await throwApiError("Update customer", res);
257
257
  }
258
258
  const result = await res.json();
259
259
  return {
@@ -281,11 +281,7 @@ function createSolvaPayClient(opts) {
281
281
  headers
282
282
  });
283
283
  if (!res.ok) {
284
- const error = await res.text();
285
- log(`\u274C API Error: ${res.status} - ${error}`);
286
- throw new SolvaPayError2(`Get customer failed (${res.status}): ${error}`, {
287
- status: res.status
288
- });
284
+ await throwApiError("Get customer", res);
289
285
  }
290
286
  const result = await res.json();
291
287
  let customer = result;
@@ -319,11 +315,7 @@ function createSolvaPayClient(opts) {
319
315
  body: JSON.stringify(body)
320
316
  });
321
317
  if (!res.ok) {
322
- const error = await res.text();
323
- log(`\u274C API Error: ${res.status} - ${error}`);
324
- throw new SolvaPayError2(`Assign credits failed (${res.status}): ${error}`, {
325
- status: res.status
326
- });
318
+ await throwApiError("Assign credits", res);
327
319
  }
328
320
  return await res.json();
329
321
  },
@@ -335,11 +327,7 @@ function createSolvaPayClient(opts) {
335
327
  headers
336
328
  });
337
329
  if (!res.ok) {
338
- const error = await res.text();
339
- log(`\u274C API Error: ${res.status} - ${error}`);
340
- throw new SolvaPayError2(`Get merchant failed (${res.status}): ${error}`, {
341
- status: res.status
342
- });
330
+ await throwApiError("Get merchant", res);
343
331
  }
344
332
  return res.json();
345
333
  },
@@ -351,11 +339,7 @@ function createSolvaPayClient(opts) {
351
339
  headers
352
340
  });
353
341
  if (!res.ok) {
354
- const error = await res.text();
355
- log(`\u274C API Error: ${res.status} - ${error}`);
356
- throw new SolvaPayError2(`Get platform config failed (${res.status}): ${error}`, {
357
- status: res.status
358
- });
342
+ await throwApiError("Get platform config", res);
359
343
  }
360
344
  return res.json();
361
345
  },
@@ -367,11 +351,7 @@ function createSolvaPayClient(opts) {
367
351
  headers
368
352
  });
369
353
  if (!res.ok) {
370
- const error = await res.text();
371
- log(`\u274C API Error: ${res.status} - ${error}`);
372
- throw new SolvaPayError2(`Get product failed (${res.status}): ${error}`, {
373
- status: res.status
374
- });
354
+ await throwApiError("Get product", res);
375
355
  }
376
356
  const result = await res.json();
377
357
  const data = result.data || {};
@@ -386,11 +366,7 @@ function createSolvaPayClient(opts) {
386
366
  headers
387
367
  });
388
368
  if (!res.ok) {
389
- const error = await res.text();
390
- log(`\u274C API Error: ${res.status} - ${error}`);
391
- throw new SolvaPayError2(`List products failed (${res.status}): ${error}`, {
392
- status: res.status
393
- });
369
+ await throwApiError("List products", res);
394
370
  }
395
371
  const result = await res.json();
396
372
  const products = Array.isArray(result) ? result : result.products || [];
@@ -408,11 +384,7 @@ function createSolvaPayClient(opts) {
408
384
  body: JSON.stringify(params)
409
385
  });
410
386
  if (!res.ok) {
411
- const error = await res.text();
412
- log(`\u274C API Error: ${res.status} - ${error}`);
413
- throw new SolvaPayError2(`Create product failed (${res.status}): ${error}`, {
414
- status: res.status
415
- });
387
+ await throwApiError("Create product", res);
416
388
  }
417
389
  const result = await res.json();
418
390
  return result;
@@ -426,11 +398,7 @@ function createSolvaPayClient(opts) {
426
398
  body: JSON.stringify(params)
427
399
  });
428
400
  if (!res.ok) {
429
- const error = await res.text();
430
- log(`\u274C API Error: ${res.status} - ${error}`);
431
- throw new SolvaPayError2(`Bootstrap MCP product failed (${res.status}): ${error}`, {
432
- status: res.status
433
- });
401
+ await throwApiError("Bootstrap MCP product", res);
434
402
  }
435
403
  return await res.json();
436
404
  },
@@ -443,11 +411,7 @@ function createSolvaPayClient(opts) {
443
411
  body: JSON.stringify(params)
444
412
  });
445
413
  if (!res.ok) {
446
- const error = await res.text();
447
- log(`\u274C API Error: ${res.status} - ${error}`);
448
- throw new SolvaPayError2(`Configure MCP plans failed (${res.status}): ${error}`, {
449
- status: res.status
450
- });
414
+ await throwApiError("Configure MCP plans", res);
451
415
  }
452
416
  return await res.json();
453
417
  },
@@ -459,11 +423,7 @@ function createSolvaPayClient(opts) {
459
423
  headers
460
424
  });
461
425
  if (!res.ok && res.status !== 404) {
462
- const error = await res.text();
463
- log(`\u274C API Error: ${res.status} - ${error}`);
464
- throw new SolvaPayError2(`Delete product failed (${res.status}): ${error}`, {
465
- status: res.status
466
- });
426
+ await throwApiError("Delete product", res);
467
427
  }
468
428
  },
469
429
  // POST: /v1/sdk/products/{productRef}/clone
@@ -475,11 +435,7 @@ function createSolvaPayClient(opts) {
475
435
  body: JSON.stringify(overrides || {})
476
436
  });
477
437
  if (!res.ok) {
478
- const error = await res.text();
479
- log(`\u274C API Error: ${res.status} - ${error}`);
480
- throw new SolvaPayError2(`Clone product failed (${res.status}): ${error}`, {
481
- status: res.status
482
- });
438
+ await throwApiError("Clone product", res);
483
439
  }
484
440
  return await res.json();
485
441
  },
@@ -491,11 +447,7 @@ function createSolvaPayClient(opts) {
491
447
  headers
492
448
  });
493
449
  if (!res.ok) {
494
- const error = await res.text();
495
- log(`\u274C API Error: ${res.status} - ${error}`);
496
- throw new SolvaPayError2(`List plans failed (${res.status}): ${error}`, {
497
- status: res.status
498
- });
450
+ await throwApiError("List plans", res);
499
451
  }
500
452
  const result = await res.json();
501
453
  const plans = Array.isArray(result) ? result : result.plans || [];
@@ -520,11 +472,7 @@ function createSolvaPayClient(opts) {
520
472
  body: JSON.stringify(params)
521
473
  });
522
474
  if (!res.ok) {
523
- const error = await res.text();
524
- log(`\u274C API Error: ${res.status} - ${error}`);
525
- throw new SolvaPayError2(`Create plan failed (${res.status}): ${error}`, {
526
- status: res.status
527
- });
475
+ await throwApiError("Create plan", res);
528
476
  }
529
477
  const result = await res.json();
530
478
  return result;
@@ -538,11 +486,7 @@ function createSolvaPayClient(opts) {
538
486
  body: JSON.stringify(params)
539
487
  });
540
488
  if (!res.ok) {
541
- const error = await res.text();
542
- log(`\u274C API Error: ${res.status} - ${error}`);
543
- throw new SolvaPayError2(`Update plan failed (${res.status}): ${error}`, {
544
- status: res.status
545
- });
489
+ await throwApiError("Update plan", res);
546
490
  }
547
491
  return await res.json();
548
492
  },
@@ -554,11 +498,7 @@ function createSolvaPayClient(opts) {
554
498
  headers
555
499
  });
556
500
  if (!res.ok && res.status !== 404) {
557
- const error = await res.text();
558
- log(`\u274C API Error: ${res.status} - ${error}`);
559
- throw new SolvaPayError2(`Delete plan failed (${res.status}): ${error}`, {
560
- status: res.status
561
- });
501
+ await throwApiError("Delete plan", res);
562
502
  }
563
503
  },
564
504
  // POST: /payment-intents
@@ -579,11 +519,7 @@ function createSolvaPayClient(opts) {
579
519
  })
580
520
  });
581
521
  if (!res.ok) {
582
- const error = await res.text();
583
- log(`\u274C API Error: ${res.status} - ${error}`);
584
- throw new SolvaPayError2(`Create payment intent failed (${res.status}): ${error}`, {
585
- status: res.status
586
- });
522
+ await throwApiError("Create payment intent", res);
587
523
  }
588
524
  return await res.json();
589
525
  },
@@ -607,11 +543,7 @@ function createSolvaPayClient(opts) {
607
543
  })
608
544
  });
609
545
  if (!res.ok) {
610
- const error = await res.text();
611
- log(`\u274C API Error: ${res.status} - ${error}`);
612
- throw new SolvaPayError2(`Create topup payment intent failed (${res.status}): ${error}`, {
613
- status: res.status
614
- });
546
+ await throwApiError("Create topup payment intent", res);
615
547
  }
616
548
  return await res.json();
617
549
  },
@@ -631,11 +563,7 @@ function createSolvaPayClient(opts) {
631
563
  })
632
564
  });
633
565
  if (!res.ok) {
634
- const error = await res.text();
635
- log(`\u274C API Error: ${res.status} - ${error}`);
636
- throw new SolvaPayError2(`Process payment failed (${res.status}): ${error}`, {
637
- status: res.status
638
- });
566
+ await throwApiError("Process payment", res);
639
567
  }
640
568
  const result = await res.json();
641
569
  return result;
@@ -656,54 +584,20 @@ function createSolvaPayClient(opts) {
656
584
  })
657
585
  });
658
586
  if (!res.ok) {
659
- const error = await res.text();
660
- log(`\u274C API Error: ${res.status} - ${error}`);
661
- throw new SolvaPayError2(
662
- `Attach business details failed (${res.status}): ${error}`,
663
- { status: res.status }
664
- );
665
- }
666
- return await res.json();
667
- },
668
- // POST: /v1/sdk/purchases/{purchaseRef}/cancel
669
- async cancelPurchase(params) {
670
- const url = `${base}/v1/sdk/purchases/${params.purchaseRef}/cancel`;
671
- const requestOptions = {
672
- method: "POST",
673
- headers
674
- };
675
- if (params.reason) {
676
- requestOptions.body = JSON.stringify({ reason: params.reason });
677
- }
678
- const res = await fetch(url, requestOptions);
679
- if (!res.ok) {
680
- const error = await res.text();
681
- log(`\u274C API Error: ${res.status} - ${error}`);
682
- if (res.status === 404) {
683
- throw new SolvaPayError2(`Purchase not found: ${error}`, { status: 404 });
684
- }
685
- if (res.status === 400) {
686
- throw new SolvaPayError2(
687
- `Purchase cannot be cancelled or does not belong to provider: ${error}`,
688
- { status: 400 }
689
- );
690
- }
691
- throw new SolvaPayError2(`Cancel purchase failed (${res.status}): ${error}`, {
692
- status: res.status
693
- });
587
+ await throwApiError("Cancel purchase", res);
694
588
  }
695
589
  const responseText = await res.text();
696
590
  let responseData;
697
591
  try {
698
592
  responseData = JSON.parse(responseText);
699
593
  } catch (parseError) {
700
- log(`\u274C Failed to parse response as JSON: ${parseError}`);
594
+ apiDebugLog(`\u274C Failed to parse response as JSON: ${parseError}`);
701
595
  throw new SolvaPayError2(
702
596
  `Invalid JSON response from cancel purchase endpoint: ${responseText.substring(0, 200)}`
703
597
  );
704
598
  }
705
599
  if (!responseData || typeof responseData !== "object") {
706
- log(`\u274C Invalid response structure: ${JSON.stringify(responseData)}`);
600
+ apiDebugLog(`\u274C Invalid response structure: ${JSON.stringify(responseData)}`);
707
601
  throw new SolvaPayError2(`Invalid response structure from cancel purchase endpoint`);
708
602
  }
709
603
  let result;
@@ -715,7 +609,7 @@ function createSolvaPayClient(opts) {
715
609
  result = responseData.purchase || responseData;
716
610
  }
717
611
  if (!result || typeof result !== "object") {
718
- log(`\u274C Invalid purchase data in response. Full response:`, responseData);
612
+ apiDebugLog(`\u274C Invalid purchase data in response. Full response:`, responseData);
719
613
  throw new SolvaPayError2(`Invalid purchase data in cancel purchase response`);
720
614
  }
721
615
  return result;
@@ -728,30 +622,20 @@ function createSolvaPayClient(opts) {
728
622
  headers
729
623
  });
730
624
  if (!res.ok) {
731
- const error = await res.text();
732
- log(`\u274C API Error: ${res.status} - ${error}`);
733
- if (res.status === 404) {
734
- throw new SolvaPayError2(`Purchase not found: ${error}`, { status: 404 });
735
- }
736
- if (res.status === 400) {
737
- throw new SolvaPayError2(`Purchase cannot be reactivated: ${error}`, { status: 400 });
738
- }
739
- throw new SolvaPayError2(`Reactivate purchase failed (${res.status}): ${error}`, {
740
- status: res.status
741
- });
625
+ await throwApiError("Reactivate purchase", res);
742
626
  }
743
627
  const responseText = await res.text();
744
628
  let responseData;
745
629
  try {
746
630
  responseData = JSON.parse(responseText);
747
631
  } catch (parseError) {
748
- log(`\u274C Failed to parse response as JSON: ${parseError}`);
632
+ apiDebugLog(`\u274C Failed to parse response as JSON: ${parseError}`);
749
633
  throw new SolvaPayError2(
750
634
  `Invalid JSON response from reactivate purchase endpoint: ${responseText.substring(0, 200)}`
751
635
  );
752
636
  }
753
637
  if (!responseData || typeof responseData !== "object") {
754
- log(`\u274C Invalid response structure: ${JSON.stringify(responseData)}`);
638
+ apiDebugLog(`\u274C Invalid response structure: ${JSON.stringify(responseData)}`);
755
639
  throw new SolvaPayError2(`Invalid response structure from reactivate purchase endpoint`);
756
640
  }
757
641
  let result;
@@ -763,7 +647,7 @@ function createSolvaPayClient(opts) {
763
647
  result = responseData.purchase || responseData;
764
648
  }
765
649
  if (!result || typeof result !== "object") {
766
- log(`\u274C Invalid purchase data in response. Full response:`, responseData);
650
+ apiDebugLog(`\u274C Invalid purchase data in response. Full response:`, responseData);
767
651
  throw new SolvaPayError2(`Invalid purchase data in reactivate purchase response`);
768
652
  }
769
653
  return result;
@@ -777,11 +661,7 @@ function createSolvaPayClient(opts) {
777
661
  body: JSON.stringify(params)
778
662
  });
779
663
  if (!res.ok) {
780
- const error = await res.text();
781
- log(`\u274C API Error: ${res.status} - ${error}`);
782
- throw new SolvaPayError2(`Get user info failed (${res.status}): ${error}`, {
783
- status: res.status
784
- });
664
+ await throwApiError("Get user info", res);
785
665
  }
786
666
  return await res.json();
787
667
  },
@@ -793,11 +673,7 @@ function createSolvaPayClient(opts) {
793
673
  headers
794
674
  });
795
675
  if (!res.ok) {
796
- const error = await res.text();
797
- log(`\u274C API Error: ${res.status} - ${error}`);
798
- throw new SolvaPayError2(`Get customer balance failed (${res.status}): ${error}`, {
799
- status: res.status
800
- });
676
+ await throwApiError("Get customer balance", res);
801
677
  }
802
678
  return await res.json();
803
679
  },
@@ -810,11 +686,7 @@ function createSolvaPayClient(opts) {
810
686
  body: JSON.stringify(params)
811
687
  });
812
688
  if (!res.ok) {
813
- const error = await res.text();
814
- log(`\u274C API Error: ${res.status} - ${error}`);
815
- throw new SolvaPayError2(`Create checkout session failed (${res.status}): ${error}`, {
816
- status: res.status
817
- });
689
+ await throwApiError("Create checkout session", res);
818
690
  }
819
691
  const result = await res.json();
820
692
  return result;
@@ -828,11 +700,7 @@ function createSolvaPayClient(opts) {
828
700
  body: JSON.stringify(params)
829
701
  });
830
702
  if (!res.ok) {
831
- const error = await res.text();
832
- log(`\u274C API Error: ${res.status} - ${error}`);
833
- throw new SolvaPayError2(`Create customer session failed (${res.status}): ${error}`, {
834
- status: res.status
835
- });
703
+ await throwApiError("Create customer session", res);
836
704
  }
837
705
  const result = await res.json();
838
706
  return result;
@@ -846,11 +714,7 @@ function createSolvaPayClient(opts) {
846
714
  body: JSON.stringify(params)
847
715
  });
848
716
  if (!res.ok) {
849
- const error = await res.text();
850
- log(`\u274C API Error: ${res.status} - ${error}`);
851
- throw new SolvaPayError2(`Activate plan failed (${res.status}): ${error}`, {
852
- status: res.status
853
- });
717
+ await throwApiError("Activate plan", res);
854
718
  }
855
719
  return await res.json();
856
720
  },
@@ -859,11 +723,7 @@ function createSolvaPayClient(opts) {
859
723
  url.searchParams.set("customerRef", params.customerRef);
860
724
  const res = await fetch(url.toString(), { method: "GET", headers });
861
725
  if (!res.ok) {
862
- const error = await res.text();
863
- log(`\u274C API Error: ${res.status} - ${error}`);
864
- throw new SolvaPayError2(`Get payment method failed (${res.status}): ${error}`, {
865
- status: res.status
866
- });
726
+ await throwApiError("Get payment method", res);
867
727
  }
868
728
  return await res.json();
869
729
  },
@@ -872,11 +732,7 @@ function createSolvaPayClient(opts) {
872
732
  url.searchParams.set("customerRef", params.customerRef);
873
733
  const res = await fetch(url.toString(), { method: "GET", headers });
874
734
  if (!res.ok) {
875
- const error = await res.text();
876
- log(`\u274C API Error: ${res.status} - ${error}`);
877
- throw new SolvaPayError2(`Get auto-recharge failed (${res.status}): ${error}`, {
878
- status: res.status
879
- });
735
+ await throwApiError("Get auto-recharge", res);
880
736
  }
881
737
  return await res.json();
882
738
  },
@@ -887,11 +743,7 @@ function createSolvaPayClient(opts) {
887
743
  body: JSON.stringify(params)
888
744
  });
889
745
  if (!res.ok) {
890
- const error = await res.text();
891
- log(`\u274C API Error: ${res.status} - ${error}`);
892
- throw new SolvaPayError2(`Save auto-recharge failed (${res.status}): ${error}`, {
893
- status: res.status
894
- });
746
+ await throwApiError("Save auto-recharge", res);
895
747
  }
896
748
  return await res.json();
897
749
  },
@@ -900,11 +752,7 @@ function createSolvaPayClient(opts) {
900
752
  url.searchParams.set("customerRef", params.customerRef);
901
753
  const res = await fetch(url.toString(), { method: "DELETE", headers });
902
754
  if (!res.ok) {
903
- const error = await res.text();
904
- log(`\u274C API Error: ${res.status} - ${error}`);
905
- throw new SolvaPayError2(`Disable auto-recharge failed (${res.status}): ${error}`, {
906
- status: res.status
907
- });
755
+ await throwApiError("Disable auto-recharge", res);
908
756
  }
909
757
  return await res.json();
910
758
  },
@@ -918,11 +766,7 @@ function createSolvaPayClient(opts) {
918
766
  }
919
767
  const res = await fetch(url.toString(), { method: "GET", headers });
920
768
  if (!res.ok) {
921
- const error = await res.text();
922
- log(`\u274C API Error: ${res.status} - ${error}`);
923
- throw new SolvaPayError2(`List purchases failed (${res.status}): ${error}`, {
924
- status: res.status
925
- });
769
+ await throwApiError("List purchases", res);
926
770
  }
927
771
  const data = await res.json();
928
772
  return { purchases: data.purchases ?? [] };
@@ -933,11 +777,7 @@ function createSolvaPayClient(opts) {
933
777
  if (params.limit !== void 0) url.searchParams.set("limit", String(params.limit));
934
778
  const res = await fetch(url.toString(), { method: "GET", headers });
935
779
  if (!res.ok) {
936
- const error = await res.text();
937
- log(`\u274C API Error: ${res.status} - ${error}`);
938
- throw new SolvaPayError2(`Get credit activity failed (${res.status}): ${error}`, {
939
- status: res.status
940
- });
780
+ await throwApiError("Get credit activity", res);
941
781
  }
942
782
  return await res.json();
943
783
  }
@@ -945,46 +785,92 @@ function createSolvaPayClient(opts) {
945
785
  }
946
786
 
947
787
  // src/paywall-state.ts
788
+ import { minorUnitsPerMajor } from "@solvapay/core";
948
789
  var CHECKOUT_SESSION_TTL_MINUTES = 15;
949
790
  var DOCS_HINT = "See docs://solvapay/overview.md.";
791
+ function creditSignals(limits) {
792
+ if (!limits) return { isCreditBased: false };
793
+ const creditBalance = limits.balance?.creditBalance ?? limits.creditBalance;
794
+ const creditsPerCall = limits.balance?.creditsPerUnit ?? limits.creditsPerUnit;
795
+ const isCreditBased = creditBalance !== void 0 || creditsPerCall !== void 0;
796
+ const shortfallCredits = creditBalance !== void 0 && creditsPerCall !== void 0 ? Math.max(0, creditsPerCall - creditBalance) : void 0;
797
+ let remainingCalls;
798
+ if (limits.balance?.remainingUnits !== void 0) {
799
+ remainingCalls = limits.balance.remainingUnits;
800
+ } else if (creditBalance !== void 0 && creditsPerCall !== void 0 && creditsPerCall > 0) {
801
+ remainingCalls = Math.floor(creditBalance / creditsPerCall);
802
+ } else if (limits.remaining >= 0) {
803
+ remainingCalls = limits.remaining;
804
+ }
805
+ return { creditBalance, creditsPerCall, shortfallCredits, remainingCalls, isCreditBased };
806
+ }
807
+ function nextActionFor(state) {
808
+ switch (state.kind) {
809
+ case "activation_required":
810
+ return "activate";
811
+ case "topup_required":
812
+ return "topup";
813
+ case "upgrade_required":
814
+ case "limit_reached":
815
+ return "checkout";
816
+ case "reactivation_required":
817
+ return "account";
818
+ }
819
+ }
820
+ function activePlanRefOf(limits) {
821
+ const ref = limits.planRef ?? limits.plan;
822
+ return ref && ref.length > 0 ? ref : void 0;
823
+ }
950
824
  function classifyPaywallState(limits) {
951
825
  if (!limits) return { kind: "upgrade_required" };
952
- if (limits.activationRequired === true) {
826
+ if (limits.activationRequired === true || limits.paywallReason === "activation_required") {
953
827
  return { kind: "activation_required" };
954
828
  }
829
+ if (limits.paywallReason === "topup_required") {
830
+ return { kind: "topup_required" };
831
+ }
955
832
  if (limits.needsTopUp === true) {
956
833
  return { kind: "topup_required" };
957
834
  }
958
835
  if (limits.needsUpgrade === true) {
959
836
  return { kind: "upgrade_required" };
960
837
  }
961
- const activePlan = limits.plans?.find((p) => p.reference === limits.plan);
962
- const isUsageBased = activePlan?.type === "usage-based" || limits.balance !== void 0;
963
- const creditBalance = limits.balance?.creditBalance ?? limits.creditBalance;
964
- if (isUsageBased) {
965
- if (creditBalance === 0) return { kind: "topup_required" };
966
- if (creditBalance === void 0 && limits.remaining === 0) {
838
+ const signals = creditSignals(limits);
839
+ if (signals.isCreditBased) {
840
+ if (signals.creditBalance !== void 0 && signals.creditsPerCall !== void 0 && signals.creditBalance < signals.creditsPerCall) {
841
+ return { kind: "topup_required" };
842
+ }
843
+ if (signals.creditBalance === 0) return { kind: "topup_required" };
844
+ if (signals.creditsPerCall === void 0 && limits.remaining === 0) {
967
845
  return { kind: "topup_required" };
968
846
  }
969
847
  }
970
- if (limits.plan.length > 0 && limits.remaining <= 0) {
848
+ const activeRef = activePlanRefOf(limits);
849
+ if ((limits.purchaseRef || activeRef) && limits.remaining <= 0) {
971
850
  return { kind: "limit_reached" };
972
851
  }
852
+ if (signals.isCreditBased) return { kind: "topup_required" };
853
+ if (limits.purchaseRef) return { kind: "limit_reached" };
973
854
  return { kind: "upgrade_required" };
974
855
  }
975
856
  function formatMinor(amountMinor, currency) {
976
- const major = amountMinor / 100;
857
+ const divisor = minorUnitsPerMajor(currency);
858
+ const major = amountMinor / divisor;
859
+ const fractionDigits = divisor === 1 ? 0 : 2;
977
860
  try {
978
861
  return new Intl.NumberFormat("en-US", {
979
862
  style: "currency",
980
863
  currency: currency.toUpperCase(),
981
- minimumFractionDigits: 2,
982
- maximumFractionDigits: 2
864
+ minimumFractionDigits: fractionDigits,
865
+ maximumFractionDigits: fractionDigits
983
866
  }).format(major);
984
867
  } catch {
985
- return `${currency.toUpperCase()} ${major.toFixed(2)}`;
868
+ return `${currency.toUpperCase()} ${divisor === 1 ? String(Math.round(major)) : major.toFixed(2)}`;
986
869
  }
987
870
  }
871
+ function formatCredits(value) {
872
+ return value.toLocaleString("en-US");
873
+ }
988
874
  function meterLabel(gate) {
989
875
  if (!gate.meterName) return "units";
990
876
  return gate.meterName.replace(/_/g, " ");
@@ -992,6 +878,14 @@ function meterLabel(gate) {
992
878
  function namedCheckoutMarkdown(url) {
993
879
  return `[Open checkout](${url})`;
994
880
  }
881
+ function linkLabel(name) {
882
+ return name.replace(/([[\]])/g, "\\$1");
883
+ }
884
+ function planLadder(gate) {
885
+ const linkable = (gate.plans ?? []).filter((p) => typeof p.checkoutUrl === "string" && p.checkoutUrl.length > 0).filter((p) => p.reference !== gate.planRef).sort((a, b) => a.price - b.price).slice(0, 4);
886
+ if (linkable.length === 0) return null;
887
+ return linkable.map((p) => `[${linkLabel(p.name ?? p.reference)}](${p.checkoutUrl})`).join(" \xB7 ");
888
+ }
995
889
  var VIEWER_TOOL = "account";
996
890
  function callViewer(view) {
997
891
  return view ? `call the \`${VIEWER_TOOL}\` tool with view: '${view}'` : `call the \`${VIEWER_TOOL}\` tool`;
@@ -1002,25 +896,57 @@ function recoverClause(url, verb, view) {
1002
896
  }
1003
897
  return ` ${callViewer(view).replace(/^c/, "C")}.`;
1004
898
  }
899
+ function hasActivePlan(gate) {
900
+ return Boolean(gate.purchaseRef || gate.planRef && gate.planRef.length > 0);
901
+ }
902
+ function autoRechargeDisabled(gate) {
903
+ return gate.autoRecharge?.enabled === false;
904
+ }
1005
905
  function buildGateMessage(state, gate) {
1006
906
  const url = gate.checkoutUrl && gate.checkoutUrl.length > 0 ? gate.checkoutUrl : null;
907
+ const ladder = planLadder(gate);
1007
908
  switch (state.kind) {
1008
909
  case "limit_reached": {
1009
910
  const included = gate.included;
1010
911
  const price = gate.unitPriceMinor != null && gate.currency ? formatMinor(gate.unitPriceMinor, gate.currency) : null;
1011
912
  const usedLine = included ? `You've used ${included.used} of ${included.total} included ${meterLabel(gate)} this period.` : `You've reached the included usage for this period.`;
1012
913
  const nextLine = price ? ` The next call is ${price}.` : "";
1013
- return `${usedLine}${nextLine}${recoverClause(url, "continue", "checkout")} ${DOCS_HINT}`;
914
+ const planName = gate.planName ?? "This plan";
915
+ const antiTrap = gate.creditBalance !== void 0 && gate.creditBalance > 0 && (gate.creditsPerCall === void 0 || gate.creditsPerCall === 0) ? ` Adding credits will not help, because ${planName} does not spend them.` : "";
916
+ const switchLine = ladder ? ` Or switch plan: ${ladder}.` : recoverClause(url, "continue", "checkout");
917
+ return `${usedLine}${nextLine}${antiTrap}${switchLine} ${DOCS_HINT}`;
1014
918
  }
1015
919
  case "activation_required":
1016
920
  return `Your plan needs activation.${recoverClause(url, "activate", "checkout")} Or call \`activate_plan\` with a \`planRef\`. ${DOCS_HINT}`;
1017
921
  case "topup_required": {
1018
- const currency = gate.currency ?? gate.balance?.currency ?? "USD";
1019
- const presets = [1e3, 2500, 5e3, 1e4].map((m) => formatMinor(m, currency)).join(" \xB7 ");
1020
- return `You're out of credits. Top up first (${presets}).${recoverClause(url, "add credits", "topup")} ${DOCS_HINT}`;
1021
- }
1022
- case "upgrade_required":
922
+ const balance = gate.creditBalance;
923
+ const cost = gate.creditsPerCall;
924
+ const shortfall = gate.shortfallCredits;
925
+ let lead;
926
+ if (balance !== void 0 && cost !== void 0 && shortfall !== void 0) {
927
+ lead = `Out of credits for this call. Balance ${formatCredits(balance)} credits; this call costs ${formatCredits(cost)} credits \u2014 ${formatCredits(shortfall)} short.`;
928
+ } else {
929
+ lead = "Included usage is exhausted.";
930
+ }
931
+ const topup = recoverClause(url, "add credits", "topup");
932
+ const auto = autoRechargeDisabled(gate) ? " Auto-recharge is off \u2014 turn it on from the account tool to avoid this next time." : "";
933
+ const switchLine = ladder ? ` Or switch plan: ${ladder}.` : "";
934
+ return `${lead}${topup}${auto}${switchLine} ${DOCS_HINT}`;
935
+ }
936
+ case "upgrade_required": {
937
+ if (hasActivePlan(gate)) {
938
+ const planName = gate.planName ?? "This plan";
939
+ const lead = `${planName} is active but its included usage is exhausted, and the automatic switch to the next plan did not complete.`;
940
+ if (ladder) {
941
+ return `${lead} Switch here: ${ladder}. ${DOCS_HINT}`;
942
+ }
943
+ return `${lead}${recoverClause(url, "switch plan", "checkout")} ${DOCS_HINT}`;
944
+ }
945
+ if (ladder) {
946
+ return `You don't have an active plan for this tool. Pick a plan to use this tool: ${ladder} (links expire in ${CHECKOUT_SESSION_TTL_MINUTES} minutes), or ${callViewer("checkout")}. ${DOCS_HINT}`;
947
+ }
1023
948
  return `You don't have an active plan for this tool.${recoverClause(url, "pick a plan", "checkout")} ${DOCS_HINT}`;
949
+ }
1024
950
  case "reactivation_required":
1025
951
  return `Your previous plan is no longer active. ${callViewer("account").replace(/^c/, "C")} to reactivate it, or ${callViewer("checkout")} to pick a new plan. ${DOCS_HINT}`;
1026
952
  }
@@ -1033,11 +959,23 @@ function allPaidPlansArePayg(plans) {
1033
959
  if (paidPlans.length === 0) return false;
1034
960
  return paidPlans.every((p) => p.type === "usage-based" || p.type === "hybrid");
1035
961
  }
962
+ function activePlanRefOf2(limits) {
963
+ const ref = limits.planRef ?? limits.plan;
964
+ return ref && ref.length > 0 ? ref : void 0;
965
+ }
1036
966
  function activePlanOf(limits) {
1037
- if (!limits.plan) return void 0;
1038
- return limits.plans?.find((p) => p.reference === limits.plan);
967
+ const ref = activePlanRefOf2(limits);
968
+ if (!ref) return void 0;
969
+ return limits.plans?.find((p) => p.reference === ref);
1039
970
  }
1040
971
  function includedFromLimits(limits) {
972
+ if (limits.used !== void 0 && limits.limit !== void 0) {
973
+ return {
974
+ total: limits.limit,
975
+ used: limits.used,
976
+ remaining: limits.remaining
977
+ };
978
+ }
1041
979
  const total = activePlanOf(limits)?.freeUnits;
1042
980
  if (total == null || total === 0) return void 0;
1043
981
  const remaining = limits.remaining;
@@ -1047,24 +985,49 @@ function includedFromLimits(limits) {
1047
985
  remaining
1048
986
  };
1049
987
  }
1050
- function recoveryFields(limits) {
988
+ function recoveryLinks(limits) {
989
+ const links = {};
990
+ if (limits.checkoutUrl) {
991
+ if (limits.checkoutUrl.includes("/topup")) {
992
+ links.topup = limits.checkoutUrl;
993
+ } else {
994
+ links.checkout = limits.checkoutUrl;
995
+ }
996
+ }
997
+ if (limits.confirmationUrl) {
998
+ links.manage = limits.confirmationUrl;
999
+ }
1000
+ return Object.keys(links).length > 0 ? links : void 0;
1001
+ }
1002
+ function recoveryFields(limits, state) {
1051
1003
  const plan = activePlanOf(limits);
1052
1004
  const included = includedFromLimits(limits);
1053
- const creditBalance = limits.balance?.creditBalance ?? limits.creditBalance;
1005
+ const signals = creditSignals(limits);
1006
+ const planRef = activePlanRefOf2(limits);
1007
+ const links = recoveryLinks(limits);
1054
1008
  return {
1055
- ...limits.plan ? { planRef: limits.plan } : {},
1009
+ ...planRef ? { planRef } : {},
1010
+ ...limits.planName !== void 0 ? { planName: limits.planName } : {},
1056
1011
  ...limits.plans !== void 0 ? { plans: limits.plans } : {},
1057
1012
  ...limits.meterName !== void 0 ? { meterName: limits.meterName } : {},
1058
1013
  ...plan?.perUnitChargeMinor != null ? { unitPriceMinor: plan.perUnitChargeMinor, currency: plan.currency } : limits.currency ? { currency: limits.currency } : {},
1059
1014
  ...included ? { included } : {},
1060
- ...creditBalance !== void 0 ? { creditBalance } : {}
1015
+ ...signals.creditBalance !== void 0 ? { creditBalance: signals.creditBalance } : {},
1016
+ reason: state.kind,
1017
+ nextAction: nextActionFor(state),
1018
+ ...signals.creditsPerCall !== void 0 ? { creditsPerCall: signals.creditsPerCall } : {},
1019
+ ...signals.shortfallCredits !== void 0 ? { shortfallCredits: signals.shortfallCredits } : {},
1020
+ ...signals.remainingCalls !== void 0 ? { remainingCalls: signals.remainingCalls } : {},
1021
+ ...limits.purchaseRef !== void 0 ? { purchaseRef: limits.purchaseRef } : {},
1022
+ ...limits.autoRecharge !== void 0 ? { autoRecharge: limits.autoRecharge } : {},
1023
+ ...links ? { links } : {}
1061
1024
  };
1062
1025
  }
1063
1026
  function buildPaywallGate(productRef, limits) {
1064
1027
  const checkoutUrl = limits.checkoutUrl;
1065
- const state = classifyPaywallState({ ...limits, plan: limits.plan ?? "" });
1028
+ const state = classifyPaywallState(limits);
1066
1029
  const useActivationForTopup = !limits.activationRequired && state.kind === "topup_required" && allPaidPlansArePayg(limits.plans);
1067
- const recovery = recoveryFields(limits);
1030
+ const recovery = recoveryFields(limits, state);
1068
1031
  const preMessage = limits.activationRequired || useActivationForTopup ? {
1069
1032
  kind: "activation_required",
1070
1033
  product: productRef,