@kheopskit/react 5.3.0 → 6.0.0-rc.1

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 CHANGED
@@ -1,116 +1,265 @@
1
1
  "use client";
2
- import { createKheopskitStore, getHydratedSnapshot, getKheopskit$, resolveConfig } from "@kheopskit/core";
3
- import { createContext, useContext, useEffect, useMemo, useRef, useSyncExternalStore } from "react";
2
+ import { KheopskitError, createKheopskitStore, getHydratedSnapshot, getKheopskit$, resolveConfig } from "@kheopskit/core";
3
+ import { createContext, useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useSyncExternalStore } from "react";
4
+ import { Observable, defer, shareReplay } from "rxjs";
4
5
  import { jsx } from "react/jsx-runtime";
5
6
  //#region src/context.ts
6
7
  const KheopskitContext = createContext(null);
8
+ const useKheopskitExternalStore = (hookName) => {
9
+ const store = useContext(KheopskitContext);
10
+ if (!store) throw new Error(`${hookName} can't be used without a KheopskitProvider`);
11
+ return store;
12
+ };
7
13
  //#endregion
8
14
  //#region src/createExternalStore.ts
9
- const createExternalStore = (observable$, initialValue, serverValue) => {
10
- let latestValue = null;
11
- let subscription = null;
12
- let subscriberCount = 0;
15
+ const afterThisCommitsLayoutEffects$1 = () => Promise.resolve();
16
+ const createExternalStore = (resolveClientSource, serverValue) => {
17
+ let source;
18
+ let latestValue;
19
+ let subscription;
13
20
  const listeners = /* @__PURE__ */ new Set();
14
- const ensureSubscription = () => {
15
- if (!subscription || subscription.closed) subscription = observable$.subscribe((value) => {
21
+ const getSource = () => {
22
+ source ?? (source = resolveClientSource());
23
+ return source;
24
+ };
25
+ const getSnapshot = () => latestValue ?? getSource().initialValue;
26
+ const getServerSnapshot = () => serverValue;
27
+ const releaseWhenUnobserved = () => {
28
+ if (listeners.size) return;
29
+ subscription?.unsubscribe();
30
+ subscription = void 0;
31
+ };
32
+ const subscribe = (listener) => {
33
+ if (!subscription || subscription.closed) subscription = getSource().pipeline.observable$.subscribe((value) => {
16
34
  latestValue = value;
17
- for (const listener of listeners) listener(value);
35
+ for (const notify of listeners) notify(value);
18
36
  });
19
- };
20
- const getSnapshot = () => latestValue ?? initialValue;
21
- /**
22
- * Returns the server-side snapshot for SSR hydration.
23
- * This prevents hydration mismatches by providing a consistent
24
- * value during server rendering. Must return the same value as
25
- * what the server rendered.
26
- */
27
- const getServerSnapshot = () => serverValue ?? initialValue;
28
- const subscribe = (callback) => {
29
- subscriberCount++;
30
- ensureSubscription();
31
- listeners.add(callback);
32
- callback(getSnapshot());
37
+ listeners.add(listener);
38
+ listener(getSnapshot());
33
39
  return () => {
34
- subscriberCount--;
35
- listeners.delete(callback);
40
+ listeners.delete(listener);
41
+ queueMicrotask(releaseWhenUnobserved);
36
42
  };
37
43
  };
38
- const destroy = () => {
39
- if (subscriberCount === 0 && subscription) {
40
- subscription.unsubscribe();
41
- subscription = null;
42
- }
44
+ /** The shared pipeline's liveness once this commit's layout effects ran. */
45
+ const whenLive = async (signal) => {
46
+ await afterThisCommitsLayoutEffects$1();
47
+ return getSource().pipeline.whenLive(signal);
43
48
  };
44
49
  return {
45
50
  getSnapshot,
46
51
  getServerSnapshot,
47
52
  subscribe,
48
- destroy
53
+ whenLive
49
54
  };
50
55
  };
51
56
  //#endregion
52
- //#region src/KheopskitProvider.tsx
53
- const KheopskitProvider = ({ children, config, ssrCookies }) => {
57
+ //#region src/liveActions.ts
58
+ const didNotRun = {
59
+ aborted: "was aborted",
60
+ unheld: "was called while nothing holds the pipeline (no KheopskitProvider of this instance is mounted and visible, and nothing subscribes its kheopskit$)",
61
+ errored: "did not run because the pipeline stopped with an error",
62
+ completed: "did not run because the pipeline completed"
63
+ };
64
+ const abortedError = (walletId, operation, end) => new KheopskitError("ABORTED", `${operation} of wallet ${walletId} ${didNotRun[end]}`, { walletId });
65
+ /**
66
+ * `connect` and `disconnect` for one wallet id that act on the instance's
67
+ * pipeline at call time: they wait for the restarted pipeline's first emission
68
+ * after an `<Activity>` reveal and reject `ABORTED` while nothing holds it.
69
+ */
70
+ const walletActions = (store, walletId) => {
71
+ const liveWallet = async (operation, signal) => {
72
+ const liveness = await store.whenLive(signal);
73
+ if (liveness.end) throw abortedError(walletId, operation, liveness.end);
74
+ const wallet = liveness.state.wallets.find((candidate) => candidate.id === walletId);
75
+ if (!wallet) throw new Error(`[kheopskit] no wallet ${walletId}`);
76
+ return wallet;
77
+ };
78
+ return {
79
+ connect: async (options) => (await liveWallet("connect", options?.signal)).connect(options),
80
+ disconnect: async () => (await liveWallet("disconnect")).disconnect()
81
+ };
82
+ };
83
+ const withLiveActions = (store) => {
84
+ const presented = /* @__PURE__ */ new WeakMap();
85
+ const present = (state) => {
86
+ let live = presented.get(state);
87
+ if (!live) {
88
+ live = {
89
+ ...state,
90
+ wallets: state.wallets.map((wallet) => ({
91
+ ...wallet,
92
+ ...walletActions(store, wallet.id)
93
+ }))
94
+ };
95
+ presented.set(state, live);
96
+ }
97
+ return live;
98
+ };
99
+ return {
100
+ ...store,
101
+ getSnapshot: () => present(store.getSnapshot()),
102
+ getServerSnapshot: () => present(store.getServerSnapshot())
103
+ };
104
+ };
105
+ //#endregion
106
+ //#region src/KheopskitSourceProvider.tsx
107
+ const keepPipelineRunning = () => {};
108
+ const useIsomorphicLayoutEffect$1 = typeof window === "undefined" ? useEffect : useLayoutEffect;
109
+ const hydrating = (config, snapshot) => ({
110
+ ...snapshot,
111
+ config,
112
+ isHydrating: true,
113
+ isDiscovering: true
114
+ });
115
+ const serverSnapshot = (config, ssrCookies) => hydrating(config, ssrCookies === void 0 ? {
116
+ wallets: [],
117
+ accounts: []
118
+ } : getHydratedSnapshot(createKheopskitStore({
119
+ ssrCookies,
120
+ storageKey: config.storageKey
121
+ }), config, { icons: false }));
122
+ const KheopskitSourceProvider = ({ children, config, ssrCookies, resolveClientSource }) => {
54
123
  const resolvedConfig = useMemo(() => resolveConfig(config), [config]);
55
- const lastConfigRef = useRef(config);
56
- const hasMountedRef = useRef(false);
57
- useEffect(() => {
58
- if (hasMountedRef.current && lastConfigRef.current !== config && (typeof process === "undefined" || process.env?.NODE_ENV !== "production")) console.warn("[kheopskit] KheopskitProvider received a new `config` reference; this recreates the store and re-subscribes on every render. Pass a referentially stable config (module scope, useMemo, or createKheopskit()).");
59
- hasMountedRef.current = true;
60
- lastConfigRef.current = config;
61
- }, [config]);
62
- const kheopskitStore = useMemo(() => createKheopskitStore({
63
- ssrCookies,
64
- storageKey: resolvedConfig.storageKey
65
- }), [ssrCookies, resolvedConfig.storageKey]);
66
- const serverValue = useMemo(() => {
67
- if (ssrCookies === void 0) return {
68
- wallets: [],
69
- accounts: [],
70
- config: resolvedConfig,
71
- isHydrating: true
72
- };
124
+ const externalStore = useMemo(() => withLiveActions(createExternalStore(() => {
125
+ const { store, pipeline } = resolveClientSource(resolvedConfig);
73
126
  return {
74
- ...getHydratedSnapshot(kheopskitStore, resolvedConfig.platforms),
75
- config: resolvedConfig,
76
- isHydrating: true
127
+ pipeline,
128
+ initialValue: hydrating(resolvedConfig, getHydratedSnapshot(store, resolvedConfig, { icons: true }))
77
129
  };
78
- }, [
130
+ }, serverSnapshot(resolvedConfig, ssrCookies))), [
131
+ resolvedConfig,
79
132
  ssrCookies,
80
- kheopskitStore,
81
- resolvedConfig
133
+ resolveClientSource
82
134
  ]);
83
- const initialValue = useMemo(() => {
84
- return {
85
- ...getHydratedSnapshot(kheopskitStore, resolvedConfig.platforms, { icons: true }),
86
- config: resolvedConfig,
87
- isHydrating: true
88
- };
89
- }, [kheopskitStore, resolvedConfig]);
90
- const store = useMemo(() => createExternalStore(getKheopskit$(config, {
91
- ssrCookies,
92
- store: kheopskitStore
93
- }), initialValue, serverValue), [
94
- config,
95
- ssrCookies,
96
- kheopskitStore,
97
- initialValue,
98
- serverValue
99
- ]);
100
- useEffect(() => {
101
- return () => store.destroy();
102
- }, [store]);
103
- const state = useSyncExternalStore(store.subscribe, store.getSnapshot, store.getServerSnapshot);
104
- const value = useMemo(() => ({ state }), [state]);
135
+ useIsomorphicLayoutEffect$1(() => externalStore.subscribe(keepPipelineRunning), [externalStore]);
105
136
  return /* @__PURE__ */ jsx(KheopskitContext.Provider, {
106
- value,
137
+ value: externalStore,
107
138
  children
108
139
  });
109
140
  };
110
141
  //#endregion
142
+ //#region src/livePipeline.ts
143
+ const createLivePipeline = (source$) => {
144
+ let holders = 0;
145
+ let run = 0;
146
+ let emittedRun = 0;
147
+ let latestValue;
148
+ let ended;
149
+ const firstEmissionWaiters = /* @__PURE__ */ new Set();
150
+ const settleFirstEmission = (liveness) => {
151
+ for (const waiter of firstEmissionWaiters) waiter(liveness);
152
+ };
153
+ const observable$ = new Observable((subscriber) => {
154
+ if (holders++ === 0) {
155
+ run++;
156
+ ended = void 0;
157
+ }
158
+ const thisRun = run;
159
+ const subscription = source$.subscribe({
160
+ next: (value) => {
161
+ latestValue = value;
162
+ emittedRun = thisRun;
163
+ settleFirstEmission({ state: value });
164
+ subscriber.next(value);
165
+ },
166
+ error: (error) => {
167
+ ended = "errored";
168
+ subscriber.error(error);
169
+ },
170
+ complete: () => {
171
+ ended = "completed";
172
+ subscriber.complete();
173
+ }
174
+ });
175
+ return () => {
176
+ subscription.unsubscribe();
177
+ if (--holders === 0) settleFirstEmission({ end: ended ?? "unheld" });
178
+ };
179
+ });
180
+ const whenLive = async (signal) => {
181
+ if (signal?.aborted) return { end: "aborted" };
182
+ if (ended) return { end: ended };
183
+ if (holders === 0) return { end: "unheld" };
184
+ if (emittedRun === run) return { state: latestValue };
185
+ return new Promise((resolve) => {
186
+ const settle = (liveness) => {
187
+ firstEmissionWaiters.delete(settle);
188
+ signal?.removeEventListener("abort", onAbort);
189
+ resolve(liveness);
190
+ };
191
+ const onAbort = () => settle({ end: "aborted" });
192
+ signal?.addEventListener("abort", onAbort, { once: true });
193
+ firstEmissionWaiters.add(settle);
194
+ });
195
+ };
196
+ return {
197
+ observable$,
198
+ whenLive
199
+ };
200
+ };
201
+ //#endregion
202
+ //#region src/useStateItem.ts
203
+ const isSameItemIgnoringClosures = (a, b) => {
204
+ const previous = a;
205
+ const next = b;
206
+ const keys = Object.keys(previous);
207
+ return keys.length === Object.keys(next).length && keys.every((key) => Object.hasOwn(next, key) && (Object.is(previous[key], next[key]) || typeof previous[key] === "function" && typeof next[key] === "function"));
208
+ };
209
+ const useStateItem = (hookName, key, select) => {
210
+ const store = useKheopskitExternalStore(hookName);
211
+ const snapshots = useMemo(() => {
212
+ let cached;
213
+ return {
214
+ getSnapshot: () => {
215
+ const item = select(store.getSnapshot(), key);
216
+ if (!(cached !== void 0 && item !== void 0 && isSameItemIgnoringClosures(cached, item))) cached = item;
217
+ return cached;
218
+ },
219
+ getServerSnapshot: () => select(store.getServerSnapshot(), key)
220
+ };
221
+ }, [
222
+ store,
223
+ key,
224
+ select
225
+ ]);
226
+ return useSyncExternalStore(store.subscribe, snapshots.getSnapshot, snapshots.getServerSnapshot);
227
+ };
228
+ //#endregion
229
+ //#region src/useAccount.ts
230
+ const selectAccount = (state, accountId) => state.accounts.find((account) => account.id === accountId);
231
+ /**
232
+ * Returns the account with this id, or `undefined` while the state lists none.
233
+ * Re-renders only when that account changes: its name, its placeholder flag,
234
+ * a platform field such as an Ethereum `chainId`, or an SDK handle.
235
+ *
236
+ * Pass the platform tuple as a type argument for the SDK-precise account type,
237
+ * or use the pre-typed hook from {@link createKheopskit}.
238
+ */
239
+ const useAccount = (accountId) => useStateItem("useAccount", accountId, selectAccount);
240
+ //#endregion
241
+ //#region src/useWallet.ts
242
+ const selectWallet = (state, walletId) => state.wallets.find((wallet) => wallet.id === walletId);
243
+ /**
244
+ * Returns the wallet with this id, or `undefined` while the state lists none.
245
+ * Re-renders only when that wallet changes: its status, connection, error,
246
+ * name or any other field. Its `connect` and `disconnect` act on the instance's
247
+ * pipeline when they are called, also right after an `<Activity>` reveal
248
+ * restarts it and while another provider or a `kheopskit$` subscriber holds
249
+ * it, and reject `ABORTED` while nothing holds it.
250
+ *
251
+ * Pass the platform tuple as a type argument for the SDK-precise wallet type,
252
+ * or use the pre-typed hook from {@link createKheopskit}.
253
+ */
254
+ const useWallet = (walletId) => useStateItem("useWallet", walletId, selectWallet);
255
+ //#endregion
111
256
  //#region src/useWallets.ts
112
257
  /**
113
- * Returns the current kheopskit state (wallets, accounts, config, isHydrating).
258
+ * Returns the current kheopskit state (wallets, accounts, config, isHydrating)
259
+ * and re-renders on every change. To follow one wallet or account, prefer
260
+ * {@link useWallet} or {@link useAccount}. Each wallet's `connect` and
261
+ * `disconnect` act on the instance's pipeline when they are called, while
262
+ * anything holds it.
114
263
  *
115
264
  * Pass the platform tuple as a type argument to recover SDK-precise account and
116
265
  * wallet types — `useWallets<typeof platforms>()`. React contexts can't be
@@ -118,44 +267,116 @@ const KheopskitProvider = ({ children, config, ssrCookies }) => {
118
267
  * (SDK-free) wallet/account shapes.
119
268
  */
120
269
  const useWallets = () => {
121
- const ctx = useContext(KheopskitContext);
122
- if (!ctx) throw new Error("useWallets can't be used without a KheopskitProvider");
123
- return ctx.state;
270
+ const store = useKheopskitExternalStore("useWallets");
271
+ return useSyncExternalStore(store.subscribe, store.getSnapshot, store.getServerSnapshot);
124
272
  };
125
273
  //#endregion
126
274
  //#region src/createKheopskit.tsx
275
+ const deferredStore = (claim) => ({
276
+ observable: defer(() => claim().observable),
277
+ rememberWallet: (walletId) => claim().rememberWallet(walletId),
278
+ forgetWallet: (walletId) => claim().forgetWallet(walletId),
279
+ getCachedState: () => claim().getCachedState(),
280
+ setCachedState: (wallets, accounts) => claim().setCachedState(wallets, accounts),
281
+ destroy: () => claim().destroy()
282
+ });
127
283
  /**
128
- * Binds a platform tuple once and returns a `KheopskitProvider` plus hooks
129
- * (`useWallets`, `useAccounts`) already typed to those platforms — so you don't
130
- * repeat `useWallets<typeof platforms>()` in every component.
284
+ * Binds a platform tuple once and returns one kheopskit instance: a
285
+ * `KheopskitProvider`, hooks already typed to those platforms, and the
286
+ * `kheopskit$` stream and `store` the provider uses, for code outside React.
287
+ * Subscribing `kheopskit$` while the provider is mounted runs no second
288
+ * pipeline, and holds the one pipeline for every hook action of the instance.
289
+ *
290
+ * Without `options.store`, the store is created on first use in the browser:
291
+ * backed by cookies when the provider renders first with `ssrCookies`, by
292
+ * localStorage otherwise. The caller owns `store.destroy()`.
131
293
  *
132
294
  * @example
133
295
  * ```tsx
134
296
  * // kheopskit.ts
135
- * export const { KheopskitProvider, useWallets, useAccounts } = createKheopskit({
136
- * platforms: [polkadot(), ethereum(), solana()],
137
- * });
297
+ * export const { KheopskitProvider, useWallets, useWallet, kheopskit$ } =
298
+ * createKheopskit({ platforms: [polkadot(), ethereum(), solana()] });
138
299
  *
139
300
  * // anywhere
140
301
  * const { accounts } = useWallets(); // accounts are platform-precise, no generic
141
302
  * ```
142
303
  */
143
- const createKheopskit = (config) => {
144
- const Provider = ({ children, ssrCookies }) => /* @__PURE__ */ jsx(KheopskitProvider, {
145
- config,
146
- ssrCookies,
147
- children
148
- });
304
+ const createKheopskit = (config, options = {}) => {
305
+ let claimed;
306
+ const claimStore = (ssrCookies) => {
307
+ claimed ?? (claimed = options.store ?? createKheopskitStore({
308
+ ssrCookies,
309
+ storageKey: resolveConfig(config).storageKey
310
+ }));
311
+ return claimed;
312
+ };
313
+ const shared$ = defer(() => getKheopskit$(config, { store: claimStore() })).pipe(shareReplay({
314
+ refCount: true,
315
+ bufferSize: 1
316
+ }));
317
+ const pipeline = createLivePipeline(shared$);
318
+ const kheopskit$ = pipeline.observable$;
319
+ const Provider = ({ children, ssrCookies }) => {
320
+ if (typeof window !== "undefined") claimStore(ssrCookies);
321
+ const resolveClientSource = useCallback(() => ({
322
+ store: claimStore(ssrCookies),
323
+ pipeline
324
+ }), [ssrCookies]);
325
+ return /* @__PURE__ */ jsx(KheopskitSourceProvider, {
326
+ config,
327
+ ssrCookies,
328
+ resolveClientSource,
329
+ children
330
+ });
331
+ };
149
332
  Provider.displayName = "KheopskitProvider";
150
333
  return {
151
334
  KheopskitProvider: Provider,
335
+ /** The state stream the provider subscribes to, shared with code outside React. */
336
+ kheopskit$,
337
+ /** The store `kheopskit$` reads the cache from and persists into. */
338
+ store: options.store ?? deferredStore(claimStore),
152
339
  /** Current state, typed to the bound platform tuple. */
153
340
  useWallets: () => useWallets(),
154
341
  /** Current accounts, typed to the bound platform tuple. */
155
- useAccounts: () => useWallets().accounts
342
+ useAccounts: () => useWallets().accounts,
343
+ /** The wallet with this id, typed to the bound platform tuple. */
344
+ useWallet: (walletId) => useWallet(walletId),
345
+ /** The account with this id, typed to the bound platform tuple. */
346
+ useAccount: (accountId) => useAccount(accountId)
156
347
  };
157
348
  };
158
349
  //#endregion
350
+ //#region src/KheopskitProvider.tsx
351
+ const KheopskitProvider = ({ children, config, ssrCookies, store }) => {
352
+ const lastConfigRef = useRef(config);
353
+ const hasMountedRef = useRef(false);
354
+ useEffect(() => {
355
+ if (hasMountedRef.current && lastConfigRef.current !== config && (typeof process === "undefined" || process.env?.NODE_ENV !== "production")) console.warn("[kheopskit] KheopskitProvider received a new `config` reference; this recreates the store and re-subscribes on every render. Pass a referentially stable config (module scope, useMemo, or createKheopskit()).");
356
+ hasMountedRef.current = true;
357
+ lastConfigRef.current = config;
358
+ }, [config]);
359
+ const resolveClientSource = useCallback((resolvedConfig) => {
360
+ const sourceStore = store ?? createKheopskitStore({
361
+ ssrCookies,
362
+ storageKey: resolvedConfig.storageKey
363
+ });
364
+ return {
365
+ store: sourceStore,
366
+ pipeline: createLivePipeline(getKheopskit$(resolvedConfig, {
367
+ ssrCookies,
368
+ store: sourceStore
369
+ }))
370
+ };
371
+ }, [ssrCookies, store]);
372
+ return /* @__PURE__ */ jsx(KheopskitSourceProvider, {
373
+ config,
374
+ ssrCookies,
375
+ resolveClientSource,
376
+ children
377
+ });
378
+ };
379
+ //#endregion
159
380
  //#region src/useAccounts.ts
160
381
  /**
161
382
  * Convenience hook returning just the accounts from kheopskit state. Pass the
@@ -165,6 +386,59 @@ const createKheopskit = (config) => {
165
386
  */
166
387
  const useAccounts = () => useWallets().accounts;
167
388
  //#endregion
168
- export { KheopskitProvider, createKheopskit, useAccounts, useWallets };
389
+ //#region src/useConnect.ts
390
+ const useIsomorphicLayoutEffect = typeof window === "undefined" ? useEffect : useLayoutEffect;
391
+ const afterThisCommitsLayoutEffects = () => Promise.resolve();
392
+ const createWalletActions = (store, walletId) => {
393
+ let scope = new AbortController();
394
+ const wallet = walletActions(store, walletId);
395
+ return {
396
+ connect: async () => {
397
+ if (scope.signal.aborted) await afterThisCommitsLayoutEffects();
398
+ const { signal } = scope;
399
+ if (signal.aborted) throw new KheopskitError("ABORTED", `connect of wallet ${walletId} started after useConnect unmounted or switched wallet`, { walletId });
400
+ try {
401
+ await wallet.connect({ signal });
402
+ } catch (error) {
403
+ if (!(signal.aborted && error instanceof KheopskitError && error.code === "ABORTED")) throw error;
404
+ }
405
+ },
406
+ disconnect: wallet.disconnect,
407
+ renew: () => {
408
+ if (scope.signal.aborted) scope = new AbortController();
409
+ },
410
+ abort: () => scope.abort()
411
+ };
412
+ };
413
+ /**
414
+ * Connect and disconnect actions for one wallet, with its status and error.
415
+ * `connect` and `disconnect` keep their identity while `walletId` is the same,
416
+ * so `useEffect(() => { connect() }, [connect])` connects on mount and after
417
+ * every `<Activity>` reveal.
418
+ *
419
+ * @example
420
+ * ```tsx
421
+ * const ConnectButton = ({ walletId }: { walletId: WalletId }) => {
422
+ * const { connect, disconnect, status } = useConnect(walletId);
423
+ * if (status === "connected") return <button onClick={disconnect}>Disconnect</button>;
424
+ * return <button disabled={status === "connecting"} onClick={connect}>Connect</button>;
425
+ * };
426
+ * ```
427
+ */
428
+ const useConnect = (walletId) => {
429
+ const store = useKheopskitExternalStore("useConnect");
430
+ const wallet = useWallet(walletId);
431
+ const actions = useMemo(() => createWalletActions(store, walletId), [store, walletId]);
432
+ useIsomorphicLayoutEffect(() => actions.renew(), [actions]);
433
+ useEffect(() => () => actions.abort(), [actions]);
434
+ return {
435
+ connect: actions.connect,
436
+ disconnect: actions.disconnect,
437
+ status: wallet?.status,
438
+ error: wallet?.error
439
+ };
440
+ };
441
+ //#endregion
442
+ export { KheopskitProvider, createKheopskit, useAccount, useAccounts, useConnect, useWallet, useWallets };
169
443
 
170
444
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","names":[],"sources":["../src/context.ts","../src/createExternalStore.ts","../src/KheopskitProvider.tsx","../src/useWallets.ts","../src/createKheopskit.tsx","../src/useAccounts.ts"],"sourcesContent":["import type { KheopskitState } from \"@kheopskit/core\";\nimport { createContext } from \"react\";\n\nexport const KheopskitContext = createContext<{\n\tstate: KheopskitState;\n} | null>(null);\n","import type { Observable, Subscription } from \"rxjs\";\n\nexport const createExternalStore = <T>(\n\tobservable$: Observable<T>,\n\tinitialValue: T,\n\tserverValue?: T,\n) => {\n\t// Use null as sentinel to indicate we haven't received first emission yet\n\tlet latestValue: T | null = null;\n\tlet subscription: Subscription | null = null;\n\tlet subscriberCount = 0;\n\tconst listeners = new Set<(value: T) => void>();\n\n\tconst ensureSubscription = () => {\n\t\tif (!subscription || subscription.closed) {\n\t\t\tsubscription = observable$.subscribe((value) => {\n\t\t\t\tlatestValue = value;\n\t\t\t\tfor (const listener of listeners) {\n\t\t\t\t\tlistener(value);\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t};\n\n\t// The subscription is created lazily by subscribe() (which React calls from a\n\t// committed passive effect), never during render. React may render a tree and\n\t// throw it away without committing — StrictMode double-invokes the initial\n\t// render, and concurrent/Suspense can discard renders — so subscribing eagerly\n\t// here (createExternalStore runs inside the Provider's render-phase useMemo) would leak\n\t// the discarded store's observable subscription. Until the first emission,\n\t// getSnapshot falls back to initialValue.\n\tconst getSnapshot = () => latestValue ?? initialValue;\n\n\t/**\n\t * Returns the server-side snapshot for SSR hydration.\n\t * This prevents hydration mismatches by providing a consistent\n\t * value during server rendering. Must return the same value as\n\t * what the server rendered.\n\t */\n\tconst getServerSnapshot = () => serverValue ?? initialValue;\n\n\tconst subscribe = (callback: (value: T) => void) => {\n\t\tsubscriberCount++;\n\t\t// Subscribe to the observable BEFORE registering this listener, so a\n\t\t// synchronous replay (BehaviorSubject / shareReplay) updates latestValue\n\t\t// without double-invoking this callback — the current value is emitted once,\n\t\t// explicitly, just below.\n\t\tensureSubscription();\n\t\tlisteners.add(callback);\n\n\t\t// Immediately emit current value (BehaviorSubject semantics)\n\t\tcallback(getSnapshot());\n\n\t\treturn () => {\n\t\t\tsubscriberCount--;\n\t\t\tlisteners.delete(callback);\n\t\t\t// Don't close the observable subscription on unsubscribe\n\t\t\t// Let destroy() handle that when the store is truly being disposed\n\t\t};\n\t};\n\n\tconst destroy = () => {\n\t\t// Only unsubscribe if no one is listening\n\t\t// React StrictMode may call destroy and then immediately resubscribe\n\t\tif (subscriberCount === 0 && subscription) {\n\t\t\tsubscription.unsubscribe();\n\t\t\tsubscription = null;\n\t\t}\n\t};\n\n\treturn {\n\t\tgetSnapshot,\n\t\tgetServerSnapshot,\n\t\tsubscribe,\n\t\tdestroy,\n\t};\n};\n","import {\n\tcreateKheopskitStore,\n\tgetHydratedSnapshot,\n\tgetKheopskit$,\n\ttype KheopskitConfig,\n\ttype KheopskitState,\n\tresolveConfig,\n} from \"@kheopskit/core\";\nimport {\n\ttype FC,\n\ttype PropsWithChildren,\n\tuseEffect,\n\tuseMemo,\n\tuseRef,\n\tuseSyncExternalStore,\n} from \"react\";\nimport { KheopskitContext } from \"./context\";\nimport { createExternalStore } from \"./createExternalStore\";\n\nexport type KheopskitProviderProps = PropsWithChildren & {\n\t/**\n\t * Kheopskit configuration.\n\t *\n\t * @remarks\n\t * Must be a **referentially stable** value — define it once (module scope, a\n\t * `useMemo`, or via {@link createKheopskit}) and pass the same reference. A\n\t * new object literal on every render (`config={{ platforms: [...] }}` inline)\n\t * recreates the underlying store and re-subscribes each render.\n\t */\n\tconfig?: Partial<KheopskitConfig>;\n\t/**\n\t * Cookie string for SSR hydration.\n\t * Pass the request cookie header (e.g., from Next.js headers or TanStack Start)\n\t * to hydrate wallet state on the server.\n\t *\n\t * @remarks\n\t * This value should be stable per render to avoid unnecessary store recreation.\n\t * Compute it once in your server component or layout and pass it down.\n\t *\n\t * @example\n\t * ```tsx\n\t * // Next.js App Router\n\t * const cookieStore = await cookies();\n\t * const ssrCookies = cookieStore.getAll().map(c => `${c.name}=${c.value}`).join('; ');\n\t * return <Providers ssrCookies={ssrCookies}>{children}</Providers>\n\t * ```\n\t */\n\tssrCookies?: string;\n};\n\nexport const KheopskitProvider: FC<KheopskitProviderProps> = ({\n\tchildren,\n\tconfig,\n\tssrCookies,\n}) => {\n\tconst resolvedConfig = useMemo(() => resolveConfig(config), [config]);\n\n\t// Dev-only: warn if the `config` prop reference changes between renders. A new\n\t// object each render recreates the store and re-subscribes the whole pipeline\n\t// (re-hydrating, dropping live connection state) on every render. `config` must\n\t// be referentially stable — define it at module scope, memoize it, or use\n\t// createKheopskit() (which passes a stable reference for you).\n\tconst lastConfigRef = useRef(config);\n\tconst hasMountedRef = useRef(false);\n\tuseEffect(() => {\n\t\tif (\n\t\t\thasMountedRef.current &&\n\t\t\tlastConfigRef.current !== config &&\n\t\t\t(typeof process === \"undefined\" || process.env?.NODE_ENV !== \"production\")\n\t\t) {\n\t\t\tconsole.warn(\n\t\t\t\t\"[kheopskit] KheopskitProvider received a new `config` reference; this \" +\n\t\t\t\t\t\"recreates the store and re-subscribes on every render. Pass a \" +\n\t\t\t\t\t\"referentially stable config (module scope, useMemo, or createKheopskit()).\",\n\t\t\t);\n\t\t}\n\t\thasMountedRef.current = true;\n\t\tlastConfigRef.current = config;\n\t}, [config]);\n\n\t// Create a single store for both reading cached state and powering the observable\n\tconst kheopskitStore = useMemo(\n\t\t() =>\n\t\t\tcreateKheopskitStore({\n\t\t\t\tssrCookies,\n\t\t\t\tstorageKey: resolvedConfig.storageKey,\n\t\t\t}),\n\t\t[ssrCookies, resolvedConfig.storageKey],\n\t);\n\n\t// Read cached state from the store for SSR hydration.\n\t// Icons stay OFF: this snapshot must match the server-rendered markup, and the\n\t// server never sees the localStorage icon cache (see GetHydratedSnapshotOptions).\n\tconst serverValue = useMemo<KheopskitState>(() => {\n\t\tif (ssrCookies === undefined) {\n\t\t\treturn {\n\t\t\t\twallets: [],\n\t\t\t\taccounts: [],\n\t\t\t\tconfig: resolvedConfig,\n\t\t\t\tisHydrating: true,\n\t\t\t};\n\t\t}\n\t\treturn {\n\t\t\t...getHydratedSnapshot(kheopskitStore, resolvedConfig.platforms),\n\t\t\tconfig: resolvedConfig,\n\t\t\tisHydrating: true,\n\t\t};\n\t}, [ssrCookies, kheopskitStore, resolvedConfig]);\n\n\t// Client-only initial snapshot, read straight from the client cache so a hard\n\t// reload paints the cached wallet/account list on the very first frame instead\n\t// of flashing empty until the live observable produces its first emission —\n\t// which can be asynchronous (e.g. WalletConnect's AppKit is loaded via dynamic\n\t// import, so the underlying combineLatest can't emit synchronously).\n\t//\n\t// We can't derive this from `serverValue`: without SSR cookies that stays empty\n\t// (to keep the server/client hydration markup identical), so the SPA case would\n\t// otherwise render nothing. This snapshot is only ever read on the client via\n\t// getSnapshot, so reading the cache here is safe — and getCachedIcon returns \"\"\n\t// on the server, making the icon enrichment a no-op there.\n\tconst initialValue = useMemo<KheopskitState>(() => {\n\t\treturn {\n\t\t\t...getHydratedSnapshot(kheopskitStore, resolvedConfig.platforms, {\n\t\t\t\ticons: true,\n\t\t\t}),\n\t\t\tconfig: resolvedConfig,\n\t\t\tisHydrating: true,\n\t\t};\n\t}, [kheopskitStore, resolvedConfig]);\n\n\tconst store = useMemo(\n\t\t() =>\n\t\t\tcreateExternalStore(\n\t\t\t\tgetKheopskit$(config, { ssrCookies, store: kheopskitStore }),\n\t\t\t\tinitialValue,\n\t\t\t\tserverValue,\n\t\t\t),\n\t\t[config, ssrCookies, kheopskitStore, initialValue, serverValue],\n\t);\n\n\t// Cleanup store subscriptions when store changes or component unmounts\n\tuseEffect(() => {\n\t\treturn () => store.destroy();\n\t}, [store]);\n\n\tconst state = useSyncExternalStore(\n\t\tstore.subscribe,\n\t\tstore.getSnapshot,\n\t\tstore.getServerSnapshot,\n\t);\n\n\tconst value = useMemo(() => ({ state }), [state]);\n\n\treturn (\n\t\t<KheopskitContext.Provider value={value}>\n\t\t\t{children}\n\t\t</KheopskitContext.Provider>\n\t);\n};\n","import type { KheopskitPlatform, KheopskitState } from \"@kheopskit/core\";\nimport { useContext } from \"react\";\nimport { KheopskitContext } from \"./context\";\n\n/**\n * Returns the current kheopskit state (wallets, accounts, config, isHydrating).\n *\n * Pass the platform tuple as a type argument to recover SDK-precise account and\n * wallet types — `useWallets<typeof platforms>()`. React contexts can't be\n * generic, so without the argument the state is typed with the base\n * (SDK-free) wallet/account shapes.\n */\nexport const useWallets = <\n\tP extends readonly KheopskitPlatform[] = readonly KheopskitPlatform[],\n>(): KheopskitState<P> => {\n\tconst ctx = useContext(KheopskitContext);\n\n\tif (!ctx)\n\t\tthrow new Error(\"useWallets can't be used without a KheopskitProvider\");\n\n\treturn ctx.state as unknown as KheopskitState<P>;\n};\n","import type { KheopskitConfig, KheopskitPlatform } from \"@kheopskit/core\";\nimport type { FC, PropsWithChildren } from \"react\";\nimport { KheopskitProvider } from \"./KheopskitProvider\";\nimport { useWallets } from \"./useWallets\";\n\nexport type CreateKheopskitConfig<P extends readonly KheopskitPlatform[]> =\n\tOmit<Partial<KheopskitConfig<P>>, \"platforms\"> & {\n\t\t/** Platform plugins, e.g. `[polkadot(), solana()]`. Required. */\n\t\tplatforms: P;\n\t};\n\n/**\n * Binds a platform tuple once and returns a `KheopskitProvider` plus hooks\n * (`useWallets`, `useAccounts`) already typed to those platforms — so you don't\n * repeat `useWallets<typeof platforms>()` in every component.\n *\n * @example\n * ```tsx\n * // kheopskit.ts\n * export const { KheopskitProvider, useWallets, useAccounts } = createKheopskit({\n * platforms: [polkadot(), ethereum(), solana()],\n * });\n *\n * // anywhere\n * const { accounts } = useWallets(); // accounts are platform-precise, no generic\n * ```\n */\nexport const createKheopskit = <\n\tconst P extends readonly [KheopskitPlatform, ...KheopskitPlatform[]],\n>(\n\tconfig: CreateKheopskitConfig<P>,\n) => {\n\tconst Provider: FC<PropsWithChildren<{ ssrCookies?: string }>> = ({\n\t\tchildren,\n\t\tssrCookies,\n\t}) => (\n\t\t<KheopskitProvider config={config} ssrCookies={ssrCookies}>\n\t\t\t{children}\n\t\t</KheopskitProvider>\n\t);\n\tProvider.displayName = \"KheopskitProvider\";\n\n\treturn {\n\t\tKheopskitProvider: Provider,\n\t\t/** Current state, typed to the bound platform tuple. */\n\t\tuseWallets: () => useWallets<P>(),\n\t\t/** Current accounts, typed to the bound platform tuple. */\n\t\tuseAccounts: () => useWallets<P>().accounts,\n\t};\n};\n","import type { KheopskitPlatform } from \"@kheopskit/core\";\nimport { useWallets } from \"./useWallets\";\n\n/**\n * Convenience hook returning just the accounts from kheopskit state. Pass the\n * platform tuple as a type argument to recover SDK-precise account types —\n * `useAccounts<typeof platforms>()` — or use the pre-typed hook from\n * {@link createKheopskit}.\n */\nexport const useAccounts = <\n\tP extends readonly KheopskitPlatform[] = readonly KheopskitPlatform[],\n>() => useWallets<P>().accounts;\n"],"mappings":";;;;;AAGA,MAAa,mBAAmB,cAEtB,IAAI;;;ACHd,MAAa,uBACZ,aACA,cACA,gBACI;CAEJ,IAAI,cAAwB;CAC5B,IAAI,eAAoC;CACxC,IAAI,kBAAkB;CACtB,MAAM,4BAAY,IAAI,IAAwB;CAE9C,MAAM,2BAA2B;EAChC,IAAI,CAAC,gBAAgB,aAAa,QACjC,eAAe,YAAY,WAAW,UAAU;GAC/C,cAAc;GACd,KAAK,MAAM,YAAY,WACtB,SAAS,KAAK;EAEhB,CAAC;CAEH;CASA,MAAM,oBAAoB,eAAe;;;;;;;CAQzC,MAAM,0BAA0B,eAAe;CAE/C,MAAM,aAAa,aAAiC;EACnD;EAKA,mBAAmB;EACnB,UAAU,IAAI,QAAQ;EAGtB,SAAS,YAAY,CAAC;EAEtB,aAAa;GACZ;GACA,UAAU,OAAO,QAAQ;EAG1B;CACD;CAEA,MAA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,qBACb,MAAM,WACN,MAAM,aACN,MAAM,iBACP;CAEA,MAAM,QAAQ,eAAe,EAAE,MAAM,IAAI,CAAC,KAAK,CAAC;CAEhD,OACC,oBAAC,iBAAiB,UAAlB;EAAkC;EAChC;CACyB,CAAA;AAE7B;;;;;;;;;;;AClJA,MAAa,mBAEa;CACzB,MAAM,MAAM,WAAW,gBAAgB;CAEvC,IAAI,CAAC,KACJ,MAAM,IAAI,MAAM,sDAAsD;CAEvE,OAAO,IAAI;AACZ;;;;;;;;;;;;;;;;;;;ACMA,MAAa,mBAGZ,WACI;CACJ,MAAM,YAA4D,EACjE,UACA,iBAEA,oBAAC,mBAAD;EAA2B;EAAoB;EAC7C;CACiB,CAAA;CAEpB,SAAS,cAAc;CAEvB,OAAO;EACN,mBAAmB;;EAEnB,kBAAkB,WAAc;;EAEhC,mBAAmB,WAAc,CAAC,CAAC;CACpC;AACD;;;;;;;;;ACxCA,MAAa,oBAEN,WAAc,CAAC,CAAC"}
1
+ {"version":3,"file":"index.mjs","names":["afterThisCommitsLayoutEffects","useIsomorphicLayoutEffect"],"sources":["../src/context.ts","../src/createExternalStore.ts","../src/liveActions.ts","../src/KheopskitSourceProvider.tsx","../src/livePipeline.ts","../src/useStateItem.ts","../src/useAccount.ts","../src/useWallet.ts","../src/useWallets.ts","../src/createKheopskit.tsx","../src/KheopskitProvider.tsx","../src/useAccounts.ts","../src/useConnect.ts"],"sourcesContent":["import type { KheopskitState } from \"@kheopskit/core\";\nimport { createContext, useContext } from \"react\";\nimport type { Liveness } from \"./livePipeline\";\n\nexport type KheopskitExternalStore = {\n\tsubscribe: (onChange: () => void) => () => void;\n\tgetSnapshot: () => KheopskitState;\n\tgetServerSnapshot: () => KheopskitState;\n\twhenLive: (signal?: AbortSignal) => Promise<Liveness<KheopskitState>>;\n};\n\nexport const KheopskitContext = createContext<KheopskitExternalStore | null>(\n\tnull,\n);\n\nexport const useKheopskitExternalStore = (hookName: string) => {\n\tconst store = useContext(KheopskitContext);\n\tif (!store)\n\t\tthrow new Error(`${hookName} can't be used without a KheopskitProvider`);\n\treturn store;\n};\n","import type { Subscription } from \"rxjs\";\nimport type { Liveness, LivePipeline } from \"./livePipeline\";\n\nexport type ExternalStoreSource<T> = {\n\tpipeline: LivePipeline<T>;\n\tinitialValue: T;\n};\n\n// React runs every layout setup of a commit synchronously, so once this\n// microtask runs a mounted provider has taken its hold on the pipeline, and a\n// release queued by a hide in this task has landed.\nconst afterThisCommitsLayoutEffects = () => Promise.resolve();\n\nexport const createExternalStore = <T>(\n\tresolveClientSource: () => ExternalStoreSource<T>,\n\tserverValue: T,\n) => {\n\tlet source: ExternalStoreSource<T> | undefined;\n\tlet latestValue: T | undefined;\n\tlet subscription: Subscription | undefined;\n\tconst listeners = new Set<(value: T) => void>();\n\n\tconst getSource = () => {\n\t\tsource ??= resolveClientSource();\n\t\treturn source;\n\t};\n\n\tconst getSnapshot = () => latestValue ?? getSource().initialValue;\n\n\tconst getServerSnapshot = () => serverValue;\n\n\tconst releaseWhenUnobserved = () => {\n\t\tif (listeners.size) return;\n\t\tsubscription?.unsubscribe();\n\t\tsubscription = undefined;\n\t};\n\n\tconst subscribe = (listener: (value: T) => void) => {\n\t\tif (!subscription || subscription.closed) {\n\t\t\tsubscription = getSource().pipeline.observable$.subscribe((value) => {\n\t\t\t\tlatestValue = value;\n\t\t\t\tfor (const notify of listeners) notify(value);\n\t\t\t});\n\t\t}\n\t\tlisteners.add(listener);\n\t\tlistener(getSnapshot());\n\n\t\treturn () => {\n\t\t\tlisteners.delete(listener);\n\t\t\t// StrictMode and a changed `subscribe` unsubscribe and resubscribe in\n\t\t\t// the same task; releasing at once would restart the pipeline between.\n\t\t\tqueueMicrotask(releaseWhenUnobserved);\n\t\t};\n\t};\n\n\t/** The shared pipeline's liveness once this commit's layout effects ran. */\n\tconst whenLive = async (signal?: AbortSignal): Promise<Liveness<T>> => {\n\t\tawait afterThisCommitsLayoutEffects();\n\t\treturn getSource().pipeline.whenLive(signal);\n\t};\n\n\treturn { getSnapshot, getServerSnapshot, subscribe, whenLive };\n};\n","import {\n\ttype ConnectOptions,\n\tKheopskitError,\n\ttype KheopskitState,\n\ttype WalletId,\n} from \"@kheopskit/core\";\nimport type { KheopskitExternalStore } from \"./context\";\nimport type { PipelineEnd } from \"./livePipeline\";\n\ntype Wallet = KheopskitState[\"wallets\"][number];\n\nconst didNotRun: Record<PipelineEnd, string> = {\n\taborted: \"was aborted\",\n\tunheld:\n\t\t\"was called while nothing holds the pipeline (no KheopskitProvider of this instance is mounted and visible, and nothing subscribes its kheopskit$)\",\n\terrored: \"did not run because the pipeline stopped with an error\",\n\tcompleted: \"did not run because the pipeline completed\",\n};\n\nconst abortedError = (\n\twalletId: WalletId,\n\toperation: \"connect\" | \"disconnect\",\n\tend: PipelineEnd,\n) =>\n\tnew KheopskitError(\n\t\t\"ABORTED\",\n\t\t`${operation} of wallet ${walletId} ${didNotRun[end]}`,\n\t\t{ walletId },\n\t);\n\n/**\n * `connect` and `disconnect` for one wallet id that act on the instance's\n * pipeline at call time: they wait for the restarted pipeline's first emission\n * after an `<Activity>` reveal and reject `ABORTED` while nothing holds it.\n */\nexport const walletActions = (\n\tstore: Pick<KheopskitExternalStore, \"whenLive\">,\n\twalletId: WalletId,\n) => {\n\tconst liveWallet = async (\n\t\toperation: \"connect\" | \"disconnect\",\n\t\tsignal?: AbortSignal,\n\t) => {\n\t\tconst liveness = await store.whenLive(signal);\n\t\tif (liveness.end) throw abortedError(walletId, operation, liveness.end);\n\t\tconst wallet = liveness.state.wallets.find(\n\t\t\t(candidate) => candidate.id === walletId,\n\t\t);\n\t\tif (!wallet) throw new Error(`[kheopskit] no wallet ${walletId}`);\n\t\treturn wallet;\n\t};\n\treturn {\n\t\tconnect: async (options?: ConnectOptions) =>\n\t\t\t(await liveWallet(\"connect\", options?.signal)).connect(options),\n\t\tdisconnect: async () => (await liveWallet(\"disconnect\")).disconnect(),\n\t};\n};\n\nexport const withLiveActions = (\n\tstore: KheopskitExternalStore,\n): KheopskitExternalStore => {\n\tconst presented = new WeakMap<KheopskitState, KheopskitState>();\n\tconst present = (state: KheopskitState) => {\n\t\tlet live = presented.get(state);\n\t\tif (!live) {\n\t\t\tlive = {\n\t\t\t\t...state,\n\t\t\t\twallets: state.wallets.map(\n\t\t\t\t\t(wallet): Wallet => ({\n\t\t\t\t\t\t...wallet,\n\t\t\t\t\t\t...walletActions(store, wallet.id),\n\t\t\t\t\t}),\n\t\t\t\t),\n\t\t\t};\n\t\t\tpresented.set(state, live);\n\t\t}\n\t\treturn live;\n\t};\n\treturn {\n\t\t...store,\n\t\tgetSnapshot: () => present(store.getSnapshot()),\n\t\tgetServerSnapshot: () => present(store.getServerSnapshot()),\n\t};\n};\n","import {\n\tcreateKheopskitStore,\n\tgetHydratedSnapshot,\n\ttype HydratedSnapshot,\n\ttype KheopskitConfig,\n\ttype KheopskitState,\n\ttype KheopskitStore,\n\tresolveConfig,\n} from \"@kheopskit/core\";\nimport {\n\ttype FC,\n\ttype PropsWithChildren,\n\tuseEffect,\n\tuseLayoutEffect,\n\tuseMemo,\n} from \"react\";\nimport { KheopskitContext } from \"./context\";\nimport { createExternalStore } from \"./createExternalStore\";\nimport { withLiveActions } from \"./liveActions\";\nimport type { LivePipeline } from \"./livePipeline\";\n\ntype KheopskitSource = {\n\tstore: KheopskitStore;\n\tpipeline: LivePipeline<KheopskitState>;\n};\n\ntype KheopskitSourceProviderProps = PropsWithChildren<{\n\tconfig: Partial<KheopskitConfig> | undefined;\n\tssrCookies: string | undefined;\n\tresolveClientSource: (config: KheopskitConfig) => KheopskitSource;\n}>;\n\nconst keepPipelineRunning = () => {};\n\n// A layout effect, so that a child's layout effect calling an action on reveal\n// finds the pipeline held again one microtask later (see createExternalStore).\nconst useIsomorphicLayoutEffect =\n\ttypeof window === \"undefined\" ? useEffect : useLayoutEffect;\n\nconst hydrating = (\n\tconfig: KheopskitConfig,\n\tsnapshot: HydratedSnapshot,\n): KheopskitState => ({\n\t...snapshot,\n\tconfig,\n\tisHydrating: true,\n\tisDiscovering: true,\n});\n\nconst serverSnapshot = (\n\tconfig: KheopskitConfig,\n\tssrCookies: string | undefined,\n): KheopskitState =>\n\thydrating(\n\t\tconfig,\n\t\tssrCookies === undefined\n\t\t\t? { wallets: [], accounts: [] }\n\t\t\t: getHydratedSnapshot(\n\t\t\t\t\tcreateKheopskitStore({ ssrCookies, storageKey: config.storageKey }),\n\t\t\t\t\tconfig,\n\t\t\t\t\t{ icons: false },\n\t\t\t\t),\n\t);\n\nexport const KheopskitSourceProvider: FC<KheopskitSourceProviderProps> = ({\n\tchildren,\n\tconfig,\n\tssrCookies,\n\tresolveClientSource,\n}) => {\n\tconst resolvedConfig = useMemo(() => resolveConfig(config), [config]);\n\n\tconst externalStore = useMemo(\n\t\t() =>\n\t\t\twithLiveActions(\n\t\t\t\tcreateExternalStore(\n\t\t\t\t\t() => {\n\t\t\t\t\t\tconst { store, pipeline } = resolveClientSource(resolvedConfig);\n\t\t\t\t\t\treturn {\n\t\t\t\t\t\t\tpipeline,\n\t\t\t\t\t\t\tinitialValue: hydrating(\n\t\t\t\t\t\t\t\tresolvedConfig,\n\t\t\t\t\t\t\t\tgetHydratedSnapshot(store, resolvedConfig, { icons: true }),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t};\n\t\t\t\t\t},\n\t\t\t\t\tserverSnapshot(resolvedConfig, ssrCookies),\n\t\t\t\t),\n\t\t\t),\n\t\t[resolvedConfig, ssrCookies, resolveClientSource],\n\t);\n\n\tuseIsomorphicLayoutEffect(\n\t\t() => externalStore.subscribe(keepPipelineRunning),\n\t\t[externalStore],\n\t);\n\n\treturn (\n\t\t<KheopskitContext.Provider value={externalStore}>\n\t\t\t{children}\n\t\t</KheopskitContext.Provider>\n\t);\n};\n","import { Observable } from \"rxjs\";\n\nexport type PipelineEnd = \"aborted\" | \"unheld\" | \"errored\" | \"completed\";\n\n/** The running pipeline's state, or why it cannot serve an action. */\nexport type Liveness<T> = { state: T; end?: undefined } | { end: PipelineEnd };\n\nexport type LivePipeline<T> = {\n\t/** Subscribing holds the pipeline; it runs while at least one holder stays. */\n\tobservable$: Observable<T>;\n\t/**\n\t * The current run's state: its latest value, or its first emission once it\n\t * arrives. Ends `unheld` while nothing holds the pipeline, without starting\n\t * it, `errored` or `completed` once the run ended that way, and `aborted`\n\t * when `signal` fires first.\n\t */\n\twhenLive: (signal?: AbortSignal) => Promise<Liveness<T>>;\n};\n\nexport const createLivePipeline = <T>(\n\tsource$: Observable<T>,\n): LivePipeline<T> => {\n\tlet holders = 0;\n\tlet run = 0;\n\tlet emittedRun = 0;\n\tlet latestValue: T | undefined;\n\tlet ended: PipelineEnd | undefined;\n\tconst firstEmissionWaiters = new Set<(liveness: Liveness<T>) => void>();\n\n\tconst settleFirstEmission = (liveness: Liveness<T>) => {\n\t\tfor (const waiter of firstEmissionWaiters) waiter(liveness);\n\t};\n\n\tconst observable$ = new Observable<T>((subscriber) => {\n\t\tif (holders++ === 0) {\n\t\t\trun++;\n\t\t\tended = undefined;\n\t\t}\n\t\tconst thisRun = run;\n\t\tconst subscription = source$.subscribe({\n\t\t\tnext: (value) => {\n\t\t\t\tlatestValue = value;\n\t\t\t\temittedRun = thisRun;\n\t\t\t\tsettleFirstEmission({ state: value });\n\t\t\t\tsubscriber.next(value);\n\t\t\t},\n\t\t\terror: (error) => {\n\t\t\t\tended = \"errored\";\n\t\t\t\tsubscriber.error(error);\n\t\t\t},\n\t\t\tcomplete: () => {\n\t\t\t\tended = \"completed\";\n\t\t\t\tsubscriber.complete();\n\t\t\t},\n\t\t});\n\t\treturn () => {\n\t\t\tsubscription.unsubscribe();\n\t\t\tif (--holders === 0) settleFirstEmission({ end: ended ?? \"unheld\" });\n\t\t};\n\t});\n\n\tconst whenLive = async (signal?: AbortSignal): Promise<Liveness<T>> => {\n\t\tif (signal?.aborted) return { end: \"aborted\" };\n\t\tif (ended) return { end: ended };\n\t\tif (holders === 0) return { end: \"unheld\" };\n\t\tif (emittedRun === run) return { state: latestValue as T };\n\t\treturn new Promise((resolve) => {\n\t\t\tconst settle = (liveness: Liveness<T>) => {\n\t\t\t\tfirstEmissionWaiters.delete(settle);\n\t\t\t\tsignal?.removeEventListener(\"abort\", onAbort);\n\t\t\t\tresolve(liveness);\n\t\t\t};\n\t\t\tconst onAbort = () => settle({ end: \"aborted\" });\n\t\t\tsignal?.addEventListener(\"abort\", onAbort, { once: true });\n\t\t\tfirstEmissionWaiters.add(settle);\n\t\t});\n\t};\n\n\treturn { observable$, whenLive };\n};\n","import type { KheopskitState } from \"@kheopskit/core\";\nimport { useMemo, useSyncExternalStore } from \"react\";\nimport { useKheopskitExternalStore } from \"./context\";\n\nconst isSameItemIgnoringClosures = (a: object, b: object) => {\n\tconst previous = a as Record<string, unknown>;\n\tconst next = b as Record<string, unknown>;\n\tconst keys = Object.keys(previous);\n\treturn (\n\t\tkeys.length === Object.keys(next).length &&\n\t\tkeys.every(\n\t\t\t(key) =>\n\t\t\t\tObject.hasOwn(next, key) &&\n\t\t\t\t(Object.is(previous[key], next[key]) ||\n\t\t\t\t\t(typeof previous[key] === \"function\" &&\n\t\t\t\t\t\ttypeof next[key] === \"function\")),\n\t\t)\n\t);\n};\n\nexport const useStateItem = <K, T extends object>(\n\thookName: string,\n\tkey: K,\n\tselect: (state: KheopskitState, key: K) => T | undefined,\n): T | undefined => {\n\tconst store = useKheopskitExternalStore(hookName);\n\tconst snapshots = useMemo(() => {\n\t\tlet cached: T | undefined;\n\t\treturn {\n\t\t\tgetSnapshot: () => {\n\t\t\t\tconst item = select(store.getSnapshot(), key);\n\t\t\t\tconst reusable =\n\t\t\t\t\tcached !== undefined &&\n\t\t\t\t\titem !== undefined &&\n\t\t\t\t\tisSameItemIgnoringClosures(cached, item);\n\t\t\t\tif (!reusable) cached = item;\n\t\t\t\treturn cached;\n\t\t\t},\n\t\t\tgetServerSnapshot: () => select(store.getServerSnapshot(), key),\n\t\t};\n\t}, [store, key, select]);\n\treturn useSyncExternalStore(\n\t\tstore.subscribe,\n\t\tsnapshots.getSnapshot,\n\t\tsnapshots.getServerSnapshot,\n\t);\n};\n","import type {\n\tKheopskitPlatform,\n\tKheopskitState,\n\tWalletAccountId,\n} from \"@kheopskit/core\";\nimport { useStateItem } from \"./useStateItem\";\n\nconst selectAccount = (state: KheopskitState, accountId: WalletAccountId) =>\n\tstate.accounts.find((account) => account.id === accountId);\n\n/**\n * Returns the account with this id, or `undefined` while the state lists none.\n * Re-renders only when that account changes: its name, its placeholder flag,\n * a platform field such as an Ethereum `chainId`, or an SDK handle.\n *\n * Pass the platform tuple as a type argument for the SDK-precise account type,\n * or use the pre-typed hook from {@link createKheopskit}.\n */\nexport const useAccount = <\n\tP extends readonly KheopskitPlatform[] = readonly KheopskitPlatform[],\n>(\n\taccountId: WalletAccountId,\n) =>\n\tuseStateItem(\"useAccount\", accountId, selectAccount) as\n\t\t| KheopskitState<P>[\"accounts\"][number]\n\t\t| undefined;\n","import type {\n\tKheopskitPlatform,\n\tKheopskitState,\n\tWalletId,\n} from \"@kheopskit/core\";\nimport { useStateItem } from \"./useStateItem\";\n\nconst selectWallet = (state: KheopskitState, walletId: WalletId) =>\n\tstate.wallets.find((wallet) => wallet.id === walletId);\n\n/**\n * Returns the wallet with this id, or `undefined` while the state lists none.\n * Re-renders only when that wallet changes: its status, connection, error,\n * name or any other field. Its `connect` and `disconnect` act on the instance's\n * pipeline when they are called, also right after an `<Activity>` reveal\n * restarts it and while another provider or a `kheopskit$` subscriber holds\n * it, and reject `ABORTED` while nothing holds it.\n *\n * Pass the platform tuple as a type argument for the SDK-precise wallet type,\n * or use the pre-typed hook from {@link createKheopskit}.\n */\nexport const useWallet = <\n\tP extends readonly KheopskitPlatform[] = readonly KheopskitPlatform[],\n>(\n\twalletId: WalletId,\n) =>\n\tuseStateItem(\"useWallet\", walletId, selectWallet) as\n\t\t| KheopskitState<P>[\"wallets\"][number]\n\t\t| undefined;\n","import type { KheopskitPlatform, KheopskitState } from \"@kheopskit/core\";\nimport { useSyncExternalStore } from \"react\";\nimport { useKheopskitExternalStore } from \"./context\";\n\n/**\n * Returns the current kheopskit state (wallets, accounts, config, isHydrating)\n * and re-renders on every change. To follow one wallet or account, prefer\n * {@link useWallet} or {@link useAccount}. Each wallet's `connect` and\n * `disconnect` act on the instance's pipeline when they are called, while\n * anything holds it.\n *\n * Pass the platform tuple as a type argument to recover SDK-precise account and\n * wallet types — `useWallets<typeof platforms>()`. React contexts can't be\n * generic, so without the argument the state is typed with the base\n * (SDK-free) wallet/account shapes.\n */\nexport const useWallets = <\n\tP extends readonly KheopskitPlatform[] = readonly KheopskitPlatform[],\n>(): KheopskitState<P> => {\n\tconst store = useKheopskitExternalStore(\"useWallets\");\n\treturn useSyncExternalStore(\n\t\tstore.subscribe,\n\t\tstore.getSnapshot,\n\t\tstore.getServerSnapshot,\n\t) as unknown as KheopskitState<P>;\n};\n","import {\n\tcreateKheopskitStore,\n\tgetKheopskit$,\n\ttype KheopskitConfig,\n\ttype KheopskitPlatform,\n\ttype KheopskitState,\n\ttype KheopskitStore,\n\tresolveConfig,\n\ttype WalletAccountId,\n\ttype WalletId,\n} from \"@kheopskit/core\";\nimport { type FC, type PropsWithChildren, useCallback } from \"react\";\nimport { defer, type Observable, shareReplay } from \"rxjs\";\nimport { KheopskitSourceProvider } from \"./KheopskitSourceProvider\";\nimport { createLivePipeline, type LivePipeline } from \"./livePipeline\";\nimport { useAccount } from \"./useAccount\";\nimport { useWallet } from \"./useWallet\";\nimport { useWallets } from \"./useWallets\";\n\nexport type CreateKheopskitConfig<P extends readonly KheopskitPlatform[]> =\n\tOmit<Partial<KheopskitConfig<P>>, \"platforms\"> & {\n\t\t/** Platform plugins, e.g. `[polkadot(), solana()]`. Required. */\n\t\tplatforms: P;\n\t};\n\nexport type CreateKheopskitOptions = {\n\t/**\n\t * Store the shared instance reads the cache from and persists into. Pass one\n\t * when code outside React reads `store` or subscribes `kheopskit$` before\n\t * the provider renders in an SSR app, and in tests.\n\t */\n\tstore?: KheopskitStore;\n};\n\nconst deferredStore = (claim: () => KheopskitStore): KheopskitStore => ({\n\tobservable: defer(() => claim().observable),\n\trememberWallet: (walletId) => claim().rememberWallet(walletId),\n\tforgetWallet: (walletId) => claim().forgetWallet(walletId),\n\tgetCachedState: () => claim().getCachedState(),\n\tsetCachedState: (wallets, accounts) =>\n\t\tclaim().setCachedState(wallets, accounts),\n\tdestroy: () => claim().destroy(),\n});\n\n/**\n * Binds a platform tuple once and returns one kheopskit instance: a\n * `KheopskitProvider`, hooks already typed to those platforms, and the\n * `kheopskit$` stream and `store` the provider uses, for code outside React.\n * Subscribing `kheopskit$` while the provider is mounted runs no second\n * pipeline, and holds the one pipeline for every hook action of the instance.\n *\n * Without `options.store`, the store is created on first use in the browser:\n * backed by cookies when the provider renders first with `ssrCookies`, by\n * localStorage otherwise. The caller owns `store.destroy()`.\n *\n * @example\n * ```tsx\n * // kheopskit.ts\n * export const { KheopskitProvider, useWallets, useWallet, kheopskit$ } =\n * createKheopskit({ platforms: [polkadot(), ethereum(), solana()] });\n *\n * // anywhere\n * const { accounts } = useWallets(); // accounts are platform-precise, no generic\n * ```\n */\nexport const createKheopskit = <\n\tconst P extends readonly [KheopskitPlatform, ...KheopskitPlatform[]],\n>(\n\tconfig: CreateKheopskitConfig<P>,\n\toptions: CreateKheopskitOptions = {},\n) => {\n\tlet claimed: KheopskitStore | undefined;\n\tconst claimStore = (ssrCookies?: string) => {\n\t\tclaimed ??=\n\t\t\toptions.store ??\n\t\t\tcreateKheopskitStore({\n\t\t\t\tssrCookies,\n\t\t\t\tstorageKey: resolveConfig(config).storageKey,\n\t\t\t});\n\t\treturn claimed;\n\t};\n\n\tconst shared$: Observable<KheopskitState<P>> = defer(() =>\n\t\tgetKheopskit$(config, { store: claimStore() }),\n\t).pipe(shareReplay({ refCount: true, bufferSize: 1 }));\n\tconst pipeline = createLivePipeline(shared$);\n\tconst kheopskit$ = pipeline.observable$;\n\n\tconst Provider: FC<PropsWithChildren<{ ssrCookies?: string }>> = ({\n\t\tchildren,\n\t\tssrCookies,\n\t}) => {\n\t\tif (typeof window !== \"undefined\") claimStore(ssrCookies);\n\t\tconst resolveClientSource = useCallback(\n\t\t\t() => ({\n\t\t\t\tstore: claimStore(ssrCookies),\n\t\t\t\tpipeline: pipeline as unknown as LivePipeline<KheopskitState>,\n\t\t\t}),\n\t\t\t[ssrCookies],\n\t\t);\n\t\treturn (\n\t\t\t<KheopskitSourceProvider\n\t\t\t\tconfig={config}\n\t\t\t\tssrCookies={ssrCookies}\n\t\t\t\tresolveClientSource={resolveClientSource}\n\t\t\t>\n\t\t\t\t{children}\n\t\t\t</KheopskitSourceProvider>\n\t\t);\n\t};\n\tProvider.displayName = \"KheopskitProvider\";\n\n\treturn {\n\t\tKheopskitProvider: Provider,\n\t\t/** The state stream the provider subscribes to, shared with code outside React. */\n\t\tkheopskit$,\n\t\t/** The store `kheopskit$` reads the cache from and persists into. */\n\t\tstore: options.store ?? deferredStore(claimStore),\n\t\t/** Current state, typed to the bound platform tuple. */\n\t\tuseWallets: () => useWallets<P>(),\n\t\t/** Current accounts, typed to the bound platform tuple. */\n\t\tuseAccounts: () => useWallets<P>().accounts,\n\t\t/** The wallet with this id, typed to the bound platform tuple. */\n\t\tuseWallet: (walletId: WalletId) => useWallet<P>(walletId),\n\t\t/** The account with this id, typed to the bound platform tuple. */\n\t\tuseAccount: (accountId: WalletAccountId) => useAccount<P>(accountId),\n\t};\n};\n","import {\n\tcreateKheopskitStore,\n\tgetKheopskit$,\n\ttype KheopskitConfig,\n\ttype KheopskitStore,\n} from \"@kheopskit/core\";\nimport {\n\ttype FC,\n\ttype PropsWithChildren,\n\tuseCallback,\n\tuseEffect,\n\tuseRef,\n} from \"react\";\nimport { KheopskitSourceProvider } from \"./KheopskitSourceProvider\";\nimport { createLivePipeline } from \"./livePipeline\";\n\nexport type KheopskitProviderProps = PropsWithChildren & {\n\t/**\n\t * Kheopskit configuration.\n\t *\n\t * @remarks\n\t * Must be a **referentially stable** value — define it once (module scope, a\n\t * `useMemo`, or via {@link createKheopskit}) and pass the same reference. A\n\t * new object literal on every render (`config={{ platforms: [...] }}` inline)\n\t * recreates the underlying store and re-subscribes each render.\n\t */\n\tconfig?: Partial<KheopskitConfig>;\n\t/**\n\t * Cookie string for SSR hydration.\n\t * Pass the request cookie header (e.g., from Next.js headers or TanStack Start)\n\t * to hydrate wallet state on the server.\n\t *\n\t * @remarks\n\t * This value should be stable per render to avoid unnecessary store recreation.\n\t * Compute it once in your server component or layout and pass it down.\n\t *\n\t * @example\n\t * ```tsx\n\t * // Next.js App Router\n\t * const cookieStore = await cookies();\n\t * const ssrCookies = cookieStore.getAll().map(c => `${c.name}=${c.value}`).join('; ');\n\t * return <Providers ssrCookies={ssrCookies}>{children}</Providers>\n\t * ```\n\t */\n\tssrCookies?: string;\n\t/**\n\t * Store the provider reads the cache from and persists into, on the client.\n\t * Defaults to a store per mount, backed by cookies when `ssrCookies` is set\n\t * and by localStorage otherwise. The server snapshot always comes from\n\t * `ssrCookies`.\n\t *\n\t * @example\n\t * ```tsx\n\t * // tests\n\t * const store = createKheopskitStore({ storage: createMemoryStorage() });\n\t * render(<KheopskitProvider config={config} store={store}>…</KheopskitProvider>);\n\t * ```\n\t */\n\tstore?: KheopskitStore;\n};\n\nexport const KheopskitProvider: FC<KheopskitProviderProps> = ({\n\tchildren,\n\tconfig,\n\tssrCookies,\n\tstore,\n}) => {\n\t// Dev-only: warn if the `config` prop reference changes between renders. A new\n\t// object each render recreates the store and re-subscribes the whole pipeline\n\t// (re-hydrating, dropping live connection state) on every render. `config` must\n\t// be referentially stable — define it at module scope, memoize it, or use\n\t// createKheopskit() (which passes a stable reference for you).\n\tconst lastConfigRef = useRef(config);\n\tconst hasMountedRef = useRef(false);\n\tuseEffect(() => {\n\t\tif (\n\t\t\thasMountedRef.current &&\n\t\t\tlastConfigRef.current !== config &&\n\t\t\t(typeof process === \"undefined\" || process.env?.NODE_ENV !== \"production\")\n\t\t) {\n\t\t\tconsole.warn(\n\t\t\t\t\"[kheopskit] KheopskitProvider received a new `config` reference; this \" +\n\t\t\t\t\t\"recreates the store and re-subscribes on every render. Pass a \" +\n\t\t\t\t\t\"referentially stable config (module scope, useMemo, or createKheopskit()).\",\n\t\t\t);\n\t\t}\n\t\thasMountedRef.current = true;\n\t\tlastConfigRef.current = config;\n\t}, [config]);\n\n\tconst resolveClientSource = useCallback(\n\t\t(resolvedConfig: KheopskitConfig) => {\n\t\t\tconst sourceStore =\n\t\t\t\tstore ??\n\t\t\t\tcreateKheopskitStore({\n\t\t\t\t\tssrCookies,\n\t\t\t\t\tstorageKey: resolvedConfig.storageKey,\n\t\t\t\t});\n\t\t\treturn {\n\t\t\t\tstore: sourceStore,\n\t\t\t\tpipeline: createLivePipeline(\n\t\t\t\t\tgetKheopskit$(resolvedConfig, { ssrCookies, store: sourceStore }),\n\t\t\t\t),\n\t\t\t};\n\t\t},\n\t\t[ssrCookies, store],\n\t);\n\n\treturn (\n\t\t<KheopskitSourceProvider\n\t\t\tconfig={config}\n\t\t\tssrCookies={ssrCookies}\n\t\t\tresolveClientSource={resolveClientSource}\n\t\t>\n\t\t\t{children}\n\t\t</KheopskitSourceProvider>\n\t);\n};\n","import type { KheopskitPlatform } from \"@kheopskit/core\";\nimport { useWallets } from \"./useWallets\";\n\n/**\n * Convenience hook returning just the accounts from kheopskit state. Pass the\n * platform tuple as a type argument to recover SDK-precise account types —\n * `useAccounts<typeof platforms>()` — or use the pre-typed hook from\n * {@link createKheopskit}.\n */\nexport const useAccounts = <\n\tP extends readonly KheopskitPlatform[] = readonly KheopskitPlatform[],\n>() => useWallets<P>().accounts;\n","import {\n\tKheopskitError,\n\ttype WalletId,\n\ttype WalletStatus,\n} from \"@kheopskit/core\";\nimport { useEffect, useLayoutEffect, useMemo } from \"react\";\nimport {\n\ttype KheopskitExternalStore,\n\tuseKheopskitExternalStore,\n} from \"./context\";\nimport { walletActions } from \"./liveActions\";\nimport { useWallet } from \"./useWallet\";\n\nexport type UseConnectResult = {\n\t/**\n\t * Connects the wallet through the pipeline that runs when it is called, and\n\t * waits for that pipeline's first emission when an `<Activity>` reveal has\n\t * just restarted it. Resolves once the state shows the wallet connected.\n\t * Unmounting the component or changing `walletId` aborts a pending connect,\n\t * which then resolves without connecting. A connect that starts after\n\t * unmount, or through a `connect` captured before `walletId` changed,\n\t * rejects `ABORTED` without asking the wallet. Rejects with the wallet's\n\t * `KheopskitError` otherwise, such as `USER_REJECTED`, and with an `Error`\n\t * when the state lists no wallet with this id.\n\t */\n\tconnect: () => Promise<void>;\n\t/**\n\t * Disconnects the wallet through the instance's pipeline, like a `useWallet`\n\t * wallet's `disconnect`, also after this component unmounted. Resolves once\n\t * the state shows it disconnected.\n\t */\n\tdisconnect: () => Promise<void>;\n\t/** `undefined` while the state lists no wallet with this id. */\n\tstatus: WalletStatus | undefined;\n\t/** The last connect the platform refused or failed. */\n\terror: KheopskitError | undefined;\n};\n\nconst useIsomorphicLayoutEffect =\n\ttypeof window === \"undefined\" ? useEffect : useLayoutEffect;\n\n// React runs every layout setup of a commit synchronously, so once this\n// microtask runs a mounted owner has renewed its scope.\nconst afterThisCommitsLayoutEffects = () => Promise.resolve();\n\nconst createWalletActions = (\n\tstore: KheopskitExternalStore,\n\twalletId: WalletId,\n) => {\n\tlet scope = new AbortController();\n\tconst wallet = walletActions(store, walletId);\n\n\treturn {\n\t\tconnect: async () => {\n\t\t\tif (scope.signal.aborted) await afterThisCommitsLayoutEffects();\n\t\t\tconst { signal } = scope;\n\t\t\tif (signal.aborted)\n\t\t\t\tthrow new KheopskitError(\n\t\t\t\t\t\"ABORTED\",\n\t\t\t\t\t`connect of wallet ${walletId} started after useConnect unmounted or switched wallet`,\n\t\t\t\t\t{ walletId },\n\t\t\t\t);\n\t\t\ttry {\n\t\t\t\tawait wallet.connect({ signal });\n\t\t\t} catch (error) {\n\t\t\t\tconst abortedByCleanup =\n\t\t\t\t\tsignal.aborted &&\n\t\t\t\t\terror instanceof KheopskitError &&\n\t\t\t\t\terror.code === \"ABORTED\";\n\t\t\t\tif (!abortedByCleanup) throw error;\n\t\t\t}\n\t\t},\n\t\tdisconnect: wallet.disconnect,\n\t\trenew: () => {\n\t\t\tif (scope.signal.aborted) scope = new AbortController();\n\t\t},\n\t\tabort: () => scope.abort(),\n\t};\n};\n\n/**\n * Connect and disconnect actions for one wallet, with its status and error.\n * `connect` and `disconnect` keep their identity while `walletId` is the same,\n * so `useEffect(() => { connect() }, [connect])` connects on mount and after\n * every `<Activity>` reveal.\n *\n * @example\n * ```tsx\n * const ConnectButton = ({ walletId }: { walletId: WalletId }) => {\n * const { connect, disconnect, status } = useConnect(walletId);\n * if (status === \"connected\") return <button onClick={disconnect}>Disconnect</button>;\n * return <button disabled={status === \"connecting\"} onClick={connect}>Connect</button>;\n * };\n * ```\n */\nexport const useConnect = (walletId: WalletId): UseConnectResult => {\n\tconst store = useKheopskitExternalStore(\"useConnect\");\n\tconst wallet = useWallet(walletId);\n\tconst actions = useMemo(\n\t\t() => createWalletActions(store, walletId),\n\t\t[store, walletId],\n\t);\n\n\tuseIsomorphicLayoutEffect(() => actions.renew(), [actions]);\n\tuseEffect(() => () => actions.abort(), [actions]);\n\n\treturn {\n\t\tconnect: actions.connect,\n\t\tdisconnect: actions.disconnect,\n\t\tstatus: wallet?.status,\n\t\terror: wallet?.error,\n\t};\n};\n"],"mappings":";;;;;;AAWA,MAAa,mBAAmB,cAC/B,IACD;AAEA,MAAa,6BAA6B,aAAqB;CAC9D,MAAM,QAAQ,WAAW,gBAAgB;CACzC,IAAI,CAAC,OACJ,MAAM,IAAI,MAAM,GAAG,SAAS,2CAA2C;CACxE,OAAO;AACR;;;ACTA,MAAMA,wCAAsC,QAAQ,QAAQ;AAE5D,MAAa,uBACZ,qBACA,gBACI;CACJ,IAAI;CACJ,IAAI;CACJ,IAAI;CACJ,MAAM,4BAAY,IAAI,IAAwB;CAE9C,MAAM,kBAAkB;EACvB,WAAA,SAAW,oBAAoB;EAC/B,OAAO;CACR;CAEA,MAA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