@fairmint/canton-node-sdk 0.0.291 → 0.0.292

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.
Files changed (34) hide show
  1. package/README.md +51 -0
  2. package/build/src/wallets/connector.d.ts +181 -0
  3. package/build/src/wallets/connector.d.ts.map +1 -0
  4. package/build/src/wallets/connector.js +686 -0
  5. package/build/src/wallets/connector.js.map +1 -0
  6. package/build/src/wallets/errors.d.ts +29 -3
  7. package/build/src/wallets/errors.d.ts.map +1 -1
  8. package/build/src/wallets/errors.js +38 -1
  9. package/build/src/wallets/errors.js.map +1 -1
  10. package/build/src/wallets/index.d.ts +7 -2
  11. package/build/src/wallets/index.d.ts.map +1 -1
  12. package/build/src/wallets/index.js +13 -2
  13. package/build/src/wallets/index.js.map +1 -1
  14. package/build/src/wallets/latch.d.ts +70 -0
  15. package/build/src/wallets/latch.d.ts.map +1 -0
  16. package/build/src/wallets/latch.js +100 -0
  17. package/build/src/wallets/latch.js.map +1 -0
  18. package/build/src/wallets/loop.d.ts +36 -0
  19. package/build/src/wallets/loop.d.ts.map +1 -0
  20. package/build/src/wallets/loop.js +59 -0
  21. package/build/src/wallets/loop.js.map +1 -0
  22. package/build/src/wallets/options.d.ts +76 -0
  23. package/build/src/wallets/options.d.ts.map +1 -0
  24. package/build/src/wallets/options.js +21 -0
  25. package/build/src/wallets/options.js.map +1 -0
  26. package/build/src/wallets/storage.d.ts +17 -0
  27. package/build/src/wallets/storage.d.ts.map +1 -0
  28. package/build/src/wallets/storage.js +55 -0
  29. package/build/src/wallets/storage.js.map +1 -0
  30. package/build/src/wallets/store.d.ts +57 -6
  31. package/build/src/wallets/store.d.ts.map +1 -1
  32. package/build/src/wallets/store.js +155 -36
  33. package/build/src/wallets/store.js.map +1 -1
  34. package/package.json +1 -1
