@routstr/sdk 0.1.0

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.mjs ADDED
@@ -0,0 +1,3538 @@
1
+ import { createStore } from 'zustand/vanilla';
2
+ import { getDecodedToken } from '@cashu/cashu-ts';
3
+
4
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
5
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
6
+ }) : x)(function(x) {
7
+ if (typeof require !== "undefined") return require.apply(this, arguments);
8
+ throw Error('Dynamic require of "' + x + '" is not supported');
9
+ });
10
+
11
+ // core/errors.ts
12
+ var InsufficientBalanceError = class extends Error {
13
+ constructor(required, available, maxMintBalance = 0, maxMintUrl = "") {
14
+ super(
15
+ `Insufficient balance: need ${required} sats, have ${available} sats available. ` + (maxMintBalance > 0 ? `Largest mint balance: ${maxMintBalance} sats from ${maxMintUrl}` : "")
16
+ );
17
+ this.required = required;
18
+ this.available = available;
19
+ this.maxMintBalance = maxMintBalance;
20
+ this.maxMintUrl = maxMintUrl;
21
+ this.name = "InsufficientBalanceError";
22
+ }
23
+ };
24
+ var ProviderError = class extends Error {
25
+ constructor(baseUrl, statusCode, message, requestId) {
26
+ super(
27
+ `Provider ${baseUrl} returned ${statusCode}: ${message}` + (requestId ? ` (Request ID: ${requestId})` : "")
28
+ );
29
+ this.baseUrl = baseUrl;
30
+ this.statusCode = statusCode;
31
+ this.requestId = requestId;
32
+ this.name = "ProviderError";
33
+ }
34
+ };
35
+ var MintUnreachableError = class extends Error {
36
+ constructor(mintUrl) {
37
+ super(
38
+ `Your mint ${mintUrl} is unreachable or is blocking your IP. Please try again later or switch mints.`
39
+ );
40
+ this.mintUrl = mintUrl;
41
+ this.name = "MintUnreachableError";
42
+ }
43
+ };
44
+ var TokenOperationError = class extends Error {
45
+ constructor(message, operation, mintUrl) {
46
+ super(message);
47
+ this.operation = operation;
48
+ this.mintUrl = mintUrl;
49
+ this.name = "TokenOperationError";
50
+ }
51
+ };
52
+ var FailoverError = class extends Error {
53
+ constructor(originalProvider, failedProviders, message) {
54
+ super(
55
+ message || `All providers failed. Original: ${originalProvider}, Failed: ${failedProviders.join(", ")}`
56
+ );
57
+ this.originalProvider = originalProvider;
58
+ this.failedProviders = failedProviders;
59
+ this.name = "FailoverError";
60
+ }
61
+ };
62
+ var StreamingError = class extends Error {
63
+ constructor(message, finishReason, accumulatedContent) {
64
+ super(message);
65
+ this.finishReason = finishReason;
66
+ this.accumulatedContent = accumulatedContent;
67
+ this.name = "StreamingError";
68
+ }
69
+ };
70
+ var ModelNotFoundError = class extends Error {
71
+ constructor(modelId, baseUrl) {
72
+ super(`Model '${modelId}' not found on provider ${baseUrl}`);
73
+ this.modelId = modelId;
74
+ this.baseUrl = baseUrl;
75
+ this.name = "ModelNotFoundError";
76
+ }
77
+ };
78
+ var ProviderBootstrapError = class extends Error {
79
+ constructor(failedProviders, message) {
80
+ super(
81
+ message || `Failed to bootstrap providers. Tried: ${failedProviders.join(", ")}`
82
+ );
83
+ this.failedProviders = failedProviders;
84
+ this.name = "ProviderBootstrapError";
85
+ }
86
+ };
87
+ var NoProvidersAvailableError = class extends Error {
88
+ constructor() {
89
+ super("No providers are available for model discovery");
90
+ this.name = "NoProvidersAvailableError";
91
+ }
92
+ };
93
+ var MintDiscoveryError = class extends Error {
94
+ constructor(baseUrl, message) {
95
+ super(message || `Failed to discover mints from provider ${baseUrl}`);
96
+ this.baseUrl = baseUrl;
97
+ this.name = "MintDiscoveryError";
98
+ }
99
+ };
100
+
101
+ // discovery/ModelManager.ts
102
+ var ModelManager = class _ModelManager {
103
+ constructor(adapter, config = {}) {
104
+ this.adapter = adapter;
105
+ this.providerDirectoryUrl = config.providerDirectoryUrl || "https://api.routstr.com/v1/providers/";
106
+ this.cacheTTL = config.cacheTTL || 21 * 60 * 1e3;
107
+ this.includeProviderUrls = config.includeProviderUrls || [];
108
+ this.excludeProviderUrls = config.excludeProviderUrls || [];
109
+ }
110
+ cacheTTL;
111
+ providerDirectoryUrl;
112
+ includeProviderUrls;
113
+ excludeProviderUrls;
114
+ /**
115
+ * Get the list of bootstrapped provider base URLs
116
+ * @returns Array of provider base URLs
117
+ */
118
+ getBaseUrls() {
119
+ return this.adapter.getBaseUrlsList();
120
+ }
121
+ static async init(adapter, config = {}, options = {}) {
122
+ const manager = new _ModelManager(adapter, config);
123
+ const torMode = options.torMode ?? false;
124
+ const forceRefresh = options.forceRefresh ?? false;
125
+ const providers = await manager.bootstrapProviders(torMode);
126
+ await manager.fetchModels(providers, forceRefresh);
127
+ return manager;
128
+ }
129
+ /**
130
+ * Bootstrap provider list from the provider directory
131
+ * Fetches available providers and caches their base URLs
132
+ * @param torMode Whether running in Tor context
133
+ * @returns Array of provider base URLs
134
+ * @throws ProviderBootstrapError if all providers fail to fetch
135
+ */
136
+ async bootstrapProviders(torMode = false) {
137
+ try {
138
+ const cachedUrls = this.adapter.getBaseUrlsList();
139
+ if (cachedUrls.length > 0) {
140
+ const lastUpdate = this.adapter.getBaseUrlsLastUpdate();
141
+ const cacheValid = lastUpdate && Date.now() - lastUpdate <= this.cacheTTL;
142
+ if (cacheValid) {
143
+ return this.filterBaseUrlsForTor(cachedUrls, torMode);
144
+ }
145
+ }
146
+ const res = await fetch(this.providerDirectoryUrl);
147
+ if (!res.ok) {
148
+ throw new Error(`Failed to fetch providers: ${res.status}`);
149
+ }
150
+ const data = await res.json();
151
+ const providers = Array.isArray(data?.providers) ? data.providers : [];
152
+ const bases = /* @__PURE__ */ new Set();
153
+ for (const p of providers) {
154
+ const endpoints = this.getProviderEndpoints(p, torMode);
155
+ for (const endpoint of endpoints) {
156
+ bases.add(endpoint);
157
+ }
158
+ }
159
+ for (const url of this.includeProviderUrls) {
160
+ const normalized = this.normalizeUrl(url);
161
+ if (!torMode || normalized.includes(".onion")) {
162
+ bases.add(normalized);
163
+ }
164
+ }
165
+ const excluded = new Set(
166
+ this.excludeProviderUrls.map((url) => this.normalizeUrl(url))
167
+ );
168
+ const list = Array.from(bases).filter((base) => {
169
+ if (excluded.has(base)) return false;
170
+ return true;
171
+ });
172
+ if (list.length > 0) {
173
+ this.adapter.setBaseUrlsList(list);
174
+ this.adapter.setBaseUrlsLastUpdate(Date.now());
175
+ }
176
+ return list;
177
+ } catch (e) {
178
+ console.error("Failed to bootstrap providers", e);
179
+ throw new ProviderBootstrapError([], `Provider bootstrap failed: ${e}`);
180
+ }
181
+ }
182
+ /**
183
+ * Fetch models from all providers and select best-priced options
184
+ * Uses cache if available and not expired
185
+ * @param baseUrls List of provider base URLs to fetch from
186
+ * @param forceRefresh Ignore cache and fetch fresh data
187
+ * @returns Array of unique models with best prices selected
188
+ */
189
+ async fetchModels(baseUrls, forceRefresh = false) {
190
+ if (baseUrls.length === 0) {
191
+ throw new NoProvidersAvailableError();
192
+ }
193
+ const bestById = /* @__PURE__ */ new Map();
194
+ const modelsFromAllProviders = {};
195
+ const disabledProviders = this.adapter.getDisabledProviders();
196
+ const estimateMinCost = (m) => {
197
+ return m?.sats_pricing?.completion ?? 0;
198
+ };
199
+ const fetchPromises = baseUrls.map(async (url) => {
200
+ const base = url.endsWith("/") ? url : `${url}/`;
201
+ try {
202
+ let list;
203
+ if (!forceRefresh) {
204
+ const lastUpdate = this.adapter.getProviderLastUpdate(base);
205
+ const cacheValid = lastUpdate && Date.now() - lastUpdate <= this.cacheTTL;
206
+ if (cacheValid) {
207
+ const cachedModels = this.adapter.getCachedModels();
208
+ const cachedList = cachedModels[base] || [];
209
+ list = cachedList;
210
+ } else {
211
+ list = await this.fetchModelsFromProvider(base);
212
+ }
213
+ } else {
214
+ list = await this.fetchModelsFromProvider(base);
215
+ }
216
+ modelsFromAllProviders[base] = list;
217
+ this.adapter.setProviderLastUpdate(base, Date.now());
218
+ if (!disabledProviders.includes(base)) {
219
+ for (const m of list) {
220
+ const existing = bestById.get(m.id);
221
+ if (!m.sats_pricing) continue;
222
+ if (!existing) {
223
+ bestById.set(m.id, { model: m, base });
224
+ continue;
225
+ }
226
+ const currentCost = estimateMinCost(m);
227
+ const existingCost = estimateMinCost(existing.model);
228
+ if (currentCost < existingCost && m.sats_pricing) {
229
+ bestById.set(m.id, { model: m, base });
230
+ }
231
+ }
232
+ }
233
+ return { success: true, base, list };
234
+ } catch (error) {
235
+ if (this.isProviderDownError(error)) {
236
+ console.warn(`Provider ${base} is down right now.`);
237
+ } else {
238
+ console.warn(`Failed to fetch models from ${base}:`, error);
239
+ }
240
+ this.adapter.setProviderLastUpdate(base, Date.now());
241
+ return { success: false, base };
242
+ }
243
+ });
244
+ await Promise.allSettled(fetchPromises);
245
+ const existingCache = this.adapter.getCachedModels();
246
+ this.adapter.setCachedModels({
247
+ ...existingCache,
248
+ ...modelsFromAllProviders
249
+ });
250
+ return Array.from(bestById.values()).map((v) => v.model);
251
+ }
252
+ /**
253
+ * Fetch models from a single provider
254
+ * @param baseUrl Provider base URL
255
+ * @returns Array of models from provider
256
+ */
257
+ async fetchModelsFromProvider(baseUrl) {
258
+ const res = await fetch(`${baseUrl}v1/models`);
259
+ if (!res.ok) {
260
+ throw new Error(`Failed to fetch models: ${res.status}`);
261
+ }
262
+ const json = await res.json();
263
+ const list = Array.isArray(json?.data) ? json.data.map((m) => ({
264
+ ...m,
265
+ id: m.id.split("/").pop() || m.id
266
+ })) : [];
267
+ return list;
268
+ }
269
+ isProviderDownError(error) {
270
+ if (!(error instanceof Error)) return false;
271
+ const msg = error.message.toLowerCase();
272
+ if (msg.includes("fetch failed")) return true;
273
+ if (msg.includes("502")) return true;
274
+ if (msg.includes("503")) return true;
275
+ if (msg.includes("504")) return true;
276
+ const cause = error.cause;
277
+ return cause?.code === "ENOTFOUND";
278
+ }
279
+ /**
280
+ * Get all cached models from all providers
281
+ * @returns Record mapping baseUrl -> models
282
+ */
283
+ getAllCachedModels() {
284
+ return this.adapter.getCachedModels();
285
+ }
286
+ /**
287
+ * Clear cache for a specific provider
288
+ * @param baseUrl Provider base URL
289
+ */
290
+ clearProviderCache(baseUrl) {
291
+ const base = baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`;
292
+ const cached = this.adapter.getCachedModels();
293
+ delete cached[base];
294
+ this.adapter.setCachedModels(cached);
295
+ this.adapter.setProviderLastUpdate(base, 0);
296
+ }
297
+ /**
298
+ * Clear all model caches
299
+ */
300
+ clearAllCache() {
301
+ this.adapter.setCachedModels({});
302
+ }
303
+ /**
304
+ * Filter base URLs based on Tor context
305
+ * @param baseUrls Provider URLs to filter
306
+ * @param torMode Whether in Tor context
307
+ * @returns Filtered URLs appropriate for Tor mode
308
+ */
309
+ filterBaseUrlsForTor(baseUrls, torMode) {
310
+ if (!torMode) {
311
+ return baseUrls.filter((url) => !url.includes(".onion"));
312
+ }
313
+ return baseUrls.filter((url) => url.includes(".onion"));
314
+ }
315
+ /**
316
+ * Get provider endpoints from provider info
317
+ * @param provider Provider object from directory
318
+ * @param torMode Whether in Tor context
319
+ * @returns Array of endpoint URLs
320
+ */
321
+ getProviderEndpoints(provider, torMode) {
322
+ const endpoints = [];
323
+ if (torMode && provider.onion_url) {
324
+ endpoints.push(this.normalizeUrl(provider.onion_url));
325
+ } else if (provider.endpoint_url) {
326
+ endpoints.push(this.normalizeUrl(provider.endpoint_url));
327
+ }
328
+ return endpoints;
329
+ }
330
+ /**
331
+ * Normalize provider URL with trailing slash
332
+ * @param url URL to normalize
333
+ * @returns Normalized URL
334
+ */
335
+ normalizeUrl(url) {
336
+ if (!url.startsWith("http")) {
337
+ url = `https://${url}`;
338
+ }
339
+ return url.endsWith("/") ? url : `${url}/`;
340
+ }
341
+ };
342
+
343
+ // discovery/MintDiscovery.ts
344
+ var MintDiscovery = class {
345
+ constructor(adapter, config = {}) {
346
+ this.adapter = adapter;
347
+ this.cacheTTL = config.cacheTTL || 21 * 60 * 1e3;
348
+ }
349
+ cacheTTL;
350
+ /**
351
+ * Fetch mints from all providers via their /v1/info endpoints
352
+ * Caches mints and full provider info for later access
353
+ * @param baseUrls List of provider base URLs to fetch from
354
+ * @returns Object with mints and provider info from all providers
355
+ */
356
+ async discoverMints(baseUrls, options = {}) {
357
+ if (baseUrls.length === 0) {
358
+ return { mintsFromProviders: {}, infoFromProviders: {} };
359
+ }
360
+ const mintsFromAllProviders = {};
361
+ const infoFromAllProviders = {};
362
+ const forceRefresh = options.forceRefresh ?? false;
363
+ const fetchPromises = baseUrls.map(async (url) => {
364
+ const base = url.endsWith("/") ? url : `${url}/`;
365
+ try {
366
+ if (!forceRefresh) {
367
+ const lastUpdate = this.adapter.getProviderLastUpdate(base);
368
+ const cacheValid = lastUpdate && Date.now() - lastUpdate <= this.cacheTTL;
369
+ if (cacheValid) {
370
+ const cachedMints = this.adapter.getCachedMints()[base] || [];
371
+ const cachedInfo = this.adapter.getCachedProviderInfo()[base];
372
+ mintsFromAllProviders[base] = cachedMints;
373
+ if (cachedInfo) {
374
+ infoFromAllProviders[base] = cachedInfo;
375
+ }
376
+ return {
377
+ success: true,
378
+ base,
379
+ mints: cachedMints,
380
+ info: cachedInfo
381
+ };
382
+ }
383
+ }
384
+ const res = await fetch(`${base}v1/info`);
385
+ if (!res.ok) {
386
+ throw new Error(`Failed to fetch info: ${res.status}`);
387
+ }
388
+ const json = await res.json();
389
+ const mints = Array.isArray(json?.mints) ? json.mints : [];
390
+ const normalizedMints = mints.map(
391
+ (mint) => mint.endsWith("/") ? mint.slice(0, -1) : mint
392
+ );
393
+ mintsFromAllProviders[base] = normalizedMints;
394
+ infoFromAllProviders[base] = json;
395
+ this.adapter.setProviderLastUpdate(base, Date.now());
396
+ return { success: true, base, mints: normalizedMints, info: json };
397
+ } catch (error) {
398
+ this.adapter.setProviderLastUpdate(base, Date.now());
399
+ if (this.isProviderDownError(error)) {
400
+ console.warn(`Provider ${base} is down right now.`);
401
+ } else {
402
+ console.warn(`Failed to fetch mints from ${base}:`, error);
403
+ }
404
+ return { success: false, base, mints: [], info: null };
405
+ }
406
+ });
407
+ const results = await Promise.allSettled(fetchPromises);
408
+ for (const result of results) {
409
+ if (result.status === "fulfilled") {
410
+ const { base, mints, info } = result.value;
411
+ mintsFromAllProviders[base] = mints;
412
+ if (info) {
413
+ infoFromAllProviders[base] = info;
414
+ }
415
+ } else {
416
+ console.error("Mint discovery error:", result.reason);
417
+ }
418
+ }
419
+ try {
420
+ this.adapter.setCachedMints(mintsFromAllProviders);
421
+ this.adapter.setCachedProviderInfo(infoFromAllProviders);
422
+ } catch (error) {
423
+ console.error("Error caching mint discovery results:", error);
424
+ }
425
+ return {
426
+ mintsFromProviders: mintsFromAllProviders,
427
+ infoFromProviders: infoFromAllProviders
428
+ };
429
+ }
430
+ /**
431
+ * Get cached mints from all providers
432
+ * @returns Record mapping baseUrl -> mint URLs
433
+ */
434
+ getCachedMints() {
435
+ return this.adapter.getCachedMints();
436
+ }
437
+ /**
438
+ * Get cached provider info from all providers
439
+ * @returns Record mapping baseUrl -> provider info
440
+ */
441
+ getCachedProviderInfo() {
442
+ return this.adapter.getCachedProviderInfo();
443
+ }
444
+ /**
445
+ * Get mints for a specific provider
446
+ * @param baseUrl Provider base URL
447
+ * @returns Array of mint URLs for the provider
448
+ */
449
+ getProviderMints(baseUrl) {
450
+ const normalized = baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`;
451
+ const allMints = this.getCachedMints();
452
+ return allMints[normalized] || [];
453
+ }
454
+ /**
455
+ * Get info for a specific provider
456
+ * @param baseUrl Provider base URL
457
+ * @returns Provider info object or null if not found
458
+ */
459
+ getProviderInfo(baseUrl) {
460
+ const normalized = baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`;
461
+ const allInfo = this.getCachedProviderInfo();
462
+ return allInfo[normalized] || null;
463
+ }
464
+ /**
465
+ * Clear mint cache for a specific provider
466
+ * @param baseUrl Provider base URL
467
+ */
468
+ clearProviderMintCache(baseUrl) {
469
+ const normalized = baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`;
470
+ const mints = this.getCachedMints();
471
+ delete mints[normalized];
472
+ this.adapter.setCachedMints(mints);
473
+ const info = this.getCachedProviderInfo();
474
+ delete info[normalized];
475
+ this.adapter.setCachedProviderInfo(info);
476
+ }
477
+ /**
478
+ * Clear all mint caches
479
+ */
480
+ clearAllCache() {
481
+ this.adapter.setCachedMints({});
482
+ this.adapter.setCachedProviderInfo({});
483
+ }
484
+ isProviderDownError(error) {
485
+ if (!(error instanceof Error)) return false;
486
+ const msg = error.message.toLowerCase();
487
+ if (msg.includes("fetch failed")) return true;
488
+ if (msg.includes("502")) return true;
489
+ if (msg.includes("503")) return true;
490
+ if (msg.includes("504")) return true;
491
+ const cause = error.cause;
492
+ if (cause?.code === "ENOTFOUND") return true;
493
+ return false;
494
+ }
495
+ };
496
+
497
+ // wallet/AuditLogger.ts
498
+ var AuditLogger = class _AuditLogger {
499
+ static instance = null;
500
+ static getInstance() {
501
+ if (!_AuditLogger.instance) {
502
+ _AuditLogger.instance = new _AuditLogger();
503
+ }
504
+ return _AuditLogger.instance;
505
+ }
506
+ async log(entry) {
507
+ const fullEntry = {
508
+ ...entry,
509
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
510
+ };
511
+ const logLine = JSON.stringify(fullEntry) + "\n";
512
+ if (typeof window === "undefined") {
513
+ try {
514
+ const fs = await import('fs');
515
+ const path = await import('path');
516
+ const logPath = path.join(process.cwd(), "audit.log");
517
+ fs.appendFileSync(logPath, logLine);
518
+ } catch (error) {
519
+ console.error("[AuditLogger] Failed to write to file:", error);
520
+ }
521
+ } else {
522
+ console.log("[AUDIT]", logLine.trim());
523
+ }
524
+ }
525
+ async logBalanceSnapshot(action, amounts, options) {
526
+ await this.log({
527
+ action,
528
+ totalBalance: amounts.totalBalance,
529
+ providerBalances: amounts.providerBalances,
530
+ mintBalances: amounts.mintBalances,
531
+ amount: options?.amount,
532
+ mintUrl: options?.mintUrl,
533
+ baseUrl: options?.baseUrl,
534
+ status: options?.status ?? "success",
535
+ details: options?.details
536
+ });
537
+ }
538
+ };
539
+ var auditLogger = AuditLogger.getInstance();
540
+
541
+ // wallet/CashuSpender.ts
542
+ var CashuSpender = class {
543
+ constructor(walletAdapter, storageAdapter, providerRegistry, balanceManager) {
544
+ this.walletAdapter = walletAdapter;
545
+ this.storageAdapter = storageAdapter;
546
+ this.providerRegistry = providerRegistry;
547
+ this.balanceManager = balanceManager;
548
+ }
549
+ _isBusy = false;
550
+ async _getBalanceState() {
551
+ const mintBalances = await this.walletAdapter.getBalances();
552
+ const units = this.walletAdapter.getMintUnits();
553
+ let totalMintBalance = 0;
554
+ const normalizedMintBalances = {};
555
+ for (const url in mintBalances) {
556
+ const balance = mintBalances[url];
557
+ const unit = units[url];
558
+ const balanceInSats = unit === "msat" ? balance / 1e3 : balance;
559
+ normalizedMintBalances[url] = balanceInSats;
560
+ totalMintBalance += balanceInSats;
561
+ }
562
+ const pendingDistribution = this.storageAdapter.getPendingTokenDistribution();
563
+ const providerBalances = {};
564
+ let totalProviderBalance = 0;
565
+ for (const pending of pendingDistribution) {
566
+ providerBalances[pending.baseUrl] = pending.amount;
567
+ totalProviderBalance += pending.amount;
568
+ }
569
+ const apiKeys = this.storageAdapter.getAllApiKeys();
570
+ for (const apiKey of apiKeys) {
571
+ if (!providerBalances[apiKey.baseUrl]) {
572
+ providerBalances[apiKey.baseUrl] = apiKey.balance;
573
+ totalProviderBalance += apiKey.balance;
574
+ }
575
+ }
576
+ return {
577
+ totalBalance: totalMintBalance + totalProviderBalance,
578
+ providerBalances,
579
+ mintBalances: normalizedMintBalances
580
+ };
581
+ }
582
+ async _logTransaction(action, options) {
583
+ const balanceState = await this._getBalanceState();
584
+ await auditLogger.logBalanceSnapshot(action, balanceState, options);
585
+ }
586
+ /**
587
+ * Check if the spender is currently in a critical operation
588
+ */
589
+ get isBusy() {
590
+ return this._isBusy;
591
+ }
592
+ /**
593
+ * Spend Cashu tokens with automatic mint selection and retry logic
594
+ */
595
+ async spend(options) {
596
+ const {
597
+ mintUrl,
598
+ amount,
599
+ baseUrl,
600
+ reuseToken = false,
601
+ p2pkPubkey,
602
+ excludeMints = [],
603
+ retryCount = 0
604
+ } = options;
605
+ this._isBusy = true;
606
+ try {
607
+ return await this._spendInternal({
608
+ mintUrl,
609
+ amount,
610
+ baseUrl,
611
+ reuseToken,
612
+ p2pkPubkey,
613
+ excludeMints,
614
+ retryCount
615
+ });
616
+ } finally {
617
+ this._isBusy = false;
618
+ }
619
+ }
620
+ /**
621
+ * Internal spending logic
622
+ */
623
+ async _spendInternal(options) {
624
+ let {
625
+ mintUrl,
626
+ amount,
627
+ baseUrl,
628
+ reuseToken,
629
+ p2pkPubkey,
630
+ excludeMints,
631
+ retryCount
632
+ } = options;
633
+ let adjustedAmount = Math.ceil(amount);
634
+ if (!adjustedAmount || isNaN(adjustedAmount)) {
635
+ return {
636
+ token: null,
637
+ status: "failed",
638
+ balance: 0,
639
+ error: "Please enter a valid amount"
640
+ };
641
+ }
642
+ if (reuseToken && baseUrl) {
643
+ const existingResult = await this._tryReuseToken(
644
+ baseUrl,
645
+ adjustedAmount,
646
+ mintUrl
647
+ );
648
+ if (existingResult) {
649
+ return existingResult;
650
+ }
651
+ }
652
+ const balances = await this.walletAdapter.getBalances();
653
+ const units = this.walletAdapter.getMintUnits();
654
+ let totalBalance = 0;
655
+ for (const url in balances) {
656
+ const balance = balances[url];
657
+ const unit = units[url];
658
+ const balanceInSats = unit === "msat" ? balance / 1e3 : balance;
659
+ totalBalance += balanceInSats;
660
+ }
661
+ const pendingDistribution = this.storageAdapter.getPendingTokenDistribution();
662
+ const totalPending = pendingDistribution.reduce(
663
+ (sum, item) => sum + item.amount,
664
+ 0
665
+ );
666
+ if (totalBalance < adjustedAmount && totalPending + totalBalance > adjustedAmount && (retryCount ?? 0) < 1) {
667
+ return await this._refundAndRetry(options);
668
+ }
669
+ const totalAvailableBalance = totalBalance + totalPending;
670
+ if (totalAvailableBalance < adjustedAmount) {
671
+ return this._createInsufficientBalanceError(
672
+ adjustedAmount,
673
+ balances,
674
+ units,
675
+ totalAvailableBalance
676
+ );
677
+ }
678
+ let { selectedMintUrl, selectedMintBalance } = this._selectMintWithBalance(
679
+ balances,
680
+ units,
681
+ adjustedAmount,
682
+ excludeMints
683
+ );
684
+ if (selectedMintUrl && baseUrl && this.providerRegistry) {
685
+ const providerMints = this.providerRegistry.getProviderMints(baseUrl);
686
+ if (providerMints.length > 0 && !providerMints.includes(selectedMintUrl)) {
687
+ const alternateResult = await this._findAlternateMint(
688
+ options,
689
+ balances,
690
+ units,
691
+ providerMints
692
+ );
693
+ if (alternateResult) {
694
+ return alternateResult;
695
+ }
696
+ adjustedAmount += 2;
697
+ }
698
+ }
699
+ const activeMintBalance = balances[mintUrl] || 0;
700
+ const activeMintUnit = units[mintUrl];
701
+ const activeMintBalanceInSats = activeMintUnit === "msat" ? activeMintBalance / 1e3 : activeMintBalance;
702
+ let token = null;
703
+ if (activeMintBalanceInSats >= adjustedAmount && (baseUrl === "" || !this.providerRegistry)) {
704
+ try {
705
+ token = await this.walletAdapter.sendToken(
706
+ mintUrl,
707
+ adjustedAmount,
708
+ p2pkPubkey
709
+ );
710
+ } catch (error) {
711
+ return this._handleSendError(error, options, balances, units);
712
+ }
713
+ } else if (selectedMintUrl && selectedMintBalance >= adjustedAmount) {
714
+ try {
715
+ token = await this.walletAdapter.sendToken(
716
+ selectedMintUrl,
717
+ adjustedAmount,
718
+ p2pkPubkey
719
+ );
720
+ } catch (error) {
721
+ return this._handleSendError(error, options, balances, units);
722
+ }
723
+ } else {
724
+ return this._createInsufficientBalanceError(
725
+ adjustedAmount,
726
+ balances,
727
+ units
728
+ );
729
+ }
730
+ if (token && baseUrl) {
731
+ this.storageAdapter.setToken(baseUrl, token);
732
+ }
733
+ this._logTransaction("spend", {
734
+ amount: adjustedAmount,
735
+ mintUrl: selectedMintUrl || mintUrl,
736
+ baseUrl,
737
+ status: "success"
738
+ });
739
+ return {
740
+ token,
741
+ status: "success",
742
+ balance: adjustedAmount,
743
+ unit: activeMintUnit
744
+ };
745
+ }
746
+ /**
747
+ * Try to reuse an existing token
748
+ */
749
+ async _tryReuseToken(baseUrl, amount, mintUrl) {
750
+ const storedToken = this.storageAdapter.getToken(baseUrl);
751
+ if (!storedToken) return null;
752
+ const pendingDistribution = this.storageAdapter.getPendingTokenDistribution();
753
+ const balanceForBaseUrl = pendingDistribution.find((b) => b.baseUrl === baseUrl)?.amount || 0;
754
+ console.log("RESUINGDSR GSODGNSD", balanceForBaseUrl, amount);
755
+ if (balanceForBaseUrl > amount) {
756
+ const units = this.walletAdapter.getMintUnits();
757
+ const unit = units[mintUrl] || "sat";
758
+ return {
759
+ token: storedToken,
760
+ status: "success",
761
+ balance: balanceForBaseUrl,
762
+ unit
763
+ };
764
+ }
765
+ if (this.balanceManager) {
766
+ const topUpAmount = Math.ceil(amount * 1.2 - balanceForBaseUrl);
767
+ const topUpResult = await this.balanceManager.topUp({
768
+ mintUrl,
769
+ baseUrl,
770
+ amount: topUpAmount
771
+ });
772
+ console.log("TOPUP ", topUpResult);
773
+ if (topUpResult.success && topUpResult.toppedUpAmount) {
774
+ const newBalance = balanceForBaseUrl + topUpResult.toppedUpAmount;
775
+ const units = this.walletAdapter.getMintUnits();
776
+ const unit = units[mintUrl] || "sat";
777
+ this._logTransaction("topup", {
778
+ amount: topUpResult.toppedUpAmount,
779
+ mintUrl,
780
+ baseUrl,
781
+ status: "success"
782
+ });
783
+ return {
784
+ token: storedToken,
785
+ status: "success",
786
+ balance: newBalance,
787
+ unit
788
+ };
789
+ }
790
+ const providerBalance = await this._getProviderTokenBalance(
791
+ baseUrl,
792
+ storedToken
793
+ );
794
+ console.log(providerBalance);
795
+ if (providerBalance <= 0) {
796
+ this.storageAdapter.removeToken(baseUrl);
797
+ }
798
+ }
799
+ return null;
800
+ }
801
+ /**
802
+ * Refund pending tokens and retry
803
+ */
804
+ async _refundAndRetry(options) {
805
+ const { mintUrl, baseUrl, retryCount } = options;
806
+ const pendingDistribution = this.storageAdapter.getPendingTokenDistribution();
807
+ const refundResults = await Promise.allSettled(
808
+ pendingDistribution.map(async (pending) => {
809
+ const token = this.storageAdapter.getToken(pending.baseUrl);
810
+ if (!token || !this.balanceManager || pending.baseUrl === baseUrl) {
811
+ return { baseUrl: pending.baseUrl, success: false };
812
+ }
813
+ const tokenBalance = await this.balanceManager.getTokenBalance(token, pending.baseUrl);
814
+ if (tokenBalance.reserved > 0) {
815
+ return { baseUrl: pending.baseUrl, success: false };
816
+ }
817
+ const result = await this.balanceManager.refund({
818
+ mintUrl,
819
+ baseUrl: pending.baseUrl,
820
+ token
821
+ });
822
+ return { baseUrl: pending.baseUrl, success: result.success };
823
+ })
824
+ );
825
+ for (const result of refundResults) {
826
+ const refundResult = result.status === "fulfilled" ? result.value : { baseUrl: "", success: false };
827
+ if (refundResult.success) {
828
+ this.storageAdapter.removeToken(refundResult.baseUrl);
829
+ }
830
+ }
831
+ const successfulRefunds = refundResults.filter(
832
+ (r) => r.status === "fulfilled" && r.value.success
833
+ ).length;
834
+ if (successfulRefunds > 0) {
835
+ this._logTransaction("refund", {
836
+ amount: pendingDistribution.length,
837
+ mintUrl,
838
+ status: "success",
839
+ details: `Refunded ${successfulRefunds} of ${pendingDistribution.length} tokens`
840
+ });
841
+ }
842
+ return this._spendInternal({
843
+ ...options,
844
+ retryCount: (retryCount || 0) + 1
845
+ });
846
+ }
847
+ /**
848
+ * Find an alternate mint that the provider accepts
849
+ */
850
+ async _findAlternateMint(options, balances, units, providerMints) {
851
+ const { amount, excludeMints } = options;
852
+ const adjustedAmount = Math.ceil(amount) + 2;
853
+ const extendedExcludes = [...excludeMints || []];
854
+ while (true) {
855
+ const { selectedMintUrl } = this._selectMintWithBalance(
856
+ balances,
857
+ units,
858
+ adjustedAmount,
859
+ extendedExcludes
860
+ );
861
+ if (!selectedMintUrl) break;
862
+ if (providerMints.includes(selectedMintUrl)) {
863
+ try {
864
+ const token = await this.walletAdapter.sendToken(
865
+ selectedMintUrl,
866
+ adjustedAmount
867
+ );
868
+ if (options.baseUrl) {
869
+ this.storageAdapter.setToken(options.baseUrl, token);
870
+ }
871
+ return {
872
+ token,
873
+ status: "success",
874
+ balance: adjustedAmount,
875
+ unit: units[selectedMintUrl] || "sat"
876
+ };
877
+ } catch (error) {
878
+ extendedExcludes.push(selectedMintUrl);
879
+ }
880
+ } else {
881
+ extendedExcludes.push(selectedMintUrl);
882
+ }
883
+ }
884
+ return null;
885
+ }
886
+ /**
887
+ * Handle send errors with retry logic for network errors
888
+ */
889
+ async _handleSendError(error, options, balances, units) {
890
+ const errorMsg = error instanceof Error ? error.message : String(error);
891
+ const isNetworkError = error instanceof Error && (error.message.includes(
892
+ "NetworkError when attempting to fetch resource"
893
+ ) || error.message.includes("Failed to fetch") || error.message.includes("Load failed"));
894
+ if (isNetworkError) {
895
+ const { mintUrl, amount, baseUrl, p2pkPubkey, excludeMints, retryCount } = options;
896
+ const extendedExcludes = [...excludeMints || [], mintUrl];
897
+ const { selectedMintUrl } = this._selectMintWithBalance(
898
+ balances,
899
+ units,
900
+ Math.ceil(amount),
901
+ extendedExcludes
902
+ );
903
+ if (selectedMintUrl && (retryCount || 0) < Object.keys(balances).length) {
904
+ return this._spendInternal({
905
+ ...options,
906
+ mintUrl: selectedMintUrl,
907
+ excludeMints: extendedExcludes,
908
+ retryCount: (retryCount || 0) + 1
909
+ });
910
+ }
911
+ throw new MintUnreachableError(mintUrl);
912
+ }
913
+ return {
914
+ token: null,
915
+ status: "failed",
916
+ balance: 0,
917
+ error: `Error generating token: ${errorMsg}`
918
+ };
919
+ }
920
+ /**
921
+ * Select a mint with sufficient balance
922
+ */
923
+ _selectMintWithBalance(balances, units, amount, excludeMints = []) {
924
+ for (const mintUrl in balances) {
925
+ if (excludeMints.includes(mintUrl)) {
926
+ continue;
927
+ }
928
+ const balance = balances[mintUrl];
929
+ const unit = units[mintUrl];
930
+ const balanceInSats = unit === "msat" ? balance / 1e3 : balance;
931
+ if (balanceInSats >= amount) {
932
+ return { selectedMintUrl: mintUrl, selectedMintBalance: balanceInSats };
933
+ }
934
+ }
935
+ return { selectedMintUrl: null, selectedMintBalance: 0 };
936
+ }
937
+ /**
938
+ * Create an insufficient balance error result
939
+ */
940
+ _createInsufficientBalanceError(required, balances, units, availableBalance) {
941
+ let maxBalance = 0;
942
+ let maxMintUrl = "";
943
+ for (const mintUrl in balances) {
944
+ const balance = balances[mintUrl];
945
+ const unit = units[mintUrl];
946
+ const balanceInSats = unit === "msat" ? balance / 1e3 : balance;
947
+ if (balanceInSats > maxBalance) {
948
+ maxBalance = balanceInSats;
949
+ maxMintUrl = mintUrl;
950
+ }
951
+ }
952
+ const error = new InsufficientBalanceError(
953
+ required,
954
+ availableBalance ?? maxBalance,
955
+ maxBalance,
956
+ maxMintUrl
957
+ );
958
+ return {
959
+ token: null,
960
+ status: "failed",
961
+ balance: 0,
962
+ error: error.message,
963
+ errorDetails: {
964
+ required,
965
+ available: availableBalance ?? maxBalance,
966
+ maxMintBalance: maxBalance,
967
+ maxMintUrl
968
+ }
969
+ };
970
+ }
971
+ async _getProviderTokenBalance(baseUrl, token) {
972
+ try {
973
+ const response = await fetch(`${baseUrl}v1/wallet/info`, {
974
+ headers: {
975
+ Authorization: `Bearer ${token}`
976
+ }
977
+ });
978
+ if (response.ok) {
979
+ const data = await response.json();
980
+ return data.balance / 1e3;
981
+ }
982
+ } catch {
983
+ return 0;
984
+ }
985
+ return 0;
986
+ }
987
+ };
988
+
989
+ // wallet/BalanceManager.ts
990
+ var BalanceManager = class {
991
+ constructor(walletAdapter, storageAdapter) {
992
+ this.walletAdapter = walletAdapter;
993
+ this.storageAdapter = storageAdapter;
994
+ }
995
+ /**
996
+ * Unified refund - handles both NIP-60 and legacy wallet refunds
997
+ */
998
+ async refund(options) {
999
+ const { mintUrl, baseUrl, token: providedToken } = options;
1000
+ const storedToken = providedToken || this.storageAdapter.getToken(baseUrl);
1001
+ if (!storedToken) {
1002
+ console.log("[BalanceManager] No token to refund, returning early");
1003
+ return { success: true, message: "No API key to refund" };
1004
+ }
1005
+ let fetchResult;
1006
+ try {
1007
+ fetchResult = await this._fetchRefundToken(baseUrl, storedToken);
1008
+ if (!fetchResult.success) {
1009
+ return {
1010
+ success: false,
1011
+ message: fetchResult.error || "Refund failed",
1012
+ requestId: fetchResult.requestId
1013
+ };
1014
+ }
1015
+ if (!fetchResult.token) {
1016
+ return {
1017
+ success: false,
1018
+ message: "No token received from refund",
1019
+ requestId: fetchResult.requestId
1020
+ };
1021
+ }
1022
+ if (fetchResult.error === "No balance to refund") {
1023
+ console.log(
1024
+ "[BalanceManager] No balance to refund, removing stored token"
1025
+ );
1026
+ this.storageAdapter.removeToken(baseUrl);
1027
+ return { success: true, message: "No balance to refund" };
1028
+ }
1029
+ const receiveResult = await this.walletAdapter.receiveToken(
1030
+ fetchResult.token
1031
+ );
1032
+ const totalAmountMsat = receiveResult.unit === "msat" ? receiveResult.amount : receiveResult.amount * 1e3;
1033
+ if (!providedToken) {
1034
+ this.storageAdapter.removeToken(baseUrl);
1035
+ }
1036
+ return {
1037
+ success: receiveResult.success,
1038
+ refundedAmount: totalAmountMsat,
1039
+ requestId: fetchResult.requestId
1040
+ };
1041
+ } catch (error) {
1042
+ console.error("[BalanceManager] Refund error", error);
1043
+ return this._handleRefundError(error, mintUrl, fetchResult?.requestId);
1044
+ }
1045
+ }
1046
+ /**
1047
+ * Top up API key balance with a cashu token
1048
+ */
1049
+ async topUp(options) {
1050
+ const { mintUrl, baseUrl, amount, token: providedToken } = options;
1051
+ if (!amount || amount <= 0) {
1052
+ return { success: false, message: "Invalid top up amount" };
1053
+ }
1054
+ const storedToken = providedToken || this.storageAdapter.getToken(baseUrl);
1055
+ if (!storedToken) {
1056
+ return { success: false, message: "No API key available for top up" };
1057
+ }
1058
+ let cashuToken = null;
1059
+ let requestId;
1060
+ try {
1061
+ cashuToken = await this.walletAdapter.sendToken(mintUrl, amount);
1062
+ const topUpResult = await this._postTopUp(
1063
+ baseUrl,
1064
+ storedToken,
1065
+ cashuToken
1066
+ );
1067
+ requestId = topUpResult.requestId;
1068
+ if (!topUpResult.success) {
1069
+ await this._recoverFailedTopUp(cashuToken);
1070
+ return {
1071
+ success: false,
1072
+ message: topUpResult.error || "Top up failed",
1073
+ requestId,
1074
+ recoveredToken: true
1075
+ };
1076
+ }
1077
+ return {
1078
+ success: true,
1079
+ toppedUpAmount: amount,
1080
+ requestId
1081
+ };
1082
+ } catch (error) {
1083
+ if (cashuToken) {
1084
+ await this._recoverFailedTopUp(cashuToken);
1085
+ }
1086
+ return this._handleTopUpError(error, mintUrl, requestId);
1087
+ }
1088
+ }
1089
+ /**
1090
+ * Fetch refund token from provider API
1091
+ */
1092
+ async _fetchRefundToken(baseUrl, storedToken) {
1093
+ if (!baseUrl) {
1094
+ return {
1095
+ success: false,
1096
+ error: "No base URL configured"
1097
+ };
1098
+ }
1099
+ const normalizedBaseUrl = baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`;
1100
+ const url = `${normalizedBaseUrl}v1/wallet/refund`;
1101
+ const controller = new AbortController();
1102
+ const timeoutId = setTimeout(() => {
1103
+ controller.abort();
1104
+ }, 6e4);
1105
+ try {
1106
+ const response = await fetch(url, {
1107
+ method: "POST",
1108
+ headers: {
1109
+ Authorization: `Bearer ${storedToken}`,
1110
+ "Content-Type": "application/json"
1111
+ },
1112
+ signal: controller.signal
1113
+ });
1114
+ clearTimeout(timeoutId);
1115
+ const requestId = response.headers.get("x-routstr-request-id") || void 0;
1116
+ if (!response.ok) {
1117
+ const errorData = await response.json().catch(() => ({}));
1118
+ if (response.status === 400 && errorData?.detail === "No balance to refund") {
1119
+ this.storageAdapter.removeToken(baseUrl);
1120
+ return {
1121
+ success: false,
1122
+ requestId,
1123
+ error: "No balance to refund"
1124
+ };
1125
+ }
1126
+ return {
1127
+ success: false,
1128
+ requestId,
1129
+ error: `Refund request failed with status ${response.status}: ${errorData?.detail || response.statusText}`
1130
+ };
1131
+ }
1132
+ const data = await response.json();
1133
+ console.log("refund rsule", data);
1134
+ return {
1135
+ success: true,
1136
+ token: data.token,
1137
+ requestId
1138
+ };
1139
+ } catch (error) {
1140
+ clearTimeout(timeoutId);
1141
+ console.error("[BalanceManager._fetchRefundToken] Fetch error", error);
1142
+ if (error instanceof Error) {
1143
+ if (error.name === "AbortError") {
1144
+ return {
1145
+ success: false,
1146
+ error: "Request timed out after 1 minute"
1147
+ };
1148
+ }
1149
+ return {
1150
+ success: false,
1151
+ error: error.message
1152
+ };
1153
+ }
1154
+ return {
1155
+ success: false,
1156
+ error: "Unknown error occurred during refund request"
1157
+ };
1158
+ }
1159
+ }
1160
+ /**
1161
+ * Post topup request to provider API
1162
+ */
1163
+ async _postTopUp(baseUrl, storedToken, cashuToken) {
1164
+ if (!baseUrl) {
1165
+ return {
1166
+ success: false,
1167
+ error: "No base URL configured"
1168
+ };
1169
+ }
1170
+ const normalizedBaseUrl = baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`;
1171
+ const url = `${normalizedBaseUrl}v1/wallet/topup?cashu_token=${encodeURIComponent(
1172
+ cashuToken
1173
+ )}`;
1174
+ const controller = new AbortController();
1175
+ const timeoutId = setTimeout(() => {
1176
+ controller.abort();
1177
+ }, 6e4);
1178
+ try {
1179
+ const response = await fetch(url, {
1180
+ method: "POST",
1181
+ headers: {
1182
+ Authorization: `Bearer ${storedToken}`,
1183
+ "Content-Type": "application/json"
1184
+ },
1185
+ signal: controller.signal
1186
+ });
1187
+ clearTimeout(timeoutId);
1188
+ const requestId = response.headers.get("x-routstr-request-id") || void 0;
1189
+ if (!response.ok) {
1190
+ const errorData = await response.json().catch(() => ({}));
1191
+ return {
1192
+ success: false,
1193
+ requestId,
1194
+ error: errorData?.detail || `Top up failed with status ${response.status}`
1195
+ };
1196
+ }
1197
+ return { success: true, requestId };
1198
+ } catch (error) {
1199
+ clearTimeout(timeoutId);
1200
+ console.error("[BalanceManager._postTopUp] Fetch error", error);
1201
+ if (error instanceof Error) {
1202
+ if (error.name === "AbortError") {
1203
+ return {
1204
+ success: false,
1205
+ error: "Request timed out after 1 minute"
1206
+ };
1207
+ }
1208
+ return {
1209
+ success: false,
1210
+ error: error.message
1211
+ };
1212
+ }
1213
+ return {
1214
+ success: false,
1215
+ error: "Unknown error occurred during top up request"
1216
+ };
1217
+ }
1218
+ }
1219
+ /**
1220
+ * Attempt to receive token back after failed top up
1221
+ */
1222
+ async _recoverFailedTopUp(cashuToken) {
1223
+ try {
1224
+ await this.walletAdapter.receiveToken(cashuToken);
1225
+ } catch (error) {
1226
+ console.error(
1227
+ "[BalanceManager._recoverFailedTopUp] Failed to recover token",
1228
+ error
1229
+ );
1230
+ }
1231
+ }
1232
+ /**
1233
+ * Handle refund errors with specific error types
1234
+ */
1235
+ _handleRefundError(error, mintUrl, requestId) {
1236
+ if (error instanceof Error) {
1237
+ if (error.message.includes(
1238
+ "NetworkError when attempting to fetch resource"
1239
+ ) || error.message.includes("Failed to fetch") || error.message.includes("Load failed")) {
1240
+ return {
1241
+ success: false,
1242
+ message: `Failed to connect to the mint: ${mintUrl}`,
1243
+ requestId
1244
+ };
1245
+ }
1246
+ if (error.message.includes("Wallet not found")) {
1247
+ return {
1248
+ success: false,
1249
+ message: `Wallet couldn't be loaded. Please save this refunded cashu token manually.`,
1250
+ requestId
1251
+ };
1252
+ }
1253
+ return {
1254
+ success: false,
1255
+ message: error.message,
1256
+ requestId
1257
+ };
1258
+ }
1259
+ return {
1260
+ success: false,
1261
+ message: "Refund failed",
1262
+ requestId
1263
+ };
1264
+ }
1265
+ /**
1266
+ * Get token balance from provider
1267
+ */
1268
+ async getTokenBalance(token, baseUrl) {
1269
+ try {
1270
+ const response = await fetch(`${baseUrl}v1/wallet/info`, {
1271
+ headers: {
1272
+ Authorization: `Bearer ${token}`
1273
+ }
1274
+ });
1275
+ if (response.ok) {
1276
+ const data = await response.json();
1277
+ return {
1278
+ amount: data.balance,
1279
+ reserved: data.reserved ?? 0,
1280
+ unit: "msat",
1281
+ apiKey: data.api_key
1282
+ };
1283
+ }
1284
+ } catch {
1285
+ }
1286
+ return { amount: 0, reserved: 0, unit: "sat", apiKey: "" };
1287
+ }
1288
+ /**
1289
+ * Handle topup errors with specific error types
1290
+ */
1291
+ _handleTopUpError(error, mintUrl, requestId) {
1292
+ if (error instanceof Error) {
1293
+ if (error.message.includes(
1294
+ "NetworkError when attempting to fetch resource"
1295
+ ) || error.message.includes("Failed to fetch") || error.message.includes("Load failed")) {
1296
+ return {
1297
+ success: false,
1298
+ message: `Failed to connect to the mint: ${mintUrl}`,
1299
+ requestId
1300
+ };
1301
+ }
1302
+ if (error.message.includes("Wallet not found")) {
1303
+ return {
1304
+ success: false,
1305
+ message: "Wallet couldn't be loaded. The cashu token was recovered locally.",
1306
+ requestId
1307
+ };
1308
+ }
1309
+ return {
1310
+ success: false,
1311
+ message: error.message,
1312
+ requestId
1313
+ };
1314
+ }
1315
+ return {
1316
+ success: false,
1317
+ message: "Top up failed",
1318
+ requestId
1319
+ };
1320
+ }
1321
+ };
1322
+
1323
+ // client/StreamProcessor.ts
1324
+ var StreamProcessor = class {
1325
+ accumulatedContent = "";
1326
+ accumulatedThinking = "";
1327
+ accumulatedImages = [];
1328
+ isInThinking = false;
1329
+ isInContent = false;
1330
+ /**
1331
+ * Process a streaming response
1332
+ */
1333
+ async process(response, callbacks, modelId) {
1334
+ if (!response.body) {
1335
+ throw new Error("Response body is not available");
1336
+ }
1337
+ const reader = response.body.getReader();
1338
+ const decoder = new TextDecoder("utf-8");
1339
+ let buffer = "";
1340
+ this.accumulatedContent = "";
1341
+ this.accumulatedThinking = "";
1342
+ this.accumulatedImages = [];
1343
+ this.isInThinking = false;
1344
+ this.isInContent = false;
1345
+ let usage;
1346
+ let model;
1347
+ let finish_reason;
1348
+ let citations;
1349
+ let annotations;
1350
+ try {
1351
+ while (true) {
1352
+ const { done, value } = await reader.read();
1353
+ if (done) {
1354
+ break;
1355
+ }
1356
+ const chunk = decoder.decode(value, { stream: true });
1357
+ buffer += chunk;
1358
+ const lines = buffer.split("\n");
1359
+ buffer = lines.pop() || "";
1360
+ for (const line of lines) {
1361
+ const parsed = this._parseLine(line);
1362
+ if (!parsed) continue;
1363
+ if (parsed.content) {
1364
+ this._handleContent(parsed.content, callbacks, modelId);
1365
+ }
1366
+ if (parsed.reasoning) {
1367
+ this._handleThinking(parsed.reasoning, callbacks);
1368
+ }
1369
+ if (parsed.usage) {
1370
+ usage = parsed.usage;
1371
+ }
1372
+ if (parsed.model) {
1373
+ model = parsed.model;
1374
+ }
1375
+ if (parsed.finish_reason) {
1376
+ finish_reason = parsed.finish_reason;
1377
+ }
1378
+ if (parsed.citations) {
1379
+ citations = parsed.citations;
1380
+ }
1381
+ if (parsed.annotations) {
1382
+ annotations = parsed.annotations;
1383
+ }
1384
+ if (parsed.images) {
1385
+ this._mergeImages(parsed.images);
1386
+ }
1387
+ }
1388
+ }
1389
+ } finally {
1390
+ reader.releaseLock();
1391
+ }
1392
+ return {
1393
+ content: this.accumulatedContent,
1394
+ thinking: this.accumulatedThinking || void 0,
1395
+ images: this.accumulatedImages.length > 0 ? this.accumulatedImages : void 0,
1396
+ usage,
1397
+ model,
1398
+ finish_reason,
1399
+ citations,
1400
+ annotations
1401
+ };
1402
+ }
1403
+ /**
1404
+ * Parse a single SSE line
1405
+ */
1406
+ _parseLine(line) {
1407
+ if (!line.trim()) return null;
1408
+ if (!line.startsWith("data: ")) {
1409
+ return null;
1410
+ }
1411
+ const jsonData = line.slice(6);
1412
+ if (jsonData === "[DONE]") {
1413
+ return null;
1414
+ }
1415
+ try {
1416
+ const parsed = JSON.parse(jsonData);
1417
+ const result = {};
1418
+ if (parsed.choices?.[0]?.delta?.content) {
1419
+ result.content = parsed.choices[0].delta.content;
1420
+ }
1421
+ if (parsed.choices?.[0]?.delta?.reasoning) {
1422
+ result.reasoning = parsed.choices[0].delta.reasoning;
1423
+ }
1424
+ if (parsed.usage) {
1425
+ result.usage = {
1426
+ total_tokens: parsed.usage.total_tokens,
1427
+ prompt_tokens: parsed.usage.prompt_tokens,
1428
+ completion_tokens: parsed.usage.completion_tokens
1429
+ };
1430
+ }
1431
+ if (parsed.model) {
1432
+ result.model = parsed.model;
1433
+ }
1434
+ if (parsed.citations) {
1435
+ result.citations = parsed.citations;
1436
+ }
1437
+ if (parsed.annotations) {
1438
+ result.annotations = parsed.annotations;
1439
+ }
1440
+ if (parsed.choices?.[0]?.finish_reason) {
1441
+ result.finish_reason = parsed.choices[0].finish_reason;
1442
+ }
1443
+ const images = parsed.choices?.[0]?.message?.images || parsed.choices?.[0]?.delta?.images;
1444
+ if (images && Array.isArray(images)) {
1445
+ result.images = images;
1446
+ }
1447
+ return result;
1448
+ } catch {
1449
+ return null;
1450
+ }
1451
+ }
1452
+ /**
1453
+ * Handle content delta with thinking support
1454
+ */
1455
+ _handleContent(content, callbacks, modelId) {
1456
+ if (this.isInThinking && !this.isInContent) {
1457
+ this.accumulatedThinking += "</thinking>";
1458
+ callbacks.onThinking(this.accumulatedThinking);
1459
+ this.isInThinking = false;
1460
+ this.isInContent = true;
1461
+ }
1462
+ if (modelId) {
1463
+ this._extractThinkingFromContent(content, callbacks);
1464
+ } else {
1465
+ this.accumulatedContent += content;
1466
+ }
1467
+ callbacks.onContent(this.accumulatedContent);
1468
+ }
1469
+ /**
1470
+ * Handle thinking/reasoning content
1471
+ */
1472
+ _handleThinking(reasoning, callbacks) {
1473
+ if (!this.isInThinking) {
1474
+ this.accumulatedThinking += "<thinking> ";
1475
+ this.isInThinking = true;
1476
+ }
1477
+ this.accumulatedThinking += reasoning;
1478
+ callbacks.onThinking(this.accumulatedThinking);
1479
+ }
1480
+ /**
1481
+ * Extract thinking blocks from content (for models with inline thinking)
1482
+ */
1483
+ _extractThinkingFromContent(content, callbacks) {
1484
+ const parts = content.split(/(<thinking>|<\/thinking>)/);
1485
+ for (const part of parts) {
1486
+ if (part === "<thinking>") {
1487
+ this.isInThinking = true;
1488
+ if (!this.accumulatedThinking.includes("<thinking>")) {
1489
+ this.accumulatedThinking += "<thinking> ";
1490
+ }
1491
+ } else if (part === "</thinking>") {
1492
+ this.isInThinking = false;
1493
+ this.accumulatedThinking += "</thinking>";
1494
+ } else if (this.isInThinking) {
1495
+ this.accumulatedThinking += part;
1496
+ } else {
1497
+ this.accumulatedContent += part;
1498
+ }
1499
+ }
1500
+ }
1501
+ /**
1502
+ * Merge images into accumulated array, avoiding duplicates
1503
+ */
1504
+ _mergeImages(newImages) {
1505
+ for (const img of newImages) {
1506
+ const newUrl = img.image_url?.url;
1507
+ const existingIndex = this.accumulatedImages.findIndex((existing) => {
1508
+ const existingUrl = existing.image_url?.url;
1509
+ if (newUrl && existingUrl) {
1510
+ return existingUrl === newUrl;
1511
+ }
1512
+ if (img.index !== void 0 && existing.index !== void 0) {
1513
+ return existing.index === img.index;
1514
+ }
1515
+ return false;
1516
+ });
1517
+ if (existingIndex === -1) {
1518
+ this.accumulatedImages.push(img);
1519
+ } else {
1520
+ this.accumulatedImages[existingIndex] = img;
1521
+ }
1522
+ }
1523
+ }
1524
+ };
1525
+
1526
+ // utils/torUtils.ts
1527
+ var TOR_ONION_SUFFIX = ".onion";
1528
+ var isTorContext = () => {
1529
+ if (typeof window === "undefined") return false;
1530
+ const hostname = window.location.hostname.toLowerCase();
1531
+ return hostname.endsWith(TOR_ONION_SUFFIX);
1532
+ };
1533
+ var isOnionUrl = (url) => {
1534
+ if (!url) return false;
1535
+ const trimmed = url.trim().toLowerCase();
1536
+ if (!trimmed) return false;
1537
+ try {
1538
+ const candidate = trimmed.startsWith("http") ? trimmed : `http://${trimmed}`;
1539
+ return new URL(candidate).hostname.endsWith(TOR_ONION_SUFFIX);
1540
+ } catch {
1541
+ return trimmed.includes(TOR_ONION_SUFFIX);
1542
+ }
1543
+ };
1544
+ var shouldAllowHttp = (url, torMode) => {
1545
+ if (!url.startsWith("http://")) return true;
1546
+ if (url.includes("localhost") || url.includes("127.0.0.1")) return true;
1547
+ return torMode && isOnionUrl(url);
1548
+ };
1549
+ var normalizeProviderUrl = (url, torMode = false) => {
1550
+ if (!url || typeof url !== "string") return null;
1551
+ const trimmed = url.trim();
1552
+ if (!trimmed) return null;
1553
+ if (/^https?:\/\//i.test(trimmed)) {
1554
+ return trimmed.endsWith("/") ? trimmed : `${trimmed}/`;
1555
+ }
1556
+ const useHttpForOnion = torMode && isOnionUrl(trimmed);
1557
+ const withProto = `${useHttpForOnion ? "http" : "https"}://${trimmed}`;
1558
+ return withProto.endsWith("/") ? withProto : `${withProto}/`;
1559
+ };
1560
+ var dedupePreserveOrder = (urls) => {
1561
+ const seen = /* @__PURE__ */ new Set();
1562
+ const out = [];
1563
+ for (const url of urls) {
1564
+ if (!seen.has(url)) {
1565
+ seen.add(url);
1566
+ out.push(url);
1567
+ }
1568
+ }
1569
+ return out;
1570
+ };
1571
+ var getProviderEndpoints = (provider, torMode) => {
1572
+ const rawUrls = [
1573
+ provider.endpoint_url,
1574
+ ...Array.isArray(provider.endpoint_urls) ? provider.endpoint_urls : [],
1575
+ provider.onion_url,
1576
+ ...Array.isArray(provider.onion_urls) ? provider.onion_urls : []
1577
+ ];
1578
+ const normalized = rawUrls.map((value) => normalizeProviderUrl(value, torMode)).filter((value) => Boolean(value));
1579
+ const unique = dedupePreserveOrder(normalized).filter(
1580
+ (value) => shouldAllowHttp(value, torMode)
1581
+ );
1582
+ if (unique.length === 0) return [];
1583
+ const onion = unique.filter((value) => isOnionUrl(value));
1584
+ const clearnet = unique.filter((value) => !isOnionUrl(value));
1585
+ if (torMode) {
1586
+ return onion.length > 0 ? onion : clearnet;
1587
+ }
1588
+ return clearnet;
1589
+ };
1590
+ var filterBaseUrlsForTor = (baseUrls, torMode) => {
1591
+ if (!Array.isArray(baseUrls)) return [];
1592
+ const normalized = baseUrls.map((value) => normalizeProviderUrl(value, torMode)).filter((value) => Boolean(value));
1593
+ const filtered = normalized.filter(
1594
+ (value) => torMode ? true : !isOnionUrl(value)
1595
+ );
1596
+ return dedupePreserveOrder(
1597
+ filtered.filter((value) => shouldAllowHttp(value, torMode))
1598
+ );
1599
+ };
1600
+
1601
+ // client/ProviderManager.ts
1602
+ function getImageResolutionFromDataUrl(dataUrl) {
1603
+ try {
1604
+ if (typeof dataUrl !== "string" || !dataUrl.startsWith("data:"))
1605
+ return null;
1606
+ const commaIdx = dataUrl.indexOf(",");
1607
+ if (commaIdx === -1) return null;
1608
+ const meta = dataUrl.slice(5, commaIdx);
1609
+ const base64 = dataUrl.slice(commaIdx + 1);
1610
+ const binary = typeof atob === "function" ? atob(base64) : Buffer.from(base64, "base64").toString("binary");
1611
+ const len = binary.length;
1612
+ const bytes = new Uint8Array(len);
1613
+ for (let i = 0; i < len; i++) bytes[i] = binary.charCodeAt(i);
1614
+ const isPNG = meta.includes("image/png");
1615
+ const isJPEG = meta.includes("image/jpeg") || meta.includes("image/jpg");
1616
+ if (isPNG) {
1617
+ const sig = [137, 80, 78, 71, 13, 10, 26, 10];
1618
+ for (let i = 0; i < sig.length; i++) {
1619
+ if (bytes[i] !== sig[i]) return null;
1620
+ }
1621
+ const view = new DataView(
1622
+ bytes.buffer,
1623
+ bytes.byteOffset,
1624
+ bytes.byteLength
1625
+ );
1626
+ const width = view.getUint32(16, false);
1627
+ const height = view.getUint32(20, false);
1628
+ if (width > 0 && height > 0) return { width, height };
1629
+ return null;
1630
+ }
1631
+ if (isJPEG) {
1632
+ let offset = 0;
1633
+ if (bytes[offset++] !== 255 || bytes[offset++] !== 216) return null;
1634
+ while (offset < bytes.length) {
1635
+ while (offset < bytes.length && bytes[offset] !== 255) offset++;
1636
+ if (offset + 1 >= bytes.length) break;
1637
+ while (bytes[offset] === 255) offset++;
1638
+ const marker = bytes[offset++];
1639
+ if (marker === 216 || marker === 217) continue;
1640
+ if (offset + 1 >= bytes.length) break;
1641
+ const length = bytes[offset] << 8 | bytes[offset + 1];
1642
+ offset += 2;
1643
+ if (marker === 192 || marker === 194) {
1644
+ if (length < 7 || offset + length - 2 > bytes.length) return null;
1645
+ const precision = bytes[offset];
1646
+ const height = bytes[offset + 1] << 8 | bytes[offset + 2];
1647
+ const width = bytes[offset + 3] << 8 | bytes[offset + 4];
1648
+ if (precision > 0 && width > 0 && height > 0)
1649
+ return { width, height };
1650
+ return null;
1651
+ } else {
1652
+ offset += length - 2;
1653
+ }
1654
+ }
1655
+ return null;
1656
+ }
1657
+ return null;
1658
+ } catch {
1659
+ return null;
1660
+ }
1661
+ }
1662
+ function calculateImageTokens(width, height, detail = "auto") {
1663
+ if (detail === "low") return 85;
1664
+ let w = width;
1665
+ let h = height;
1666
+ if (w > 2048 || h > 2048) {
1667
+ const aspectRatio = w / h;
1668
+ if (w > h) {
1669
+ w = 2048;
1670
+ h = Math.floor(w / aspectRatio);
1671
+ } else {
1672
+ h = 2048;
1673
+ w = Math.floor(h * aspectRatio);
1674
+ }
1675
+ }
1676
+ if (w > 768 || h > 768) {
1677
+ const aspectRatio = w / h;
1678
+ if (w > h) {
1679
+ w = 768;
1680
+ h = Math.floor(w / aspectRatio);
1681
+ } else {
1682
+ h = 768;
1683
+ w = Math.floor(h * aspectRatio);
1684
+ }
1685
+ }
1686
+ const tilesWidth = Math.floor((w + 511) / 512);
1687
+ const tilesHeight = Math.floor((h + 511) / 512);
1688
+ const numTiles = tilesWidth * tilesHeight;
1689
+ return 85 + 170 * numTiles;
1690
+ }
1691
+ var ProviderManager = class {
1692
+ constructor(providerRegistry) {
1693
+ this.providerRegistry = providerRegistry;
1694
+ }
1695
+ failedProviders = /* @__PURE__ */ new Set();
1696
+ /**
1697
+ * Reset the failed providers list
1698
+ */
1699
+ resetFailedProviders() {
1700
+ this.failedProviders.clear();
1701
+ }
1702
+ /**
1703
+ * Mark a provider as failed
1704
+ */
1705
+ markFailed(baseUrl) {
1706
+ this.failedProviders.add(baseUrl);
1707
+ }
1708
+ /**
1709
+ * Check if a provider has failed
1710
+ */
1711
+ hasFailed(baseUrl) {
1712
+ return this.failedProviders.has(baseUrl);
1713
+ }
1714
+ /**
1715
+ * Find the next best provider for a model
1716
+ * @param modelId The model ID to find a provider for
1717
+ * @param currentBaseUrl The current provider to exclude
1718
+ * @returns The best provider URL or null if none available
1719
+ */
1720
+ findNextBestProvider(modelId, currentBaseUrl) {
1721
+ try {
1722
+ const torMode = isTorContext();
1723
+ const disabledProviders = new Set(
1724
+ this.providerRegistry.getDisabledProviders()
1725
+ );
1726
+ const allProviders = this.providerRegistry.getAllProvidersModels();
1727
+ const candidates = [];
1728
+ for (const [baseUrl, models] of Object.entries(allProviders)) {
1729
+ if (baseUrl === currentBaseUrl || this.failedProviders.has(baseUrl) || disabledProviders.has(baseUrl)) {
1730
+ continue;
1731
+ }
1732
+ if (!torMode && isOnionUrl(baseUrl)) {
1733
+ continue;
1734
+ }
1735
+ const model = models.find((m) => m.id === modelId);
1736
+ if (!model) continue;
1737
+ const cost = model.sats_pricing?.completion ?? 0;
1738
+ candidates.push({ baseUrl, model, cost });
1739
+ }
1740
+ candidates.sort((a, b) => a.cost - b.cost);
1741
+ return candidates.length > 0 ? candidates[0].baseUrl : null;
1742
+ } catch (error) {
1743
+ console.error("Error finding next best provider:", error);
1744
+ return null;
1745
+ }
1746
+ }
1747
+ /**
1748
+ * Find the best model for a provider
1749
+ * Useful when switching providers and need to find equivalent model
1750
+ */
1751
+ async getModelForProvider(baseUrl, modelId) {
1752
+ const models = this.providerRegistry.getModelsForProvider(baseUrl);
1753
+ const exactMatch = models.find((m) => m.id === modelId);
1754
+ if (exactMatch) return exactMatch;
1755
+ const providerInfo = await this.providerRegistry.getProviderInfo(baseUrl);
1756
+ if (providerInfo?.version && /^0\.1\./.test(providerInfo.version)) {
1757
+ const suffix = modelId.split("/").pop();
1758
+ const suffixMatch = models.find((m) => m.id === suffix);
1759
+ if (suffixMatch) return suffixMatch;
1760
+ }
1761
+ return null;
1762
+ }
1763
+ /**
1764
+ * Get all available providers for a model
1765
+ * Returns sorted list by price
1766
+ */
1767
+ getAllProvidersForModel(modelId) {
1768
+ const candidates = [];
1769
+ const allProviders = this.providerRegistry.getAllProvidersModels();
1770
+ const disabledProviders = new Set(
1771
+ this.providerRegistry.getDisabledProviders()
1772
+ );
1773
+ const torMode = isTorContext();
1774
+ for (const [baseUrl, models] of Object.entries(allProviders)) {
1775
+ if (disabledProviders.has(baseUrl)) continue;
1776
+ if (!torMode && isOnionUrl(baseUrl)) continue;
1777
+ const model = models.find((m) => m.id === modelId);
1778
+ if (!model) continue;
1779
+ const cost = model.sats_pricing?.completion ?? 0;
1780
+ candidates.push({ baseUrl, model, cost });
1781
+ }
1782
+ return candidates.sort((a, b) => a.cost - b.cost);
1783
+ }
1784
+ /**
1785
+ * Get providers for a model sorted by prompt+completion pricing
1786
+ */
1787
+ getProviderPriceRankingForModel(modelId, options = {}) {
1788
+ const normalizedId = this.normalizeModelId(modelId);
1789
+ const includeDisabled = options.includeDisabled ?? false;
1790
+ const torMode = options.torMode ?? false;
1791
+ const disabledProviders = new Set(
1792
+ this.providerRegistry.getDisabledProviders()
1793
+ );
1794
+ const allModels = this.providerRegistry.getAllProvidersModels();
1795
+ const results = [];
1796
+ for (const [baseUrl, models] of Object.entries(allModels)) {
1797
+ if (!includeDisabled && disabledProviders.has(baseUrl)) continue;
1798
+ if (torMode && !baseUrl.includes(".onion")) continue;
1799
+ if (!torMode && baseUrl.includes(".onion")) continue;
1800
+ const match = models.find(
1801
+ (model) => this.normalizeModelId(model.id) === normalizedId
1802
+ );
1803
+ if (!match?.sats_pricing) continue;
1804
+ const prompt = match.sats_pricing.prompt;
1805
+ const completion = match.sats_pricing.completion;
1806
+ if (typeof prompt !== "number" || typeof completion !== "number") {
1807
+ continue;
1808
+ }
1809
+ const promptPerMillion = prompt * 1e6;
1810
+ const completionPerMillion = completion * 1e6;
1811
+ const totalPerMillion = promptPerMillion + completionPerMillion;
1812
+ results.push({
1813
+ baseUrl,
1814
+ model: match,
1815
+ promptPerMillion,
1816
+ completionPerMillion,
1817
+ totalPerMillion
1818
+ });
1819
+ }
1820
+ return results.sort((a, b) => {
1821
+ if (a.totalPerMillion !== b.totalPerMillion) {
1822
+ return a.totalPerMillion - b.totalPerMillion;
1823
+ }
1824
+ return a.baseUrl.localeCompare(b.baseUrl);
1825
+ });
1826
+ }
1827
+ /**
1828
+ * Get best-priced provider for a specific model
1829
+ */
1830
+ getBestProviderForModel(modelId, options = {}) {
1831
+ const ranking = this.getProviderPriceRankingForModel(modelId, options);
1832
+ return ranking[0]?.baseUrl ?? null;
1833
+ }
1834
+ normalizeModelId(modelId) {
1835
+ return modelId.includes("/") ? modelId.split("/").pop() || modelId : modelId;
1836
+ }
1837
+ /**
1838
+ * Check if a provider accepts a specific mint
1839
+ */
1840
+ providerAcceptsMint(baseUrl, mintUrl) {
1841
+ const providerMints = this.providerRegistry.getProviderMints(baseUrl);
1842
+ if (providerMints.length === 0) {
1843
+ return true;
1844
+ }
1845
+ return providerMints.includes(mintUrl);
1846
+ }
1847
+ /**
1848
+ * Get required sats for a model based on message history
1849
+ * Simple estimation based on typical usage
1850
+ */
1851
+ getRequiredSatsForModel(model, apiMessages, maxTokens) {
1852
+ try {
1853
+ let imageTokens = 0;
1854
+ if (apiMessages) {
1855
+ for (const msg of apiMessages) {
1856
+ const content = msg?.content;
1857
+ if (Array.isArray(content)) {
1858
+ for (const part of content) {
1859
+ const isImage = part && typeof part === "object" && part.type === "image_url";
1860
+ const url = isImage ? typeof part.image_url === "string" ? part.image_url : part.image_url?.url : void 0;
1861
+ if (url && typeof url === "string" && url.startsWith("data:")) {
1862
+ const res = getImageResolutionFromDataUrl(url);
1863
+ if (res) {
1864
+ const tokensFromImage = calculateImageTokens(
1865
+ res.width,
1866
+ res.height
1867
+ );
1868
+ imageTokens += tokensFromImage;
1869
+ console.log("IMAGE INPUT RESOLUTION", {
1870
+ width: res.width,
1871
+ height: res.height,
1872
+ tokensFromImage
1873
+ });
1874
+ } else {
1875
+ console.log(
1876
+ "IMAGE INPUT RESOLUTION",
1877
+ "unknown (unsupported format or parse failure)"
1878
+ );
1879
+ }
1880
+ }
1881
+ }
1882
+ }
1883
+ }
1884
+ }
1885
+ const apiMessagesNoImages = apiMessages ? apiMessages.map((m) => {
1886
+ if (Array.isArray(m?.content)) {
1887
+ const filtered = m.content.filter(
1888
+ (p) => !(p && typeof p === "object" && p.type === "image_url")
1889
+ );
1890
+ return { ...m, content: filtered };
1891
+ }
1892
+ return m;
1893
+ }) : void 0;
1894
+ const approximateTokens = apiMessagesNoImages ? Math.ceil(JSON.stringify(apiMessagesNoImages, null, 2).length / 2.84) : 1e4;
1895
+ const totalInputTokens = approximateTokens + imageTokens;
1896
+ const sp = model?.sats_pricing;
1897
+ if (!sp) return 0;
1898
+ if (!sp.max_completion_cost) {
1899
+ return sp.max_cost ?? 50;
1900
+ }
1901
+ const promptCosts = (sp.prompt || 0) * totalInputTokens;
1902
+ let completionCost = sp.max_completion_cost;
1903
+ if (maxTokens !== void 0 && sp.completion) {
1904
+ completionCost = sp.completion * maxTokens;
1905
+ }
1906
+ const totalEstimatedCosts = (promptCosts + completionCost) * 1.05;
1907
+ return totalEstimatedCosts;
1908
+ } catch (e) {
1909
+ console.error(e);
1910
+ return 0;
1911
+ }
1912
+ }
1913
+ };
1914
+
1915
+ // client/RoutstrClient.ts
1916
+ var RoutstrClient = class {
1917
+ constructor(walletAdapter, storageAdapter, providerRegistry, alertLevel, mode = "xcashu") {
1918
+ this.walletAdapter = walletAdapter;
1919
+ this.storageAdapter = storageAdapter;
1920
+ this.providerRegistry = providerRegistry;
1921
+ this.balanceManager = new BalanceManager(walletAdapter, storageAdapter);
1922
+ this.cashuSpender = new CashuSpender(
1923
+ walletAdapter,
1924
+ storageAdapter,
1925
+ providerRegistry,
1926
+ this.balanceManager
1927
+ );
1928
+ this.streamProcessor = new StreamProcessor();
1929
+ this.providerManager = new ProviderManager(providerRegistry);
1930
+ this.alertLevel = alertLevel;
1931
+ this.mode = mode;
1932
+ }
1933
+ cashuSpender;
1934
+ balanceManager;
1935
+ streamProcessor;
1936
+ providerManager;
1937
+ alertLevel;
1938
+ mode;
1939
+ /**
1940
+ * Get the current client mode
1941
+ */
1942
+ getMode() {
1943
+ return this.mode;
1944
+ }
1945
+ /**
1946
+ * Get the CashuSpender instance
1947
+ */
1948
+ getCashuSpender() {
1949
+ return this.cashuSpender;
1950
+ }
1951
+ /**
1952
+ * Get the BalanceManager instance
1953
+ */
1954
+ getBalanceManager() {
1955
+ return this.balanceManager;
1956
+ }
1957
+ /**
1958
+ * Get the ProviderManager instance
1959
+ */
1960
+ getProviderManager() {
1961
+ return this.providerManager;
1962
+ }
1963
+ /**
1964
+ * Check if the client is currently busy (in critical section)
1965
+ */
1966
+ get isBusy() {
1967
+ return this.cashuSpender.isBusy;
1968
+ }
1969
+ /**
1970
+ * Route an API request to the upstream provider
1971
+ *
1972
+ * This is a simpler alternative to fetchAIResponse that just proxies
1973
+ * the request upstream without the streaming callback machinery.
1974
+ * Useful for daemon-style routing where you just need to forward
1975
+ * requests and get responses back.
1976
+ */
1977
+ async routeRequest(params) {
1978
+ const {
1979
+ path,
1980
+ method,
1981
+ body,
1982
+ headers = {},
1983
+ baseUrl,
1984
+ mintUrl,
1985
+ modelId
1986
+ } = params;
1987
+ await this._checkBalance();
1988
+ let requiredSats = 1;
1989
+ let selectedModel;
1990
+ if (modelId) {
1991
+ const providerModel = await this.providerManager.getModelForProvider(
1992
+ baseUrl,
1993
+ modelId
1994
+ );
1995
+ selectedModel = providerModel ?? void 0;
1996
+ if (selectedModel) {
1997
+ requiredSats = this.providerManager.getRequiredSatsForModel(
1998
+ selectedModel,
1999
+ []
2000
+ );
2001
+ }
2002
+ }
2003
+ const { token, tokenBalance, tokenBalanceUnit } = await this._spendToken({
2004
+ mintUrl,
2005
+ amount: requiredSats,
2006
+ baseUrl
2007
+ });
2008
+ let requestBody = body;
2009
+ if (body && typeof body === "object") {
2010
+ const bodyObj = body;
2011
+ if (!bodyObj.stream) {
2012
+ requestBody = { ...bodyObj, stream: false };
2013
+ }
2014
+ }
2015
+ const baseHeaders = this._buildBaseHeaders(headers);
2016
+ const requestHeaders = this._withAuthHeader(baseHeaders, token);
2017
+ const response = await this._makeRequest({
2018
+ path,
2019
+ method,
2020
+ body: method === "GET" ? void 0 : requestBody,
2021
+ baseUrl,
2022
+ mintUrl,
2023
+ token,
2024
+ requiredSats,
2025
+ headers: requestHeaders,
2026
+ baseHeaders,
2027
+ selectedModel
2028
+ });
2029
+ const tokenBalanceInSats = tokenBalanceUnit === "msat" ? tokenBalance / 1e3 : tokenBalance;
2030
+ await this._handlePostResponseBalanceUpdate({
2031
+ token,
2032
+ baseUrl,
2033
+ initialTokenBalance: tokenBalanceInSats,
2034
+ response
2035
+ });
2036
+ return response;
2037
+ }
2038
+ /**
2039
+ * Fetch AI response with streaming
2040
+ */
2041
+ async fetchAIResponse(options, callbacks) {
2042
+ const {
2043
+ messageHistory,
2044
+ selectedModel,
2045
+ baseUrl,
2046
+ mintUrl,
2047
+ balance,
2048
+ transactionHistory,
2049
+ maxTokens,
2050
+ headers
2051
+ } = options;
2052
+ const apiMessages = await this._convertMessages(messageHistory);
2053
+ const requiredSats = this.providerManager.getRequiredSatsForModel(
2054
+ selectedModel,
2055
+ apiMessages,
2056
+ maxTokens
2057
+ );
2058
+ try {
2059
+ await this._checkBalance();
2060
+ callbacks.onPaymentProcessing?.(true);
2061
+ const spendResult = await this._spendToken({
2062
+ mintUrl,
2063
+ amount: requiredSats,
2064
+ baseUrl
2065
+ });
2066
+ let token = spendResult.token;
2067
+ let tokenBalance = spendResult.tokenBalance;
2068
+ let tokenBalanceUnit = spendResult.tokenBalanceUnit;
2069
+ const tokenBalanceInSats = tokenBalanceUnit === "msat" ? tokenBalance / 1e3 : tokenBalance;
2070
+ callbacks.onTokenCreated?.(this._getPendingCashuTokenAmount());
2071
+ const baseHeaders = this._buildBaseHeaders(headers);
2072
+ const requestHeaders = this._withAuthHeader(baseHeaders, token);
2073
+ this.providerManager.resetFailedProviders();
2074
+ const providerInfo = await this.providerRegistry.getProviderInfo(baseUrl);
2075
+ const providerVersion = providerInfo?.version ?? "";
2076
+ let modelIdForRequest = selectedModel.id;
2077
+ if (/^0\.1\./.test(providerVersion)) {
2078
+ const newModel = await this.providerManager.getModelForProvider(
2079
+ baseUrl,
2080
+ selectedModel.id
2081
+ );
2082
+ modelIdForRequest = newModel?.id ?? selectedModel.id;
2083
+ }
2084
+ const body = {
2085
+ model: modelIdForRequest,
2086
+ messages: apiMessages,
2087
+ stream: true
2088
+ };
2089
+ if (maxTokens !== void 0) {
2090
+ body.max_tokens = maxTokens;
2091
+ }
2092
+ if (selectedModel?.name?.startsWith("OpenAI:")) {
2093
+ body.tools = [{ type: "web_search" }];
2094
+ }
2095
+ const response = await this._makeRequest({
2096
+ path: "/v1/chat/completions",
2097
+ method: "POST",
2098
+ body,
2099
+ selectedModel,
2100
+ baseUrl,
2101
+ mintUrl,
2102
+ token,
2103
+ requiredSats,
2104
+ maxTokens,
2105
+ headers: requestHeaders,
2106
+ baseHeaders
2107
+ });
2108
+ if (!response.body) {
2109
+ throw new Error("Response body is not available");
2110
+ }
2111
+ if (response.status === 200) {
2112
+ const baseUrlUsed = response.baseUrl || baseUrl;
2113
+ const streamingResult = await this.streamProcessor.process(
2114
+ response,
2115
+ {
2116
+ onContent: callbacks.onStreamingUpdate,
2117
+ onThinking: callbacks.onThinkingUpdate
2118
+ },
2119
+ selectedModel.id
2120
+ );
2121
+ if (streamingResult.finish_reason === "content_filter") {
2122
+ callbacks.onMessageAppend({
2123
+ role: "assistant",
2124
+ content: "Your request was denied due to content filtering."
2125
+ });
2126
+ } else if (streamingResult.content || streamingResult.images && streamingResult.images.length > 0) {
2127
+ const message = await this._createAssistantMessage(streamingResult);
2128
+ callbacks.onMessageAppend(message);
2129
+ } else {
2130
+ callbacks.onMessageAppend({
2131
+ role: "system",
2132
+ content: "The provider did not respond to this request."
2133
+ });
2134
+ }
2135
+ callbacks.onStreamingUpdate("");
2136
+ callbacks.onThinkingUpdate("");
2137
+ const isApikeysEstimate = this.mode === "apikeys";
2138
+ let satsSpent = await this._handlePostResponseBalanceUpdate({
2139
+ token,
2140
+ baseUrl: baseUrlUsed,
2141
+ initialTokenBalance: tokenBalanceInSats,
2142
+ fallbackSatsSpent: isApikeysEstimate ? this._getEstimatedCosts(selectedModel, streamingResult) : void 0,
2143
+ response
2144
+ });
2145
+ const estimatedCosts = this._getEstimatedCosts(
2146
+ selectedModel,
2147
+ streamingResult
2148
+ );
2149
+ const onLastMessageSatsUpdate = callbacks.onLastMessageSatsUpdate;
2150
+ onLastMessageSatsUpdate?.(satsSpent, estimatedCosts);
2151
+ } else {
2152
+ throw new Error(`${response.status} ${response.statusText}`);
2153
+ }
2154
+ } catch (error) {
2155
+ this._handleError(error, callbacks);
2156
+ } finally {
2157
+ callbacks.onPaymentProcessing?.(false);
2158
+ }
2159
+ }
2160
+ /**
2161
+ * Make the API request with failover support
2162
+ */
2163
+ async _makeRequest(params) {
2164
+ const { path, method, body, baseUrl, token, headers } = params;
2165
+ try {
2166
+ const url = `${baseUrl.replace(/\/$/, "")}${path}`;
2167
+ const response = await fetch(url, {
2168
+ method,
2169
+ headers,
2170
+ body: body === void 0 || method === "GET" ? void 0 : JSON.stringify(body)
2171
+ });
2172
+ response.baseUrl = baseUrl;
2173
+ if (!response.ok) {
2174
+ return await this._handleErrorResponse(response, params, token);
2175
+ }
2176
+ return response;
2177
+ } catch (error) {
2178
+ if (this._isNetworkError(error?.message || "")) {
2179
+ return await this._handleNetworkError(error, params);
2180
+ }
2181
+ throw error;
2182
+ }
2183
+ }
2184
+ /**
2185
+ * Handle error responses with failover
2186
+ */
2187
+ async _handleErrorResponse(response, params, token) {
2188
+ const { path, method, body, selectedModel, baseUrl, mintUrl } = params;
2189
+ const status = response.status;
2190
+ if (this.mode === "apikeys") {
2191
+ console.log("error ;", status);
2192
+ if (status === 401 || status === 403) {
2193
+ const parentApiKey = this.storageAdapter.getApiKey(baseUrl);
2194
+ if (parentApiKey) {
2195
+ try {
2196
+ const childKeyResult = await this._createChildKey(
2197
+ baseUrl,
2198
+ parentApiKey
2199
+ );
2200
+ this.storageAdapter.setChildKey(
2201
+ baseUrl,
2202
+ childKeyResult.childKey,
2203
+ childKeyResult.balance,
2204
+ childKeyResult.validityDate,
2205
+ childKeyResult.balanceLimit
2206
+ );
2207
+ return this._makeRequest({
2208
+ ...params,
2209
+ token: childKeyResult.childKey,
2210
+ headers: this._withAuthHeader(
2211
+ params.baseHeaders,
2212
+ childKeyResult.childKey
2213
+ )
2214
+ });
2215
+ } catch (e) {
2216
+ }
2217
+ }
2218
+ } else if (status === 402) {
2219
+ const parentApiKey = this.storageAdapter.getApiKey(baseUrl);
2220
+ if (parentApiKey) {
2221
+ const topupResult = await this.balanceManager.topUp({
2222
+ mintUrl,
2223
+ baseUrl,
2224
+ amount: params.requiredSats * 3,
2225
+ token: parentApiKey
2226
+ });
2227
+ console.log(topupResult);
2228
+ return this._makeRequest({
2229
+ ...params,
2230
+ token: params.token,
2231
+ headers: this._withAuthHeader(params.baseHeaders, params.token)
2232
+ });
2233
+ }
2234
+ }
2235
+ throw new ProviderError(baseUrl, status, await response.text());
2236
+ }
2237
+ await this.balanceManager.refund({
2238
+ mintUrl,
2239
+ baseUrl,
2240
+ token
2241
+ });
2242
+ this.providerManager.markFailed(baseUrl);
2243
+ this.storageAdapter.removeToken(baseUrl);
2244
+ if (status === 401 || status === 403 || status === 402 || status === 413 || status === 400 || status === 500 || status === 502) {
2245
+ if (!selectedModel) {
2246
+ throw new ProviderError(baseUrl, status, await response.text());
2247
+ }
2248
+ const nextProvider = this.providerManager.findNextBestProvider(
2249
+ selectedModel.id,
2250
+ baseUrl
2251
+ );
2252
+ if (nextProvider) {
2253
+ const newModel = await this.providerManager.getModelForProvider(
2254
+ nextProvider,
2255
+ selectedModel.id
2256
+ ) ?? selectedModel;
2257
+ const messagesForPricing = Array.isArray(
2258
+ body?.messages
2259
+ ) ? body.messages : [];
2260
+ const newRequiredSats = this.providerManager.getRequiredSatsForModel(
2261
+ newModel,
2262
+ messagesForPricing,
2263
+ params.maxTokens
2264
+ );
2265
+ const spendResult = await this.cashuSpender.spend({
2266
+ mintUrl,
2267
+ amount: newRequiredSats,
2268
+ baseUrl: nextProvider,
2269
+ reuseToken: true
2270
+ });
2271
+ if (spendResult.status === "failed" || !spendResult.token) {
2272
+ if (spendResult.errorDetails) {
2273
+ throw new InsufficientBalanceError(
2274
+ spendResult.errorDetails.required,
2275
+ spendResult.errorDetails.available,
2276
+ spendResult.errorDetails.maxMintBalance,
2277
+ spendResult.errorDetails.maxMintUrl
2278
+ );
2279
+ }
2280
+ throw new Error(
2281
+ spendResult.error || `Insufficient balance for ${nextProvider}`
2282
+ );
2283
+ }
2284
+ return this._makeRequest({
2285
+ ...params,
2286
+ path,
2287
+ method,
2288
+ body,
2289
+ baseUrl: nextProvider,
2290
+ selectedModel: newModel,
2291
+ token: spendResult.token,
2292
+ requiredSats: newRequiredSats,
2293
+ headers: this._withAuthHeader(params.baseHeaders, spendResult.token)
2294
+ });
2295
+ }
2296
+ }
2297
+ throw new ProviderError(baseUrl, status, await response.text());
2298
+ }
2299
+ /**
2300
+ * Handle network errors with failover
2301
+ */
2302
+ async _handleNetworkError(error, params) {
2303
+ const { path, method, body, selectedModel, baseUrl, mintUrl } = params;
2304
+ await this.balanceManager.refund({
2305
+ mintUrl,
2306
+ baseUrl,
2307
+ token: params.token
2308
+ });
2309
+ this.providerManager.markFailed(baseUrl);
2310
+ if (!selectedModel) {
2311
+ throw error;
2312
+ }
2313
+ const nextProvider = this.providerManager.findNextBestProvider(
2314
+ selectedModel.id,
2315
+ baseUrl
2316
+ );
2317
+ if (!nextProvider) {
2318
+ throw new FailoverError(baseUrl, Array.from(this.providerManager));
2319
+ }
2320
+ const newModel = await this.providerManager.getModelForProvider(
2321
+ nextProvider,
2322
+ selectedModel.id
2323
+ ) ?? selectedModel;
2324
+ const messagesForPricing = Array.isArray(
2325
+ body?.messages
2326
+ ) ? body.messages : [];
2327
+ const newRequiredSats = this.providerManager.getRequiredSatsForModel(
2328
+ newModel,
2329
+ messagesForPricing,
2330
+ params.maxTokens
2331
+ );
2332
+ const spendResult = await this.cashuSpender.spend({
2333
+ mintUrl,
2334
+ amount: newRequiredSats,
2335
+ baseUrl: nextProvider,
2336
+ reuseToken: true
2337
+ });
2338
+ if (spendResult.status === "failed" || !spendResult.token) {
2339
+ if (spendResult.errorDetails) {
2340
+ throw new InsufficientBalanceError(
2341
+ spendResult.errorDetails.required,
2342
+ spendResult.errorDetails.available,
2343
+ spendResult.errorDetails.maxMintBalance,
2344
+ spendResult.errorDetails.maxMintUrl
2345
+ );
2346
+ }
2347
+ throw new Error(
2348
+ spendResult.error || `Insufficient balance for ${nextProvider}`
2349
+ );
2350
+ }
2351
+ return this._makeRequest({
2352
+ ...params,
2353
+ path,
2354
+ method,
2355
+ body,
2356
+ baseUrl: nextProvider,
2357
+ selectedModel: newModel,
2358
+ token: spendResult.token,
2359
+ requiredSats: newRequiredSats,
2360
+ headers: this._withAuthHeader(params.baseHeaders, spendResult.token)
2361
+ });
2362
+ }
2363
+ /**
2364
+ * Handle post-response refund and balance updates
2365
+ */
2366
+ async _handlePostResponseRefund(params) {
2367
+ const {
2368
+ mintUrl,
2369
+ baseUrl,
2370
+ tokenBalance,
2371
+ tokenBalanceUnit,
2372
+ initialBalance,
2373
+ selectedModel,
2374
+ streamingResult,
2375
+ callbacks
2376
+ } = params;
2377
+ const tokenBalanceInSats = tokenBalanceUnit === "msat" ? tokenBalance / 1e3 : tokenBalance;
2378
+ const estimatedCosts = this._getEstimatedCosts(
2379
+ selectedModel,
2380
+ streamingResult
2381
+ );
2382
+ const refundResult = await this.balanceManager.refund({
2383
+ mintUrl,
2384
+ baseUrl
2385
+ });
2386
+ if (refundResult.success) {
2387
+ refundResult.refundedAmount !== void 0 ? refundResult.refundedAmount / 1e3 : 0;
2388
+ }
2389
+ let satsSpent;
2390
+ if (refundResult.success) {
2391
+ if (refundResult.refundedAmount !== void 0) {
2392
+ satsSpent = tokenBalanceInSats - refundResult.refundedAmount / 1e3;
2393
+ } else if (refundResult.message?.includes("No API key to refund")) {
2394
+ satsSpent = 0;
2395
+ } else {
2396
+ satsSpent = tokenBalanceInSats;
2397
+ }
2398
+ const newBalance = initialBalance - satsSpent;
2399
+ callbacks.onBalanceUpdate(newBalance);
2400
+ } else {
2401
+ if (refundResult.message?.includes("Refund request failed with status 401")) {
2402
+ this.storageAdapter.removeToken(baseUrl);
2403
+ }
2404
+ satsSpent = tokenBalanceInSats;
2405
+ }
2406
+ const netCosts = satsSpent - estimatedCosts;
2407
+ const overchargeThreshold = tokenBalanceUnit === "msat" ? 0.05 : 1;
2408
+ if (netCosts > overchargeThreshold) {
2409
+ if (this.alertLevel === "max") {
2410
+ callbacks.onMessageAppend({
2411
+ role: "system",
2412
+ content: `ATTENTION: Provider may be overcharging. Estimated: ${estimatedCosts.toFixed(
2413
+ tokenBalanceUnit === "msat" ? 3 : 0
2414
+ )}, Actual: ${satsSpent.toFixed(
2415
+ tokenBalanceUnit === "msat" ? 3 : 0
2416
+ )}`
2417
+ });
2418
+ }
2419
+ }
2420
+ const newTransaction = {
2421
+ type: "spent",
2422
+ amount: satsSpent,
2423
+ timestamp: Date.now(),
2424
+ status: "success",
2425
+ model: selectedModel.id,
2426
+ message: "Tokens spent",
2427
+ balance: initialBalance - satsSpent
2428
+ };
2429
+ callbacks.onTransactionUpdate(newTransaction);
2430
+ return satsSpent;
2431
+ }
2432
+ /**
2433
+ * Handle post-response balance update for all modes
2434
+ */
2435
+ async _handlePostResponseBalanceUpdate(params) {
2436
+ const { token, baseUrl, initialTokenBalance, fallbackSatsSpent, response } = params;
2437
+ let satsSpent = initialTokenBalance;
2438
+ if (this.mode === "xcashu" && response) {
2439
+ const refundToken = response.headers.get("x-cashu") ?? void 0;
2440
+ if (refundToken) {
2441
+ try {
2442
+ const receiveResult = await this.walletAdapter.receiveToken(refundToken);
2443
+ satsSpent = initialTokenBalance - receiveResult.amount * (receiveResult.unit == "sat" ? 1 : 1e3);
2444
+ } catch (error) {
2445
+ console.error("[xcashu] Failed to receive refund token:", error);
2446
+ }
2447
+ }
2448
+ } else if (this.mode === "lazyrefund") {
2449
+ const latestBalanceInfo = await this.balanceManager.getTokenBalance(
2450
+ token,
2451
+ baseUrl
2452
+ );
2453
+ const latestTokenBalance = latestBalanceInfo.unit === "msat" ? latestBalanceInfo.amount / 1e3 : latestBalanceInfo.amount;
2454
+ this.storageAdapter.updateTokenBalance(baseUrl, latestTokenBalance);
2455
+ satsSpent = initialTokenBalance - latestTokenBalance;
2456
+ } else if (this.mode === "apikeys") {
2457
+ try {
2458
+ const latestBalanceInfo = await this._getApiKeyBalance(baseUrl, token);
2459
+ console.log("LATEST BANAL", latestBalanceInfo);
2460
+ const latestTokenBalance = latestBalanceInfo.unit === "msat" ? latestBalanceInfo.amount / 1e3 : latestBalanceInfo.amount;
2461
+ this.storageAdapter.updateChildKeyBalance(baseUrl, latestTokenBalance);
2462
+ satsSpent = initialTokenBalance - latestTokenBalance;
2463
+ } catch (e) {
2464
+ console.warn("Could not get updated API key balance:", e);
2465
+ satsSpent = fallbackSatsSpent ?? initialTokenBalance;
2466
+ }
2467
+ }
2468
+ return satsSpent;
2469
+ }
2470
+ /**
2471
+ * Convert messages for API format
2472
+ */
2473
+ async _convertMessages(messages) {
2474
+ return Promise.all(
2475
+ messages.filter((m) => m.role !== "system").map(async (m) => ({
2476
+ role: m.role,
2477
+ content: typeof m.content === "string" ? m.content : m.content
2478
+ }))
2479
+ );
2480
+ }
2481
+ /**
2482
+ * Create assistant message from streaming result
2483
+ */
2484
+ async _createAssistantMessage(result) {
2485
+ if (result.images && result.images.length > 0) {
2486
+ const content = [];
2487
+ if (result.content) {
2488
+ content.push({
2489
+ type: "text",
2490
+ text: result.content,
2491
+ thinking: result.thinking,
2492
+ citations: result.citations,
2493
+ annotations: result.annotations
2494
+ });
2495
+ }
2496
+ for (const img of result.images) {
2497
+ content.push({
2498
+ type: "image_url",
2499
+ image_url: {
2500
+ url: img.image_url.url
2501
+ }
2502
+ });
2503
+ }
2504
+ return {
2505
+ role: "assistant",
2506
+ content
2507
+ };
2508
+ }
2509
+ return {
2510
+ role: "assistant",
2511
+ content: result.content || ""
2512
+ };
2513
+ }
2514
+ /**
2515
+ * Create a child key for a parent API key via the provider's API
2516
+ * POST /v1/balance/child-key
2517
+ */
2518
+ async _createChildKey(baseUrl, parentApiKey, options) {
2519
+ const response = await fetch(`${baseUrl}v1/balance/child-key`, {
2520
+ method: "POST",
2521
+ headers: {
2522
+ "Content-Type": "application/json",
2523
+ Authorization: `Bearer ${parentApiKey}`
2524
+ },
2525
+ body: JSON.stringify({
2526
+ count: options?.count ?? 1,
2527
+ balance_limit: options?.balanceLimit,
2528
+ balance_limit_reset: options?.balanceLimitReset,
2529
+ validity_date: options?.validityDate
2530
+ })
2531
+ });
2532
+ if (!response.ok) {
2533
+ throw new Error(
2534
+ `Failed to create child key: ${response.status} ${await response.text()}`
2535
+ );
2536
+ }
2537
+ const data = await response.json();
2538
+ return {
2539
+ childKey: data.api_keys?.[0],
2540
+ balance: data.balance ?? 0,
2541
+ balanceLimit: data.balance_limit,
2542
+ validityDate: data.validity_date
2543
+ };
2544
+ }
2545
+ /**
2546
+ * Get balance for an API key from the provider
2547
+ */
2548
+ async _getApiKeyBalance(baseUrl, apiKey) {
2549
+ try {
2550
+ const response = await fetch(`${baseUrl}v1/wallet/info`, {
2551
+ headers: {
2552
+ Authorization: `Bearer ${apiKey}`
2553
+ }
2554
+ });
2555
+ if (response.ok) {
2556
+ const data = await response.json();
2557
+ console.log(data);
2558
+ return {
2559
+ amount: data.balance,
2560
+ unit: "msat"
2561
+ };
2562
+ }
2563
+ } catch {
2564
+ }
2565
+ return { amount: 0, unit: "sat" };
2566
+ }
2567
+ /**
2568
+ * Calculate estimated costs from usage
2569
+ */
2570
+ _getEstimatedCosts(selectedModel, streamingResult) {
2571
+ let estimatedCosts = 0;
2572
+ if (streamingResult.usage) {
2573
+ const { completion_tokens, prompt_tokens } = streamingResult.usage;
2574
+ if (completion_tokens !== void 0 && prompt_tokens !== void 0) {
2575
+ estimatedCosts = (selectedModel.sats_pricing?.completion ?? 0) * completion_tokens + (selectedModel.sats_pricing?.prompt ?? 0) * prompt_tokens;
2576
+ }
2577
+ }
2578
+ return estimatedCosts;
2579
+ }
2580
+ /**
2581
+ * Get pending cashu token amount
2582
+ */
2583
+ _getPendingCashuTokenAmount() {
2584
+ const distribution = this.storageAdapter.getPendingTokenDistribution();
2585
+ return distribution.reduce((total, item) => total + item.amount, 0);
2586
+ }
2587
+ /**
2588
+ * Check if error message indicates a network error
2589
+ */
2590
+ _isNetworkError(message) {
2591
+ return message.includes("NetworkError when attempting to fetch resource") || message.includes("Failed to fetch") || message.includes("Load failed");
2592
+ }
2593
+ /**
2594
+ * Handle errors and notify callbacks
2595
+ */
2596
+ _handleError(error, callbacks) {
2597
+ console.error("RoutstrClient error:", error);
2598
+ if (error instanceof Error) {
2599
+ const modifiedErrorMsg = error.message.includes("Error in input stream") || error.message.includes("Load failed") ? "AI stream was cut off, turn on Keep Active or please try again" : error.message;
2600
+ callbacks.onMessageAppend({
2601
+ role: "system",
2602
+ content: "Uncaught Error: " + modifiedErrorMsg + (this.alertLevel === "max" ? " | " + error.stack : "")
2603
+ });
2604
+ } else {
2605
+ callbacks.onMessageAppend({
2606
+ role: "system",
2607
+ content: "Unknown Error: Please tag Routstr on Nostr and/or retry."
2608
+ });
2609
+ }
2610
+ }
2611
+ /**
2612
+ * Check wallet balance and throw if insufficient
2613
+ */
2614
+ async _checkBalance() {
2615
+ const balances = await this.walletAdapter.getBalances();
2616
+ const totalBalance = Object.values(balances).reduce((sum, v) => sum + v, 0);
2617
+ if (totalBalance <= 0) {
2618
+ throw new InsufficientBalanceError(1, 0);
2619
+ }
2620
+ }
2621
+ /**
2622
+ * Spend a token using CashuSpender with standardized error handling
2623
+ */
2624
+ async _spendToken(params) {
2625
+ const { mintUrl, amount, baseUrl } = params;
2626
+ if (this.mode === "apikeys") {
2627
+ let parentApiKey = this.storageAdapter.getApiKey(baseUrl);
2628
+ if (!parentApiKey) {
2629
+ const spendResult2 = await this.cashuSpender.spend({
2630
+ mintUrl,
2631
+ amount: amount * 3,
2632
+ baseUrl: "",
2633
+ reuseToken: false
2634
+ });
2635
+ if (spendResult2.status === "failed" || !spendResult2.token) {
2636
+ const errorMsg = spendResult2.error || `Insufficient balance. Need ${amount} sats.`;
2637
+ if (this._isNetworkError(errorMsg)) {
2638
+ throw new Error(
2639
+ `Your mint ${mintUrl} is unreachable or is blocking your IP. Please try again later or switch mints.`
2640
+ );
2641
+ }
2642
+ if (spendResult2.errorDetails) {
2643
+ throw new InsufficientBalanceError(
2644
+ spendResult2.errorDetails.required,
2645
+ spendResult2.errorDetails.available,
2646
+ spendResult2.errorDetails.maxMintBalance,
2647
+ spendResult2.errorDetails.maxMintUrl
2648
+ );
2649
+ }
2650
+ throw new Error(errorMsg);
2651
+ }
2652
+ const apiKeyCreated = await this.balanceManager.getTokenBalance(
2653
+ spendResult2.token,
2654
+ baseUrl
2655
+ );
2656
+ parentApiKey = apiKeyCreated.apiKey;
2657
+ this.storageAdapter.setApiKey(baseUrl, parentApiKey);
2658
+ }
2659
+ let childKeyEntry = this.storageAdapter.getChildKey(baseUrl);
2660
+ if (!childKeyEntry) {
2661
+ try {
2662
+ const childKeyResult = await this._createChildKey(
2663
+ baseUrl,
2664
+ parentApiKey
2665
+ );
2666
+ this.storageAdapter.setChildKey(
2667
+ baseUrl,
2668
+ childKeyResult.childKey,
2669
+ childKeyResult.balance,
2670
+ childKeyResult.validityDate,
2671
+ childKeyResult.balanceLimit
2672
+ );
2673
+ childKeyEntry = {
2674
+ parentBaseUrl: baseUrl,
2675
+ childKey: childKeyResult.childKey,
2676
+ balance: childKeyResult.balance,
2677
+ balanceLimit: childKeyResult.balanceLimit,
2678
+ validityDate: childKeyResult.validityDate,
2679
+ createdAt: Date.now()
2680
+ };
2681
+ } catch (e) {
2682
+ console.warn("Could not create child key, using parent key:", e);
2683
+ childKeyEntry = {
2684
+ parentBaseUrl: baseUrl,
2685
+ childKey: parentApiKey,
2686
+ balance: 0,
2687
+ createdAt: Date.now()
2688
+ };
2689
+ }
2690
+ }
2691
+ let tokenBalance = childKeyEntry.balance;
2692
+ let tokenBalanceUnit = "sat";
2693
+ if (tokenBalance === 0) {
2694
+ try {
2695
+ const balanceInfo = await this._getApiKeyBalance(
2696
+ baseUrl,
2697
+ childKeyEntry.childKey
2698
+ );
2699
+ tokenBalance = balanceInfo.amount;
2700
+ tokenBalanceUnit = balanceInfo.unit;
2701
+ } catch (e) {
2702
+ console.warn("Could not get initial API key balance:", e);
2703
+ }
2704
+ }
2705
+ return {
2706
+ token: childKeyEntry.childKey,
2707
+ tokenBalance,
2708
+ tokenBalanceUnit
2709
+ };
2710
+ }
2711
+ const spendResult = await this.cashuSpender.spend({
2712
+ mintUrl,
2713
+ amount,
2714
+ baseUrl,
2715
+ reuseToken: true
2716
+ });
2717
+ if (spendResult.status === "failed" || !spendResult.token) {
2718
+ const errorMsg = spendResult.error || `Insufficient balance. Need ${amount} sats.`;
2719
+ if (this._isNetworkError(errorMsg)) {
2720
+ throw new Error(
2721
+ `Your mint ${mintUrl} is unreachable or is blocking your IP. Please try again later or switch mints.`
2722
+ );
2723
+ }
2724
+ if (spendResult.errorDetails) {
2725
+ throw new InsufficientBalanceError(
2726
+ spendResult.errorDetails.required,
2727
+ spendResult.errorDetails.available,
2728
+ spendResult.errorDetails.maxMintBalance,
2729
+ spendResult.errorDetails.maxMintUrl
2730
+ );
2731
+ }
2732
+ throw new Error(errorMsg);
2733
+ }
2734
+ return {
2735
+ token: spendResult.token,
2736
+ tokenBalance: spendResult.balance,
2737
+ tokenBalanceUnit: spendResult.unit ?? "sat"
2738
+ };
2739
+ }
2740
+ /**
2741
+ * Build request headers with common defaults and dev mock controls
2742
+ */
2743
+ _buildBaseHeaders(additionalHeaders = {}, token) {
2744
+ const headers = {
2745
+ ...additionalHeaders,
2746
+ "Content-Type": "application/json"
2747
+ };
2748
+ return headers;
2749
+ }
2750
+ /**
2751
+ * Attach auth headers using the active client mode
2752
+ */
2753
+ _withAuthHeader(headers, token) {
2754
+ const nextHeaders = { ...headers };
2755
+ if (this.mode === "xcashu") {
2756
+ nextHeaders["X-Cashu"] = token;
2757
+ } else {
2758
+ nextHeaders["Authorization"] = `Bearer ${token}`;
2759
+ }
2760
+ return nextHeaders;
2761
+ }
2762
+ };
2763
+
2764
+ // storage/drivers/localStorage.ts
2765
+ var canUseLocalStorage = () => {
2766
+ return typeof window !== "undefined" && typeof window.localStorage !== "undefined";
2767
+ };
2768
+ var isQuotaExceeded = (error) => {
2769
+ const e = error;
2770
+ return !!e && (e?.name === "QuotaExceededError" || e?.code === 22 || e?.code === 1014);
2771
+ };
2772
+ var NON_CRITICAL_KEYS = /* @__PURE__ */ new Set(["modelsFromAllProviders"]);
2773
+ var localStorageDriver = {
2774
+ getItem(key, defaultValue) {
2775
+ if (!canUseLocalStorage()) return defaultValue;
2776
+ try {
2777
+ const item = window.localStorage.getItem(key);
2778
+ if (item === null) return defaultValue;
2779
+ try {
2780
+ return JSON.parse(item);
2781
+ } catch (parseError) {
2782
+ if (typeof defaultValue === "string") {
2783
+ return item;
2784
+ }
2785
+ throw parseError;
2786
+ }
2787
+ } catch (error) {
2788
+ console.error(`Error retrieving item with key "${key}":`, error);
2789
+ if (canUseLocalStorage()) {
2790
+ try {
2791
+ window.localStorage.removeItem(key);
2792
+ } catch (removeError) {
2793
+ console.error(
2794
+ `Error removing corrupted item with key "${key}":`,
2795
+ removeError
2796
+ );
2797
+ }
2798
+ }
2799
+ return defaultValue;
2800
+ }
2801
+ },
2802
+ setItem(key, value) {
2803
+ if (!canUseLocalStorage()) return;
2804
+ try {
2805
+ window.localStorage.setItem(key, JSON.stringify(value));
2806
+ } catch (error) {
2807
+ if (isQuotaExceeded(error)) {
2808
+ if (NON_CRITICAL_KEYS.has(key)) {
2809
+ console.warn(
2810
+ `Storage quota exceeded; skipping non-critical key "${key}".`
2811
+ );
2812
+ return;
2813
+ }
2814
+ try {
2815
+ window.localStorage.removeItem("modelsFromAllProviders");
2816
+ } catch {
2817
+ }
2818
+ try {
2819
+ window.localStorage.setItem(key, JSON.stringify(value));
2820
+ return;
2821
+ } catch (retryError) {
2822
+ console.warn(
2823
+ `Storage quota exceeded; unable to persist key "${key}" after cleanup attempt.`,
2824
+ retryError
2825
+ );
2826
+ return;
2827
+ }
2828
+ }
2829
+ console.error(`Error storing item with key "${key}":`, error);
2830
+ }
2831
+ },
2832
+ removeItem(key) {
2833
+ if (!canUseLocalStorage()) return;
2834
+ try {
2835
+ window.localStorage.removeItem(key);
2836
+ } catch (error) {
2837
+ console.error(`Error removing item with key "${key}":`, error);
2838
+ }
2839
+ }
2840
+ };
2841
+
2842
+ // storage/drivers/memory.ts
2843
+ var createMemoryDriver = (seed) => {
2844
+ const store = /* @__PURE__ */ new Map();
2845
+ if (seed) {
2846
+ for (const [key, value] of Object.entries(seed)) {
2847
+ store.set(key, value);
2848
+ }
2849
+ }
2850
+ return {
2851
+ getItem(key, defaultValue) {
2852
+ const item = store.get(key);
2853
+ if (item === void 0) return defaultValue;
2854
+ try {
2855
+ return JSON.parse(item);
2856
+ } catch (parseError) {
2857
+ if (typeof defaultValue === "string") {
2858
+ return item;
2859
+ }
2860
+ throw parseError;
2861
+ }
2862
+ },
2863
+ setItem(key, value) {
2864
+ store.set(key, JSON.stringify(value));
2865
+ },
2866
+ removeItem(key) {
2867
+ store.delete(key);
2868
+ }
2869
+ };
2870
+ };
2871
+
2872
+ // storage/drivers/sqlite.ts
2873
+ var createDatabase = (dbPath) => {
2874
+ let Database = null;
2875
+ try {
2876
+ Database = __require("better-sqlite3");
2877
+ } catch (error) {
2878
+ throw new Error(
2879
+ `better-sqlite3 is required for sqlite storage. Install it to use sqlite storage. (${error})`
2880
+ );
2881
+ }
2882
+ return new Database(dbPath);
2883
+ };
2884
+ var createSqliteDriver = (options = {}) => {
2885
+ const dbPath = options.dbPath || "routstr.sqlite";
2886
+ const tableName = options.tableName || "sdk_storage";
2887
+ const db = createDatabase(dbPath);
2888
+ db.exec(
2889
+ `CREATE TABLE IF NOT EXISTS ${tableName} (key TEXT PRIMARY KEY, value TEXT NOT NULL)`
2890
+ );
2891
+ const selectStmt = db.prepare(`SELECT value FROM ${tableName} WHERE key = ?`);
2892
+ const upsertStmt = db.prepare(
2893
+ `INSERT INTO ${tableName} (key, value) VALUES (?, ?)
2894
+ ON CONFLICT(key) DO UPDATE SET value = excluded.value`
2895
+ );
2896
+ const deleteStmt = db.prepare(`DELETE FROM ${tableName} WHERE key = ?`);
2897
+ return {
2898
+ getItem(key, defaultValue) {
2899
+ try {
2900
+ const row = selectStmt.get(key);
2901
+ if (!row || typeof row.value !== "string") return defaultValue;
2902
+ try {
2903
+ return JSON.parse(row.value);
2904
+ } catch (parseError) {
2905
+ if (typeof defaultValue === "string") {
2906
+ return row.value;
2907
+ }
2908
+ throw parseError;
2909
+ }
2910
+ } catch (error) {
2911
+ console.error(`SQLite getItem failed for key "${key}":`, error);
2912
+ return defaultValue;
2913
+ }
2914
+ },
2915
+ setItem(key, value) {
2916
+ try {
2917
+ upsertStmt.run(key, JSON.stringify(value));
2918
+ } catch (error) {
2919
+ console.error(`SQLite setItem failed for key "${key}":`, error);
2920
+ }
2921
+ },
2922
+ removeItem(key) {
2923
+ try {
2924
+ deleteStmt.run(key);
2925
+ } catch (error) {
2926
+ console.error(`SQLite removeItem failed for key "${key}":`, error);
2927
+ }
2928
+ }
2929
+ };
2930
+ };
2931
+
2932
+ // storage/keys.ts
2933
+ var SDK_STORAGE_KEYS = {
2934
+ MODELS_FROM_ALL_PROVIDERS: "modelsFromAllProviders",
2935
+ LAST_USED_MODEL: "lastUsedModel",
2936
+ BASE_URLS_LIST: "base_urls_list",
2937
+ DISABLED_PROVIDERS: "disabled_providers",
2938
+ MINTS_FROM_ALL_PROVIDERS: "mints_from_all_providers",
2939
+ INFO_FROM_ALL_PROVIDERS: "info_from_all_providers",
2940
+ LAST_MODELS_UPDATE: "lastModelsUpdate",
2941
+ LAST_BASE_URLS_UPDATE: "lastBaseUrlsUpdate",
2942
+ LOCAL_CASHU_TOKENS: "local_cashu_tokens",
2943
+ API_KEYS: "api_keys",
2944
+ CHILD_KEYS: "child_keys"
2945
+ };
2946
+
2947
+ // storage/store.ts
2948
+ var normalizeBaseUrl = (baseUrl) => baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`;
2949
+ var getTokenBalance = (token) => {
2950
+ try {
2951
+ const decoded = getDecodedToken(token);
2952
+ const unitDivisor = decoded.unit === "msat" ? 1e3 : 1;
2953
+ let sum = 0;
2954
+ for (const proof of decoded.proofs) {
2955
+ sum += proof.amount / unitDivisor;
2956
+ }
2957
+ return sum;
2958
+ } catch {
2959
+ return 0;
2960
+ }
2961
+ };
2962
+ var createSdkStore = ({ driver }) => {
2963
+ return createStore((set, get) => ({
2964
+ modelsFromAllProviders: Object.fromEntries(
2965
+ Object.entries(
2966
+ driver.getItem(
2967
+ SDK_STORAGE_KEYS.MODELS_FROM_ALL_PROVIDERS,
2968
+ {}
2969
+ )
2970
+ ).map(([baseUrl, models]) => [normalizeBaseUrl(baseUrl), models])
2971
+ ),
2972
+ lastUsedModel: driver.getItem(
2973
+ SDK_STORAGE_KEYS.LAST_USED_MODEL,
2974
+ null
2975
+ ),
2976
+ baseUrlsList: driver.getItem(SDK_STORAGE_KEYS.BASE_URLS_LIST, []).map((url) => normalizeBaseUrl(url)),
2977
+ lastBaseUrlsUpdate: driver.getItem(
2978
+ SDK_STORAGE_KEYS.LAST_BASE_URLS_UPDATE,
2979
+ null
2980
+ ),
2981
+ disabledProviders: driver.getItem(SDK_STORAGE_KEYS.DISABLED_PROVIDERS, []).map((url) => normalizeBaseUrl(url)),
2982
+ mintsFromAllProviders: Object.fromEntries(
2983
+ Object.entries(
2984
+ driver.getItem(
2985
+ SDK_STORAGE_KEYS.MINTS_FROM_ALL_PROVIDERS,
2986
+ {}
2987
+ )
2988
+ ).map(([baseUrl, mints]) => [
2989
+ normalizeBaseUrl(baseUrl),
2990
+ mints.map((mint) => mint.endsWith("/") ? mint.slice(0, -1) : mint)
2991
+ ])
2992
+ ),
2993
+ infoFromAllProviders: Object.fromEntries(
2994
+ Object.entries(
2995
+ driver.getItem(
2996
+ SDK_STORAGE_KEYS.INFO_FROM_ALL_PROVIDERS,
2997
+ {}
2998
+ )
2999
+ ).map(([baseUrl, info]) => [normalizeBaseUrl(baseUrl), info])
3000
+ ),
3001
+ lastModelsUpdate: Object.fromEntries(
3002
+ Object.entries(
3003
+ driver.getItem(
3004
+ SDK_STORAGE_KEYS.LAST_MODELS_UPDATE,
3005
+ {}
3006
+ )
3007
+ ).map(([baseUrl, timestamp]) => [normalizeBaseUrl(baseUrl), timestamp])
3008
+ ),
3009
+ cachedTokens: driver.getItem(SDK_STORAGE_KEYS.LOCAL_CASHU_TOKENS, []).map((entry) => ({
3010
+ ...entry,
3011
+ baseUrl: normalizeBaseUrl(entry.baseUrl),
3012
+ balance: typeof entry.balance === "number" ? entry.balance : getTokenBalance(entry.token),
3013
+ lastUsed: entry.lastUsed ?? null
3014
+ })),
3015
+ apiKeys: driver.getItem(SDK_STORAGE_KEYS.API_KEYS, []).map((entry) => ({
3016
+ ...entry,
3017
+ baseUrl: normalizeBaseUrl(entry.baseUrl),
3018
+ balance: entry.balance ?? 0,
3019
+ lastUsed: entry.lastUsed ?? null
3020
+ })),
3021
+ childKeys: driver.getItem(SDK_STORAGE_KEYS.CHILD_KEYS, []).map((entry) => ({
3022
+ parentBaseUrl: normalizeBaseUrl(entry.parentBaseUrl),
3023
+ childKey: entry.childKey,
3024
+ balance: entry.balance ?? 0,
3025
+ balanceLimit: entry.balanceLimit,
3026
+ validityDate: entry.validityDate,
3027
+ createdAt: entry.createdAt ?? Date.now()
3028
+ })),
3029
+ setModelsFromAllProviders: (value) => {
3030
+ const normalized = {};
3031
+ for (const [baseUrl, models] of Object.entries(value)) {
3032
+ normalized[normalizeBaseUrl(baseUrl)] = models;
3033
+ }
3034
+ driver.setItem(SDK_STORAGE_KEYS.MODELS_FROM_ALL_PROVIDERS, normalized);
3035
+ set({ modelsFromAllProviders: normalized });
3036
+ },
3037
+ setLastUsedModel: (value) => {
3038
+ driver.setItem(SDK_STORAGE_KEYS.LAST_USED_MODEL, value);
3039
+ set({ lastUsedModel: value });
3040
+ },
3041
+ setBaseUrlsList: (value) => {
3042
+ const normalized = value.map((url) => normalizeBaseUrl(url));
3043
+ driver.setItem(SDK_STORAGE_KEYS.BASE_URLS_LIST, normalized);
3044
+ set({ baseUrlsList: normalized });
3045
+ },
3046
+ setBaseUrlsLastUpdate: (value) => {
3047
+ driver.setItem(SDK_STORAGE_KEYS.LAST_BASE_URLS_UPDATE, value);
3048
+ set({ lastBaseUrlsUpdate: value });
3049
+ },
3050
+ setDisabledProviders: (value) => {
3051
+ const normalized = value.map((url) => normalizeBaseUrl(url));
3052
+ driver.setItem(SDK_STORAGE_KEYS.DISABLED_PROVIDERS, normalized);
3053
+ set({ disabledProviders: normalized });
3054
+ },
3055
+ setMintsFromAllProviders: (value) => {
3056
+ const normalized = {};
3057
+ for (const [baseUrl, mints] of Object.entries(value)) {
3058
+ normalized[normalizeBaseUrl(baseUrl)] = mints.map(
3059
+ (mint) => mint.endsWith("/") ? mint.slice(0, -1) : mint
3060
+ );
3061
+ }
3062
+ driver.setItem(SDK_STORAGE_KEYS.MINTS_FROM_ALL_PROVIDERS, normalized);
3063
+ set({ mintsFromAllProviders: normalized });
3064
+ },
3065
+ setInfoFromAllProviders: (value) => {
3066
+ const normalized = {};
3067
+ for (const [baseUrl, info] of Object.entries(value)) {
3068
+ normalized[normalizeBaseUrl(baseUrl)] = info;
3069
+ }
3070
+ driver.setItem(SDK_STORAGE_KEYS.INFO_FROM_ALL_PROVIDERS, normalized);
3071
+ set({ infoFromAllProviders: normalized });
3072
+ },
3073
+ setLastModelsUpdate: (value) => {
3074
+ const normalized = {};
3075
+ for (const [baseUrl, timestamp] of Object.entries(value)) {
3076
+ normalized[normalizeBaseUrl(baseUrl)] = timestamp;
3077
+ }
3078
+ driver.setItem(SDK_STORAGE_KEYS.LAST_MODELS_UPDATE, normalized);
3079
+ set({ lastModelsUpdate: normalized });
3080
+ },
3081
+ setCachedTokens: (value) => {
3082
+ set((state) => {
3083
+ const updates = typeof value === "function" ? value(state.cachedTokens) : value;
3084
+ const normalized = updates.map((entry) => ({
3085
+ ...entry,
3086
+ baseUrl: normalizeBaseUrl(entry.baseUrl),
3087
+ balance: typeof entry.balance === "number" ? entry.balance : getTokenBalance(entry.token),
3088
+ lastUsed: entry.lastUsed ?? null
3089
+ }));
3090
+ driver.setItem(SDK_STORAGE_KEYS.LOCAL_CASHU_TOKENS, normalized);
3091
+ return { cachedTokens: normalized };
3092
+ });
3093
+ },
3094
+ setApiKeys: (value) => {
3095
+ set((state) => {
3096
+ const updates = typeof value === "function" ? value(state.apiKeys) : value;
3097
+ const normalized = updates.map((entry) => ({
3098
+ ...entry,
3099
+ baseUrl: normalizeBaseUrl(entry.baseUrl),
3100
+ balance: entry.balance ?? 0,
3101
+ lastUsed: entry.lastUsed ?? null
3102
+ }));
3103
+ driver.setItem(SDK_STORAGE_KEYS.API_KEYS, normalized);
3104
+ return { apiKeys: normalized };
3105
+ });
3106
+ },
3107
+ setChildKeys: (value) => {
3108
+ set((state) => {
3109
+ const updates = typeof value === "function" ? value(state.childKeys) : value;
3110
+ const normalized = updates.map((entry) => ({
3111
+ parentBaseUrl: normalizeBaseUrl(entry.parentBaseUrl),
3112
+ childKey: entry.childKey,
3113
+ balance: entry.balance ?? 0,
3114
+ balanceLimit: entry.balanceLimit,
3115
+ validityDate: entry.validityDate,
3116
+ createdAt: entry.createdAt ?? Date.now()
3117
+ }));
3118
+ driver.setItem(SDK_STORAGE_KEYS.CHILD_KEYS, normalized);
3119
+ return { childKeys: normalized };
3120
+ });
3121
+ }
3122
+ }));
3123
+ };
3124
+ var createDiscoveryAdapterFromStore = (store) => ({
3125
+ getCachedModels: () => store.getState().modelsFromAllProviders,
3126
+ setCachedModels: (models) => store.getState().setModelsFromAllProviders(models),
3127
+ getCachedMints: () => store.getState().mintsFromAllProviders,
3128
+ setCachedMints: (mints) => store.getState().setMintsFromAllProviders(mints),
3129
+ getCachedProviderInfo: () => store.getState().infoFromAllProviders,
3130
+ setCachedProviderInfo: (info) => store.getState().setInfoFromAllProviders(info),
3131
+ getProviderLastUpdate: (baseUrl) => {
3132
+ const normalized = normalizeBaseUrl(baseUrl);
3133
+ const timestamps = store.getState().lastModelsUpdate;
3134
+ return timestamps[normalized] || null;
3135
+ },
3136
+ setProviderLastUpdate: (baseUrl, timestamp) => {
3137
+ const normalized = normalizeBaseUrl(baseUrl);
3138
+ const timestamps = { ...store.getState().lastModelsUpdate };
3139
+ timestamps[normalized] = timestamp;
3140
+ store.getState().setLastModelsUpdate(timestamps);
3141
+ },
3142
+ getLastUsedModel: () => store.getState().lastUsedModel,
3143
+ setLastUsedModel: (modelId) => store.getState().setLastUsedModel(modelId),
3144
+ getDisabledProviders: () => store.getState().disabledProviders,
3145
+ getBaseUrlsList: () => store.getState().baseUrlsList,
3146
+ setBaseUrlsList: (urls) => store.getState().setBaseUrlsList(urls),
3147
+ getBaseUrlsLastUpdate: () => store.getState().lastBaseUrlsUpdate,
3148
+ setBaseUrlsLastUpdate: (timestamp) => store.getState().setBaseUrlsLastUpdate(timestamp)
3149
+ });
3150
+ var createStorageAdapterFromStore = (store) => ({
3151
+ getToken: (baseUrl) => {
3152
+ const normalized = normalizeBaseUrl(baseUrl);
3153
+ const entry = store.getState().cachedTokens.find((token) => token.baseUrl === normalized);
3154
+ if (!entry) return null;
3155
+ const next = store.getState().cachedTokens.map(
3156
+ (token) => token.baseUrl === normalized ? { ...token, lastUsed: Date.now() } : token
3157
+ );
3158
+ store.getState().setCachedTokens(next);
3159
+ return entry.token;
3160
+ },
3161
+ setToken: (baseUrl, token) => {
3162
+ const normalized = normalizeBaseUrl(baseUrl);
3163
+ const tokens = store.getState().cachedTokens;
3164
+ const balance = getTokenBalance(token);
3165
+ const existingIndex = tokens.findIndex(
3166
+ (entry) => entry.baseUrl === normalized
3167
+ );
3168
+ if (existingIndex !== -1) {
3169
+ throw new Error(`Token already exists for baseUrl: ${normalized}`);
3170
+ }
3171
+ const next = [...tokens];
3172
+ next.push({
3173
+ baseUrl: normalized,
3174
+ token,
3175
+ balance,
3176
+ lastUsed: Date.now()
3177
+ });
3178
+ store.getState().setCachedTokens(next);
3179
+ },
3180
+ removeToken: (baseUrl) => {
3181
+ const normalized = normalizeBaseUrl(baseUrl);
3182
+ const next = store.getState().cachedTokens.filter((entry) => entry.baseUrl !== normalized);
3183
+ store.getState().setCachedTokens(next);
3184
+ },
3185
+ updateTokenBalance: (baseUrl, balance) => {
3186
+ const normalized = normalizeBaseUrl(baseUrl);
3187
+ const tokens = store.getState().cachedTokens;
3188
+ const next = tokens.map(
3189
+ (entry) => entry.baseUrl === normalized ? { ...entry, balance } : entry
3190
+ );
3191
+ store.getState().setCachedTokens(next);
3192
+ },
3193
+ getPendingTokenDistribution: () => {
3194
+ const tokens = store.getState().cachedTokens;
3195
+ const distributionMap = {};
3196
+ for (const entry of tokens) {
3197
+ const sum = entry.balance || 0;
3198
+ if (sum > 0) {
3199
+ distributionMap[entry.baseUrl] = (distributionMap[entry.baseUrl] || 0) + sum;
3200
+ }
3201
+ }
3202
+ return Object.entries(distributionMap).map(([baseUrl, amt]) => ({ baseUrl, amount: amt })).sort((a, b) => b.amount - a.amount);
3203
+ },
3204
+ saveProviderInfo: (baseUrl, info) => {
3205
+ const normalized = normalizeBaseUrl(baseUrl);
3206
+ const next = { ...store.getState().infoFromAllProviders };
3207
+ next[normalized] = info;
3208
+ store.getState().setInfoFromAllProviders(next);
3209
+ },
3210
+ getProviderInfo: (baseUrl) => {
3211
+ const normalized = normalizeBaseUrl(baseUrl);
3212
+ return store.getState().infoFromAllProviders[normalized] || null;
3213
+ },
3214
+ // ========== API Keys (for apikeys mode) ==========
3215
+ getApiKey: (baseUrl) => {
3216
+ const normalized = normalizeBaseUrl(baseUrl);
3217
+ const entry = store.getState().apiKeys.find((key) => key.baseUrl === normalized);
3218
+ if (!entry) return null;
3219
+ const next = store.getState().apiKeys.map(
3220
+ (key) => key.baseUrl === normalized ? { ...key, lastUsed: Date.now() } : key
3221
+ );
3222
+ store.getState().setApiKeys(next);
3223
+ return entry.key;
3224
+ },
3225
+ setApiKey: (baseUrl, key) => {
3226
+ const normalized = normalizeBaseUrl(baseUrl);
3227
+ const keys = store.getState().apiKeys;
3228
+ const existingIndex = keys.findIndex(
3229
+ (entry) => entry.baseUrl === normalized
3230
+ );
3231
+ if (existingIndex !== -1) {
3232
+ const next = keys.map(
3233
+ (entry) => entry.baseUrl === normalized ? { ...entry, key, lastUsed: Date.now() } : entry
3234
+ );
3235
+ store.getState().setApiKeys(next);
3236
+ } else {
3237
+ const next = [...keys];
3238
+ next.push({
3239
+ baseUrl: normalized,
3240
+ key,
3241
+ balance: 0,
3242
+ lastUsed: Date.now()
3243
+ });
3244
+ store.getState().setApiKeys(next);
3245
+ }
3246
+ },
3247
+ updateApiKeyBalance: (baseUrl, balance) => {
3248
+ const normalized = normalizeBaseUrl(baseUrl);
3249
+ const keys = store.getState().apiKeys;
3250
+ const next = keys.map(
3251
+ (entry) => entry.baseUrl === normalized ? { ...entry, balance } : entry
3252
+ );
3253
+ store.getState().setApiKeys(next);
3254
+ },
3255
+ getAllApiKeys: () => {
3256
+ return store.getState().apiKeys.map((entry) => ({
3257
+ baseUrl: entry.baseUrl,
3258
+ key: entry.key,
3259
+ balance: entry.balance,
3260
+ lastUsed: entry.lastUsed
3261
+ }));
3262
+ },
3263
+ // ========== Child Keys ==========
3264
+ getChildKey: (parentBaseUrl) => {
3265
+ const normalized = normalizeBaseUrl(parentBaseUrl);
3266
+ const entry = store.getState().childKeys.find((key) => key.parentBaseUrl === normalized);
3267
+ if (!entry) return null;
3268
+ return {
3269
+ parentBaseUrl: entry.parentBaseUrl,
3270
+ childKey: entry.childKey,
3271
+ balance: entry.balance,
3272
+ balanceLimit: entry.balanceLimit,
3273
+ validityDate: entry.validityDate,
3274
+ createdAt: entry.createdAt
3275
+ };
3276
+ },
3277
+ setChildKey: (parentBaseUrl, childKey, balance, validityDate, balanceLimit) => {
3278
+ const normalized = normalizeBaseUrl(parentBaseUrl);
3279
+ const keys = store.getState().childKeys;
3280
+ const existingIndex = keys.findIndex(
3281
+ (entry) => entry.parentBaseUrl === normalized
3282
+ );
3283
+ if (existingIndex !== -1) {
3284
+ const next = keys.map(
3285
+ (entry) => entry.parentBaseUrl === normalized ? {
3286
+ ...entry,
3287
+ childKey,
3288
+ balance: balance ?? 0,
3289
+ validityDate,
3290
+ balanceLimit,
3291
+ createdAt: Date.now()
3292
+ } : entry
3293
+ );
3294
+ store.getState().setChildKeys(next);
3295
+ } else {
3296
+ const next = [...keys];
3297
+ next.push({
3298
+ parentBaseUrl: normalized,
3299
+ childKey,
3300
+ balance: balance ?? 0,
3301
+ validityDate,
3302
+ balanceLimit,
3303
+ createdAt: Date.now()
3304
+ });
3305
+ store.getState().setChildKeys(next);
3306
+ }
3307
+ },
3308
+ updateChildKeyBalance: (parentBaseUrl, balance) => {
3309
+ const normalized = normalizeBaseUrl(parentBaseUrl);
3310
+ const keys = store.getState().childKeys;
3311
+ const next = keys.map(
3312
+ (entry) => entry.parentBaseUrl === normalized ? { ...entry, balance } : entry
3313
+ );
3314
+ store.getState().setChildKeys(next);
3315
+ },
3316
+ removeChildKey: (parentBaseUrl) => {
3317
+ const normalized = normalizeBaseUrl(parentBaseUrl);
3318
+ const next = store.getState().childKeys.filter((entry) => entry.parentBaseUrl !== normalized);
3319
+ store.getState().setChildKeys(next);
3320
+ },
3321
+ getAllChildKeys: () => {
3322
+ return store.getState().childKeys.map((entry) => ({
3323
+ parentBaseUrl: entry.parentBaseUrl,
3324
+ childKey: entry.childKey,
3325
+ balance: entry.balance,
3326
+ balanceLimit: entry.balanceLimit,
3327
+ validityDate: entry.validityDate,
3328
+ createdAt: entry.createdAt
3329
+ }));
3330
+ }
3331
+ });
3332
+ var createProviderRegistryFromStore = (store) => ({
3333
+ getModelsForProvider: (baseUrl) => {
3334
+ const normalized = normalizeBaseUrl(baseUrl);
3335
+ return store.getState().modelsFromAllProviders[normalized] || [];
3336
+ },
3337
+ getDisabledProviders: () => store.getState().disabledProviders,
3338
+ getProviderMints: (baseUrl) => {
3339
+ const normalized = normalizeBaseUrl(baseUrl);
3340
+ return store.getState().mintsFromAllProviders[normalized] || [];
3341
+ },
3342
+ getProviderInfo: async (baseUrl) => {
3343
+ const normalized = normalizeBaseUrl(baseUrl);
3344
+ const cached = store.getState().infoFromAllProviders[normalized];
3345
+ if (cached) return cached;
3346
+ try {
3347
+ const response = await fetch(`${normalized}v1/info`);
3348
+ if (!response.ok) {
3349
+ throw new Error(`Failed ${response.status}`);
3350
+ }
3351
+ const info = await response.json();
3352
+ const next = { ...store.getState().infoFromAllProviders };
3353
+ next[normalized] = info;
3354
+ store.getState().setInfoFromAllProviders(next);
3355
+ return info;
3356
+ } catch (error) {
3357
+ console.warn(`Failed to fetch provider info from ${normalized}:`, error);
3358
+ return null;
3359
+ }
3360
+ },
3361
+ getAllProvidersModels: () => store.getState().modelsFromAllProviders
3362
+ });
3363
+
3364
+ // storage/index.ts
3365
+ var isBrowser = () => {
3366
+ try {
3367
+ return typeof window !== "undefined" && typeof window.localStorage !== "undefined";
3368
+ } catch {
3369
+ return false;
3370
+ }
3371
+ };
3372
+ var isNode = () => {
3373
+ try {
3374
+ return typeof process !== "undefined" && process.versions != null && process.versions.node != null;
3375
+ } catch {
3376
+ return false;
3377
+ }
3378
+ };
3379
+ var defaultDriver = null;
3380
+ var getDefaultSdkDriver = () => {
3381
+ if (defaultDriver) return defaultDriver;
3382
+ if (isBrowser()) {
3383
+ defaultDriver = localStorageDriver;
3384
+ return defaultDriver;
3385
+ }
3386
+ if (isNode()) {
3387
+ defaultDriver = createSqliteDriver();
3388
+ return defaultDriver;
3389
+ }
3390
+ defaultDriver = createMemoryDriver();
3391
+ return defaultDriver;
3392
+ };
3393
+ var defaultStore = null;
3394
+ var getDefaultSdkStore = () => {
3395
+ if (!defaultStore) {
3396
+ defaultStore = createSdkStore({ driver: getDefaultSdkDriver() });
3397
+ }
3398
+ return defaultStore;
3399
+ };
3400
+ var getDefaultDiscoveryAdapter = () => createDiscoveryAdapterFromStore(getDefaultSdkStore());
3401
+ var getDefaultStorageAdapter = () => createStorageAdapterFromStore(getDefaultSdkStore());
3402
+ var getDefaultProviderRegistry = () => createProviderRegistryFromStore(getDefaultSdkStore());
3403
+
3404
+ // routeRequests.ts
3405
+ async function routeRequests(options) {
3406
+ const {
3407
+ modelId,
3408
+ requestBody,
3409
+ path = "/v1/chat/completions",
3410
+ forcedProvider,
3411
+ walletAdapter,
3412
+ storageAdapter,
3413
+ providerRegistry,
3414
+ discoveryAdapter,
3415
+ includeProviderUrls = [],
3416
+ torMode = false,
3417
+ forceRefresh = false,
3418
+ modelManager: providedModelManager
3419
+ } = options;
3420
+ let modelManager;
3421
+ let providers;
3422
+ if (providedModelManager) {
3423
+ modelManager = providedModelManager;
3424
+ providers = modelManager.getBaseUrls();
3425
+ if (providers.length === 0) {
3426
+ throw new Error("No providers available - run bootstrap first");
3427
+ }
3428
+ } else {
3429
+ modelManager = new ModelManager(discoveryAdapter, {
3430
+ includeProviderUrls: forcedProvider ? [forcedProvider, ...includeProviderUrls] : includeProviderUrls
3431
+ });
3432
+ providers = await modelManager.bootstrapProviders(torMode);
3433
+ if (providers.length === 0) {
3434
+ throw new Error("No providers available");
3435
+ }
3436
+ await modelManager.fetchModels(providers, forceRefresh);
3437
+ }
3438
+ const providerManager = new ProviderManager(providerRegistry);
3439
+ let baseUrl;
3440
+ let selectedModel;
3441
+ if (forcedProvider) {
3442
+ const normalizedProvider = forcedProvider.endsWith("/") ? forcedProvider : `${forcedProvider}/`;
3443
+ const cachedModels = modelManager.getAllCachedModels();
3444
+ const models = cachedModels[normalizedProvider] || [];
3445
+ const match = models.find((m) => m.id === modelId);
3446
+ if (!match) {
3447
+ throw new Error(
3448
+ `Provider ${normalizedProvider} does not offer model: ${modelId}`
3449
+ );
3450
+ }
3451
+ baseUrl = normalizedProvider;
3452
+ selectedModel = match;
3453
+ } else {
3454
+ const ranking = providerManager.getProviderPriceRankingForModel(modelId, {
3455
+ torMode,
3456
+ includeDisabled: false
3457
+ });
3458
+ if (ranking.length === 0) {
3459
+ throw new Error(`No providers found for model: ${modelId}`);
3460
+ }
3461
+ const cheapest = ranking[0];
3462
+ baseUrl = cheapest.baseUrl;
3463
+ selectedModel = cheapest.model;
3464
+ }
3465
+ const balances = await walletAdapter.getBalances();
3466
+ const totalBalance = Object.values(balances).reduce((sum, v) => sum + v, 0);
3467
+ if (totalBalance <= 0) {
3468
+ throw new Error(
3469
+ "Wallet balance is empty. Add a mint and fund it before making requests."
3470
+ );
3471
+ }
3472
+ const providerMints = providerRegistry.getProviderMints(baseUrl);
3473
+ const mintUrl = walletAdapter.getActiveMintUrl() || providerMints[0] || Object.keys(balances)[0];
3474
+ if (!mintUrl) {
3475
+ throw new Error("No mint configured in wallet");
3476
+ }
3477
+ const alertLevel = "min";
3478
+ const client = new RoutstrClient(
3479
+ walletAdapter,
3480
+ storageAdapter,
3481
+ providerRegistry,
3482
+ alertLevel,
3483
+ "apikeys"
3484
+ );
3485
+ const maxTokens = extractMaxTokens(requestBody);
3486
+ const stream = extractStream(requestBody);
3487
+ let response = null;
3488
+ try {
3489
+ const proxiedBody = requestBody && typeof requestBody === "object" ? { ...requestBody } : {};
3490
+ proxiedBody.model = selectedModel.id;
3491
+ if (stream !== void 0) {
3492
+ proxiedBody.stream = stream;
3493
+ }
3494
+ if (maxTokens !== void 0) {
3495
+ proxiedBody.max_tokens = maxTokens;
3496
+ }
3497
+ response = await client.routeRequest({
3498
+ path,
3499
+ method: "POST",
3500
+ body: proxiedBody,
3501
+ baseUrl,
3502
+ mintUrl,
3503
+ modelId
3504
+ });
3505
+ if (!response.ok) {
3506
+ throw new Error(`${response.status} ${response.statusText}`);
3507
+ }
3508
+ return response;
3509
+ } catch (error) {
3510
+ if (error instanceof Error && (error.message.includes("401") || error.message.includes("402") || error.message.includes("403"))) {
3511
+ throw new Error(`Authentication failed: ${error.message}`);
3512
+ }
3513
+ throw error;
3514
+ }
3515
+ }
3516
+ function extractMaxTokens(requestBody) {
3517
+ if (!requestBody || typeof requestBody !== "object") {
3518
+ return void 0;
3519
+ }
3520
+ const body = requestBody;
3521
+ const maxTokens = body.max_tokens;
3522
+ if (typeof maxTokens === "number") {
3523
+ return maxTokens;
3524
+ }
3525
+ return void 0;
3526
+ }
3527
+ function extractStream(requestBody) {
3528
+ if (!requestBody || typeof requestBody !== "object") {
3529
+ return false;
3530
+ }
3531
+ const body = requestBody;
3532
+ const stream = body.stream;
3533
+ return stream === true;
3534
+ }
3535
+
3536
+ export { BalanceManager, CashuSpender, FailoverError, InsufficientBalanceError, MintDiscovery, MintDiscoveryError, MintUnreachableError, ModelManager, ModelNotFoundError, NoProvidersAvailableError, ProviderBootstrapError, ProviderError, ProviderManager, RoutstrClient, SDK_STORAGE_KEYS, StreamProcessor, StreamingError, TokenOperationError, createMemoryDriver, createSdkStore, createSqliteDriver, filterBaseUrlsForTor, getDefaultDiscoveryAdapter, getDefaultProviderRegistry, getDefaultSdkDriver, getDefaultSdkStore, getDefaultStorageAdapter, getProviderEndpoints, isOnionUrl, isTorContext, localStorageDriver, normalizeProviderUrl, routeRequests };
3537
+ //# sourceMappingURL=index.mjs.map
3538
+ //# sourceMappingURL=index.mjs.map