@solana/subscribable 7.0.0-canary-20260630075708 → 7.0.0-canary-20260630082225
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/README.md +6 -10
- package/dist/index.browser.cjs +0 -10
- package/dist/index.browser.cjs.map +1 -1
- package/dist/index.browser.mjs +0 -10
- package/dist/index.browser.mjs.map +1 -1
- package/dist/index.native.mjs +0 -10
- package/dist/index.native.mjs.map +1 -1
- package/dist/index.node.cjs +0 -10
- package/dist/index.node.cjs.map +1 -1
- package/dist/index.node.mjs +0 -10
- package/dist/index.node.mjs.map +1 -1
- package/dist/types/reactive-action-store.d.ts +7 -1
- package/dist/types/reactive-action-store.d.ts.map +1 -1
- package/dist/types/reactive-stream-store.d.ts +5 -34
- package/dist/types/reactive-stream-store.d.ts.map +1 -1
- package/package.json +3 -3
- package/src/reactive-action-store.ts +7 -1
- package/src/reactive-stream-store.ts +6 -46
package/README.md
CHANGED
|
@@ -29,9 +29,9 @@ dataPublisher.on('error', e => {
|
|
|
29
29
|
|
|
30
30
|
### `ReactiveStreamStore<T>`
|
|
31
31
|
|
|
32
|
-
This type represents a reactive store that holds the latest value published to a data channel. It exposes a `{
|
|
32
|
+
This type represents a reactive store that holds the latest value published to a data channel. It exposes a `{ getState, retry, subscribe }` contract compatible with `useSyncExternalStore`, Svelte stores, and other reactive primitives.
|
|
33
33
|
|
|
34
|
-
`
|
|
34
|
+
`getState()` returns a discriminated snapshot of the store's lifecycle:
|
|
35
35
|
|
|
36
36
|
```ts
|
|
37
37
|
type ReactiveState<T> =
|
|
@@ -49,7 +49,7 @@ The store starts in `status: 'idle'`. Call `connect()` to open the underlying st
|
|
|
49
49
|
const store: ReactiveStreamStore<AccountInfo> = /* ... */;
|
|
50
50
|
|
|
51
51
|
// React — snapshot identity is stable between updates, so it can be passed directly.
|
|
52
|
-
const state = useSyncExternalStore(store.subscribe, store.
|
|
52
|
+
const state = useSyncExternalStore(store.subscribe, store.getState);
|
|
53
53
|
useEffect(() => {
|
|
54
54
|
store.connect();
|
|
55
55
|
return () => store.reset();
|
|
@@ -64,17 +64,13 @@ return (
|
|
|
64
64
|
);
|
|
65
65
|
|
|
66
66
|
// Vue
|
|
67
|
-
const snapshot = shallowRef(store.
|
|
67
|
+
const snapshot = shallowRef(store.getState());
|
|
68
68
|
store.subscribe(() => {
|
|
69
|
-
snapshot.value = store.
|
|
69
|
+
snapshot.value = store.getState();
|
|
70
70
|
});
|
|
71
71
|
store.connect();
|
|
72
72
|
```
|
|
73
73
|
|
|
74
|
-
`retry()` is a deprecated alias for the error-recovery case — prefer calling `connect()` directly. `connect()` always reopens the stream, regardless of current status; wrap with a status guard at the call site if you need the error-only behaviour.
|
|
75
|
-
|
|
76
|
-
The individual `getState()` and `getError()` getters on `ReactiveStreamStore<T>` are `@deprecated` — prefer `getUnifiedState()`, which exposes the same information with a stable snapshot identity and `status` discriminator.
|
|
77
|
-
|
|
78
74
|
### `ReactiveActionStore<TArgs, TResult>`
|
|
79
75
|
|
|
80
76
|
A framework-agnostic state machine for wrapping an async action (a function you dispatch on demand — like a form submission, a mutation, or an on-click fetch). It exposes a `{ dispatch, getState, subscribe, reset }` contract that bridges trivially into `useSyncExternalStore`, Svelte stores, Vue's `shallowRef`, and similar reactive primitives.
|
|
@@ -210,7 +206,7 @@ const store = createReactiveStoreFromDataPublisherFactory({
|
|
|
210
206
|
errorChannelName: 'error',
|
|
211
207
|
});
|
|
212
208
|
const unsubscribe = store.subscribe(() => {
|
|
213
|
-
const snapshot = store.
|
|
209
|
+
const snapshot = store.getState();
|
|
214
210
|
if (snapshot.status === 'error') console.error('Connection failed:', snapshot.error);
|
|
215
211
|
else if (snapshot.status === 'loaded') console.log('Latest:', snapshot.data);
|
|
216
212
|
});
|
package/dist/index.browser.cjs
CHANGED
|
@@ -346,20 +346,10 @@ function createReactiveStoreFromDataPublisherFactory({
|
|
|
346
346
|
connect() {
|
|
347
347
|
performConnect(void 0);
|
|
348
348
|
},
|
|
349
|
-
getError() {
|
|
350
|
-
return currentState.error;
|
|
351
|
-
},
|
|
352
349
|
getState() {
|
|
353
|
-
return currentState.data;
|
|
354
|
-
},
|
|
355
|
-
getUnifiedState() {
|
|
356
350
|
return currentState;
|
|
357
351
|
},
|
|
358
352
|
reset: performReset,
|
|
359
|
-
retry() {
|
|
360
|
-
if (currentState.status !== "error") return;
|
|
361
|
-
performConnect(void 0);
|
|
362
|
-
},
|
|
363
353
|
subscribe(callback) {
|
|
364
354
|
subscribers.add(callback);
|
|
365
355
|
return () => {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../event-target-impl/src/index.browser.ts","../src/reactive-action-store.ts","../src/async-iterable.ts","../src/data-publisher.ts","../src/demultiplex.ts","../src/reactive-stream-store.ts"],"names":["AbortController","EventTarget","getAbortablePromise","SolanaError","SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING","SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE","IDLE_STATE"],"mappings":";;;;;;AAAO,IAAMA,IAAkB,UAAA,CAAW,eAAA;AAAnC,IACMC,IAAc,UAAA,CAAW,WAAA;ACqGtC,IAAM,UAAA,GAAyC,OAAO,MAAA,CAAO;AAAA,EACzD,IAAA,EAAM,MAAA;AAAA,EACN,KAAA,EAAO,MAAA;AAAA,EACP,MAAA,EAAQ;AACZ,CAAC,CAAA;AAsCM,SAAS,0BACZ,EAAA,EACmC;AACnC,EAAA,IAAI,KAAA,GAAsC,UAAA;AAC1C,EAAA,IAAI,iBAAA;AACJ,EAAA,MAAM,SAAA,uBAAgB,GAAA,EAAgB;AAEtC,EAAA,SAAS,SAAS,IAAA,EAAoC;AAClD,IAAA,IAAI,KAAA,CAAM,MAAA,KAAW,IAAA,CAAK,MAAA,IAAU,KAAA,CAAM,IAAA,KAAS,IAAA,CAAK,IAAA,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AAAA,IACA,QAAA,GAA8B;AAC1B,MAAA,OAAO,YAAA,CAAa,IAAA;AAAA,IACxB,CAAA;AAAA,IACA,eAAA,GAAwC;AACpC,MAAA,OAAO,YAAA;AAAA,IACX,CAAA;AAAA,IACA,KAAA,EAAO,YAAA;AAAA,IACP,KAAA,GAAc;AACV,MAAA,IAAI,YAAA,CAAa,WAAW,OAAA,EAAS;AACrC,MAAA,cAAA,CAAe,MAAS,CAAA;AAAA,IAC5B,CAAA;AAAA,IACA,UAAU,QAAA,EAAkC;AACxC,MAAA,WAAA,CAAY,IAAI,QAAQ,CAAA;AACxB,MAAA,OAAO,MAAM;AACT,QAAA,WAAA,CAAY,OAAO,QAAQ,CAAA;AAAA,MAC/B,CAAA;AAAA,IACJ,CAAA;AAAA,IACA,WAAW,MAAA,EAAqB;AAC5B,MAAA,OAAO;AAAA,QACH,OAAA,GAAgB;AACZ,UAAA,cAAA,CAAe,MAAM,CAAA;AAAA,QACzB;AAAA,OACJ;AAAA,IACJ;AAAA,GACJ;AACJ","file":"index.browser.cjs","sourcesContent":["export const AbortController = globalThis.AbortController;\nexport const EventTarget = globalThis.EventTarget;\n","import { AbortController } from '@solana/event-target-impl';\nimport { getAbortablePromise } from '@solana/promises';\n\n/** Lifecycle status of a {@link ReactiveActionStore}. */\nexport type ReactiveActionStatus = 'error' | 'idle' | 'running' | 'success';\n\n/**\n * Discriminated state of a {@link ReactiveActionStore}, keyed by {@link ReactiveActionStatus}.\n *\n * `data` holds the most recent successful result and `error` holds the most recent failure. Both\n * persist through subsequent `running` states so call sites can keep rendering stale content\n * while a retry is in flight. `success` clears `error`; only `reset()` clears `data`.\n */\nexport type ReactiveActionState<TResult> =\n | { readonly data: TResult | undefined; readonly error: unknown; readonly status: 'error' }\n | { readonly data: TResult | undefined; readonly error: unknown; readonly status: 'running' }\n | { readonly data: TResult; readonly error: undefined; readonly status: 'success' }\n | { readonly data: undefined; readonly error: undefined; readonly status: 'idle' };\n\n/**\n * A framework-agnostic state machine that wraps an async function and exposes a\n * `{ dispatch, getState, subscribe, reset }` contract. Bridges trivially into\n * `useSyncExternalStore`, Svelte stores, Vue's `shallowRef`, and similar reactive primitives.\n *\n * @see {@link createReactiveActionStore}\n */\nexport type ReactiveActionStore<TArgs extends readonly unknown[], TResult> = {\n /**\n * Fire-and-forget dispatch. Returns `undefined` synchronously and never throws — failures\n * surface on state as `{ status: 'error' }`, and superseded or `reset()`-aborted calls produce\n * no state update. Use from UI event handlers; there's no promise to handle or `.catch`.\n *\n * @see {@link ReactiveActionStore.dispatchAsync} when you need the resolved value or propagated errors.\n * @see {@link ReactiveActionStore.withSignal} to attach a caller-provided `AbortSignal` to a dispatch.\n */\n readonly dispatch: (...args: TArgs) => void;\n /**\n * Promise-returning dispatch for imperative callers. Resolves with the wrapped function's\n * result on success. Rejects with the thrown error on failure, and with an `AbortError` when\n * the call is superseded or `reset()` is invoked — filter those with `isAbortError` from\n * `@solana/promises`.\n */\n readonly dispatchAsync: (...args: TArgs) => Promise<TResult>;\n /** Returns the current state. */\n readonly getState: () => ReactiveActionState<TResult>;\n /** Aborts any in-flight dispatch and resets the state to `{ status: 'idle' }`. */\n readonly reset: () => void;\n /** Registers a listener called on every state change. Returns an unsubscribe function. */\n readonly subscribe: (listener: () => void) => () => void;\n /**\n * Returns a thin wrapper exposing `dispatch` / `dispatchAsync` that compose `signal` with the\n * store's internal per-dispatch controller via `AbortSignal.any` — aborting either cancels\n * the in-flight call. Aborting the caller-provided signal surfaces the abort reason on state\n * as `{ status: 'error' }`; the internal controller path (supersession by a newer dispatch or\n * `reset()`) is silent by design so the newer dispatch owns state. Use this to attach a\n * caller-provided cancellation source (per-attempt timeout, shared kill switch, parent-context\n * signal) without touching the bare `dispatch` / `dispatchAsync` API.\n *\n * - Per-attempt timeout: `store.withSignal(AbortSignal.timeout(5_000)).dispatch(args)` — fresh\n * clock per call.\n * - Permanent kill switch: hold one `AbortController`, bind the wrapper once\n * (`const killable = store.withSignal(killCtrl.signal)`), and use `killable.dispatch(...)`\n * everywhere; aborting the controller cancels in-flight and short-circuits future calls.\n *\n * The wrapper exposes only `dispatch` / `dispatchAsync` — `getState` / `subscribe` / `reset`\n * remain store-level concerns on the parent.\n */\n readonly withSignal: (signal: AbortSignal) => {\n readonly dispatch: (...args: TArgs) => void;\n readonly dispatchAsync: (...args: TArgs) => Promise<TResult>;\n };\n};\n\n/**\n * Duck-type for objects that build a {@link ReactiveActionStore} on demand via `reactiveStore()`.\n * Satisfied by `PendingRpcRequest<T>`. The `[]` argument tuple is intentional — the operation's\n * arguments are already baked into the pending request, so each `dispatch()` re-fires the same\n * call.\n *\n * The returned store is in the `idle` state — the caller is responsible for calling `dispatch()`\n * to fire the first attempt. Attach a caller-provided cancellation source per dispatch via\n * `store.withSignal(signal).dispatch(...)` — see {@link ReactiveActionStore.withSignal}.\n *\n * @typeParam T - The value type resolved by the wrapped operation.\n *\n * @example\n * ```ts\n * function bind<T>(source: ReactiveActionSource<T>) {\n * const store = source.reactiveStore();\n * // Per-attempt timeout, fresh signal per call:\n * store.withSignal(AbortSignal.timeout(30_000)).dispatch();\n * return store;\n * }\n * ```\n *\n * @see {@link ReactiveActionStore}\n * @see {@link ReactiveStreamSource}\n */\nexport type ReactiveActionSource<T> = {\n reactiveStore(): ReactiveActionStore<[], T>;\n};\n\nconst IDLE_STATE: ReactiveActionState<never> = Object.freeze({\n data: undefined,\n error: undefined,\n status: 'idle',\n});\n\n/**\n * Wraps an async function in a {@link ReactiveActionStore}. Each `dispatch` creates a fresh\n * {@link AbortController} and aborts the previous one; the superseded call's outcome is dropped,\n * so only the most recent dispatch can mutate state.\n *\n * The wrapped function receives the `AbortSignal` as its first argument, followed by whatever\n * arguments were passed to `dispatch`. Callers attach their own cancellation source per-call via\n * {@link ReactiveActionStore.withSignal} — `store.withSignal(signal).dispatch(...)`. The caller's\n * signal is composed with the per-dispatch controller via `AbortSignal.any`, so aborting it\n * cancels the in-flight call and surfaces the abort reason on state.\n *\n * @typeParam TArgs - Argument tuple forwarded from `dispatch` to `fn`.\n * @typeParam TResult - Resolved value type of `fn`.\n * @param fn - Async function to wrap. Receives an {@link AbortSignal} plus the dispatch arguments.\n * @return A {@link ReactiveActionStore} exposing `dispatch`, `dispatchAsync`, `getState`, `subscribe`,\n * `reset`, and `withSignal`.\n *\n * @example\n * ```ts\n * const store = createReactiveActionStore(async (signal, accountId: Address) => {\n * const response = await fetch(`/api/accounts/${accountId}`, { signal });\n * return response.json();\n * });\n *\n * store.subscribe(() => console.log(store.getState()));\n * store.dispatch(someAccountId); // fire-and-forget; state is the source of truth\n *\n * // Per-attempt timeout — fresh signal per call:\n * store.withSignal(AbortSignal.timeout(30_000)).dispatch(someAccountId);\n *\n * // Imperative call with the resolved value:\n * const account = await store.dispatchAsync(someAccountId);\n * ```\n *\n * @see {@link ReactiveActionStore}\n */\nexport function createReactiveActionStore<TArgs extends readonly unknown[], TResult>(\n fn: (signal: AbortSignal, ...args: TArgs) => Promise<TResult>,\n): ReactiveActionStore<TArgs, TResult> {\n let state: ReactiveActionState<TResult> = IDLE_STATE;\n let currentController: AbortController | undefined;\n const listeners = new Set<() => void>();\n\n function setState(next: ReactiveActionState<TResult>) {\n if (state.status === next.status && state.data === next.data && state.error === next.error) {\n return;\n }\n state = next;\n listeners.forEach(listener => listener());\n }\n\n const dispatchAsyncWithSignal = async (userSignal: AbortSignal | undefined, ...args: TArgs): Promise<TResult> => {\n currentController?.abort();\n // If the caller's signal is already aborted, surface as error and bail.\n if (userSignal?.aborted) {\n setState({ data: state.data, error: userSignal.reason, status: 'error' });\n throw userSignal.reason;\n }\n const controller = new AbortController();\n currentController = controller;\n const signal = userSignal ? AbortSignal.any([controller.signal, userSignal]) : controller.signal;\n const previousData = state.data;\n const previousError = state.error;\n setState({ data: previousData, error: previousError, status: 'running' });\n try {\n const result = await getAbortablePromise(fn(signal, ...args), signal);\n if (signal.aborted) {\n throw signal.reason;\n }\n setState({ data: result, error: undefined, status: 'success' });\n return result;\n } catch (error) {\n // Superseded by a newer dispatch or `reset()` — drop silently so only the most recent\n // dispatch mutates state, and reject with the abort reason rather than any underlying\n // failure that happened to race the abort.\n if (controller.signal.aborted) {\n throw controller.signal.reason;\n }\n // Real failure or the caller-provided signal firing — surface as error state.\n setState({ data: previousData, error, status: 'error' });\n throw error;\n }\n };\n\n const dispatchAsync = (...args: TArgs): Promise<TResult> => dispatchAsyncWithSignal(undefined, ...args);\n const dispatch = (...args: TArgs): void => {\n dispatchAsync(...args).catch(() => {});\n };\n\n return {\n dispatch,\n dispatchAsync,\n getState: () => state,\n reset: () => {\n currentController?.abort();\n currentController = undefined;\n setState(IDLE_STATE);\n },\n subscribe: listener => {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n withSignal: (signal: AbortSignal) => ({\n dispatch: (...args: TArgs): void => {\n dispatchAsyncWithSignal(signal, ...args).catch(() => {});\n },\n dispatchAsync: (...args: TArgs): Promise<TResult> => dispatchAsyncWithSignal(signal, ...args),\n }),\n };\n}\n","import {\n SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE,\n SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING,\n SolanaError,\n} from '@solana/errors';\nimport { AbortController } from '@solana/event-target-impl';\n\nimport { DataPublisher } from './data-publisher';\n\ntype Config = Readonly<{\n /**\n * Triggering this abort signal will cause all iterators spawned from this iterator to return\n * once they have published all queued messages.\n */\n abortSignal: AbortSignal;\n /**\n * Messages from this channel of `dataPublisher` will be the ones yielded through the iterators.\n *\n * Messages only begin to be queued after the first time an iterator begins to poll. Channel\n * messages published before that time will be dropped.\n */\n dataChannelName: string;\n // FIXME: It would be nice to be able to constrain the type of `dataPublisher` to one that\n // definitely supports the `dataChannelName` and `errorChannelName` channels, and\n // furthermore publishes `TData` on the `dataChannelName` channel. This is more difficult\n // than it should be: https://tsplay.dev/NlZelW\n dataPublisher: DataPublisher;\n /**\n * Messages from this channel of `dataPublisher` will be the ones thrown through the iterators.\n *\n * Any new iterators created after the first error is encountered will reject with that error\n * when polled.\n */\n errorChannelName: string;\n}>;\n\nconst enum PublishType {\n DATA,\n ERROR,\n}\n\ntype IteratorKey = symbol;\ntype IteratorState<TData> =\n | {\n __hasPolled: false;\n publishQueue: (\n | {\n __type: PublishType.DATA;\n data: TData;\n }\n | {\n __type: PublishType.ERROR;\n err: unknown;\n }\n )[];\n }\n | {\n __hasPolled: true;\n onData: (data: TData) => void;\n onError: Parameters<ConstructorParameters<typeof Promise>[0]>[1];\n };\n\nlet EXPLICIT_ABORT_TOKEN: symbol;\nfunction createExplicitAbortToken() {\n // This function is an annoying workaround to prevent `process.env.NODE_ENV` from appearing at\n // the top level of this module and thwarting an optimizing compiler's attempt to tree-shake.\n return Symbol(\n process.env.NODE_ENV !== \"production\"\n ? \"This symbol is thrown from a socket's iterator when the connection is explicitly \" +\n 'aborted by the user'\n : undefined,\n );\n}\n\nconst UNINITIALIZED = Symbol();\n\n/**\n * Returns an `AsyncIterable` given a data publisher.\n *\n * The iterable will produce iterators that vend messages published to `dataChannelName` and will\n * throw the first time a message is published to `errorChannelName`. Triggering the abort signal\n * will cause all iterators spawned from this iterator to return once they have published all queued\n * messages.\n *\n * Things to note:\n *\n * - If a message is published over a channel before the `AsyncIterator` attached to it has polled\n * for the next result, the message will be queued in memory.\n * - Messages only begin to be queued after the first time an iterator begins to poll. Channel\n * messages published before that time will be dropped.\n * - If there are messages in the queue and an error occurs, all queued messages will be vended to\n * the iterator before the error is thrown.\n * - If there are messages in the queue and the abort signal fires, all queued messages will be\n * vended to the iterator after which it will return.\n * - Any new iterators created after the first error is encountered will reject with that error when\n * polled.\n *\n * @param config\n *\n * @example\n * ```ts\n * const iterable = createAsyncIterableFromDataPublisher({\n * abortSignal: AbortSignal.timeout(10_000),\n * dataChannelName: 'message',\n * dataPublisher,\n * errorChannelName: 'error',\n * });\n * try {\n * for await (const message of iterable) {\n * console.log('Got message', message);\n * }\n * } catch (e) {\n * console.error('An error was published to the error channel', e);\n * } finally {\n * console.log(\"It's been 10 seconds; that's enough for now.\");\n * }\n * ```\n */\nexport function createAsyncIterableFromDataPublisher<TData>({\n abortSignal,\n dataChannelName,\n dataPublisher,\n errorChannelName,\n}: Config): AsyncIterable<TData> {\n const iteratorState: Map<IteratorKey, IteratorState<TData>> = new Map();\n function publishErrorToAllIterators(reason: unknown) {\n for (const [iteratorKey, state] of iteratorState.entries()) {\n if (state.__hasPolled) {\n iteratorState.delete(iteratorKey);\n state.onError(reason);\n } else {\n state.publishQueue.push({\n __type: PublishType.ERROR,\n err: reason,\n });\n }\n }\n }\n const abortController = new AbortController();\n abortSignal.addEventListener('abort', () => {\n abortController.abort();\n publishErrorToAllIterators((EXPLICIT_ABORT_TOKEN ||= createExplicitAbortToken()));\n });\n const options = { signal: abortController.signal } as const;\n let firstError: unknown = UNINITIALIZED;\n dataPublisher.on(\n errorChannelName,\n err => {\n if (firstError === UNINITIALIZED) {\n firstError = err;\n abortController.abort();\n publishErrorToAllIterators(err);\n }\n },\n options,\n );\n dataPublisher.on(\n dataChannelName,\n data => {\n iteratorState.forEach((state, iteratorKey) => {\n if (state.__hasPolled) {\n const { onData } = state;\n iteratorState.set(iteratorKey, { __hasPolled: false, publishQueue: [] });\n onData(data as TData);\n } else {\n state.publishQueue.push({\n __type: PublishType.DATA,\n data: data as TData,\n });\n }\n });\n },\n options,\n );\n return {\n async *[Symbol.asyncIterator]() {\n if (abortSignal.aborted) {\n return;\n }\n if (firstError !== UNINITIALIZED) {\n throw firstError;\n }\n const iteratorKey = Symbol();\n iteratorState.set(iteratorKey, { __hasPolled: false, publishQueue: [] });\n try {\n while (true) {\n const state = iteratorState.get(iteratorKey);\n if (!state) {\n // There should always be state by now.\n throw new SolanaError(SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING);\n }\n if (state.__hasPolled) {\n // You should never be able to poll twice in a row.\n throw new SolanaError(\n SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE,\n );\n }\n const publishQueue = state.publishQueue;\n try {\n if (publishQueue.length) {\n state.publishQueue = [];\n for (const item of publishQueue) {\n if (item.__type === PublishType.DATA) {\n yield item.data;\n } else {\n throw item.err;\n }\n }\n } else {\n yield await new Promise<TData>((resolve, reject) => {\n iteratorState.set(iteratorKey, {\n __hasPolled: true,\n onData: resolve,\n onError: reject,\n });\n });\n }\n } catch (e) {\n if (e === (EXPLICIT_ABORT_TOKEN ||= createExplicitAbortToken())) {\n return;\n } else {\n throw e;\n }\n }\n }\n } finally {\n iteratorState.delete(iteratorKey);\n }\n },\n };\n}\n","import { TypedEventEmitter, TypedEventTarget } from './event-emitter';\n\ntype UnsubscribeFn = () => void;\n\n/**\n * Represents an object with an `on` function that you can call to subscribe to certain data over a\n * named channel.\n *\n * @example\n * ```ts\n * let dataPublisher: DataPublisher<{ error: SolanaError }>;\n * dataPublisher.on('data', handleData); // ERROR. `data` is not a known channel name.\n * dataPublisher.on('error', e => {\n * console.error(e);\n * }); // OK.\n * ```\n */\nexport interface DataPublisher<TDataByChannelName extends Record<string, unknown> = Record<string, unknown>> {\n /**\n * Call this to subscribe to data over a named channel.\n *\n * @param channelName The name of the channel on which to subscribe for messages\n * @param subscriber The function to call when a message becomes available\n * @param options.signal An abort signal you can fire to unsubscribe\n *\n * @returns A function that you can call to unsubscribe\n */\n on<const TChannelName extends keyof TDataByChannelName>(\n channelName: TChannelName,\n subscriber: (data: TDataByChannelName[TChannelName]) => void,\n options?: { signal: AbortSignal },\n ): UnsubscribeFn;\n}\n\n/**\n * Returns an object with an `on` function that you can call to subscribe to certain data over a\n * named channel.\n *\n * The `on` function returns an unsubscribe function.\n *\n * @example\n * ```ts\n * const socketDataPublisher = getDataPublisherFromEventEmitter(new WebSocket('wss://api.devnet.solana.com'));\n * const unsubscribe = socketDataPublisher.on('message', message => {\n * if (JSON.parse(message.data).id === 42) {\n * console.log('Got response 42');\n * unsubscribe();\n * }\n * });\n * ```\n */\nexport function getDataPublisherFromEventEmitter<TEventMap extends Record<string, Event>>(\n eventEmitter: TypedEventEmitter<TEventMap> | TypedEventTarget<TEventMap>,\n): DataPublisher<{\n [TEventType in keyof TEventMap]: TEventMap[TEventType] extends CustomEvent ? TEventMap[TEventType]['detail'] : null;\n}> {\n return {\n on(channelName, subscriber, options) {\n function innerListener(ev: Event) {\n if (ev instanceof CustomEvent) {\n const data = (ev as CustomEvent<TEventMap[typeof channelName]>).detail;\n (subscriber as unknown as (data: TEventMap[typeof channelName]) => void)(data);\n } else {\n (subscriber as () => void)();\n }\n }\n eventEmitter.addEventListener(channelName, innerListener, options);\n return () => {\n eventEmitter.removeEventListener(channelName, innerListener);\n };\n },\n };\n}\n","import { EventTarget } from '@solana/event-target-impl';\n\nimport { DataPublisher, getDataPublisherFromEventEmitter } from './data-publisher';\n\n/**\n * Given a channel that carries messages for multiple subscribers on a single channel name, this\n * function returns a new {@link DataPublisher} that splits them into multiple channel names.\n *\n * @param messageTransformer A function that receives the message as the first argument, and returns\n * a tuple of the derived channel name and the message.\n *\n * @example\n * Imagine a channel that carries multiple notifications whose destination is contained within the\n * message itself.\n *\n * ```ts\n * const demuxedDataPublisher = demultiplexDataPublisher(channel, 'message', message => {\n * const destinationChannelName = `notification-for:${message.subscriberId}`;\n * return [destinationChannelName, message];\n * });\n * ```\n *\n * Now you can subscribe to _only_ the messages you are interested in, without having to subscribe\n * to the entire `'message'` channel and filter out the messages that are not for you.\n *\n * ```ts\n * demuxedDataPublisher.on(\n * 'notification-for:123',\n * message => {\n * console.log('Got a message for subscriber 123', message);\n * },\n * { signal: AbortSignal.timeout(5_000) },\n * );\n * ```\n */\nexport function demultiplexDataPublisher<\n TDataPublisher extends DataPublisher,\n const TChannelName extends Parameters<TDataPublisher['on']>[0],\n>(\n publisher: TDataPublisher,\n sourceChannelName: TChannelName,\n messageTransformer: (\n // FIXME: Deriving the type of the message from `TDataPublisher` and `TChannelName` would\n // help callers to constrain their transform functions.\n message: unknown,\n ) => [destinationChannelName: string, message: unknown] | void,\n): DataPublisher {\n let innerPublisherState:\n | {\n readonly dispose: () => void;\n numSubscribers: number;\n }\n | undefined;\n const eventTarget = new EventTarget();\n const demultiplexedDataPublisher = getDataPublisherFromEventEmitter(eventTarget);\n return {\n ...demultiplexedDataPublisher,\n on(channelName, subscriber, options) {\n if (!innerPublisherState) {\n const innerPublisherUnsubscribe = publisher.on(sourceChannelName, sourceMessage => {\n const transformResult = messageTransformer(sourceMessage);\n if (!transformResult) {\n return;\n }\n const [destinationChannelName, message] = transformResult;\n eventTarget.dispatchEvent(\n new CustomEvent(destinationChannelName, {\n detail: message,\n }),\n );\n });\n innerPublisherState = {\n dispose: innerPublisherUnsubscribe,\n numSubscribers: 0,\n };\n }\n innerPublisherState.numSubscribers++;\n const unsubscribe = demultiplexedDataPublisher.on(channelName, subscriber, options);\n let isActive = true;\n function handleUnsubscribe() {\n if (!isActive) {\n return;\n }\n isActive = false;\n options?.signal.removeEventListener('abort', handleUnsubscribe);\n innerPublisherState!.numSubscribers--;\n if (innerPublisherState!.numSubscribers === 0) {\n innerPublisherState!.dispose();\n innerPublisherState = undefined;\n }\n unsubscribe();\n }\n options?.signal.addEventListener('abort', handleUnsubscribe);\n return handleUnsubscribe;\n },\n };\n}\n","import { AbortController } from '@solana/event-target-impl';\n\nimport { DataPublisher } from './data-publisher';\n\ntype FactoryConfig = Readonly<{\n // FIXME: It would be nice to be able to constrain the type returned by `createDataPublisher` to one that\n // definitely supports the `dataChannelName` and `errorChannelName` channels, and\n // furthermore publishes `TData` on the `dataChannelName` channel. This is more difficult\n // than it should be: https://tsplay.dev/NlZelW\n /**\n * An async factory that produces a fresh {@link DataPublisher} each time it is invoked. Called\n * on every {@link ReactiveStreamStore.connect | `connect()`}.\n *\n * Receives an {@link AbortSignal} that fires when this specific connection window should tear\n * down — composed from the per-connection inner controller and (if attached via\n * {@link ReactiveStreamStore.withSignal | `withSignal()`}) the caller-provided signal via\n * `AbortSignal.any`. Thread it into the underlying transport's own cancellation so the\n * connection itself stops on per-connection abort, not just the stream-store's listeners.\n * Rejections surface as a store error.\n */\n createDataPublisher: (signal: AbortSignal) => Promise<DataPublisher>;\n /**\n * Messages from this channel of the produced `DataPublisher` will be used to update the store's\n * state.\n */\n dataChannelName: string;\n /**\n * Messages from this channel of the produced `DataPublisher` will transition the store to an\n * error state, preserving the last known value.\n */\n errorChannelName: string;\n}>;\n\n/**\n * The lifecycle state of a {@link ReactiveStreamStore} as a single snapshot.\n *\n * - `idle`: the store has not yet been connected, or has been reset via\n * {@link ReactiveStreamStore.reset | `reset()`}. Call\n * {@link ReactiveStreamStore.connect | `connect()`} to open the underlying stream.\n * - `loading`: a connection is in progress. `data` and `error` are preserved from the previous\n * connection (if any) — stale-while-revalidate UX. A subsequent `loaded` clears `error`; a\n * subsequent `error` replaces it.\n * - `loaded`: a value has been received and no error is active.\n * - `error`: the stream failed. `data` holds the last known value (or `undefined` if none ever\n * arrived) and `error` holds the failure.\n */\nexport type ReactiveState<T> =\n | { readonly data: T | undefined; readonly error: unknown; readonly status: 'error' }\n | { readonly data: T | undefined; readonly error: unknown; readonly status: 'loading' }\n | { readonly data: T; readonly error: undefined; readonly status: 'loaded' }\n | { readonly data: undefined; readonly error: undefined; readonly status: 'idle' };\n\nconst IDLE_STATE: ReactiveState<never> = Object.freeze({\n data: undefined,\n error: undefined,\n status: 'idle',\n});\n\n/**\n * A reactive store that holds the latest value published to a data channel and allows external\n * systems to subscribe to changes. Compatible with `useSyncExternalStore`, Svelte stores, Solid's\n * `from()`, and other reactive primitives that expect a `{ subscribe, getUnifiedState }` contract.\n *\n * The store starts in `status: 'idle'`. Call {@link ReactiveStreamStore.connect | `connect()`}\n * to open the underlying stream; the store transitions through `loading` → `loaded` (or `error`).\n * Subsequent `connect()` calls also pass through `loading` while preserving the last known\n * `data` and `error` (stale-while-revalidate).\n *\n * @example\n * ```ts\n * // React — the unified state snapshot has stable identity per update, making it suitable as\n * // the second argument to `useSyncExternalStore`.\n * const state = useSyncExternalStore(store.subscribe, store.getUnifiedState);\n * useEffect(() => {\n * store.connect();\n * return () => store.reset();\n * }, [store]);\n * if (state.status === 'error') return <ErrorMessage error={state.error} onRetry={store.connect} />;\n * if (state.status === 'loading' || state.status === 'idle') return <Spinner />;\n * return <View data={state.data} />;\n * ```\n *\n * @see {@link createReactiveStoreFromDataPublisherFactory}\n */\nexport type ReactiveStreamStore<T> = {\n /**\n * Open the underlying stream. Aborts any currently active connection, invokes the configured\n * factory, and transitions the store to `loading` (preserving the last known `data` and\n * `error` for stale-while-revalidate) before settling into `loaded` (on data) or `error`\n * (on failure).\n */\n connect(): void;\n /**\n * Returns the error published to the error channel, or `undefined` if no error has occurred.\n *\n * @deprecated Use {@link ReactiveStreamStore.getUnifiedState | `getUnifiedState()`} instead. This\n * getter returns only the error field and cannot narrow the relationship between the current\n * value, error, and status.\n */\n getError(): unknown;\n /**\n * Returns the most recent value published to the data channel, or `undefined` if no\n * notification has arrived yet. On error, continues to return the last known value.\n *\n * @deprecated Use {@link ReactiveStreamStore.getUnifiedState | `getUnifiedState()`} instead. This\n * getter returns only the value field and does not surface lifecycle status (e.g. `loading`).\n */\n getState(): T | undefined;\n /**\n * Returns the current lifecycle snapshot: `{ data, error, status }`. The returned object has\n * stable identity between state changes, making it safe to pass directly as the\n * `getSnapshot` argument to React's `useSyncExternalStore`.\n *\n * @see {@link ReactiveState}\n */\n getUnifiedState(): ReactiveState<T>;\n /**\n * Aborts any currently active connection and resets the store to `{ status: 'idle' }`. Both\n * `data` and `error` are cleared. Use this to tear down the connection without permanently\n * killing the store — a follow-up {@link ReactiveStreamStore.connect | `connect()`} will open\n * a fresh stream.\n */\n reset(): void;\n /**\n * Re-opens the stream after an error. No-op when the store is not in `status: 'error'`.\n *\n * @deprecated Use {@link ReactiveStreamStore.connect | `connect()`} instead. `connect()`\n * always (re)connects, regardless of current status — wrap with a status guard at the call\n * site if you need the error-only behaviour.\n */\n retry(): void;\n /**\n * Registers a callback to be called whenever the state changes or an error is received.\n * Returns an unsubscribe function. Safe to call multiple times.\n */\n subscribe(callback: () => void): () => void;\n /**\n * Returns a thin wrapper exposing `connect()` that composes `signal` with the store's internal\n * per-connection controller via `AbortSignal.any` — aborting either tears down the active\n * connection. Aborting the caller-provided signal surfaces the abort reason on state as\n * `{ status: 'error' }`; the internal controller path (supersession by a newer `connect()` or\n * `reset()`) is silent by design so the newer call owns state. Use this to attach a\n * caller-provided cancellation source (per-connection timeout, shared kill switch,\n * parent-context signal) without touching the bare `connect()` API.\n *\n * - Per-connection timeout: `store.withSignal(AbortSignal.timeout(30_000)).connect()` — fresh\n * clock per call.\n * - Permanent kill switch: hold one `AbortController`, bind the wrapper once\n * (`const killable = store.withSignal(killCtrl.signal)`), and use `killable.connect()`\n * everywhere; aborting the controller cancels the active connection and short-circuits\n * future calls through the bound wrapper.\n *\n * The wrapper exposes only `connect()` — `getUnifiedState` / `subscribe` / `reset` remain\n * store-level concerns on the parent.\n */\n withSignal(signal: AbortSignal): { readonly connect: () => void };\n};\n\n/**\n * @deprecated Use {@link ReactiveStreamStore} instead. This alias will be removed in a future\n * major release.\n */\nexport type ReactiveStore<T> = ReactiveStreamStore<T>;\n\n/**\n * Duck-type for objects that build a {@link ReactiveStreamStore} on demand via a `reactiveStore()`\n * method. Satisfied by `PendingRpcSubscriptionsRequest<T>`. Reactive-framework bindings (e.g.\n * React's `useSubscription`) consume this duck-type so they don't have to name a concrete producer\n * type.\n *\n * The returned store is in `status: 'idle'` — the caller is responsible for invoking\n * {@link ReactiveStreamStore.connect | `connect()`} to open the underlying stream. Attach a\n * caller-provided cancellation source via {@link ReactiveStreamStore.withSignal | `withSignal()`}\n * — `store.withSignal(signal).connect()`.\n *\n * @typeParam T - The value type emitted by the resulting stream store.\n *\n * @example\n * ```ts\n * function bindWithTimeout<T>(source: ReactiveStreamSource<T>) {\n * const store = source.reactiveStore();\n * store.withSignal(AbortSignal.timeout(30_000)).connect();\n * return store;\n * }\n * ```\n *\n * @see {@link ReactiveStreamStore}\n * @see {@link ReactiveActionSource}\n */\nexport type ReactiveStreamSource<T> = {\n reactiveStore(): ReactiveStreamStore<T>;\n};\n\n/**\n * Returns a {@link ReactiveStreamStore} that wires itself to a fresh {@link DataPublisher} on\n * every {@link ReactiveStreamStore.connect | `connect()`}.\n *\n * The store accepts a `createDataPublisher` factory rather than a ready-made publisher — that\n * lets the store tear down a broken stream and open a new one without losing subscribers or the\n * last known value. The factory receives the per-connection signal so the underlying transport\n * can stop on per-connection abort, not just the stream-store's listeners.\n *\n * Things to note:\n *\n * - The returned store starts in `status: 'idle'`. Call `connect()` to open the first stream.\n * - `createDataPublisher` is invoked on every `connect()`. The store transitions through\n * `loading`, preserving the last known `data` and `error` (stale-while-revalidate).\n * - If `createDataPublisher` rejects, the store transitions to `status: 'error'` with the\n * rejection as the error. Call `connect()` to try again.\n * - `reset()` aborts the current connection and returns the store to `idle`, clearing `data`\n * and `error`. A follow-up `connect()` opens a fresh stream.\n * - Attach a caller-provided cancellation source via\n * {@link ReactiveStreamStore.withSignal | `withSignal()`} — `store.withSignal(signal).connect()`\n * composes the signal with the per-connection controller. Aborting the caller's signal\n * transitions the store to `error` with that abort reason.\n *\n * @param config\n *\n * @example\n * ```ts\n * const store = createReactiveStoreFromDataPublisherFactory({\n * createDataPublisher: signal => getDataPublisherFromEventEmitter(new WebSocket(url, { signal })),\n * dataChannelName: 'message',\n * errorChannelName: 'error',\n * });\n * const unsubscribe = store.subscribe(() => {\n * const snapshot = store.getUnifiedState();\n * if (snapshot.status === 'error') console.error('Connection failed:', snapshot.error);\n * else if (snapshot.status === 'loaded') console.log('Latest:', snapshot.data);\n * });\n * // Fresh 30-second clock per connection attempt:\n * store.withSignal(AbortSignal.timeout(30_000)).connect();\n * ```\n */\nexport function createReactiveStoreFromDataPublisherFactory<TData>({\n createDataPublisher,\n dataChannelName,\n errorChannelName,\n}: FactoryConfig): ReactiveStreamStore<TData> {\n let currentState: ReactiveState<TData> = IDLE_STATE;\n let currentInnerController: AbortController | undefined;\n const subscribers = new Set<() => void>();\n\n function notify() {\n subscribers.forEach(cb => cb());\n }\n\n function setState(next: ReactiveState<TData>) {\n if (\n currentState.status === next.status &&\n currentState.data === next.data &&\n currentState.error === next.error\n ) {\n return;\n }\n currentState = next;\n notify();\n }\n\n function performConnect(callerSignal: AbortSignal | undefined) {\n // Abort any currently active connection before starting a fresh one.\n currentInnerController?.abort();\n // If the caller's signal is already aborted, surface as error and bail.\n if (callerSignal?.aborted) {\n setState({ data: currentState.data, error: callerSignal.reason, status: 'error' });\n return;\n }\n // Transition to `loading`, preserving the last known `data` and `error` for SWR. If\n // already `loading` with the same data/error, `setState` no-ops — no spurious notify.\n setState({ data: currentState.data, error: currentState.error, status: 'loading' });\n // Inner signal is passed to the data publisher (composed with caller signal if any).\n const innerController = new AbortController();\n currentInnerController = innerController;\n const signal = callerSignal ? AbortSignal.any([innerController.signal, callerSignal]) : innerController.signal;\n // Caller's signal aborting (not just supersede via the inner controller) transitions the\n // store to error with the caller's abort reason. Scoped to the inner signal so the\n // listener is removed automatically on reconnect / reset.\n if (callerSignal) {\n callerSignal.addEventListener(\n 'abort',\n () => {\n if (innerController.signal.aborted) return;\n setState({ data: currentState.data, error: callerSignal.reason, status: 'error' });\n innerController.abort(callerSignal.reason);\n },\n { signal: innerController.signal },\n );\n }\n createDataPublisher(signal).then(\n publisher => {\n if (signal.aborted) return;\n publisher.on(\n dataChannelName,\n data => {\n setState({ data: data as TData, error: undefined, status: 'loaded' });\n },\n { signal },\n );\n publisher.on(\n errorChannelName,\n err => {\n if (currentState.status === 'error') return;\n setState({ data: currentState.data, error: err, status: 'error' });\n innerController.abort(err);\n },\n { signal },\n );\n },\n err => {\n if (signal.aborted) return;\n setState({ data: currentState.data, error: err, status: 'error' });\n innerController.abort(err);\n },\n );\n }\n\n function performReset() {\n currentInnerController?.abort();\n currentInnerController = undefined;\n setState(IDLE_STATE);\n }\n\n return {\n connect(): void {\n performConnect(undefined);\n },\n getError(): unknown {\n return currentState.error;\n },\n getState(): TData | undefined {\n return currentState.data;\n },\n getUnifiedState(): ReactiveState<TData> {\n return currentState;\n },\n reset: performReset,\n retry(): void {\n if (currentState.status !== 'error') return;\n performConnect(undefined);\n },\n subscribe(callback: () => void): () => void {\n subscribers.add(callback);\n return () => {\n subscribers.delete(callback);\n };\n },\n withSignal(signal: AbortSignal) {\n return {\n connect(): void {\n performConnect(signal);\n },\n };\n },\n };\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../../event-target-impl/src/index.browser.ts","../src/reactive-action-store.ts","../src/async-iterable.ts","../src/data-publisher.ts","../src/demultiplex.ts","../src/reactive-stream-store.ts"],"names":["AbortController","EventTarget","getAbortablePromise","SolanaError","SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING","SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE","IDLE_STATE"],"mappings":";;;;;;AAAO,IAAMA,IAAkB,UAAA,CAAW,eAAA;AAAnC,IACMC,IAAc,UAAA,CAAW,WAAA;AC2GtC,IAAM,UAAA,GAAyC,OAAO,MAAA,CAAO;AAAA,EACzD,IAAA,EAAM,MAAA;AAAA,EACN,KAAA,EAAO,MAAA;AAAA,EACP,MAAA,EAAQ;AACZ,CAAC,CAAA;AAsCM,SAAS,0BACZ,EAAA,EACmC;AACnC,EAAA,IAAI,KAAA,GAAsC,UAAA;AAC1C,EAAA,IAAI,iBAAA;AACJ,EAAA,MAAM,SAAA,uBAAgB,GAAA,EAAgB;AAEtC,EAAA,SAAS,SAAS,IAAA,EAAoC;AAClD,IAAA,IAAI,KAAA,CAAM,MAAA,KAAW,IAAA,CAAK,MAAA,IAAU,KAAA,CAAM,IAAA,KAAS,IAAA,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AAAA,IACA,KAAA,EAAO,YAAA;AAAA,IACP,UAAU,QAAA,EAAkC;AACxC,MAAA,WAAA,CAAY,IAAI,QAAQ,CAAA;AACxB,MAAA,OAAO,MAAM;AACT,QAAA,WAAA,CAAY,OAAO,QAAQ,CAAA;AAAA,MAC/B,CAAA;AAAA,IACJ,CAAA;AAAA,IACA,WAAW,MAAA,EAAqB;AAC5B,MAAA,OAAO;AAAA,QACH,OAAA,GAAgB;AACZ,UAAA,cAAA,CAAe,MAAM,CAAA;AAAA,QACzB;AAAA,OACJ;AAAA,IACJ;AAAA,GACJ;AACJ","file":"index.browser.cjs","sourcesContent":["export const AbortController = globalThis.AbortController;\nexport const EventTarget = globalThis.EventTarget;\n","import { AbortController } from '@solana/event-target-impl';\nimport { getAbortablePromise } from '@solana/promises';\n\n/** Lifecycle status of a {@link ReactiveActionStore}. */\nexport type ReactiveActionStatus = 'error' | 'idle' | 'running' | 'success';\n\n/**\n * Discriminated state of a {@link ReactiveActionStore}, keyed by {@link ReactiveActionStatus}.\n *\n * `data` holds the most recent successful result and `error` holds the most recent failure. Both\n * persist through subsequent `running` states so call sites can keep rendering stale content\n * while a retry is in flight. `success` clears `error`; only `reset()` clears `data`.\n */\nexport type ReactiveActionState<TResult> =\n | { readonly data: TResult | undefined; readonly error: unknown; readonly status: 'error' }\n | { readonly data: TResult | undefined; readonly error: unknown; readonly status: 'running' }\n | { readonly data: TResult; readonly error: undefined; readonly status: 'success' }\n | { readonly data: undefined; readonly error: undefined; readonly status: 'idle' };\n\n/**\n * A framework-agnostic state machine that wraps an async function and exposes a\n * `{ dispatch, getState, subscribe, reset }` contract. Bridges trivially into\n * `useSyncExternalStore`, Svelte stores, Vue's `shallowRef`, and similar reactive primitives.\n *\n * @see {@link createReactiveActionStore}\n */\nexport type ReactiveActionStore<TArgs extends readonly unknown[], TResult> = {\n /**\n * Fire-and-forget dispatch. Returns `undefined` synchronously and never throws — failures\n * surface on state as `{ status: 'error' }`, and superseded or `reset()`-aborted calls produce\n * no state update. Use from UI event handlers; there's no promise to handle or `.catch`.\n *\n * @see {@link ReactiveActionStore.dispatchAsync} when you need the resolved value or propagated errors.\n * @see {@link ReactiveActionStore.withSignal} to attach a caller-provided `AbortSignal` to a dispatch.\n */\n readonly dispatch: (...args: TArgs) => void;\n /**\n * Promise-returning dispatch for imperative callers. Resolves with the wrapped function's\n * result on success. Rejects with the thrown error on failure, and with an `AbortError` when\n * the call is superseded or `reset()` is invoked — filter those with `isAbortError` from\n * `@solana/promises`.\n */\n readonly dispatchAsync: (...args: TArgs) => Promise<TResult>;\n /**\n * Returns the current lifecycle snapshot: `{ data, error, status }`. The returned object has\n * stable identity between state changes, making it safe to pass directly as the\n * `getSnapshot` argument to React's `useSyncExternalStore`.\n *\n * @see {@link ReactiveActionState}\n */\n readonly getState: () => ReactiveActionState<TResult>;\n /** Aborts any in-flight dispatch and resets the state to `{ status: 'idle' }`. */\n readonly reset: () => void;\n /** Registers a listener called on every state change. Returns an unsubscribe function. */\n readonly subscribe: (listener: () => void) => () => void;\n /**\n * Returns a thin wrapper exposing `dispatch` / `dispatchAsync` that compose `signal` with the\n * store's internal per-dispatch controller via `AbortSignal.any` — aborting either cancels\n * the in-flight call. Aborting the caller-provided signal surfaces the abort reason on state\n * as `{ status: 'error' }`; the internal controller path (supersession by a newer dispatch or\n * `reset()`) is silent by design so the newer dispatch owns state. Use this to attach a\n * caller-provided cancellation source (per-attempt timeout, shared kill switch, parent-context\n * signal) without touching the bare `dispatch` / `dispatchAsync` API.\n *\n * - Per-attempt timeout: `store.withSignal(AbortSignal.timeout(5_000)).dispatch(args)` — fresh\n * clock per call.\n * - Permanent kill switch: hold one `AbortController`, bind the wrapper once\n * (`const killable = store.withSignal(killCtrl.signal)`), and use `killable.dispatch(...)`\n * everywhere; aborting the controller cancels in-flight and short-circuits future calls.\n *\n * The wrapper exposes only `dispatch` / `dispatchAsync` — `getState` / `subscribe` / `reset`\n * remain store-level concerns on the parent.\n */\n readonly withSignal: (signal: AbortSignal) => {\n readonly dispatch: (...args: TArgs) => void;\n readonly dispatchAsync: (...args: TArgs) => Promise<TResult>;\n };\n};\n\n/**\n * Duck-type for objects that build a {@link ReactiveActionStore} on demand via `reactiveStore()`.\n * Satisfied by `PendingRpcRequest<T>`. The `[]` argument tuple is intentional — the operation's\n * arguments are already baked into the pending request, so each `dispatch()` re-fires the same\n * call.\n *\n * The returned store is in the `idle` state — the caller is responsible for calling `dispatch()`\n * to fire the first attempt. Attach a caller-provided cancellation source per dispatch via\n * `store.withSignal(signal).dispatch(...)` — see {@link ReactiveActionStore.withSignal}.\n *\n * @typeParam T - The value type resolved by the wrapped operation.\n *\n * @example\n * ```ts\n * function bind<T>(source: ReactiveActionSource<T>) {\n * const store = source.reactiveStore();\n * // Per-attempt timeout, fresh signal per call:\n * store.withSignal(AbortSignal.timeout(30_000)).dispatch();\n * return store;\n * }\n * ```\n *\n * @see {@link ReactiveActionStore}\n * @see {@link ReactiveStreamSource}\n */\nexport type ReactiveActionSource<T> = {\n reactiveStore(): ReactiveActionStore<[], T>;\n};\n\nconst IDLE_STATE: ReactiveActionState<never> = Object.freeze({\n data: undefined,\n error: undefined,\n status: 'idle',\n});\n\n/**\n * Wraps an async function in a {@link ReactiveActionStore}. Each `dispatch` creates a fresh\n * {@link AbortController} and aborts the previous one; the superseded call's outcome is dropped,\n * so only the most recent dispatch can mutate state.\n *\n * The wrapped function receives the `AbortSignal` as its first argument, followed by whatever\n * arguments were passed to `dispatch`. Callers attach their own cancellation source per-call via\n * {@link ReactiveActionStore.withSignal} — `store.withSignal(signal).dispatch(...)`. The caller's\n * signal is composed with the per-dispatch controller via `AbortSignal.any`, so aborting it\n * cancels the in-flight call and surfaces the abort reason on state.\n *\n * @typeParam TArgs - Argument tuple forwarded from `dispatch` to `fn`.\n * @typeParam TResult - Resolved value type of `fn`.\n * @param fn - Async function to wrap. Receives an {@link AbortSignal} plus the dispatch arguments.\n * @return A {@link ReactiveActionStore} exposing `dispatch`, `dispatchAsync`, `getState`, `subscribe`,\n * `reset`, and `withSignal`.\n *\n * @example\n * ```ts\n * const store = createReactiveActionStore(async (signal, accountId: Address) => {\n * const response = await fetch(`/api/accounts/${accountId}`, { signal });\n * return response.json();\n * });\n *\n * store.subscribe(() => console.log(store.getState()));\n * store.dispatch(someAccountId); // fire-and-forget; state is the source of truth\n *\n * // Per-attempt timeout — fresh signal per call:\n * store.withSignal(AbortSignal.timeout(30_000)).dispatch(someAccountId);\n *\n * // Imperative call with the resolved value:\n * const account = await store.dispatchAsync(someAccountId);\n * ```\n *\n * @see {@link ReactiveActionStore}\n */\nexport function createReactiveActionStore<TArgs extends readonly unknown[], TResult>(\n fn: (signal: AbortSignal, ...args: TArgs) => Promise<TResult>,\n): ReactiveActionStore<TArgs, TResult> {\n let state: ReactiveActionState<TResult> = IDLE_STATE;\n let currentController: AbortController | undefined;\n const listeners = new Set<() => void>();\n\n function setState(next: ReactiveActionState<TResult>) {\n if (state.status === next.status && state.data === next.data && state.error === next.error) {\n return;\n }\n state = next;\n listeners.forEach(listener => listener());\n }\n\n const dispatchAsyncWithSignal = async (userSignal: AbortSignal | undefined, ...args: TArgs): Promise<TResult> => {\n currentController?.abort();\n // If the caller's signal is already aborted, surface as error and bail.\n if (userSignal?.aborted) {\n setState({ data: state.data, error: userSignal.reason, status: 'error' });\n throw userSignal.reason;\n }\n const controller = new AbortController();\n currentController = controller;\n const signal = userSignal ? AbortSignal.any([controller.signal, userSignal]) : controller.signal;\n const previousData = state.data;\n const previousError = state.error;\n setState({ data: previousData, error: previousError, status: 'running' });\n try {\n const result = await getAbortablePromise(fn(signal, ...args), signal);\n if (signal.aborted) {\n throw signal.reason;\n }\n setState({ data: result, error: undefined, status: 'success' });\n return result;\n } catch (error) {\n // Superseded by a newer dispatch or `reset()` — drop silently so only the most recent\n // dispatch mutates state, and reject with the abort reason rather than any underlying\n // failure that happened to race the abort.\n if (controller.signal.aborted) {\n throw controller.signal.reason;\n }\n // Real failure or the caller-provided signal firing — surface as error state.\n setState({ data: previousData, error, status: 'error' });\n throw error;\n }\n };\n\n const dispatchAsync = (...args: TArgs): Promise<TResult> => dispatchAsyncWithSignal(undefined, ...args);\n const dispatch = (...args: TArgs): void => {\n dispatchAsync(...args).catch(() => {});\n };\n\n return {\n dispatch,\n dispatchAsync,\n getState: () => state,\n reset: () => {\n currentController?.abort();\n currentController = undefined;\n setState(IDLE_STATE);\n },\n subscribe: listener => {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n withSignal: (signal: AbortSignal) => ({\n dispatch: (...args: TArgs): void => {\n dispatchAsyncWithSignal(signal, ...args).catch(() => {});\n },\n dispatchAsync: (...args: TArgs): Promise<TResult> => dispatchAsyncWithSignal(signal, ...args),\n }),\n };\n}\n","import {\n SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE,\n SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING,\n SolanaError,\n} from '@solana/errors';\nimport { AbortController } from '@solana/event-target-impl';\n\nimport { DataPublisher } from './data-publisher';\n\ntype Config = Readonly<{\n /**\n * Triggering this abort signal will cause all iterators spawned from this iterator to return\n * once they have published all queued messages.\n */\n abortSignal: AbortSignal;\n /**\n * Messages from this channel of `dataPublisher` will be the ones yielded through the iterators.\n *\n * Messages only begin to be queued after the first time an iterator begins to poll. Channel\n * messages published before that time will be dropped.\n */\n dataChannelName: string;\n // FIXME: It would be nice to be able to constrain the type of `dataPublisher` to one that\n // definitely supports the `dataChannelName` and `errorChannelName` channels, and\n // furthermore publishes `TData` on the `dataChannelName` channel. This is more difficult\n // than it should be: https://tsplay.dev/NlZelW\n dataPublisher: DataPublisher;\n /**\n * Messages from this channel of `dataPublisher` will be the ones thrown through the iterators.\n *\n * Any new iterators created after the first error is encountered will reject with that error\n * when polled.\n */\n errorChannelName: string;\n}>;\n\nconst enum PublishType {\n DATA,\n ERROR,\n}\n\ntype IteratorKey = symbol;\ntype IteratorState<TData> =\n | {\n __hasPolled: false;\n publishQueue: (\n | {\n __type: PublishType.DATA;\n data: TData;\n }\n | {\n __type: PublishType.ERROR;\n err: unknown;\n }\n )[];\n }\n | {\n __hasPolled: true;\n onData: (data: TData) => void;\n onError: Parameters<ConstructorParameters<typeof Promise>[0]>[1];\n };\n\nlet EXPLICIT_ABORT_TOKEN: symbol;\nfunction createExplicitAbortToken() {\n // This function is an annoying workaround to prevent `process.env.NODE_ENV` from appearing at\n // the top level of this module and thwarting an optimizing compiler's attempt to tree-shake.\n return Symbol(\n process.env.NODE_ENV !== \"production\"\n ? \"This symbol is thrown from a socket's iterator when the connection is explicitly \" +\n 'aborted by the user'\n : undefined,\n );\n}\n\nconst UNINITIALIZED = Symbol();\n\n/**\n * Returns an `AsyncIterable` given a data publisher.\n *\n * The iterable will produce iterators that vend messages published to `dataChannelName` and will\n * throw the first time a message is published to `errorChannelName`. Triggering the abort signal\n * will cause all iterators spawned from this iterator to return once they have published all queued\n * messages.\n *\n * Things to note:\n *\n * - If a message is published over a channel before the `AsyncIterator` attached to it has polled\n * for the next result, the message will be queued in memory.\n * - Messages only begin to be queued after the first time an iterator begins to poll. Channel\n * messages published before that time will be dropped.\n * - If there are messages in the queue and an error occurs, all queued messages will be vended to\n * the iterator before the error is thrown.\n * - If there are messages in the queue and the abort signal fires, all queued messages will be\n * vended to the iterator after which it will return.\n * - Any new iterators created after the first error is encountered will reject with that error when\n * polled.\n *\n * @param config\n *\n * @example\n * ```ts\n * const iterable = createAsyncIterableFromDataPublisher({\n * abortSignal: AbortSignal.timeout(10_000),\n * dataChannelName: 'message',\n * dataPublisher,\n * errorChannelName: 'error',\n * });\n * try {\n * for await (const message of iterable) {\n * console.log('Got message', message);\n * }\n * } catch (e) {\n * console.error('An error was published to the error channel', e);\n * } finally {\n * console.log(\"It's been 10 seconds; that's enough for now.\");\n * }\n * ```\n */\nexport function createAsyncIterableFromDataPublisher<TData>({\n abortSignal,\n dataChannelName,\n dataPublisher,\n errorChannelName,\n}: Config): AsyncIterable<TData> {\n const iteratorState: Map<IteratorKey, IteratorState<TData>> = new Map();\n function publishErrorToAllIterators(reason: unknown) {\n for (const [iteratorKey, state] of iteratorState.entries()) {\n if (state.__hasPolled) {\n iteratorState.delete(iteratorKey);\n state.onError(reason);\n } else {\n state.publishQueue.push({\n __type: PublishType.ERROR,\n err: reason,\n });\n }\n }\n }\n const abortController = new AbortController();\n abortSignal.addEventListener('abort', () => {\n abortController.abort();\n publishErrorToAllIterators((EXPLICIT_ABORT_TOKEN ||= createExplicitAbortToken()));\n });\n const options = { signal: abortController.signal } as const;\n let firstError: unknown = UNINITIALIZED;\n dataPublisher.on(\n errorChannelName,\n err => {\n if (firstError === UNINITIALIZED) {\n firstError = err;\n abortController.abort();\n publishErrorToAllIterators(err);\n }\n },\n options,\n );\n dataPublisher.on(\n dataChannelName,\n data => {\n iteratorState.forEach((state, iteratorKey) => {\n if (state.__hasPolled) {\n const { onData } = state;\n iteratorState.set(iteratorKey, { __hasPolled: false, publishQueue: [] });\n onData(data as TData);\n } else {\n state.publishQueue.push({\n __type: PublishType.DATA,\n data: data as TData,\n });\n }\n });\n },\n options,\n );\n return {\n async *[Symbol.asyncIterator]() {\n if (abortSignal.aborted) {\n return;\n }\n if (firstError !== UNINITIALIZED) {\n throw firstError;\n }\n const iteratorKey = Symbol();\n iteratorState.set(iteratorKey, { __hasPolled: false, publishQueue: [] });\n try {\n while (true) {\n const state = iteratorState.get(iteratorKey);\n if (!state) {\n // There should always be state by now.\n throw new SolanaError(SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_STATE_MISSING);\n }\n if (state.__hasPolled) {\n // You should never be able to poll twice in a row.\n throw new SolanaError(\n SOLANA_ERROR__INVARIANT_VIOLATION__SUBSCRIPTION_ITERATOR_MUST_NOT_POLL_BEFORE_RESOLVING_EXISTING_MESSAGE_PROMISE,\n );\n }\n const publishQueue = state.publishQueue;\n try {\n if (publishQueue.length) {\n state.publishQueue = [];\n for (const item of publishQueue) {\n if (item.__type === PublishType.DATA) {\n yield item.data;\n } else {\n throw item.err;\n }\n }\n } else {\n yield await new Promise<TData>((resolve, reject) => {\n iteratorState.set(iteratorKey, {\n __hasPolled: true,\n onData: resolve,\n onError: reject,\n });\n });\n }\n } catch (e) {\n if (e === (EXPLICIT_ABORT_TOKEN ||= createExplicitAbortToken())) {\n return;\n } else {\n throw e;\n }\n }\n }\n } finally {\n iteratorState.delete(iteratorKey);\n }\n },\n };\n}\n","import { TypedEventEmitter, TypedEventTarget } from './event-emitter';\n\ntype UnsubscribeFn = () => void;\n\n/**\n * Represents an object with an `on` function that you can call to subscribe to certain data over a\n * named channel.\n *\n * @example\n * ```ts\n * let dataPublisher: DataPublisher<{ error: SolanaError }>;\n * dataPublisher.on('data', handleData); // ERROR. `data` is not a known channel name.\n * dataPublisher.on('error', e => {\n * console.error(e);\n * }); // OK.\n * ```\n */\nexport interface DataPublisher<TDataByChannelName extends Record<string, unknown> = Record<string, unknown>> {\n /**\n * Call this to subscribe to data over a named channel.\n *\n * @param channelName The name of the channel on which to subscribe for messages\n * @param subscriber The function to call when a message becomes available\n * @param options.signal An abort signal you can fire to unsubscribe\n *\n * @returns A function that you can call to unsubscribe\n */\n on<const TChannelName extends keyof TDataByChannelName>(\n channelName: TChannelName,\n subscriber: (data: TDataByChannelName[TChannelName]) => void,\n options?: { signal: AbortSignal },\n ): UnsubscribeFn;\n}\n\n/**\n * Returns an object with an `on` function that you can call to subscribe to certain data over a\n * named channel.\n *\n * The `on` function returns an unsubscribe function.\n *\n * @example\n * ```ts\n * const socketDataPublisher = getDataPublisherFromEventEmitter(new WebSocket('wss://api.devnet.solana.com'));\n * const unsubscribe = socketDataPublisher.on('message', message => {\n * if (JSON.parse(message.data).id === 42) {\n * console.log('Got response 42');\n * unsubscribe();\n * }\n * });\n * ```\n */\nexport function getDataPublisherFromEventEmitter<TEventMap extends Record<string, Event>>(\n eventEmitter: TypedEventEmitter<TEventMap> | TypedEventTarget<TEventMap>,\n): DataPublisher<{\n [TEventType in keyof TEventMap]: TEventMap[TEventType] extends CustomEvent ? TEventMap[TEventType]['detail'] : null;\n}> {\n return {\n on(channelName, subscriber, options) {\n function innerListener(ev: Event) {\n if (ev instanceof CustomEvent) {\n const data = (ev as CustomEvent<TEventMap[typeof channelName]>).detail;\n (subscriber as unknown as (data: TEventMap[typeof channelName]) => void)(data);\n } else {\n (subscriber as () => void)();\n }\n }\n eventEmitter.addEventListener(channelName, innerListener, options);\n return () => {\n eventEmitter.removeEventListener(channelName, innerListener);\n };\n },\n };\n}\n","import { EventTarget } from '@solana/event-target-impl';\n\nimport { DataPublisher, getDataPublisherFromEventEmitter } from './data-publisher';\n\n/**\n * Given a channel that carries messages for multiple subscribers on a single channel name, this\n * function returns a new {@link DataPublisher} that splits them into multiple channel names.\n *\n * @param messageTransformer A function that receives the message as the first argument, and returns\n * a tuple of the derived channel name and the message.\n *\n * @example\n * Imagine a channel that carries multiple notifications whose destination is contained within the\n * message itself.\n *\n * ```ts\n * const demuxedDataPublisher = demultiplexDataPublisher(channel, 'message', message => {\n * const destinationChannelName = `notification-for:${message.subscriberId}`;\n * return [destinationChannelName, message];\n * });\n * ```\n *\n * Now you can subscribe to _only_ the messages you are interested in, without having to subscribe\n * to the entire `'message'` channel and filter out the messages that are not for you.\n *\n * ```ts\n * demuxedDataPublisher.on(\n * 'notification-for:123',\n * message => {\n * console.log('Got a message for subscriber 123', message);\n * },\n * { signal: AbortSignal.timeout(5_000) },\n * );\n * ```\n */\nexport function demultiplexDataPublisher<\n TDataPublisher extends DataPublisher,\n const TChannelName extends Parameters<TDataPublisher['on']>[0],\n>(\n publisher: TDataPublisher,\n sourceChannelName: TChannelName,\n messageTransformer: (\n // FIXME: Deriving the type of the message from `TDataPublisher` and `TChannelName` would\n // help callers to constrain their transform functions.\n message: unknown,\n ) => [destinationChannelName: string, message: unknown] | void,\n): DataPublisher {\n let innerPublisherState:\n | {\n readonly dispose: () => void;\n numSubscribers: number;\n }\n | undefined;\n const eventTarget = new EventTarget();\n const demultiplexedDataPublisher = getDataPublisherFromEventEmitter(eventTarget);\n return {\n ...demultiplexedDataPublisher,\n on(channelName, subscriber, options) {\n if (!innerPublisherState) {\n const innerPublisherUnsubscribe = publisher.on(sourceChannelName, sourceMessage => {\n const transformResult = messageTransformer(sourceMessage);\n if (!transformResult) {\n return;\n }\n const [destinationChannelName, message] = transformResult;\n eventTarget.dispatchEvent(\n new CustomEvent(destinationChannelName, {\n detail: message,\n }),\n );\n });\n innerPublisherState = {\n dispose: innerPublisherUnsubscribe,\n numSubscribers: 0,\n };\n }\n innerPublisherState.numSubscribers++;\n const unsubscribe = demultiplexedDataPublisher.on(channelName, subscriber, options);\n let isActive = true;\n function handleUnsubscribe() {\n if (!isActive) {\n return;\n }\n isActive = false;\n options?.signal.removeEventListener('abort', handleUnsubscribe);\n innerPublisherState!.numSubscribers--;\n if (innerPublisherState!.numSubscribers === 0) {\n innerPublisherState!.dispose();\n innerPublisherState = undefined;\n }\n unsubscribe();\n }\n options?.signal.addEventListener('abort', handleUnsubscribe);\n return handleUnsubscribe;\n },\n };\n}\n","import { AbortController } from '@solana/event-target-impl';\n\nimport { DataPublisher } from './data-publisher';\n\ntype FactoryConfig = Readonly<{\n // FIXME: It would be nice to be able to constrain the type returned by `createDataPublisher` to one that\n // definitely supports the `dataChannelName` and `errorChannelName` channels, and\n // furthermore publishes `TData` on the `dataChannelName` channel. This is more difficult\n // than it should be: https://tsplay.dev/NlZelW\n /**\n * An async factory that produces a fresh {@link DataPublisher} each time it is invoked. Called\n * on every {@link ReactiveStreamStore.connect | `connect()`}.\n *\n * Receives an {@link AbortSignal} that fires when this specific connection window should tear\n * down — composed from the per-connection inner controller and (if attached via\n * {@link ReactiveStreamStore.withSignal | `withSignal()`}) the caller-provided signal via\n * `AbortSignal.any`. Thread it into the underlying transport's own cancellation so the\n * connection itself stops on per-connection abort, not just the stream-store's listeners.\n * Rejections surface as a store error.\n */\n createDataPublisher: (signal: AbortSignal) => Promise<DataPublisher>;\n /**\n * Messages from this channel of the produced `DataPublisher` will be used to update the store's\n * state.\n */\n dataChannelName: string;\n /**\n * Messages from this channel of the produced `DataPublisher` will transition the store to an\n * error state, preserving the last known value.\n */\n errorChannelName: string;\n}>;\n\n/**\n * The lifecycle state of a {@link ReactiveStreamStore} as a single snapshot.\n *\n * - `idle`: the store has not yet been connected, or has been reset via\n * {@link ReactiveStreamStore.reset | `reset()`}. Call\n * {@link ReactiveStreamStore.connect | `connect()`} to open the underlying stream.\n * - `loading`: a connection is in progress. `data` and `error` are preserved from the previous\n * connection (if any) — stale-while-revalidate UX. A subsequent `loaded` clears `error`; a\n * subsequent `error` replaces it.\n * - `loaded`: a value has been received and no error is active.\n * - `error`: the stream failed. `data` holds the last known value (or `undefined` if none ever\n * arrived) and `error` holds the failure.\n */\nexport type ReactiveState<T> =\n | { readonly data: T | undefined; readonly error: unknown; readonly status: 'error' }\n | { readonly data: T | undefined; readonly error: unknown; readonly status: 'loading' }\n | { readonly data: T; readonly error: undefined; readonly status: 'loaded' }\n | { readonly data: undefined; readonly error: undefined; readonly status: 'idle' };\n\nconst IDLE_STATE: ReactiveState<never> = Object.freeze({\n data: undefined,\n error: undefined,\n status: 'idle',\n});\n\n/**\n * A reactive store that holds the latest value published to a data channel and allows external\n * systems to subscribe to changes. Compatible with `useSyncExternalStore`, Svelte stores, Solid's\n * `from()`, and other reactive primitives that expect a `{ subscribe, getState }` contract.\n *\n * The store starts in `status: 'idle'`. Call {@link ReactiveStreamStore.connect | `connect()`}\n * to open the underlying stream; the store transitions through `loading` → `loaded` (or `error`).\n * Subsequent `connect()` calls also pass through `loading` while preserving the last known\n * `data` and `error` (stale-while-revalidate).\n *\n * @example\n * ```ts\n * // React — the unified state snapshot has stable identity per update, making it suitable as\n * // the second argument to `useSyncExternalStore`.\n * const state = useSyncExternalStore(store.subscribe, store.getState);\n * useEffect(() => {\n * store.connect();\n * return () => store.reset();\n * }, [store]);\n * if (state.status === 'error') return <ErrorMessage error={state.error} onRetry={store.connect} />;\n * if (state.status === 'loading' || state.status === 'idle') return <Spinner />;\n * return <View data={state.data} />;\n * ```\n *\n * @see {@link createReactiveStoreFromDataPublisherFactory}\n */\nexport type ReactiveStreamStore<T> = {\n /**\n * Open the underlying stream. Aborts any currently active connection, invokes the configured\n * factory, and transitions the store to `loading` (preserving the last known `data` and\n * `error` for stale-while-revalidate) before settling into `loaded` (on data) or `error`\n * (on failure).\n */\n connect(): void;\n /**\n * Returns the current lifecycle snapshot: `{ data, error, status }`. The returned object has\n * stable identity between state changes, making it safe to pass directly as the\n * `getSnapshot` argument to React's `useSyncExternalStore`.\n *\n * @see {@link ReactiveState}\n */\n getState(): ReactiveState<T>;\n /**\n * Aborts any currently active connection and resets the store to `{ status: 'idle' }`. Both\n * `data` and `error` are cleared. Use this to tear down the connection without permanently\n * killing the store — a follow-up {@link ReactiveStreamStore.connect | `connect()`} will open\n * a fresh stream.\n */\n reset(): void;\n /**\n * Registers a callback to be called whenever the state changes or an error is received.\n * Returns an unsubscribe function. Safe to call multiple times.\n */\n subscribe(callback: () => void): () => void;\n /**\n * Returns a thin wrapper exposing `connect()` that composes `signal` with the store's internal\n * per-connection controller via `AbortSignal.any` — aborting either tears down the active\n * connection. Aborting the caller-provided signal surfaces the abort reason on state as\n * `{ status: 'error' }`; the internal controller path (supersession by a newer `connect()` or\n * `reset()`) is silent by design so the newer call owns state. Use this to attach a\n * caller-provided cancellation source (per-connection timeout, shared kill switch,\n * parent-context signal) without touching the bare `connect()` API.\n *\n * - Per-connection timeout: `store.withSignal(AbortSignal.timeout(30_000)).connect()` — fresh\n * clock per call.\n * - Permanent kill switch: hold one `AbortController`, bind the wrapper once\n * (`const killable = store.withSignal(killCtrl.signal)`), and use `killable.connect()`\n * everywhere; aborting the controller cancels the active connection and short-circuits\n * future calls through the bound wrapper.\n *\n * The wrapper exposes only `connect()` — `getState` / `subscribe` / `reset` remain\n * store-level concerns on the parent.\n */\n withSignal(signal: AbortSignal): { readonly connect: () => void };\n};\n\n/**\n * Duck-type for objects that build a {@link ReactiveStreamStore} on demand via a `reactiveStore()`\n * method. Satisfied by `PendingRpcSubscriptionsRequest<T>`. Reactive-framework bindings (e.g.\n * React's `useSubscription`) consume this duck-type so they don't have to name a concrete producer\n * type.\n *\n * The returned store is in `status: 'idle'` — the caller is responsible for invoking\n * {@link ReactiveStreamStore.connect | `connect()`} to open the underlying stream. Attach a\n * caller-provided cancellation source via {@link ReactiveStreamStore.withSignal | `withSignal()`}\n * — `store.withSignal(signal).connect()`.\n *\n * @typeParam T - The value type emitted by the resulting stream store.\n *\n * @example\n * ```ts\n * function bindWithTimeout<T>(source: ReactiveStreamSource<T>) {\n * const store = source.reactiveStore();\n * store.withSignal(AbortSignal.timeout(30_000)).connect();\n * return store;\n * }\n * ```\n *\n * @see {@link ReactiveStreamStore}\n * @see {@link ReactiveActionSource}\n */\nexport type ReactiveStreamSource<T> = {\n reactiveStore(): ReactiveStreamStore<T>;\n};\n\n/**\n * Returns a {@link ReactiveStreamStore} that wires itself to a fresh {@link DataPublisher} on\n * every {@link ReactiveStreamStore.connect | `connect()`}.\n *\n * The store accepts a `createDataPublisher` factory rather than a ready-made publisher — that\n * lets the store tear down a broken stream and open a new one without losing subscribers or the\n * last known value. The factory receives the per-connection signal so the underlying transport\n * can stop on per-connection abort, not just the stream-store's listeners.\n *\n * Things to note:\n *\n * - The returned store starts in `status: 'idle'`. Call `connect()` to open the first stream.\n * - `createDataPublisher` is invoked on every `connect()`. The store transitions through\n * `loading`, preserving the last known `data` and `error` (stale-while-revalidate).\n * - If `createDataPublisher` rejects, the store transitions to `status: 'error'` with the\n * rejection as the error. Call `connect()` to try again.\n * - `reset()` aborts the current connection and returns the store to `idle`, clearing `data`\n * and `error`. A follow-up `connect()` opens a fresh stream.\n * - Attach a caller-provided cancellation source via\n * {@link ReactiveStreamStore.withSignal | `withSignal()`} — `store.withSignal(signal).connect()`\n * composes the signal with the per-connection controller. Aborting the caller's signal\n * transitions the store to `error` with that abort reason.\n *\n * @param config\n *\n * @example\n * ```ts\n * const store = createReactiveStoreFromDataPublisherFactory({\n * createDataPublisher: signal => getDataPublisherFromEventEmitter(new WebSocket(url, { signal })),\n * dataChannelName: 'message',\n * errorChannelName: 'error',\n * });\n * const unsubscribe = store.subscribe(() => {\n * const snapshot = store.getState();\n * if (snapshot.status === 'error') console.error('Connection failed:', snapshot.error);\n * else if (snapshot.status === 'loaded') console.log('Latest:', snapshot.data);\n * });\n * // Fresh 30-second clock per connection attempt:\n * store.withSignal(AbortSignal.timeout(30_000)).connect();\n * ```\n */\nexport function createReactiveStoreFromDataPublisherFactory<TData>({\n createDataPublisher,\n dataChannelName,\n errorChannelName,\n}: FactoryConfig): ReactiveStreamStore<TData> {\n let currentState: ReactiveState<TData> = IDLE_STATE;\n let currentInnerController: AbortController | undefined;\n const subscribers = new Set<() => void>();\n\n function notify() {\n subscribers.forEach(cb => cb());\n }\n\n function setState(next: ReactiveState<TData>) {\n if (\n currentState.status === next.status &&\n currentState.data === next.data &&\n currentState.error === next.error\n ) {\n return;\n }\n currentState = next;\n notify();\n }\n\n function performConnect(callerSignal: AbortSignal | undefined) {\n // Abort any currently active connection before starting a fresh one.\n currentInnerController?.abort();\n // If the caller's signal is already aborted, surface as error and bail.\n if (callerSignal?.aborted) {\n setState({ data: currentState.data, error: callerSignal.reason, status: 'error' });\n return;\n }\n // Transition to `loading`, preserving the last known `data` and `error` for SWR. If\n // already `loading` with the same data/error, `setState` no-ops — no spurious notify.\n setState({ data: currentState.data, error: currentState.error, status: 'loading' });\n // Inner signal is passed to the data publisher (composed with caller signal if any).\n const innerController = new AbortController();\n currentInnerController = innerController;\n const signal = callerSignal ? AbortSignal.any([innerController.signal, callerSignal]) : innerController.signal;\n // Caller's signal aborting (not just supersede via the inner controller) transitions the\n // store to error with the caller's abort reason. Scoped to the inner signal so the\n // listener is removed automatically on reconnect / reset.\n if (callerSignal) {\n callerSignal.addEventListener(\n 'abort',\n () => {\n if (innerController.signal.aborted) return;\n setState({ data: currentState.data, error: callerSignal.reason, status: 'error' });\n innerController.abort(callerSignal.reason);\n },\n { signal: innerController.signal },\n );\n }\n createDataPublisher(signal).then(\n publisher => {\n if (signal.aborted) return;\n publisher.on(\n dataChannelName,\n data => {\n setState({ data: data as TData, error: undefined, status: 'loaded' });\n },\n { signal },\n );\n publisher.on(\n errorChannelName,\n err => {\n if (currentState.status === 'error') return;\n setState({ data: currentState.data, error: err, status: 'error' });\n innerController.abort(err);\n },\n { signal },\n );\n },\n err => {\n if (signal.aborted) return;\n setState({ data: currentState.data, error: err, status: 'error' });\n innerController.abort(err);\n },\n );\n }\n\n function performReset() {\n currentInnerController?.abort();\n currentInnerController = undefined;\n setState(IDLE_STATE);\n }\n\n return {\n connect(): void {\n performConnect(undefined);\n },\n getState(): ReactiveState<TData> {\n return currentState;\n },\n reset: performReset,\n subscribe(callback: () => void): () => void {\n subscribers.add(callback);\n return () => {\n subscribers.delete(callback);\n };\n },\n withSignal(signal: AbortSignal) {\n return {\n connect(): void {\n performConnect(signal);\n },\n };\n },\n };\n}\n"]}
|
package/dist/index.browser.mjs
CHANGED
|
@@ -344,20 +344,10 @@ function createReactiveStoreFromDataPublisherFactory({
|
|
|
344
344
|
connect() {
|
|
345
345
|
performConnect(void 0);
|
|
346
346
|
},
|
|
347
|
-
getError() {
|
|
348
|
-
return currentState.error;
|
|
349
|
-
},
|
|
350
347
|
getState() {
|
|
351
|
-
return currentState.data;
|
|
352
|
-
},
|
|
353
|
-
getUnifiedState() {
|
|
354
348
|
return currentState;
|
|
355
349
|
},
|
|
356
350
|
reset: performReset,
|
|
357
|
-
retry() {
|
|
358
|
-
if (currentState.status !== "error") return;
|
|
359
|
-
performConnect(void 0);
|
|
360
|
-
},
|
|
361
351
|
subscribe(callback) {
|
|
362
352
|
subscribers.add(callback);
|
|
363
353
|
return () => {
|