@novasamatech/host-api 0.6.5 → 0.6.6-1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -23,5 +23,5 @@ export { RemotePermissionRequest } from './protocol/v1/remotePermission.js';
23
23
  export { PushNotification } from './protocol/v1/notification.js';
24
24
  export { NavigateToErr } from './protocol/v1/navigation.js';
25
25
  export { PreimageKey, PreimageSubmitErr, PreimageValue } from './protocol/v1/preimage.js';
26
- export { CustomRendererNode } from './protocol/v1/customRenderer.js';
26
+ export { Arrangement, BorderStyle, ButtonVariant, ColorToken, ContentAlignment, CustomRendererNode, Dimensions, HorizontalAlignment, Modifier, Shape, Size, TypographyStyle, VerticalAlignment, } from './protocol/v1/customRenderer.js';
27
27
  export { ChainHeadEvent, ChainHeadFollowV1_start, OperationStartedResult, RuntimeType, StorageQueryItem, StorageQueryType, StorageResultItem, TransactionBroadcastV1_request, TransactionBroadcastV1_response, TransactionStopV1_request, TransactionStopV1_response, } from './protocol/v1/chainInteraction.js';
package/dist/index.js CHANGED
@@ -18,5 +18,5 @@ export { RemotePermissionRequest } from './protocol/v1/remotePermission.js';
18
18
  export { PushNotification } from './protocol/v1/notification.js';
19
19
  export { NavigateToErr } from './protocol/v1/navigation.js';
20
20
  export { PreimageKey, PreimageSubmitErr, PreimageValue } from './protocol/v1/preimage.js';
21
- export { CustomRendererNode } from './protocol/v1/customRenderer.js';
21
+ export { Arrangement, BorderStyle, ButtonVariant, ColorToken, ContentAlignment, CustomRendererNode, Dimensions, HorizontalAlignment, Modifier, Shape, Size, TypographyStyle, VerticalAlignment, } from './protocol/v1/customRenderer.js';
22
22
  export { ChainHeadEvent, ChainHeadFollowV1_start, OperationStartedResult, RuntimeType, StorageQueryItem, StorageQueryType, StorageResultItem, TransactionBroadcastV1_request, TransactionBroadcastV1_response, TransactionStopV1_request, TransactionStopV1_response, } from './protocol/v1/chainInteraction.js';
