@solana/rpc-subscriptions-spec 2.0.0-20241006045741

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.
@@ -0,0 +1,228 @@
1
+ import { SolanaError, SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN, getSolanaErrorFromJsonRpcError, SOLANA_ERROR__RPC_SUBSCRIPTIONS__EXPECTED_SERVER_SUBSCRIPTION_ID, SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED } from '@solana/errors';
2
+ import { createAsyncIterableFromDataPublisher, demultiplexDataPublisher } from '@solana/subscribable';
3
+ import { safeRace } from '@solana/promises';
4
+ import { createRpcMessage } from '@solana/rpc-spec-types';
5
+
6
+ // src/rpc-subscriptions.ts
7
+ function createSubscriptionRpc(rpcConfig) {
8
+ return new Proxy(rpcConfig.api, {
9
+ defineProperty() {
10
+ return false;
11
+ },
12
+ deleteProperty() {
13
+ return false;
14
+ },
15
+ get(target, p, receiver) {
16
+ return function(...rawParams) {
17
+ const notificationName = p.toString();
18
+ const createRpcSubscriptionPlan = Reflect.get(target, notificationName, receiver);
19
+ if (!createRpcSubscriptionPlan) {
20
+ throw new SolanaError(SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN, {
21
+ notificationName
22
+ });
23
+ }
24
+ const subscriptionPlan = createRpcSubscriptionPlan(...rawParams);
25
+ return createPendingRpcSubscription(rpcConfig.transport, subscriptionPlan);
26
+ };
27
+ }
28
+ });
29
+ }
30
+ function createPendingRpcSubscription(transport, subscriptionsPlan) {
31
+ return {
32
+ async subscribe({ abortSignal }) {
33
+ const notificationsDataPublisher = await transport({
34
+ signal: abortSignal,
35
+ ...subscriptionsPlan
36
+ });
37
+ return createAsyncIterableFromDataPublisher({
38
+ abortSignal,
39
+ dataChannelName: "notification",
40
+ dataPublisher: notificationsDataPublisher,
41
+ errorChannelName: "error"
42
+ });
43
+ }
44
+ };
45
+ }
46
+
47
+ // src/rpc-subscriptions-api.ts
48
+ var UNINITIALIZED = Symbol();
49
+ function createRpcSubscriptionsApi(config) {
50
+ return new Proxy({}, {
51
+ defineProperty() {
52
+ return false;
53
+ },
54
+ deleteProperty() {
55
+ return false;
56
+ },
57
+ get(...args) {
58
+ const [_, p] = args;
59
+ const notificationName = p.toString();
60
+ return function(...params) {
61
+ let _cachedSubscriptionHash = UNINITIALIZED;
62
+ return {
63
+ executeSubscriptionPlan(planConfig) {
64
+ return config.planExecutor({
65
+ ...planConfig,
66
+ notificationName,
67
+ params
68
+ });
69
+ },
70
+ get subscriptionConfigurationHash() {
71
+ if (_cachedSubscriptionHash === UNINITIALIZED) {
72
+ _cachedSubscriptionHash = config?.getSubscriptionConfigurationHash?.({
73
+ notificationName,
74
+ params
75
+ });
76
+ }
77
+ return _cachedSubscriptionHash;
78
+ }
79
+ };
80
+ };
81
+ }
82
+ });
83
+ }
84
+ var subscriberCountBySubscriptionIdByChannel = /* @__PURE__ */ new WeakMap();
85
+ function decrementSubscriberCountAndReturnNewCount(channel, subscriptionId) {
86
+ return augmentSubscriberCountAndReturnNewCount(-1, channel, subscriptionId);
87
+ }
88
+ function incrementSubscriberCount(channel, subscriptionId) {
89
+ augmentSubscriberCountAndReturnNewCount(1, channel, subscriptionId);
90
+ }
91
+ function augmentSubscriberCountAndReturnNewCount(amount, channel, subscriptionId) {
92
+ if (subscriptionId === void 0) {
93
+ return;
94
+ }
95
+ let subscriberCountBySubscriptionId = subscriberCountBySubscriptionIdByChannel.get(channel);
96
+ if (!subscriberCountBySubscriptionId && amount > 0) {
97
+ subscriberCountBySubscriptionIdByChannel.set(
98
+ channel,
99
+ subscriberCountBySubscriptionId = { [subscriptionId]: 0 }
100
+ );
101
+ }
102
+ if (subscriberCountBySubscriptionId[subscriptionId] !== void 0) {
103
+ return subscriberCountBySubscriptionId[subscriptionId] = amount + subscriberCountBySubscriptionId[subscriptionId];
104
+ }
105
+ }
106
+ var cache = /* @__PURE__ */ new WeakMap();
107
+ function getMemoizedDemultiplexedNotificationPublisherFromChannelAndResponseTransformer(channel, responseTransformer) {
108
+ let publisherByResponseTransformer = cache.get(channel);
109
+ if (!publisherByResponseTransformer) {
110
+ cache.set(channel, publisherByResponseTransformer = /* @__PURE__ */ new WeakMap());
111
+ }
112
+ const responseTransformerKey = responseTransformer ?? channel;
113
+ let publisher = publisherByResponseTransformer.get(responseTransformerKey);
114
+ if (!publisher) {
115
+ publisherByResponseTransformer.set(
116
+ responseTransformerKey,
117
+ publisher = demultiplexDataPublisher(channel, "message", (rawMessage) => {
118
+ const message = rawMessage;
119
+ if (!("method" in message)) {
120
+ return;
121
+ }
122
+ const transformedNotification = responseTransformer ? responseTransformer(message.params.result, message.method) : message.params.result;
123
+ return [`notification:${message.params.subscription}`, transformedNotification];
124
+ })
125
+ );
126
+ }
127
+ return publisher;
128
+ }
129
+ async function executeRpcPubSubSubscriptionPlan({
130
+ channel,
131
+ responseTransformer,
132
+ signal,
133
+ subscribeMethodName,
134
+ subscribeParams,
135
+ unsubscribeMethodName
136
+ }) {
137
+ let subscriptionId;
138
+ channel.on(
139
+ "error",
140
+ () => {
141
+ subscriptionId = void 0;
142
+ subscriberCountBySubscriptionIdByChannel.delete(channel);
143
+ },
144
+ { signal }
145
+ );
146
+ const abortPromise = new Promise((_, reject) => {
147
+ function handleAbort() {
148
+ if (decrementSubscriberCountAndReturnNewCount(channel, subscriptionId) === 0) {
149
+ const unsubscribePayload = createRpcMessage(unsubscribeMethodName, [subscriptionId]);
150
+ subscriptionId = void 0;
151
+ channel.send(unsubscribePayload).catch(() => {
152
+ });
153
+ }
154
+ reject(this.reason);
155
+ }
156
+ if (signal.aborted) {
157
+ handleAbort.call(signal);
158
+ } else {
159
+ signal.addEventListener("abort", handleAbort);
160
+ }
161
+ });
162
+ const subscribePayload = createRpcMessage(subscribeMethodName, subscribeParams);
163
+ await channel.send(subscribePayload);
164
+ const subscriptionIdPromise = new Promise((resolve, reject) => {
165
+ const abortController = new AbortController();
166
+ signal.addEventListener("abort", abortController.abort.bind(abortController));
167
+ const options = { signal: abortController.signal };
168
+ channel.on(
169
+ "error",
170
+ (err) => {
171
+ abortController.abort();
172
+ reject(err);
173
+ },
174
+ options
175
+ );
176
+ channel.on(
177
+ "message",
178
+ (message) => {
179
+ if (message && typeof message === "object" && "id" in message && message.id === subscribePayload.id) {
180
+ abortController.abort();
181
+ if ("error" in message) {
182
+ reject(getSolanaErrorFromJsonRpcError(message.error));
183
+ } else {
184
+ resolve(message.result);
185
+ }
186
+ }
187
+ },
188
+ options
189
+ );
190
+ });
191
+ subscriptionId = await safeRace([abortPromise, subscriptionIdPromise]);
192
+ if (subscriptionId == null) {
193
+ throw new SolanaError(SOLANA_ERROR__RPC_SUBSCRIPTIONS__EXPECTED_SERVER_SUBSCRIPTION_ID);
194
+ }
195
+ incrementSubscriberCount(channel, subscriptionId);
196
+ const notificationPublisher = getMemoizedDemultiplexedNotificationPublisherFromChannelAndResponseTransformer(
197
+ channel,
198
+ responseTransformer
199
+ );
200
+ const notificationKey = `notification:${subscriptionId}`;
201
+ return {
202
+ on(type, listener, options) {
203
+ switch (type) {
204
+ case "notification":
205
+ return notificationPublisher.on(
206
+ notificationKey,
207
+ listener,
208
+ options
209
+ );
210
+ case "error":
211
+ return channel.on(
212
+ "error",
213
+ listener,
214
+ options
215
+ );
216
+ default:
217
+ throw new SolanaError(SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED, {
218
+ channelName: type,
219
+ supportedChannelNames: ["notification", "error"]
220
+ });
221
+ }
222
+ }
223
+ };
224
+ }
225
+
226
+ export { createRpcSubscriptionsApi, createSubscriptionRpc, executeRpcPubSubSubscriptionPlan };
227
+ //# sourceMappingURL=index.node.mjs.map
228
+ //# sourceMappingURL=index.node.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/rpc-subscriptions.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,uEAAyE,EAAA;AAAA,YAC3F,WAAa,EAAA,IAAA;AAAA,YACb,qBAAA,EAAuB,CAAC,cAAA,EAAgB,OAAO,CAAA;AAAA,WAClD,CAAA,CAAA;AAAA,OACT;AAAA,KACJ;AAAA,GACJ,CAAA;AACJ","file":"index.node.mjs","sourcesContent":["import { SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN, SolanaError } from '@solana/errors';\nimport { Callable, Flatten, OverloadImplementations, UnionToIntersection } from '@solana/rpc-spec-types';\nimport { createAsyncIterableFromDataPublisher } from '@solana/subscribable';\n\nimport { RpcSubscriptionsApi, RpcSubscriptionsPlan } from './rpc-subscriptions-api';\nimport { PendingRpcSubscriptionsRequest, RpcSubscribeOptions } from './rpc-subscriptions-request';\nimport { RpcSubscriptionsTransport } from './rpc-subscriptions-transport';\n\nexport type RpcSubscriptionsConfig<TRpcMethods> = Readonly<{\n api: RpcSubscriptionsApi<TRpcMethods>;\n transport: RpcSubscriptionsTransport;\n}>;\n\nexport type RpcSubscriptions<TRpcSubscriptionsMethods> = {\n [TMethodName in keyof TRpcSubscriptionsMethods]: PendingRpcSubscriptionsRequestBuilder<\n OverloadImplementations<TRpcSubscriptionsMethods, TMethodName>\n >;\n};\n\ntype PendingRpcSubscriptionsRequestBuilder<TSubscriptionMethodImplementations> = UnionToIntersection<\n Flatten<{\n [P in keyof TSubscriptionMethodImplementations]: PendingRpcSubscriptionsRequestReturnTypeMapper<\n TSubscriptionMethodImplementations[P]\n >;\n }>\n>;\n\ntype PendingRpcSubscriptionsRequestReturnTypeMapper<TSubscriptionMethodImplementation> =\n // Check that this property of the TRpcSubscriptionMethods interface is, in fact, a function.\n TSubscriptionMethodImplementation extends Callable\n ? (\n ...args: Parameters<TSubscriptionMethodImplementation>\n ) => PendingRpcSubscriptionsRequest<ReturnType<TSubscriptionMethodImplementation>>\n : never;\n\nexport function createSubscriptionRpc<TRpcSubscriptionsApiMethods>(\n rpcConfig: RpcSubscriptionsConfig<TRpcSubscriptionsApiMethods>,\n): RpcSubscriptions<TRpcSubscriptionsApiMethods> {\n return new Proxy(rpcConfig.api, {\n defineProperty() {\n return false;\n },\n deleteProperty() {\n return false;\n },\n get(target, p, receiver) {\n return function (...rawParams: unknown[]) {\n const notificationName = p.toString();\n const createRpcSubscriptionPlan = Reflect.get(target, notificationName, receiver);\n if (!createRpcSubscriptionPlan) {\n throw new SolanaError(SOLANA_ERROR__RPC_SUBSCRIPTIONS__CANNOT_CREATE_SUBSCRIPTION_PLAN, {\n notificationName,\n });\n }\n const subscriptionPlan = createRpcSubscriptionPlan(...rawParams);\n return createPendingRpcSubscription(rpcConfig.transport, subscriptionPlan);\n };\n },\n }) as RpcSubscriptions<TRpcSubscriptionsApiMethods>;\n}\n\nfunction createPendingRpcSubscription<TNotification>(\n transport: RpcSubscriptionsTransport,\n subscriptionsPlan: RpcSubscriptionsPlan<TNotification>,\n): PendingRpcSubscriptionsRequest<TNotification> {\n return {\n async subscribe({ abortSignal }: RpcSubscribeOptions): Promise<AsyncIterable<TNotification>> {\n const notificationsDataPublisher = await transport({\n signal: abortSignal,\n ...subscriptionsPlan,\n });\n return createAsyncIterableFromDataPublisher<TNotification>({\n abortSignal,\n dataChannelName: 'notification',\n dataPublisher: notificationsDataPublisher,\n errorChannelName: 'error',\n });\n },\n };\n}\n","import { Callable } from '@solana/rpc-spec-types';\nimport { DataPublisher } from '@solana/subscribable';\n\nimport { RpcSubscriptionsChannel } from './rpc-subscriptions-channel';\nimport { RpcSubscriptionsTransportDataEvents } from './rpc-subscriptions-transport';\n\nexport type RpcSubscriptionsApiConfig<TApiMethods extends RpcSubscriptionsApiMethods> = Readonly<{\n getSubscriptionConfigurationHash?: (\n details: Readonly<{\n notificationName: string;\n params: unknown;\n }>,\n ) => string | undefined;\n planExecutor: RpcSubscriptionsPlanExecutor<ReturnType<TApiMethods[keyof TApiMethods]>>;\n}>;\n\ntype RpcSubscriptionsPlanExecutor<TNotification> = (\n config: Readonly<{\n channel: RpcSubscriptionsChannel<unknown, unknown>;\n notificationName: string;\n params?: unknown[];\n signal: AbortSignal;\n }>,\n) => Promise<DataPublisher<RpcSubscriptionsTransportDataEvents<TNotification>>>;\n\nexport type RpcSubscriptionsPlan<TNotification> = Readonly<{\n /**\n * This method may be called with a newly-opened channel or a pre-established channel.\n */\n executeSubscriptionPlan: (\n config: Readonly<{\n channel: RpcSubscriptionsChannel<unknown, unknown>;\n signal: AbortSignal;\n }>,\n ) => Promise<DataPublisher<RpcSubscriptionsTransportDataEvents<TNotification>>>;\n /**\n * This hash uniquely identifies the configuration of a subscription. It is typically used by\n * consumers of this API to deduplicate multiple subscriptions for the same notification.\n */\n subscriptionConfigurationHash: string | undefined;\n}>;\n\nexport type RpcSubscriptionsApi<TRpcSubscriptionMethods> = {\n [MethodName in keyof TRpcSubscriptionMethods]: RpcSubscriptionsReturnTypeMapper<\n TRpcSubscriptionMethods[MethodName]\n >;\n};\n\ntype RpcSubscriptionsReturnTypeMapper<TRpcMethod> = TRpcMethod extends Callable\n ? (...rawParams: unknown[]) => RpcSubscriptionsPlan<ReturnType<TRpcMethod>>\n : never;\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype RpcSubscriptionsApiMethod = (...args: any) => any;\nexport interface RpcSubscriptionsApiMethods {\n [methodName: string]: RpcSubscriptionsApiMethod;\n}\n\nconst UNINITIALIZED = Symbol();\n\nexport function createRpcSubscriptionsApi<TRpcSubscriptionsApiMethods extends RpcSubscriptionsApiMethods>(\n config: RpcSubscriptionsApiConfig<TRpcSubscriptionsApiMethods>,\n): RpcSubscriptionsApi<TRpcSubscriptionsApiMethods> {\n return new Proxy({} as RpcSubscriptionsApi<TRpcSubscriptionsApiMethods>, {\n defineProperty() {\n return false;\n },\n deleteProperty() {\n return false;\n },\n get<TNotificationName extends keyof RpcSubscriptionsApi<TRpcSubscriptionsApiMethods>>(\n ...args: Parameters<NonNullable<ProxyHandler<RpcSubscriptionsApi<TRpcSubscriptionsApiMethods>>['get']>>\n ) {\n const [_, p] = args;\n const notificationName = p.toString() as keyof TRpcSubscriptionsApiMethods as string;\n return function (\n ...params: Parameters<\n TRpcSubscriptionsApiMethods[TNotificationName] extends CallableFunction\n ? TRpcSubscriptionsApiMethods[TNotificationName]\n : never\n >\n ): RpcSubscriptionsPlan<ReturnType<TRpcSubscriptionsApiMethods[TNotificationName]>> {\n let _cachedSubscriptionHash: string | typeof UNINITIALIZED | undefined = UNINITIALIZED;\n return {\n executeSubscriptionPlan(planConfig) {\n return config.planExecutor({\n ...planConfig,\n notificationName,\n params,\n });\n },\n get subscriptionConfigurationHash() {\n if (_cachedSubscriptionHash === UNINITIALIZED) {\n _cachedSubscriptionHash = config?.getSubscriptionConfigurationHash?.({\n notificationName,\n params,\n });\n }\n return _cachedSubscriptionHash;\n },\n };\n };\n },\n });\n}\n","import {\n getSolanaErrorFromJsonRpcError,\n SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED,\n SOLANA_ERROR__RPC_SUBSCRIPTIONS__EXPECTED_SERVER_SUBSCRIPTION_ID,\n SolanaError,\n} from '@solana/errors';\nimport { safeRace } from '@solana/promises';\nimport { createRpcMessage, RpcResponseData } from '@solana/rpc-spec-types';\nimport { DataPublisher } from '@solana/subscribable';\nimport { demultiplexDataPublisher } from '@solana/subscribable';\n\nimport { RpcSubscriptionChannelEvents } from './rpc-subscriptions-channel';\nimport { RpcSubscriptionsChannel } from './rpc-subscriptions-channel';\n\ntype Config<TNotification> = Readonly<{\n channel: RpcSubscriptionsChannel<unknown, RpcNotification<TNotification> | RpcResponseData<RpcSubscriptionId>>;\n responseTransformer?: <T>(response: unknown, notificationName: string) => T;\n signal: AbortSignal;\n subscribeMethodName: string;\n subscribeParams?: unknown[];\n unsubscribeMethodName: string;\n}>;\n\ntype RpcNotification<TNotification> = Readonly<{\n method: string;\n params: Readonly<{\n result: TNotification;\n subscription: number;\n }>;\n}>;\n\ntype RpcSubscriptionId = number;\n\ntype RpcSubscriptionNotificationEvents<TNotification> = Omit<RpcSubscriptionChannelEvents<TNotification>, 'message'> & {\n notification: TNotification;\n};\n\nconst subscriberCountBySubscriptionIdByChannel = new WeakMap();\nfunction decrementSubscriberCountAndReturnNewCount(channel: WeakKey, subscriptionId?: number): number | undefined {\n return augmentSubscriberCountAndReturnNewCount(-1, channel, subscriptionId);\n}\nfunction incrementSubscriberCount(channel: WeakKey, subscriptionId?: number): void {\n augmentSubscriberCountAndReturnNewCount(1, channel, subscriptionId);\n}\nfunction augmentSubscriberCountAndReturnNewCount(\n amount: -1 | 1,\n channel: WeakKey,\n subscriptionId?: number,\n): number | undefined {\n if (subscriptionId === undefined) {\n return;\n }\n let subscriberCountBySubscriptionId = subscriberCountBySubscriptionIdByChannel.get(channel);\n if (!subscriberCountBySubscriptionId && amount > 0) {\n subscriberCountBySubscriptionIdByChannel.set(\n channel,\n (subscriberCountBySubscriptionId = { [subscriptionId]: 0 }),\n );\n }\n if (subscriberCountBySubscriptionId[subscriptionId] !== undefined) {\n return (subscriberCountBySubscriptionId[subscriptionId] =\n amount + subscriberCountBySubscriptionId[subscriptionId]);\n }\n}\n\nconst cache = new WeakMap();\nfunction getMemoizedDemultiplexedNotificationPublisherFromChannelAndResponseTransformer<TNotification>(\n channel: RpcSubscriptionsChannel<unknown, RpcNotification<TNotification>>,\n responseTransformer?: <T>(response: unknown, notificationName: string) => T,\n): DataPublisher<{\n [channelName: `notification:${number}`]: TNotification;\n}> {\n let publisherByResponseTransformer = cache.get(channel);\n if (!publisherByResponseTransformer) {\n cache.set(channel, (publisherByResponseTransformer = new WeakMap()));\n }\n const responseTransformerKey = responseTransformer ?? channel;\n let publisher = publisherByResponseTransformer.get(responseTransformerKey);\n if (!publisher) {\n publisherByResponseTransformer.set(\n responseTransformerKey,\n (publisher = demultiplexDataPublisher(channel, 'message', rawMessage => {\n const message = rawMessage as RpcNotification<unknown> | RpcResponseData<unknown>;\n if (!('method' in message)) {\n return;\n }\n const transformedNotification = responseTransformer\n ? responseTransformer(message.params.result, message.method)\n : message.params.result;\n return [`notification:${message.params.subscription}`, transformedNotification];\n })),\n );\n }\n return publisher;\n}\n\nexport async function executeRpcPubSubSubscriptionPlan<TNotification>({\n channel,\n responseTransformer,\n signal,\n subscribeMethodName,\n subscribeParams,\n unsubscribeMethodName,\n}: Config<TNotification>): Promise<DataPublisher<RpcSubscriptionNotificationEvents<TNotification>>> {\n let subscriptionId: number | undefined;\n channel.on(\n 'error',\n () => {\n // An error on the channel indicates that the subscriptions are dead.\n // There is no longer any sense hanging on to subscription ids.\n // Erasing it here will prevent the unsubscribe code from running.\n subscriptionId = undefined;\n subscriberCountBySubscriptionIdByChannel.delete(channel);\n },\n { signal },\n );\n /**\n * STEP 1\n * Create a promise that rejects if this subscription is aborted and sends\n * the unsubscribe message if the subscription is active at that time.\n */\n const abortPromise = new Promise<never>((_, reject) => {\n function handleAbort(this: AbortSignal) {\n /**\n * Because of https://github.com/solana-labs/solana/pull/18943, two subscriptions for\n * materially the same notification will be coalesced on the server. This means they\n * will be assigned the same subscription id, and will occupy one subscription slot. We\n * must be careful not to send the unsubscribe message until the last subscriber aborts.\n */\n if (decrementSubscriberCountAndReturnNewCount(channel, subscriptionId) === 0) {\n const unsubscribePayload = createRpcMessage(unsubscribeMethodName, [subscriptionId]);\n subscriptionId = undefined;\n channel.send(unsubscribePayload).catch(() => {});\n }\n reject(this.reason);\n }\n if (signal.aborted) {\n handleAbort.call(signal);\n } else {\n signal.addEventListener('abort', handleAbort);\n }\n });\n /**\n * STEP 2\n * Send the subscription request.\n */\n const subscribePayload = createRpcMessage(subscribeMethodName, subscribeParams);\n await channel.send(subscribePayload);\n /**\n * STEP 3\n * Wait for the acknowledgement from the server with the subscription id.\n */\n const subscriptionIdPromise = new Promise<RpcSubscriptionId>((resolve, reject) => {\n const abortController = new AbortController();\n signal.addEventListener('abort', abortController.abort.bind(abortController));\n const options = { signal: abortController.signal } as const;\n channel.on(\n 'error',\n err => {\n abortController.abort();\n reject(err);\n },\n options,\n );\n channel.on(\n 'message',\n message => {\n if (message && typeof message === 'object' && 'id' in message && message.id === subscribePayload.id) {\n abortController.abort();\n if ('error' in message) {\n reject(getSolanaErrorFromJsonRpcError(message.error));\n } else {\n resolve(message.result);\n }\n }\n },\n options,\n );\n });\n subscriptionId = await safeRace([abortPromise, subscriptionIdPromise]);\n if (subscriptionId == null) {\n throw new SolanaError(SOLANA_ERROR__RPC_SUBSCRIPTIONS__EXPECTED_SERVER_SUBSCRIPTION_ID);\n }\n incrementSubscriberCount(channel, subscriptionId);\n /**\n * STEP 4\n * Filter out notifications unrelated to this subscription.\n */\n const notificationPublisher = getMemoizedDemultiplexedNotificationPublisherFromChannelAndResponseTransformer(\n channel,\n responseTransformer,\n );\n const notificationKey = `notification:${subscriptionId}` as const;\n return {\n on(type, listener, options) {\n switch (type) {\n case 'notification':\n return notificationPublisher.on(\n notificationKey,\n listener as (data: RpcSubscriptionNotificationEvents<TNotification>['notification']) => void,\n options,\n );\n case 'error':\n return channel.on(\n 'error',\n listener as (data: RpcSubscriptionNotificationEvents<TNotification>['error']) => void,\n options,\n );\n default:\n throw new SolanaError(SOLANA_ERROR__INVARIANT_VIOLATION__DATA_PUBLISHER_CHANNEL_UNIMPLEMENTED, {\n channelName: type,\n supportedChannelNames: ['notification', 'error'],\n });\n }\n },\n };\n}\n"]}
@@ -0,0 +1,7 @@
1
+ export * from './rpc-subscriptions-request';
2
+ export * from './rpc-subscriptions';
3
+ export * from './rpc-subscriptions-api';
4
+ export * from './rpc-subscriptions-channel';
5
+ export * from './rpc-subscriptions-pubsub-plan';
6
+ export * from './rpc-subscriptions-transport';
7
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,6BAA6B,CAAC;AAC5C,cAAc,qBAAqB,CAAC;AACpC,cAAc,yBAAyB,CAAC;AACxC,cAAc,6BAA6B,CAAC;AAC5C,cAAc,iCAAiC,CAAC;AAChD,cAAc,+BAA+B,CAAC"}
@@ -0,0 +1,42 @@
1
+ import { Callable } from '@solana/rpc-spec-types';
2
+ import { DataPublisher } from '@solana/subscribable';
3
+ import { RpcSubscriptionsChannel } from './rpc-subscriptions-channel';
4
+ import { RpcSubscriptionsTransportDataEvents } from './rpc-subscriptions-transport';
5
+ export type RpcSubscriptionsApiConfig<TApiMethods extends RpcSubscriptionsApiMethods> = Readonly<{
6
+ getSubscriptionConfigurationHash?: (details: Readonly<{
7
+ notificationName: string;
8
+ params: unknown;
9
+ }>) => string | undefined;
10
+ planExecutor: RpcSubscriptionsPlanExecutor<ReturnType<TApiMethods[keyof TApiMethods]>>;
11
+ }>;
12
+ type RpcSubscriptionsPlanExecutor<TNotification> = (config: Readonly<{
13
+ channel: RpcSubscriptionsChannel<unknown, unknown>;
14
+ notificationName: string;
15
+ params?: unknown[];
16
+ signal: AbortSignal;
17
+ }>) => Promise<DataPublisher<RpcSubscriptionsTransportDataEvents<TNotification>>>;
18
+ export type RpcSubscriptionsPlan<TNotification> = Readonly<{
19
+ /**
20
+ * This method may be called with a newly-opened channel or a pre-established channel.
21
+ */
22
+ executeSubscriptionPlan: (config: Readonly<{
23
+ channel: RpcSubscriptionsChannel<unknown, unknown>;
24
+ signal: AbortSignal;
25
+ }>) => Promise<DataPublisher<RpcSubscriptionsTransportDataEvents<TNotification>>>;
26
+ /**
27
+ * This hash uniquely identifies the configuration of a subscription. It is typically used by
28
+ * consumers of this API to deduplicate multiple subscriptions for the same notification.
29
+ */
30
+ subscriptionConfigurationHash: string | undefined;
31
+ }>;
32
+ export type RpcSubscriptionsApi<TRpcSubscriptionMethods> = {
33
+ [MethodName in keyof TRpcSubscriptionMethods]: RpcSubscriptionsReturnTypeMapper<TRpcSubscriptionMethods[MethodName]>;
34
+ };
35
+ type RpcSubscriptionsReturnTypeMapper<TRpcMethod> = TRpcMethod extends Callable ? (...rawParams: unknown[]) => RpcSubscriptionsPlan<ReturnType<TRpcMethod>> : never;
36
+ type RpcSubscriptionsApiMethod = (...args: any) => any;
37
+ export interface RpcSubscriptionsApiMethods {
38
+ [methodName: string]: RpcSubscriptionsApiMethod;
39
+ }
40
+ export declare function createRpcSubscriptionsApi<TRpcSubscriptionsApiMethods extends RpcSubscriptionsApiMethods>(config: RpcSubscriptionsApiConfig<TRpcSubscriptionsApiMethods>): RpcSubscriptionsApi<TRpcSubscriptionsApiMethods>;
41
+ export {};
42
+ //# sourceMappingURL=rpc-subscriptions-api.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rpc-subscriptions-api.d.ts","sourceRoot":"","sources":["../../src/rpc-subscriptions-api.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,wBAAwB,CAAC;AAClD,OAAO,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAErD,OAAO,EAAE,uBAAuB,EAAE,MAAM,6BAA6B,CAAC;AACtE,OAAO,EAAE,mCAAmC,EAAE,MAAM,+BAA+B,CAAC;AAEpF,MAAM,MAAM,yBAAyB,CAAC,WAAW,SAAS,0BAA0B,IAAI,QAAQ,CAAC;IAC7F,gCAAgC,CAAC,EAAE,CAC/B,OAAO,EAAE,QAAQ,CAAC;QACd,gBAAgB,EAAE,MAAM,CAAC;QACzB,MAAM,EAAE,OAAO,CAAC;KACnB,CAAC,KACD,MAAM,GAAG,SAAS,CAAC;IACxB,YAAY,EAAE,4BAA4B,CAAC,UAAU,CAAC,WAAW,CAAC,MAAM,WAAW,CAAC,CAAC,CAAC,CAAC;CAC1F,CAAC,CAAC;AAEH,KAAK,4BAA4B,CAAC,aAAa,IAAI,CAC/C,MAAM,EAAE,QAAQ,CAAC;IACb,OAAO,EAAE,uBAAuB,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;IACnD,gBAAgB,EAAE,MAAM,CAAC;IACzB,MAAM,CAAC,EAAE,OAAO,EAAE,CAAC;IACnB,MAA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CHANNEL_CONNECTION_CLOSED, SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT, SolanaError } from '@solana/errors';
2
+ import { DataPublisher } from '@solana/subscribable';
3
+ type RpcSubscriptionsChannelSolanaErrorCode = typeof SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CLOSED_BEFORE_MESSAGE_BUFFERED | typeof SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_CONNECTION_CLOSED | typeof SOLANA_ERROR__RPC_SUBSCRIPTIONS__CHANNEL_FAILED_TO_CONNECT;
4
+ export type RpcSubscriptionChannelEvents<TInboundMessage> = {
5
+ error: SolanaError<RpcSubscriptionsChannelSolanaErrorCode>;
6
+ message: TInboundMessage;
7
+ };
8
+ export interface RpcSubscriptionsChannel<TOutboundMessage, TInboundMessage> extends DataPublisher<RpcSubscriptionChannelEvents<TInboundMessage>> {
9
+ send(message: TOutboundMessage): Promise<void>;
10
+ }
11
+ export type RpcSubscriptionsChannelCreator<TOutboundMessage, TInboundMessage> = (config: Readonly<{
12
+ abortSignal: AbortSignal;
13
+ }>) => Promise<RpcSubscriptionsChannel<TOutboundMessage, TInboundMessage>>;
14
+ export {};
15
+ //# sourceMappingURL=rpc-subscriptions-channel.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rpc-subscriptions-channel.d.ts","sourceRoot":"","sources":["../../src/rpc-subscriptions-channel.ts"],"names":[],"mappings":"AAAA,OAAO,EACH,uEAAuE,EACvE,0DAA0D,EAC1D,0DAA0D,EAC1D,WAAW,EACd,MAAM,gBAAgB,CAAC;AACxB,OAAO,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAErD,KAAK,sCAAsC,GACrC,OAAO,uEAAuE,GAC9E,OAAO,0DAA0D,GACjE,OAAO,0DAA0D,CAAC;AAExE,MAAM,MAAM,4BAA4B,CAAC,eAAe,IAAI;IACxD,KAAK,EAAE,WAAW,CAAC,sCAAsC,CAAC,CAAC;IAC3D,OAAO,EAAE,eAAe,CAAC;CAC5B,CAAC;AAEF,MAAM,WAAW,uBAAuB,CAAC,gBAAgB,EAAE,eAAe,CACtE,SAAQ,aAAa,CAAC,4BAA4B,CAAC,eAAe,CAAC,CAAC;IACpE,IAAI,CAAC,OAAO,EAAE,gBAAgB,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CAClD;AAED,MAAM,MAAM,8BAA8B,CAAC,gBAAgB,EAAE,eAAe,IAAI,CAC5E,MAAM,EAAE,QAAQ,CAAC;IACb,WAAW,EAAE,WAAW,CAAC;CAC5B,CAAC,KACD,OAAO,CAAC,uBAAuB,CAAC,gBAAgB,EAAE,eAAe,CAAC,CAAC,CAAC"}
@@ -0,0 +1,26 @@
1
+ import { RpcResponseData } from '@solana/rpc-spec-types';
2
+ import { DataPublisher } from '@solana/subscribable';
3
+ import { RpcSubscriptionChannelEvents } from './rpc-subscriptions-channel';
4
+ import { RpcSubscriptionsChannel } from './rpc-subscriptions-channel';
5
+ type Config<TNotification> = Readonly<{
6
+ channel: RpcSubscriptionsChannel<unknown, RpcNotification<TNotification> | RpcResponseData<RpcSubscriptionId>>;
7
+ responseTransformer?: <T>(response: unknown, notificationName: string) => T;
8
+ signal: AbortSignal;
9
+ subscribeMethodName: string;
10
+ subscribeParams?: unknown[];
11
+ unsubscribeMethodName: string;
12
+ }>;
13
+ type RpcNotification<TNotification> = Readonly<{
14
+ method: string;
15
+ params: Readonly<{
16
+ result: TNotification;
17
+ subscription: number;
18
+ }>;
19
+ }>;
20
+ type RpcSubscriptionId = number;
21
+ type RpcSubscriptionNotificationEvents<TNotification> = Omit<RpcSubscriptionChannelEvents<TNotification>, 'message'> & {
22
+ notification: TNotification;
23
+ };
24
+ export declare function executeRpcPubSubSubscriptionPlan<TNotification>({ channel, responseTransformer, signal, subscribeMethodName, subscribeParams, unsubscribeMethodName, }: Config<TNotification>): Promise<DataPublisher<RpcSubscriptionNotificationEvents<TNotification>>>;
25
+ export {};
26
+ //# sour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E,EAClE,OAAO,EACP,mBAAmB,EACnB,MAAM,EACN,mBAAmB,EACnB,eAAe,EACf,qBAAqB,GACxB,EAAE,MAAM,CAAC,aAAa,CAAC,GAAG,OAAO,CAAC,aAAa,CAAC,iCAAiC,CAAC,aAAa,CAAC,CAAC,CAAC,CAiHlG"}
@@ -0,0 +1,13 @@
1
+ export type RpcSubscriptionsRequest<TResponse> = {
2
+ params: unknown[];
3
+ responseTransformer?: (response: unknown, notificationName: string) => TResponse;
4
+ subscribeMethodName: string;
5
+ unsubscribeMethodName: string;
6
+ };
7
+ export type PendingRpcSubscriptionsRequest<TNotification> = {
8
+ subscribe(options: RpcSubscribeOptions): Promise<AsyncIterable<TNotification>>;
9
+ };
10
+ export type RpcSubscribeOptions = Readonly<{
11
+ abortSignal: AbortSignal;
12
+ }>;
13
+ //# sourceMappingURL=rpc-subscriptions-request.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rpc-subscriptions-request.d.ts","sourceRoot":"","sources":["../../src/rpc-subscriptions-request.ts"],"names":[],"mappings":"AAAA,MAAM,MAAM,uBAAuB,CAAC,SAAS,IAAI;IAC7C,MAAM,EAAE,OAAO,EAAE,CAAC;IAClB,mBAAmB,CAAC,EAAE,CAAC,QAAQ,EAAE,OAAO,EAAE,gBAAgB,EAAE,MAAM,KAAK,SAAS,CAAC;IACjF,mBAAmB,EAAE,MAAM,CAAC;IAC5B,qBAAqB,EAAE,MAAM,CAAC;CACjC,CAAC;AAEF,MAAM,MAAM,8BAA8B,CAAC,aAAa,IAAI;IACxD,SAAS,CAAC,OAAO,EAAE,mBAAmB,GAAG,OAAO,CAAC,aAAa,CAAC,aAAa,CAAC,CAAC,CAAC;CAClF,CAAC;AAEF,MAAM,MAAM,mBAAmB,GAAG,QAAQ,CAAC;IACvC,WAAW,EAAE,WAAW,CAAC;CAC5B,CAAC,CAAC"}
@@ -0,0 +1,15 @@
1
+ import { SolanaError } from '@solana/errors';
2
+ import { DataPublisher } from '@solana/subscribable';
3
+ import { RpcSubscriptionsPlan } from './rpc-subscriptions-api';
4
+ export type RpcSubscriptionsTransportDataEvents<TNotification> = {
5
+ error: SolanaError;
6
+ notification: TNotification;
7
+ };
8
+ interface RpcSubscriptionsTransportConfig<TNotification> extends RpcSubscriptionsPlan<TNotification> {
9
+ signal: AbortSignal;
10
+ }
11
+ export interface RpcSubscriptionsTransport {
12
+ <TNotification>(config: RpcSubscriptionsTransportConfig<TNotification>): Promise<DataPublisher<RpcSubscriptionsTransportDataEvents<TNotification>>>;
13
+ }
14
+ export {};
15
+ //# sourceMappingURL=rpc-subscriptions-transport.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rpc-subscriptions-transport.d.ts","sourceRoot":"","sources":["../../src/rpc-subscriptions-transport.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AAC7C,OAAO,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAErD,OAAO,EAAE,oBAAoB,EAAE,MAAM,yBAAyB,CAAC;AAE/D,MAAM,MAAM,mCAAmC,CAAC,aAAa,IAAI;IAC7D,KAAK,EAAE,WAAW,CAAC;IACnB,YAAY,EAAE,aAAa,CAAC;CAC/B,CAAC;AAEF,UAAU,+BAA+B,CAAC,aAAa,CAAE,SAAQ,oBAAoB,CAAC,aAAa,CAAC;IAChG,MAAM,EAAE,WAAW,CAAC;CACvB;AAED,MAAM,WAAW,yBAAyB;IACtC,CAAC,aAAa,EACV,MAAM,EAAE,+BAA+B,CAAC,aAAa,CAAC,GACvD,OAAO,CAAC,aAAa,CAAC,mCAAmC,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC;CACjF"}
@@ -0,0 +1,18 @@
1
+ import { Callable, Flatten, OverloadImplementations, UnionToIntersection } from '@solana/rpc-spec-types';
2
+ import { RpcSubscriptionsApi } from './rpc-subscriptions-api';
3
+ import { PendingRpcSubscriptionsRequest } from './rpc-subscriptions-request';
4
+ import { RpcSubscriptionsTransport } from './rpc-subscriptions-transport';
5
+ export type RpcSubscriptionsConfig<TRpcMethods> = Readonly<{
6
+ api: RpcSubscriptionsApi<TRpcMethods>;
7
+ transport: RpcSubscriptionsTransport;
8
+ }>;
9
+ export type RpcSubscriptions<TRpcSubscriptionsMethods> = {
10
+ [TMethodName in keyof TRpcSubscriptionsMethods]: PendingRpcSubscriptionsRequestBuilder<OverloadImplementations<TRpcSubscriptionsMethods, TMethodName>>;
11
+ };
12
+ type PendingRpcSubscriptionsRequestBuilder<TSubscriptionMethodImplementations> = UnionToIntersection<Flatten<{
13
+ [P in keyof TSubscriptionMethodImplementations]: PendingRpcSubscriptionsRequestReturnTypeMapper<TSubscriptionMethodImplementations[P]>;
14
+ }>>;
15
+ type PendingRpcSubscriptionsRequestReturnTypeMapper<TSubscriptionMethodImplementation> = TSubscriptionMethodImplementation extends Callable ? (...args: Parameters<TSubscriptionMethodImplementation>) => PendingRpcSubscriptionsRequest<ReturnType<TSubscriptionMethodImplementation>> : never;
16
+ export declare function createSubscriptionRpc<TRpcSubscriptionsApiMethods>(rpcConfig: RpcSubscriptionsConfig<TRpcSubscriptionsApiMethods>): RpcSubscriptions<TRpcSubscriptionsApiMethods>;
17
+ export {};
18
+ //# sourceMappingURL=rpc-subscriptions.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"rpc-subscriptions.d.ts","sourceRoot":"","sources":["../../src/rpc-subscriptions.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,uBAAuB,EAAE,mBAAmB,EAAE,MAAM,wBAAwB,CAAC;AAGzG,OAAO,EAAE,mBAAmB,EAAwB,MAAM,yBAAyB,CAAC;AACpF,OAAO,EAAE,8BAA8B,EAAuB,MAAM,6BAA6B,CAAC;AAClG,OAAO,EAAE,yBAAyB,EAAE,MAAM,+BAA+B,CAAC;AAE1E,MAAM,MAAM,sBAAsB,CAAC,WAAW,IAAI,QAAQ,CAAC;IACvD,GAAG,EAAE,mBAAmB,CAAC,WAAW,CAAC,CAAC;IACtC,SAAS,EAAE,yBAAyB,CAAC;CACxC,CAAC,CAAC;AAEH,MAAM,MAAM,gBAAgB,CAAC,wBAAwB,IAAI;KACpD,WAAW,IAAI,MAAM,wBAAwB,GAAG,qCAAqC,CAClF,uBAAuB,CAAC,wBAAwB,EAAE,WAAW,CAAC,CACjE;CACJ,CAAC;AAEF,KAAK,qCAAqC,CAAC,kCAAkC,IAAI,mBAAmB,CAChG,OAAO,CAAC;KACH,CAAC,IAAI,MAAM,kCAAkC,GAAG,8CAA8C,CAC3F,kCAAkC,CAAC,CAAC,CAAC,CACxC;CACJ,CAAC,CACL,CAAC;AAEF,KAAK,8CAA8C,CAAC,iCAAiC,IAEjF,iCAAiC,SAAS,QAAQ,GAC5C,CACI,GAAG,IAAI,EAAE,UAAU,CAAC,iCAAiC,CAAC,KACrD,8BAA8B,CAAC,UAAU,CAAC,iCAAiC,CAAC,CAAC,GAClF,KAAK,CAAC;AAEhB,wBAAgB,qBAAqB,CAAC,2BAA2B,EAC7D,SAAS,EAAE,sBAAsB,CAAC,2BAA2B,CAAC,GAC/D,gBAAgB,CAAC,2BAA2B,CAAC,CAsB/C"}
package/package.json ADDED
@@ -0,0 +1,89 @@
1
+ {
2
+ "name": "@solana/rpc-subscriptions-spec",
3
+ "version": "2.0.0-20241006045741",
4
+ "description": "A generic implementation of JSON RPC Subscriptions using proxies",
5
+ "exports": {
6
+ "edge-light": {
7
+ "import": "./dist/index.node.mjs",
8
+ "require": "./dist/index.node.cjs"
9
+ },
10
+ "workerd": {
11
+ "import": "./dist/index.node.mjs",
12
+ "require": "./dist/index.node.cjs"
13
+ },
14
+ "browser": {
15
+ "import": "./dist/index.browser.mjs",
16
+ "require": "./dist/index.browser.cjs"
17
+ },
18
+ "node": {
19
+ "import": "./dist/index.node.mjs",
20
+ "require": "./dist/index.node.cjs"
21
+ },
22
+ "react-native": "./dist/index.native.mjs",
23
+ "types": "./dist/types/index.d.ts"
24
+ },
25
+ "browser": {
26
+ "./dist/index.node.cjs": "./dist/index.browser.cjs",
27
+ "./dist/index.node.mjs": "./dist/index.browser.mjs"
28
+ },
29
+ "main": "./dist/index.node.cjs",
30
+ "module": "./dist/index.node.mjs",
31
+ "react-native": "./dist/index.native.mjs",
32
+ "types": "./dist/types/index.d.ts",
33
+ "type": "commonjs",
34
+ "files": [
35
+ "./dist/"
36
+ ],
37
+ "sideEffects": false,
38
+ "keywords": [
39
+ "blockchain",
40
+ "solana",
41
+ "web3"
42
+ ],
43
+ "author": "Solana Labs Maintainers <maintainers@solanalabs.com>",
44
+ "license": "MIT",
45
+ "repository": {
46
+ "type": "git",
47
+ "url": "https://github.com/solana-labs/solana-web3.js"
48
+ },
49
+ "bugs": {
50
+ "url": "http://github.com/solana-labs/solana-web3.js/issues"
51
+ },
52
+ "browserslist": [
53
+ "supports bigint and not dead",
54
+ "maintained node versions"
55
+ ],
56
+ "dependencies": {
57
+ "@solana/errors": "2.0.0-20241006045741",
58
+ "@solana/rpc-spec-types": "2.0.0-20241006045741",
59
+ "@solana/promises": "2.0.0-20241006045741",
60
+ "@solana/subscribable": "2.0.0-20241006045741"
61
+ },
62
+ "peerDependencies": {
63
+ "typescript": ">=5"
64
+ },
65
+ "bundlewatch": {
66
+ "defaultCompression": "gzip",
67
+ "files": [
68
+ {
69
+ "path": "./dist/index*.js"
70
+ }
71
+ ]
72
+ },
73
+ "scripts": {
74
+ "compile:js": "tsup --config build-scripts/tsup.config.package.ts",
75
+ "compile:typedefs": "tsc -p ./tsconfig.declarations.json",
76
+ "dev": "jest -c ../../node_modules/@solana/test-config/jest-dev.config.ts --rootDir . --watch",
77
+ "publish-impl": "npm view $npm_package_name@$npm_package_version > /dev/null 2>&1 || pnpm publish --tag ${PUBLISH_TAG:-canary} --access public --no-git-checks",
78
+ "publish-packages": "pnpm prepublishOnly && pnpm publish-impl",
79
+ "style:fix": "pnpm eslint --fix src && pnpm prettier --log-level warn --ignore-unknown --write ./*",
80
+ "test:lint": "TERM_OVERRIDE=\"${TURBO_HASH:+dumb}\" TERM=${TERM_OVERRIDE:-$TERM} jest -c ../../node_modules/@solana/test-config/jest-lint.config.ts --rootDir . --silent",
81
+ "test:prettier": "TERM_OVERRIDE=\"${TURBO_HASH:+dumb}\" TERM=${TERM_OVERRIDE:-$TERM} jest -c ../../node_modules/@solana/test-config/jest-prettier.config.ts --rootDir . --silent",
82
+ "test:treeshakability:browser": "agadoo dist/index.browser.mjs",
83
+ "test:treeshakability:native": "agadoo dist/index.native.mjs",
84
+ "test:treeshakability:node": "agadoo dist/index.node.mjs",
85
+ "test:typecheck": "tsc --noEmit",
86
+ "test:unit:browser": "TERM_OVERRIDE=\"${TURBO_HASH:+dumb}\" TERM=${TERM_OVERRIDE:-$TERM} jest -c ../../node_modules/@solana/test-config/jest-unit.config.browser.ts --rootDir . --silent",
87
+ "test:unit:node": "TERM_OVERRIDE=\"${TURBO_HASH:+dumb}\" TERM=${TERM_OVERRIDE:-$TERM} jest -c ../../node_modules/@solana/test-config/jest-unit.config.node.ts --rootDir . --silent"
88
+ }
89
+ }