@@ -0,0 +1,686 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.DEFAULT_RESTORE_TIMEOUT_MS = void 0;
4
+ exports.createWalletConnector = createWalletConnector;
5
+ /**
6
+ * A page's wallet connection on one DA network: which wallet options it offers, which one is wanted, restoring the one
7
+ * remembered from an earlier visit, and connecting the session to it. It owns the page's `Cip103Session` and
8
+ * `WalletStore`, shares one write latch with them, and remembers the choice in browser storage.
9
+ *
10
+ * Observable for any UI framework: `subscribe` and `getSnapshot` (React: `useSyncExternalStore`). The snapshot carries
11
+ * codes, never sentences: the page words them.
12
+ */
13
+ const abort_1 = require("./abort");
14
+ const errors_1 = require("./errors");
15
+ const latch_1 = require("./latch");
16
+ const notify_1 = require("./notify");
17
+ const session_1 = require("./session");
18
+ const storage_1 = require("./storage");
19
+ const store_1 = require("./store");
20
+ /** The default {@link WalletConnectorInput.restoreTimeoutMs}. */
21
+ exports.DEFAULT_RESTORE_TIMEOUT_MS = 15000;
22
+ const UNSUPPORTED = Object.freeze({ available: false, reason: 'unsupported-network' });
23
+ const DISCONNECTED = Object.freeze({ status: 'disconnected', error: null });
24
+ /** A wallet the session connected outside the connector (through `connector.session` directly). */
25
+ const UNKNOWN_OPTION = Object.freeze({ key: 'unknown', kind: 'unknown', name: 'CIP-0103 wallet' });
26
+ const IDLE = { provider: 'idle', loaded: null, loadError: null, controller: null };
27
+ function info(option) {
28
+ const { key, kind, name, icon } = option;
29
+ return Object.freeze(icon === undefined ? { key, kind, name } : { key, kind, name, icon });
30
+ }
31
+ /**
32
+ * A wallet connection for `input.network`: the session, the store over it and the shared latch, plus restore and
33
+ * remember (see {@link WalletConnector}). Create one per network a page serves, and `dispose()` it when the page leaves
34
+ * that network.
35
+ */
36
+ function createWalletConnector(input) {
37
+ const { network, discover } = input;
38
+ const storageKey = input.storageKey ?? 'canton-wallet';
39
+ const walletStorageKey = `${storageKey}.wallet`;
40
+ const selectedStorageKey = `${storageKey}.selected`;
41
+ const restoreTimeoutMs = input.restoreTimeoutMs ?? exports.DEFAULT_RESTORE_TIMEOUT_MS;
42
+ if (!Number.isFinite(restoreTimeoutMs) || restoreTimeoutMs < 0 || restoreTimeoutMs > abort_1.MAX_TIMER_MS) {
43
+ throw new RangeError(`createWalletConnector: restoreTimeoutMs must be between 0 and ${abort_1.MAX_TIMER_MS}`);
44
+ }
45
+ const local = input.storage?.local === undefined ? (0, storage_1.globalStorage)('local') : input.storage.local;
46
+ const tab = input.storage?.session === undefined ? (0, storage_1.globalStorage)('session') : input.storage.session;
47
+ const ownsLatch = input.latch === undefined;
48
+ const latch = input.latch ?? (0, latch_1.createWriteLatch)();
49
+ const listeners = new Set();
50
+ const fixed = input.options;
51
+ let via = null;
52
+ let discovered = [];
53
+ const preloads = new Map();
54
+ let restore = null;
55
+ // A loaded option's connect that is still loading its provider.
56
+ let pendingLoad = null;
57
+ // The live option wanted, and the provider the connector last connected the session to for it.
58
+ let live = null;
59
+ // The connection shown while a live option reconnects with a new provider for the same retain key.
60
+ let held = null;
61
+ let lastConnection = null;
62
+ // Every connect takes a new number; a connect whose number is no longer the latest reports `cancelled`.
63
+ let attempts = 0;
64
+ // Wakes the connects waiting on the session when a newer attempt supersedes them, so they report at once.
65
+ const superseders = new Set();
66
+ let selected = null;
67
+ let error = null;
68
+ let discovery = null;
69
+ let discovering = false;
70
+ let disposed = false;
71
+ const liveSubscriptions = new Map();
72
+ /** Read through a call, so a check after an await is not narrowed by one before it. */
73
+ function isDisposed() {
74
+ return disposed;
75
+ }
76
+ /** Whether a connect that took `attempt` was superseded (by another connect, a cancel, a disconnect or dispose). */
77
+ function superseded(attempt) {
78
+ return disposed || attempt !== attempts;
79
+ }
80
+ /** Start a new attempt: every connect in flight is superseded and reports `cancelled` now. */
81
+ function nextAttempt() {
82
+ attempts += 1;
83
+ for (const wake of [...superseders])
84
+ wake();
85
+ superseders.clear();
86
+ return attempts;
87
+ }
88
+ /** The UI key of a session wallet: the live option's retain key when it came through one. */
89
+ function connectionKey(wallet) {
90
+ if (via !== null && via.provider === wallet.provider && via.option.mode === 'live') {
91
+ return `${via.option.key}:${via.retainKey ?? wallet.key}`;
92
+ }
93
+ return wallet.key;
94
+ }
95
+ const session = network === null ? null : (0, session_1.createCip103Session)({ network });
96
+ const store = session === null
97
+ ? null
98
+ : (0, store_1.createWalletStore)({
99
+ ...input.store,
100
+ session,
101
+ latch,
102
+ retainKey: (wallet) => connectionKey(wallet),
103
+ // The store holds its snapshot through a connect only while this connector holds the connection
104
+ // (`reconnecting`: a rebuilt provider for the same retain key), never through a connect to another wallet.
105
+ connectingRetainKey: () => held?.key ?? null,
106
+ });
107
+ function options() {
108
+ return [...fixed, ...discovered];
109
+ }
110
+ function findOption(key) {
111
+ return options().find((option) => option.key === key);
112
+ }
113
+ function sessionState() {
114
+ return session?.getSnapshot() ?? DISCONNECTED;
115
+ }
116
+ function availability(option) {
117
+ if (network === null)
118
+ return UNSUPPORTED;
119
+ try {
120
+ return option.availability(network);
121
+ }
122
+ catch {
123
+ return UNSUPPORTED;
124
+ }
125
+ }
126
+ function currentConnection() {
127
+ const state = sessionState();
128
+ if (state.status !== 'connected')
129
+ return null;
130
+ const { wallet } = state;
131
+ const key = connectionKey(wallet);
132
+ if (lastConnection?.wallet === wallet && lastConnection.key === key)
133
+ return lastConnection;
134
+ const option = via !== null && via.provider === wallet.provider ? info(via.option) : UNKNOWN_OPTION;
135
+ lastConnection = Object.freeze({ key, option, wallet });
136
+ return lastConnection;
137
+ }
138
+ function status() {
139
+ // The user's connect is loading its option's provider: it is in flight even while the session is still on the
140
+ // previous wallet (or still signing in to an earlier one), and cancel() must reach it.
141
+ if (pendingLoad !== null)
142
+ return 'connecting';
143
+ const state = sessionState();
144
+ if (state.status === 'connected')
145
+ return 'connected';
146
+ if (state.status === 'connecting')
147
+ return held !== null ? 'reconnecting' : 'connecting';
148
+ if (restore !== null)
149
+ return 'restoring';
150
+ if (live !== null && network !== null)
151
+ return 'preparing';
152
+ return 'disconnected';
153
+ }
154
+ function target(current, connection) {
155
+ switch (current) {
156
+ case 'connected':
157
+ return connection?.option ?? null;
158
+ case 'reconnecting':
159
+ return held?.option ?? null;
160
+ case 'restoring':
161
+ return restore?.option ?? null;
162
+ case 'connecting':
163
+ if (pendingLoad !== null)
164
+ return info(pendingLoad.option);
165
+ return via === null ? null : info(via.option);
166
+ case 'preparing':
167
+ return live === null ? null : info(live.option);
168
+ case 'disconnected':
169
+ return null;
170
+ }
171
+ }
172
+ function optionState(option) {
173
+ const base = { ...info(option), mode: option.mode, availability: availability(option) };
174
+ if (option.mode === 'live') {
175
+ let offers = false;
176
+ try {
177
+ offers = option.live.getProvider() !== null;
178
+ }
179
+ catch {
180
+ offers = false;
181
+ }
182
+ return Object.freeze({ ...base, provider: offers ? 'ready' : 'idle', loadError: null });
183
+ }
184
+ const preload = preloads.get(option.key) ?? IDLE;
185
+ return Object.freeze({ ...base, provider: preload.provider, loadError: preload.loadError });
186
+ }
187
+ function buildSnapshot() {
188
+ const current = status();
189
+ const connection = current === 'reconnecting' ? held : current === 'connecting' ? null : currentConnection();
190
+ return Object.freeze({
191
+ network,
192
+ status: current,
193
+ target: target(current, connection),
194
+ selected,
195
+ connection,
196
+ stale: current === 'reconnecting' && connection !== null,
197
+ options: Object.freeze(options().map(optionState)),
198
+ discovering,
199
+ error,
200
+ });
201
+ }
202
+ let snapshot = buildSnapshot();
203
+ function publish() {
204
+ if (disposed)
205
+ return;
206
+ snapshot = buildSnapshot();
207
+ (0, notify_1.notifyListeners)(listeners);
208
+ }
209
+ function setSelected(key) {
210
+ selected = key;
211
+ (0, storage_1.writeStorage)(tab, selectedStorageKey, key);
212
+ }
213
+ // ----- restore -----
214
+ function retireRestore() {
215
+ const run = restore;
216
+ if (run === null)
217
+ return;
218
+ restore = null;
219
+ clearTimeout(run.timer);
220
+ run.controller.abort();
221
+ }
222
+ /** Cancel or the timeout: retire the run and forget its wallet, unless the user picked another since. */
223
+ function abandonRestore(run) {
224
+ if (restore !== run)
225
+ return;
226
+ retireRestore();
227
+ if ((0, storage_1.readStorage)(local, walletStorageKey) === run.key)
228
+ (0, storage_1.writeStorage)(local, walletStorageKey, null);
229
+ }
230
+ /** Waits for discovery to settle (a rediscovery started meanwhile included). Never rejects. */
231
+ async function discoverySettled() {
232
+ let awaited = null;
233
+ while (discovery !== null && discovery.promise !== awaited) {
234
+ awaited = discovery.promise;
235
+ await awaited;
236
+ }
237
+ }
238
+ /**
239
+ * Restore the loaded option remembered under `key`: resolve it (after discovery when it is not a fixed option), load
240
+ * its provider, then `session.restore(provider)`. Retiring the run aborts its signal: the session drops an aborted
241
+ * restore without changing anything, so a retired run never connects late and never disconnects a wallet.
242
+ */
243
+ function startRestore(key, forSession, forNetwork) {
244
+ const run = { key, controller: new AbortController(), timer: undefined, option: null };
245
+ restore = run;
246
+ run.timer = setTimeout(() => {
247
+ abandonRestore(run);
248
+ publish();
249
+ }, restoreTimeoutMs);
250
+ const { signal } = run.controller;
251
+ void (async () => {
252
+ try {
253
+ let option = findOption(key);
254
+ if (option === undefined) {
255
+ await discoverySettled();
256
+ if (restore !== run)
257
+ return;
258
+ option = findOption(key);
259
+ }
260
+ // Nothing has it (an extension no longer installed): the key stays for a later visit.
261
+ if (option?.mode !== 'load' || !availability(option).available)
262
+ return;
263
+ run.option = info(option);
264
+ publish();
265
+ const provider = await option.load(forNetwork, signal);
266
+ if (restore !== run)
267
+ return;
268
+ via = { provider, option, retainKey: null };
269
+ // Connects only when the wallet still reports its session; rejects only when the run was retired.
270
+ await forSession.restore(provider, { signal });
271
+ }
272
+ catch {
273
+ // Retired, or the wallet is gone or could not be set up: the page starts disconnected.
274
+ }
275
+ finally {
276
+ if (restore === run) {
277
+ restore = null;
278
+ clearTimeout(run.timer);
279
+ publish();
280
+ }
281
+ }
282
+ })();
283
+ }
284
+ // ----- connecting -----
285
+ /** How a connect of `provider` (attempt `attempt`) ended, once `session.connect` settled. */
286
+ function settle(attempt, key, provider) {
287
+ if (superseded(attempt))
288
+ return { status: 'cancelled' };
289
+ const state = sessionState();
290
+ if (state.status === 'connected' && state.wallet.provider === provider)
291
+ return { status: 'connected' };
292
+ if (state.status === 'disconnected' && state.error !== null) {
293
+ error = Object.freeze({ code: 'connect-failed', key, description: state.error });
294
+ publish();
295
+ return { status: 'failed' };
296
+ }
297
+ return { status: 'cancelled' };
298
+ }
299
+ async function connectProvider(forSession, option, provider, retainKey) {
300
+ const attempt = nextAttempt();
301
+ via = { provider, option, retainKey };
302
+ // Started synchronously: inside the user's click when nothing was awaited before.
303
+ const pending = forSession.connect(provider).catch(() => undefined); // rejects only for a signal; none is passed
304
+ publish();
305
+ // A superseded connect reports at once; the session drops its late answer itself.
306
+ let wake = () => undefined;
307
+ const woken = new Promise((resolve) => {
308
+ wake = resolve;
309
+ });
310
+ superseders.add(wake);
311
+ await Promise.race([pending, woken]);
312
+ superseders.delete(wake);
313
+ return settle(attempt, option.key, provider);
314
+ }
315
+ /** Connect the wanted live option's current provider, unless it is the one already connected or a write runs. */
316
+ function evaluateLive() {
317
+ if (disposed || session === null || live === null)
318
+ return;
319
+ const wanted = live;
320
+ let provider;
321
+ let retainKey;
322
+ try {
323
+ provider = wanted.option.live.getProvider();
324
+ retainKey = wanted.option.live.getRetainKey();
325
+ }
326
+ catch {
327
+ provider = null;
328
+ retainKey = null;
329
+ }
330
+ if (provider === null) {
331
+ const previous = wanted.connected;
332
+ if (previous === null)
333
+ return;
334
+ // Torn down (logout, another wallet or party): leave it.
335
+ wanted.connected = null;
336
+ held = null;
337
+ const state = sessionState();
338
+ const onIt = (state.status === 'connected' && state.wallet.provider === previous) ||
339
+ (state.status === 'connecting' && via?.provider === previous);
340
+ if (onIt)
341
+ session.disconnect();
342
+ publish();
343
+ return;
344
+ }
345
+ if (provider === wanted.connected)
346
+ return;
347
+ // Never reconnect under a write: the latch's release evaluates again.
348
+ if (latch.getSnapshot().holder !== null)
349
+ return;
350
+ wanted.connected = provider;
351
+ const current = currentConnection();
352
+ held =
353
+ current !== null && retainKey !== null && current.key === `${wanted.option.key}:${retainKey}` ? current : null;
354
+ void connectProvider(session, wanted.option, provider, retainKey);
355
+ }
356
+ function stopPendingLoad() {
357
+ if (pendingLoad === null)
358
+ return;
359
+ pendingLoad.controller.abort();
360
+ pendingLoad = null;
361
+ }
362
+ // ----- discovery -----
363
+ function subscribeLive(option) {
364
+ if (option.mode !== 'live' || liveSubscriptions.has(option.key))
365
+ return;
366
+ const onChange = () => {
367
+ if (live?.option === option)
368
+ evaluateLive();
369
+ publish();
370
+ };
371
+ liveSubscriptions.set(option.key, option.live.subscribe(onChange));
372
+ }
373
+ function setDiscovered(found) {
374
+ const fixedKeys = new Set(fixed.map((option) => option.key));
375
+ const seen = new Set();
376
+ const next = found.filter((option) => {
377
+ if (fixedKeys.has(option.key) || seen.has(option.key))
378
+ return false;
379
+ seen.add(option.key);
380
+ return true;
381
+ });
382
+ const nextKeys = new Set(next.map((option) => option.key));
383
+ for (const option of discovered) {
384
+ if (nextKeys.has(option.key))
385
+ continue;
386
+ preloads.get(option.key)?.controller?.abort();
387
+ preloads.delete(option.key);
388
+ liveSubscriptions.get(option.key)?.();
389
+ liveSubscriptions.delete(option.key);
390
+ }
391
+ discovered = next;
392
+ for (const option of next)
393
+ subscribeLive(option);
394
+ }
395
+ async function runDiscover() {
396
+ if (disposed || discover === undefined)
397
+ return Promise.resolve();
398
+ discovery?.controller.abort();
399
+ const controller = new AbortController();
400
+ discovering = true;
401
+ const promise = (async () => {
402
+ try {
403
+ const found = await discover(controller.signal);
404
+ if (!isDisposed() && !controller.signal.aborted)
405
+ setDiscovered(found);
406
+ }
407
+ catch {
408
+ // Nothing found this time: the options found before stay.
409
+ }
410
+ finally {
411
+ if (discovery?.controller === controller) {
412
+ discovering = false;
413
+ publish();
414
+ }
415
+ }
416
+ })();
417
+ discovery = { controller, promise };
418
+ publish();
419
+ await promise;
420
+ }
421
+ // ----- wiring -----
422
+ const unsubscribeSession = session?.subscribe(() => {
423
+ if (sessionState().status !== 'connecting')
424
+ held = null;
425
+ publish();
426
+ }) ?? (() => undefined);
427
+ // A live connect deferred while a write held the latch runs once it is free.
428
+ const unsubscribeLatch = latch.subscribe(evaluateLive);
429
+ for (const option of fixed)
430
+ subscribeLive(option);
431
+ const flagged = (0, storage_1.readStorage)(tab, selectedStorageKey);
432
+ if (flagged !== null && fixed.some((option) => option.key === flagged && option.mode === 'live')) {
433
+ selected = flagged;
434
+ }
435
+ void runDiscover();
436
+ const remembered = (0, storage_1.readStorage)(local, walletStorageKey);
437
+ if (remembered !== null) {
438
+ const option = fixed.find((candidate) => candidate.key === remembered);
439
+ if (option?.mode === 'live') {
440
+ selected = remembered;
441
+ if (network !== null)
442
+ live = { option, connected: null };
443
+ try {
444
+ option.live.restore();
445
+ }
446
+ catch {
447
+ // The option's own recovery failed: its setup UI is open anyway.
448
+ }
449
+ evaluateLive();
450
+ }
451
+ else if (session !== null && network !== null) {
452
+ startRestore(remembered, session, network);
453
+ }
454
+ }
455
+ snapshot = buildSnapshot();
456
+ return {
457
+ subscribe(listener) {
458
+ listeners.add(listener);
459
+ return () => {
460
+ listeners.delete(listener);
461
+ };
462
+ },
463
+ getSnapshot: () => snapshot,
464
+ session,
465
+ store,
466
+ latch,
467
+ async connect(key) {
468
+ if (disposed)
469
+ return { status: 'refused', reason: 'disposed' };
470
+ if (network === null || session === null)
471
+ return { status: 'refused', reason: 'no-network' };
472
+ const option = findOption(key);
473
+ if (option === undefined)
474
+ return { status: 'refused', reason: 'unknown-option' };
475
+ if (latch.getSnapshot().holder !== null)
476
+ return { status: 'refused', reason: 'busy' };
477
+ const available = availability(option);
478
+ if (!available.available) {
479
+ error = Object.freeze({ code: 'unavailable', key, description: null, availability: available });
480
+ publish();
481
+ return { status: 'refused', reason: 'unavailable' };
482
+ }
483
+ retireRestore();
484
+ latch.bump();
485
+ (0, storage_1.writeStorage)(local, walletStorageKey, key);
486
+ error = null;
487
+ stopPendingLoad();
488
+ held = null;
489
+ if (option.mode === 'live') {
490
+ if (selected !== null && selected !== key)
491
+ setSelected(null);
492
+ // A new attempt: the same provider connects again (after a cancelled or failed connect).
493
+ live = { option, connected: null };
494
+ let provider;
495
+ let retainKey;
496
+ try {
497
+ provider = option.live.getProvider();
498
+ retainKey = option.live.getRetainKey();
499
+ }
500
+ catch {
501
+ provider = null;
502
+ retainKey = null;
503
+ }
504
+ if (provider === null) {
505
+ nextAttempt();
506
+ publish();
507
+ return { status: 'preparing' };
508
+ }
509
+ live.connected = provider;
510
+ return connectProvider(session, option, provider, retainKey);
511
+ }
512
+ live = null;
513
+ if (selected !== null)
514
+ setSelected(null);
515
+ const preload = preloads.get(key);
516
+ if (preload?.provider === 'ready' && preload.loaded !== null) {
517
+ return connectProvider(session, option, preload.loaded, null);
518
+ }
519
+ const attempt = nextAttempt();
520
+ const controller = new AbortController();
521
+ pendingLoad = { option, controller };
522
+ publish();
523
+ let provider;
524
+ try {
525
+ provider = await option.load(network, controller.signal);
526
+ }
527
+ catch (failure) {
528
+ if (superseded(attempt))
529
+ return { status: 'cancelled' };
530
+ pendingLoad = null;
531
+ const description = (0, errors_1.describeWalletError)(failure);
532
+ preloads.set(key, { provider: 'failed', loaded: null, loadError: description, controller: null });
533
+ error = Object.freeze({ code: 'load-failed', key, description });
534
+ publish();
535
+ return { status: 'failed' };
536
+ }
537
+ if (superseded(attempt))
538
+ return { status: 'cancelled' };
539
+ pendingLoad = null;
540
+ preloads.set(key, { provider: 'ready', loaded: provider, loadError: null, controller: null });
541
+ return connectProvider(session, option, provider, null);
542
+ },
543
+ select(key) {
544
+ if (disposed || latch.getSnapshot().holder !== null || status() === 'connecting')
545
+ return false;
546
+ if (key !== null) {
547
+ if (findOption(key)?.mode !== 'live')
548
+ return false;
549
+ retireRestore();
550
+ // Written now, so a login that redirects at once still finds it.
551
+ setSelected(key);
552
+ error = null;
553
+ publish();
554
+ return true;
555
+ }
556
+ const previous = selected;
557
+ retireRestore();
558
+ setSelected(null);
559
+ if (previous !== null && (0, storage_1.readStorage)(local, walletStorageKey) === previous) {
560
+ (0, storage_1.writeStorage)(local, walletStorageKey, null);
561
+ }
562
+ if (live !== null && live.option.key === previous && currentConnection()?.option.key !== previous)
563
+ live = null;
564
+ error = null;
565
+ publish();
566
+ return true;
567
+ },
568
+ preload(keys) {
569
+ if (disposed || network === null)
570
+ return () => undefined;
571
+ const started = [];
572
+ for (const option of options()) {
573
+ if (option.mode !== 'load' || (keys !== undefined && !keys.includes(option.key)))
574
+ continue;
575
+ if (!availability(option).available)
576
+ continue;
577
+ const current = preloads.get(option.key)?.provider;
578
+ if (current === 'loading' || current === 'ready')
579
+ continue;
580
+ const controller = new AbortController();
581
+ const { key } = option;
582
+ preloads.set(key, { provider: 'loading', loaded: null, loadError: null, controller });
583
+ started.push({ key, controller });
584
+ const mine = () => !disposed && preloads.get(key)?.controller === controller;
585
+ option.load(network, controller.signal).then((provider) => {
586
+ if (!mine())
587
+ return;
588
+ preloads.set(key, { provider: 'ready', loaded: provider, loadError: null, controller: null });
589
+ publish();
590
+ }, (failure) => {
591
+ if (!mine())
592
+ return;
593
+ preloads.set(key, controller.signal.aborted
594
+ ? IDLE
595
+ : { provider: 'failed', loaded: null, loadError: (0, errors_1.describeWalletError)(failure), controller: null });
596
+ publish();
597
+ });
598
+ }
599
+ if (started.length > 0)
600
+ publish();
601
+ return () => {
602
+ let changed = false;
603
+ for (const { key, controller } of started) {
604
+ const current = preloads.get(key);
605
+ if (current?.controller !== controller || current.provider !== 'loading')
606
+ continue;
607
+ controller.abort();
608
+ preloads.set(key, IDLE);
609
+ changed = true;
610
+ }
611
+ if (changed)
612
+ publish();
613
+ };
614
+ },
615
+ rediscover: runDiscover,
616
+ cancel() {
617
+ if (disposed)
618
+ return;
619
+ const current = status();
620
+ if (current === 'restoring') {
621
+ if (restore !== null)
622
+ abandonRestore(restore);
623
+ }
624
+ else if (current === 'connecting' || current === 'reconnecting') {
625
+ if (restore !== null)
626
+ abandonRestore(restore);
627
+ nextAttempt();
628
+ stopPendingLoad();
629
+ held = null;
630
+ session?.disconnect();
631
+ }
632
+ else if (current === 'preparing') {
633
+ live = null;
634
+ }
635
+ else {
636
+ return;
637
+ }
638
+ error = null;
639
+ publish();
640
+ },
641
+ disconnect() {
642
+ if (disposed)
643
+ return;
644
+ retireRestore();
645
+ latch.bump();
646
+ nextAttempt();
647
+ stopPendingLoad();
648
+ live = null;
649
+ held = null;
650
+ session?.disconnect();
651
+ setSelected(null);
652
+ (0, storage_1.writeStorage)(local, walletStorageKey, null);
653
+ error = null;
654
+ publish();
655
+ },
656
+ dispose() {
657
+ if (disposed)
658
+ return;
659
+ retireRestore();
660
+ stopPendingLoad();
661
+ nextAttempt();
662
+ discovery?.controller.abort();
663
+ for (const preload of preloads.values())
664
+ preload.controller?.abort();
665
+ for (const unsubscribe of liveSubscriptions.values())
666
+ unsubscribe();
667
+ liveSubscriptions.clear();
668
+ unsubscribeLatch();
669
+ unsubscribeSession();
670
+ disposed = true;
671
+ listeners.clear();
672
+ if (ownsLatch) {
673
+ latch.bump();
674
+ latch.dispose();
675
+ }
676
+ store?.dispose();
677
+ if (session !== null) {
678
+ // Best effort: the wallet's own session ends too.
679
+ if (session.getSnapshot().status !== 'disconnected')
680
+ session.disconnect();
681
+ session.dispose();
682
+ }
683
+ },
684
+ };
685
+ }
686
+ //# sourceMappingURL=connector.js.map