@@ -1,49 +1,17 @@
1
- export declare const PermissionErr: [import("scale-ts").Encoder<(Error & {
2
- name: "PermissionErr::Rejected";
3
- className: string;
4
- payload: undefined;
5
- }) | (Error & {
6
- name: "PermissionErr::Unknown";
7
- className: string;
8
- payload: {
1
+ export declare const PermissionErr: [import("scale-ts").Encoder<import("@novasamatech/scale").CodecError<undefined, "PermissionErr::Rejected"> | import("@novasamatech/scale").CodecError<{
2
+ reason: string;
3
+ }, "PermissionErr::Unknown">>, import("scale-ts").Decoder<import("@novasamatech/scale").CodecError<undefined, "PermissionErr::Rejected"> | import("@novasamatech/scale").CodecError<{
4
+ reason: string;
5
+ }, "PermissionErr::Unknown">>] & {
6
+ enc: import("scale-ts").Encoder<import("@novasamatech/scale").CodecError<undefined, "PermissionErr::Rejected"> | import("@novasamatech/scale").CodecError<{
9
7
  reason: string;
10
- };
11
- })>, import("scale-ts").Decoder<(Error & {
12
- name: "PermissionErr::Rejected";
13
- className: string;
14
- payload: undefined;
15
- }) | (Error & {
16
- name: "PermissionErr::Unknown";
17
- className: string;
18
- payload: {
8
+ }, "PermissionErr::Unknown">>;
9
+ dec: import("scale-ts").Decoder<import("@novasamatech/scale").CodecError<undefined, "PermissionErr::Rejected"> | import("@novasamatech/scale").CodecError<{
19
10
  reason: string;
20
- };
21
- })>] & {
22
- enc: import("scale-ts").Encoder<(Error & {
23
- name: "PermissionErr::Rejected";
24
- className: string;
25
- payload: undefined;
26
- }) | (Error & {
27
- name: "PermissionErr::Unknown";
28
- className: string;
29
- payload: {
30
- reason: string;
31
- };
32
- })>;
33
- dec: import("scale-ts").Decoder<(Error & {
34
- name: "PermissionErr::Rejected";
35
- className: string;
36
- payload: undefined;
37
- }) | (Error & {
38
- name: "PermissionErr::Unknown";
39
- className: string;
40
- payload: {
41
- reason: string;
42
- };
43
- })>;
11
+ }, "PermissionErr::Unknown">>;
44
12
  } & {
45
- readonly Rejected: import("../commonCodecs.js").ErrCodec<undefined, "PermissionErr::Rejected">;
46
- readonly Unknown: import("../commonCodecs.js").ErrCodec<{
13
+ readonly Rejected: import("@novasamatech/scale").ErrCodec<undefined, "PermissionErr::Rejected">;
14
+ readonly Unknown: import("@novasamatech/scale").ErrCodec<{
47
15
  reason: string;
48
16
  }, "PermissionErr::Unknown">;
49
17
  };
@@ -77,14 +45,6 @@ export declare const PermissionRequestV1_request: import("scale-ts").Codec<{
77
45
  tag: "NetworkRequest";
78
46
  value: string[];
79
47
  }>;
80
- export declare const PermissionRequestV1_response: import("scale-ts").Codec<import("scale-ts").ResultPayload<undefined, (Error & {
81
- name: "PermissionErr::Rejected";
82
- className: string;
83
- payload: undefined;
84
- }) | (Error & {
85
- name: "PermissionErr::Unknown";
86
- className: string;
87
- payload: {
88
- reason: string;
89
- };
90
- })>>;
48
+ export declare const PermissionRequestV1_response: import("scale-ts").Codec<import("scale-ts").ResultPayload<undefined, import("@novasamatech/scale").CodecError<undefined, "PermissionErr::Rejected"> | import("@novasamatech/scale").CodecError<{
49
+ reason: string;
50
+ }, "PermissionErr::Unknown">>>;
@@ -1,5 +1,6 @@
1
+ import { Enum, ErrEnum } from '@novasamatech/scale';
1
2
  import { Result, Struct, Vector, _void, str } from 'scale-ts';
2
- import { Enum, ErrEnum, GenericErr, GenesisHash } from '../commonCodecs.js';
3
+ import { GenericErr, GenesisHash } from '../commonCodecs.js';
3
4
  export const PermissionErr = ErrEnum('PermissionErr', {
4
5
  Rejected: [_void, 'Permission: rejected'],
5
6
  Unknown: [GenericErr, 'Permission: unknown error'],
@@ -6,7 +6,7 @@ export const SigningErr = ErrEnum('SigningErr', {
6
6
  FailedToDecode: [_void, 'Failed to decode'],
7
7
  Rejected: [_void, 'Rejected'],
8
8
  PermissionDenied: [_void, 'Permission denied'],
9
- Unknown: [GenericErr, 'Unknown error'],
9
+ Unknown: [GenericErr, ({ reason }) => reason || 'Unknown error'],
10
10
  });
11
11
  export const SigningResult = Struct({
12
12
  signature: Hex(),
package/dist/transport.js CHANGED
@@ -1,10 +1,15 @@
1
- import { enumValue, isEnumVariant, resultErr, resultOk } from '@novasamatech/scale';
1
+ import { enumValue, isEnumVariant, resultErr, resultOk, toHex } from '@novasamatech/scale';
2
2
  import { createNanoEvents } from 'nanoevents';
3
3
  import { HANDSHAKE_INTERVAL, HANDSHAKE_TIMEOUT, JAM_CODEC_PROTOCOL_ID } from './constants.js';
4
4
  import { composeAction, createRequestId, delay, promiseWithResolvers } from './helpers.js';
5
- import { Message } from './protocol/messageCodec.js';
5
+ import { Message, MessagePayload } from './protocol/messageCodec.js';
6
6
  import { HandshakeErr } from './protocol/v1/handshake.js';
7
- const isConnected = (status) => status === 'connected';
7
+ function isConnected(status) {
8
+ return status === 'connected';
9
+ }
10
+ function getSubscriptionKey(method, payload) {
11
+ return `${method}_${toHex(MessagePayload.enc(payload))}`;
12
+ }
8
13
  export function createTransport(provider) {
9
14
  let codecVersion = JAM_CODEC_PROTOCOL_ID;
10
15
  const handshakeAbortController = new AbortController();
@@ -39,6 +44,8 @@ export function createTransport(provider) {
39
44
  throwIfIncorrectEnvironment();
40
45
  throwIfInvalidCodecVersion();
41
46
  }
47
+ // subscriptions management (multiplexing)
48
+ const activeSubscriptions = new Map();
42
49
  const transport = {
43
50
  provider,
44
51
  isCorrectEnvironment() {
@@ -137,39 +144,77 @@ export function createTransport(provider) {
137
144
  subscribe(method, payload, callback) {
138
145
  checks();
139
146
  const events = createNanoEvents();
140
- const requestId = createRequestId();
141
147
  const startAction = composeAction(method, 'start');
142
- const stopAction = composeAction(method, 'stop');
143
- const interruptAction = composeAction(method, 'interrupt');
144
- const receiveAction = composeAction(method, 'receive');
145
- const unsubscribeReceive = transport.listenMessages(receiveAction, (receivedId, data) => {
146
- if (receivedId === requestId) {
147
- callback(data.value);
148
- }
149
- });
150
- const unsubscribeInterrupt = transport.listenMessages(interruptAction, receivedId => {
151
- if (receivedId === requestId) {
152
- events.emit('interrupt');
153
- stopSubscription();
148
+ const startPayload = enumValue(startAction, payload);
149
+ const subscriptionKey = getSubscriptionKey(method, startPayload);
150
+ let subscription = activeSubscriptions.get(subscriptionKey);
151
+ function unsub() {
152
+ const subscription = activeSubscriptions.get(subscriptionKey);
153
+ if (subscription) {
154
+ const newListeners = subscription.listeners.filter(listener => listener.call !== callback);
155
+ if (newListeners.length === 0) {
156
+ activeSubscriptions.delete(subscriptionKey);
157
+ subscription.kill();
158
+ }
159
+ else {
160
+ subscription.listeners = newListeners;
161
+ }
154
162
  }
155
- });
156
- const stopSubscription = () => {
157
- unsubscribeReceive();
158
- unsubscribeInterrupt();
159
- events.events = {};
163
+ }
164
+ const listener = {
165
+ call: callback,
166
+ unsubscribe: unsub,
160
167
  };
161
- const startPayload = enumValue(startAction, payload);
162
- transport.postMessage(requestId, startPayload);
163
- return {
164
- unsubscribe() {
165
- stopSubscription();
166
- const stopPayload = enumValue(stopAction, undefined);
167
- transport.postMessage(requestId, stopPayload);
168
- },
168
+ const publicSubscription = {
169
+ unsubscribe: unsub,
169
170
  onInterrupt(callback) {
170
171
  return events.on('interrupt', callback);
171
172
  },
172
173
  };
174
+ // wiring up a real subscription
175
+ if (!subscription) {
176
+ const requestId = createRequestId();
177
+ const stopAction = composeAction(method, 'stop');
178
+ const interruptAction = composeAction(method, 'interrupt');
179
+ const receiveAction = composeAction(method, 'receive');
180
+ const unsubscribeReceive = transport.listenMessages(receiveAction, (receivedId, data) => {
181
+ if (receivedId === requestId) {
182
+ const subscription = activeSubscriptions.get(subscriptionKey);
183
+ if (subscription) {
184
+ for (const listener of subscription.listeners) {
185
+ listener.call(data.value);
186
+ }
187
+ }
188
+ }
189
+ });
190
+ const unsubscribeInterrupt = transport.listenMessages(interruptAction, receivedId => {
191
+ if (receivedId === requestId) {
192
+ events.emit('interrupt');
193
+ stopSubscription();
194
+ }
195
+ });
196
+ const stopSubscription = () => {
197
+ unsubscribeReceive();
198
+ unsubscribeInterrupt();
199
+ events.events = {};
200
+ };
201
+ // creating subscription
202
+ subscription = {
203
+ requestId,
204
+ kill: () => {
205
+ stopSubscription();
206
+ const stopPayload = enumValue(stopAction, undefined);
207
+ transport.postMessage(requestId, stopPayload);
208
+ },
209
+ listeners: [listener],
210
+ };
211
+ activeSubscriptions.set(subscriptionKey, subscription);
212
+ transport.postMessage(requestId, startPayload);
213
+ }
214
+ else {
215
+ subscription.listeners.push(listener);
216
+ }
217
+ return publicSubscription;
173
218
  },
174
219
  handleSubscription(method, handler) {
175
220
  checks();
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,58 @@
1
+ import { createNanoEvents } from 'nanoevents';
2
+ import { describe, expect, it, vi } from 'vitest';
3
+ import { createDefaultLogger } from './logger.js';
4
+ import { createTransport } from './transport.js';
5
+ function createProviders() {
6
+ const bus = createNanoEvents();
7
+ function createProvider(listenTo, postTo) {
8
+ return {
9
+ logger: createDefaultLogger(),
10
+ isCorrectEnvironment: () => true,
11
+ dispose: () => delete bus.events[listenTo],
12
+ subscribe: callback => bus.on(listenTo, callback),
13
+ postMessage: message => bus.emit(postTo, message),
14
+ };
15
+ }
16
+ return {
17
+ host: createProvider('toHost', 'toSdk'),
18
+ sdk: createProvider('toSdk', 'toHost'),
19
+ };
20
+ }
21
+ describe('transport', () => {
22
+ describe('subscription', () => {
23
+ it('should multiplex subscriptions', () => {
24
+ const providers = createProviders();
25
+ const events = createNanoEvents();
26
+ const host = createTransport(providers.host);
27
+ const sdk = createTransport(providers.sdk);
28
+ const hostUnsubscribe = vi.fn();
29
+ const containerHandler = vi.fn((_, send) => {
30
+ const unsub = events.on('push', () => {
31
+ send({ tag: 'v1', value: 'connected' });
32
+ });
33
+ return () => {
34
+ unsub();
35
+ hostUnsubscribe();
36
+ };
37
+ });
38
+ host.handleSubscription('host_account_connection_status_subscribe', containerHandler);
39
+ const s1Handler = vi.fn();
40
+ const s1 = sdk.subscribe('host_account_connection_status_subscribe', { tag: 'v1', value: undefined }, s1Handler);
41
+ const s2Handler = vi.fn();
42
+ const s2 = sdk.subscribe('host_account_connection_status_subscribe', { tag: 'v1', value: undefined }, s2Handler);
43
+ events.emit('push');
44
+ expect(s1Handler).toHaveBeenCalledTimes(1);
45
+ expect(s2Handler).toHaveBeenCalledTimes(1);
46
+ s1.unsubscribe();
47
+ expect(hostUnsubscribe).not.toBeCalled();
48
+ events.emit('push');
49
+ expect(s1Handler).toHaveBeenCalledTimes(1);
50
+ expect(s2Handler).toHaveBeenCalledTimes(2);
51
+ s2.unsubscribe();
52
+ expect(hostUnsubscribe).toHaveBeenCalledTimes(1);
53
+ events.emit('push');
54
+ expect(s1Handler).toHaveBeenCalledTimes(1);
55
+ expect(s2Handler).toHaveBeenCalledTimes(2);
56
+ });
57
+ });
58
+ });
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@novasamatech/host-api",
3
3
  "type": "module",
4
- "version": "0.6.5",
4
+ "version": "0.6.6-1",
5
5
  "description": "Host API: transport implementation for host - product integration.",
6
6
  "license": "Apache-2.0",
7
7
  "repository": {
@@ -21,7 +21,7 @@
21
21
  "README.md"
22
22
  ],
23
23
  "dependencies": {
24
- "@novasamatech/scale": "0.6.5",
24
+ "@novasamatech/scale": "0.6.6-1",
25
25
  "@polkadot-api/utils": "^0.2.0",
26
26
  "nanoevents": "9.1.0",
27
27
  "nanoid": "5.1.6",