@parity/product-sdk-host 0.12.0 → 0.13.0

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,49 @@
1
+ import { isCorrectEnvironment as isCorrectEnvironment$1, getClientSync as getClientSync$1 } from '@parity/truapi/sandbox';
2
+
3
+ // src/transport.ts
4
+ var clientOverride = null;
5
+ function isProductionBuild() {
6
+ try {
7
+ return process.env.NODE_ENV === "production";
8
+ } catch {
9
+ return false;
10
+ }
11
+ }
12
+ function setTruApiClient(client) {
13
+ if (client !== null && isProductionBuild()) {
14
+ console.warn(
15
+ "[product-sdk] setTruApiClient() was called in a production build. This is a test-only seam from @parity/product-sdk-host/testing; a leaked import will silently reroute all host access to the injected client."
16
+ );
17
+ }
18
+ clientOverride = client;
19
+ }
20
+ function getClientSync() {
21
+ return clientOverride ?? getClientSync$1();
22
+ }
23
+ function isCorrectEnvironment() {
24
+ return clientOverride !== null || isCorrectEnvironment$1();
25
+ }
26
+ async function getClient() {
27
+ return getClientSync();
28
+ }
29
+ function subscribeWithInterrupt(observable, onNext) {
30
+ let interruptCallback;
31
+ const sub = observable.subscribe({
32
+ next: onNext,
33
+ error: (reason) => interruptCallback?.(reason),
34
+ complete: () => interruptCallback?.()
35
+ });
36
+ return {
37
+ unsubscribe: () => sub.unsubscribe(),
38
+ onInterrupt: (callback) => {
39
+ interruptCallback = callback;
40
+ return () => {
41
+ if (interruptCallback === callback) interruptCallback = void 0;
42
+ };
43
+ }
44
+ };
45
+ }
46
+
47
+ export { getClient, isCorrectEnvironment, setTruApiClient, subscribeWithInterrupt };
48
+ //# sourceMappingURL=chunk-3SWF5CWC.js.map
49
+ //# sourceMappingURL=chunk-3SWF5CWC.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/transport.ts"],"names":["sandboxGetClientSync","sandboxIsCorrectEnvironment"],"mappings":";;;AAyBA,IAAI,cAAA,GAAsC,IAAA;AAE1C,SAAS,iBAAA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TruAPI client (`@parity/truapi`) for the host package.\n *\n * Environment detection and the lazily-built, cached client come from\n * `@parity/truapi/sandbox`; this module layers the product-sdk-specific glue on\n * top — an async {@link getClient} accessor and {@link subscribeWithInterrupt},\n * which adapts a truapi stream into the host's {@link HostSubscription} shape.\n *\n * @module\n */\n\nimport type { ObservableLike, TrUApiClient } from \"@parity/truapi\";\nimport {\n getClientSync as sandboxGetClientSync,\n isCorrectEnvironment as sandboxIsCorrectEnvironment,\n} from \"@parity/truapi/sandbox\";\n\nimport type { HostSubscription } from \"./types.js\";\n\n// Test-only override. When set — via `setTruApiClient`, exposed through\n// `@parity/product-sdk-host/testing` — every host accessor resolves this client\n// instead of the sandbox one. `null` in production, so the branches below are\n// no-ops there.\nlet clientOverride: TrUApiClient | null = null;\n\nfunction isProductionBuild(): boolean {\n try {\n // Must stay a plain `process.env.NODE_ENV` member expression: bundlers\n // (Vite, esbuild, webpack) substitute it textually, which is how this\n // check works in browser builds where `process` doesn't exist.\n return process.env.NODE_ENV === \"production\";\n } catch {\n // No `process` and no bundler define — can't tell, stay quiet.\n return false;\n }\n}\n\n/**\n * Test-only seam: force {@link getClient} / {@link getClientSync} to return\n * `client`, and {@link isCorrectEnvironment} to report `true`. Pass `null` to\n * restore normal detection. Exposed through `@parity/product-sdk-host/testing`,\n * not the package's main entry.\n *\n * Calling this in a production build silently reroutes every host accessor to\n * the injected client, so we warn — it almost always means a `/testing` import\n * leaked into a production path.\n */\nexport function setTruApiClient(client: TrUApiClient | null): void {\n if (client !== null && isProductionBuild()) {\n console.warn(\n \"[product-sdk] setTruApiClient() was called in a production build. This is a test-only seam from @parity/product-sdk-host/testing; a leaked import will silently reroute all host access to the injected client.\",\n );\n }\n clientOverride = client;\n}\n\n/**\n * Synchronous TruAPI client accessor. Returns the injected test client when one\n * is set, otherwise the sandbox client (`null` outside a host container).\n */\nexport function getClientSync(): TrUApiClient | null {\n return clientOverride ?? sandboxGetClientSync();\n}\n\n/**\n * Host-container detection. `true` when a test client is injected, otherwise the\n * sandbox heuristic (iframe / webview marker / injected message port).\n */\nexport function isCorrectEnvironment(): boolean {\n return clientOverride !== null || sandboxIsCorrectEnvironment();\n}\n\n/**\n * Get the TruAPI client. Returns `null` outside a host container. Async wrapper\n * over {@link getClientSync} for the host wrappers that already `await` it.\n */\nexport async function getClient(): Promise<TrUApiClient | null> {\n return getClientSync();\n}\n\n/**\n * Adapt a truapi `ObservableLike` stream into the host's callback-style\n * {@link HostSubscription} (`unsubscribe` + `onInterrupt`). `onNext` fires for\n * each item; the registered `onInterrupt` callback fires when the host ends the\n * subscription server-side — which the generated client surfaces as either\n * `complete` (a host interrupt frame) or `error` (transport close). Shared by\n * the statement-store and preimage adapters, which both expose this shape.\n */\nexport function subscribeWithInterrupt<Item, Reason = never>(\n observable: ObservableLike<Item, Reason>,\n onNext: (item: Item) => void,\n): HostSubscription {\n let interruptCallback: ((reason?: unknown) => void) | undefined;\n const sub = observable.subscribe({\n next: onNext,\n error: (reason) => interruptCallback?.(reason),\n complete: () => interruptCallback?.(),\n });\n return {\n unsubscribe: () => sub.unsubscribe(),\n onInterrupt: (callback) => {\n interruptCallback = callback;\n return () => {\n if (interruptCallback === callback) interruptCallback = undefined;\n };\n },\n };\n}\n\nif (import.meta.vitest) {\n const { test, expect, afterEach } = import.meta.vitest;\n\n afterEach(() => setTruApiClient(null));\n\n // Environment detection and client building are covered by `@parity/truapi`'s\n // own sandbox tests; here we only assert the local glue degrades outside a\n // host container.\n test(\"getClientSync returns null outside a container\", () => {\n expect(getClientSync()).toBeNull();\n });\n\n test(\"getClient resolves null outside a container\", async () => {\n expect(await getClient()).toBeNull();\n });\n\n test(\"setTruApiClient overrides the client and container detection\", async () => {\n const fake = {} as TrUApiClient;\n setTruApiClient(fake);\n expect(getClientSync()).toBe(fake);\n expect(await getClient()).toBe(fake);\n expect(isCorrectEnvironment()).toBe(true);\n\n setTruApiClient(null);\n expect(getClientSync()).toBeNull();\n expect(isCorrectEnvironment()).toBe(false);\n });\n\n test(\"setTruApiClient warns when injecting in a production build\", () => {\n const original = process.env.NODE_ENV;\n const warnings: string[] = [];\n const realWarn = console.warn;\n console.warn = (...args: unknown[]) => void warnings.push(String(args[0]));\n try {\n process.env.NODE_ENV = \"production\";\n setTruApiClient({} as TrUApiClient);\n expect(warnings).toHaveLength(1);\n expect(warnings[0]).toContain(\"production build\");\n\n // Clearing the override must not warn.\n setTruApiClient(null);\n expect(warnings).toHaveLength(1);\n } finally {\n console.warn = realWarn;\n process.env.NODE_ENV = original;\n }\n });\n}\n"]}
package/dist/index.d.ts CHANGED
@@ -1,8 +1,12 @@
1
1
  import { JsonRpcProvider, PolkadotSigner } from 'polkadot-api';
2
2
  import { Topic, RemoteStatementStoreSubscribeItem, Statement, StatementProof, SignedStatement, HexString, GenericError, TrUApiClient, AllocatableResource, AllocationOutcome, HostGetUserIdError, HostRequestLoginResponse, HostRequestLoginError, ProductAccountId, ProductAccount as ProductAccount$1, HostAccountGetError, HostAccountGetAliasResponse, LegacyAccount, RingLocation, HostAccountCreateProofError, HostAccountConnectionStatusSubscribeItem, HostDevicePermissionRequest, RemotePermission, HostThemeSubscribeItem, ChatBotRegistrationStatus, HostChatCreateRoomRequest, ChatRoomRegistrationStatus, HostChatRegisterBotRequest, ChatMessageContent, ChatRoom, HostChatActionSubscribeItem, HostPaymentBalanceSubscribeItem, PaymentPurseId, Balance, PaymentTopUpSource, HostPaymentStatusSubscribeItem, HostPushNotificationRequest, NotificationId } from '@parity/truapi';
3
3
  export { AllocatableResource, AllocationOutcome, ChatMessageContent, ChatRoom, HexString, HostPaymentBalanceSubscribeItem, HostPaymentStatusSubscribeItem, NotificationId, PaymentTopUpSource, ProductAccountId, HostPushNotificationError as PushNotificationError, RemotePermission, RingLocation, SignedStatement, Statement, StatementProof, ThemeName, ThemeVariant, Topic } from '@parity/truapi';
4
+ import { SdkError } from '@parity/product-sdk-errors';
5
+ export { SdkError, isSdkError } from '@parity/product-sdk-errors';
6
+ import { Result } from '@parity/result';
7
+ export { Result, err, ok } from '@parity/result';
4
8
  import { ResultAsync as ResultAsync$1 } from 'neverthrow';
5
- export { isCorrectEnvironment as isInsideContainerSync } from '@parity/truapi/sandbox';
9
+ export { i as isInsideContainerSync } from './transport-B0cdhwrp.js';
6
10
 
7
11
  /**
8
12
  * Public types for the host wrappers.
@@ -152,13 +156,14 @@ declare function getStatementStore(): Promise<HostStatementStore | null>;
152
156
  * chain-specific endpoints used by multiple packages.
153
157
  */
154
158
  /**
155
- * Bulletin Chain RPC endpoints per network environment. `paseo` and `summit`
156
- * are populated today; `polkadot` and `kusama` are reserved for when those
157
- * Bulletin deployments go live.
159
+ * Bulletin Chain RPC endpoints per network environment. `paseo` (Paseo Next v2),
160
+ * `summit`, and `devnet` (public Paseo testnet) are populated today; `polkadot`
161
+ * and `kusama` are reserved for when those Bulletin deployments go live.
158
162
  */
159
163
  declare const BULLETIN_RPCS: {
160
164
  readonly paseo: readonly ["wss://paseo-bulletin-next-rpc.polkadot.io"];
161
165
  readonly summit: readonly ["wss://summit-bulletin-rpc.polkadot.io"];
166
+ readonly devnet: readonly ["wss://bulletin-paseo.tservices.es:8443"];
162
167
  readonly polkadot: string[];
163
168
  readonly kusama: string[];
164
169
  };
@@ -226,9 +231,12 @@ type HostErrorPayload = GenericError | {
226
231
  declare function formatHostError(error: unknown): string;
227
232
  /**
228
233
  * Base class for all host errors. Use `instanceof HostError` (or {@link isHostError})
229
- * to catch any host-related failure.
234
+ * to catch any host-related failure. Implements the cross-package
235
+ * {@link SdkError} marker so `isSdkError(e)` also recognizes it.
230
236
  */
231
- declare class HostError extends Error {
237
+ declare class HostError extends Error implements SdkError {
238
+ readonly isSdkError: true;
239
+ readonly source = "host";
232
240
  constructor(message: string, options?: ErrorOptions);
233
241
  }
234
242
  /**
@@ -252,36 +260,6 @@ declare class HostCallFailedError extends HostError {
252
260
  /** Check whether a value is any {@link HostError}. */
253
261
  declare function isHostError(error: unknown): error is HostError;
254
262
 
255
- /**
256
- * A lightweight tagged `Result` type for the host public API.
257
- *
258
- * Host functions return `Promise<Result<T, HostError>>` rather than throwing, so
259
- * consumers get typed errors on the `err` channel instead of opaque thrown
260
- * `Error`s. The shape is intentionally identical to the one
261
- * `@parity/product-sdk-signer` exposes (`{ ok: true; value } | { ok: false; error }`),
262
- * so the two layers compose with no adapter — host's `Result` flows straight into
263
- * the signer's pattern matching.
264
- *
265
- * NOTE: host owns its own copy because the dependency edge runs `signer → host`,
266
- * so host cannot import the signer's definition. If a third package ever needs
267
- * this shape, extract it into a shared `@parity/product-sdk-result` package and
268
- * have both depend on that instead of duplicating.
269
- *
270
- * @module
271
- */
272
- /** A value that is either a success (`ok`) carrying `T`, or a failure (`err`) carrying `E`. */
273
- type Result<T, E> = {
274
- ok: true;
275
- value: T;
276
- } | {
277
- ok: false;
278
- error: E;
279
- };
280
- /** Create a successful {@link Result}. */
281
- declare function ok<T>(value: T): Result<T, never>;
282
- /** Create a failed {@link Result}. */
283
- declare function err<E>(error: E): Result<never, E>;
284
-
285
263
  /**
286
264
  * TruAPI - the protocol for communicating between apps and the Polkadot host container.
287
265
  *
@@ -1020,4 +998,4 @@ declare function broadcastTransaction(genesisHash: HexString, transaction: HexSt
1020
998
  */
1021
999
  declare function stopTransaction(genesisHash: HexString, operationId: string): Promise<Result<void, HostError>>;
1022
1000
 
1023
- export { type AccountsProvider, BULLETIN_RPCS, ChainNotSupportedError, type ChainProperties, type ChainSpec, type ChatBotRegistrationResult, type ChatManager, type ChatReceivedAction, type ChatRoomRegistrationResult, type ContextualAlias, DEFAULT_BULLETIN_ENDPOINT, type DevicePermissionKind, type Feature, type HostAccount, HostCallFailedError, HostError, type HostErrorPayload, type HostLocalStorage, type HostStatementStore, type HostSubscription, HostUnavailableError, type NotificationManager, type PaymentManager, type PreimageManager, type ProductAccount, type PushNotificationInput, type RemotePermissionItem, type Result, type ResultAsync, type StatementTopicFilter, type StatementsPage, type ThemeMode, type ThemeProvider, type TruApi, broadcastTransaction, createHostLocalStorage, createHostPreimageManager, createProofAuthorized, deriveEntropy, err, featureSupported, formatHostError, fromHex, getAccountsProvider, getChainSpec, getChatManager, getHostLocalStorage, getHostProvider, getNotificationManager, getPaymentManager, getPreimageManager, getStatementStore, getThemeProvider, getTruApi, isChainSupported, isHostError, isInsideContainer, navigateTo, ok, requestDevicePermission, requestPermission, requestResourceAllocation, stopTransaction, toHex };
1001
+ export { type AccountsProvider, BULLETIN_RPCS, ChainNotSupportedError, type ChainProperties, type ChainSpec, type ChatBotRegistrationResult, type ChatManager, type ChatReceivedAction, type ChatRoomRegistrationResult, type ContextualAlias, DEFAULT_BULLETIN_ENDPOINT, type DevicePermissionKind, type Feature, type HostAccount, HostCallFailedError, HostError, type HostErrorPayload, type HostLocalStorage, type HostStatementStore, type HostSubscription, HostUnavailableError, type NotificationManager, type PaymentManager, type PreimageManager, type ProductAccount, type PushNotificationInput, type RemotePermissionItem, type ResultAsync, type StatementTopicFilter, type StatementsPage, type ThemeMode, type ThemeProvider, type TruApi, broadcastTransaction, createHostLocalStorage, createHostPreimageManager, createProofAuthorized, deriveEntropy, featureSupported, formatHostError, fromHex, getAccountsProvider, getChainSpec, getChatManager, getHostLocalStorage, getHostProvider, getNotificationManager, getPaymentManager, getPreimageManager, getStatementStore, getThemeProvider, getTruApi, isChainSupported, isHostError, isInsideContainer, navigateTo, requestDevicePermission, requestPermission, requestResourceAllocation, stopTransaction, toHex };
package/dist/index.js CHANGED
@@ -1,7 +1,10 @@
1
+ import { getClient, isCorrectEnvironment, subscribeWithInterrupt } from './chunk-3SWF5CWC.js';
2
+ export { isCorrectEnvironment as isInsideContainerSync } from './chunk-3SWF5CWC.js';
1
3
  import { createLogger } from '@parity/product-sdk-logger';
2
- import { isCorrectEnvironment, getClientSync } from '@parity/truapi/sandbox';
3
- export { isCorrectEnvironment as isInsideContainerSync } from '@parity/truapi/sandbox';
4
4
  import { scale } from '@parity/truapi';
5
+ import { err, ok } from '@parity/result';
6
+ export { err, ok } from '@parity/result';
7
+ export { isSdkError } from '@parity/product-sdk-errors';
5
8
  import { unifyMetadata, decAnyMetadata } from '@polkadot-api/substrate-bindings';
6
9
  import { AccountId } from 'polkadot-api';
7
10
 
@@ -34,6 +37,8 @@ function formatHostError(error) {
34
37
  }
35
38
  }
36
39
  var HostError = class extends Error {
40
+ isSdkError = true;
41
+ source = "host";
37
42
  constructor(message, options) {
38
43
  super(message, options);
39
44
  this.name = "HostError";
@@ -56,28 +61,6 @@ var HostCallFailedError = class extends HostError {
56
61
  function isHostError(error) {
57
62
  return error instanceof HostError;
58
63
  }
59
- async function getClient() {
60
- return getClientSync();
61
- }
62
- function subscribeWithInterrupt(observable, onNext) {
63
- let interruptCallback;
64
- const sub = observable.subscribe({
65
- next: onNext,
66
- error: (reason) => interruptCallback?.(reason),
67
- complete: () => interruptCallback?.()
68
- });
69
- return {
70
- unsubscribe: () => sub.unsubscribe(),
71
- onInterrupt: (callback) => {
72
- interruptCallback = callback;
73
- return () => {
74
- if (interruptCallback === callback) interruptCallback = void 0;
75
- };
76
- }
77
- };
78
- }
79
-
80
- // src/papi-provider.ts
81
64
  var log = createLogger("host:papi");
82
65
  var JSON_RPC_INTERNAL_ERROR = -32603;
83
66
  var JSON_RPC_METHOD_NOT_FOUND = -32601;
@@ -395,14 +378,6 @@ function createHostPapiProvider(client, genesisHash) {
395
378
  };
396
379
  }
397
380
 
398
- // src/result.ts
399
- function ok(value) {
400
- return { ok: true, value };
401
- }
402
- function err(error) {
403
- return { ok: false, error };
404
- }
405
-
406
381
  // src/truapi.ts
407
382
  var log2 = createLogger("host");
408
383
  function unwrapHostResult(result, label) {
@@ -578,6 +553,7 @@ async function getStatementStore() {
578
553
  var BULLETIN_RPCS = {
579
554
  paseo: ["wss://paseo-bulletin-next-rpc.polkadot.io"],
580
555
  summit: ["wss://summit-bulletin-rpc.polkadot.io"],
556
+ devnet: ["wss://bulletin-paseo.tservices.es:8443"],
581
557
  polkadot: [],
582
558
  kusama: []
583
559
  };
@@ -968,6 +944,6 @@ async function stopTransaction(genesisHash, operationId) {
968
944
  );
969
945
  }
970
946
 
971
- export { BULLETIN_RPCS, ChainNotSupportedError, DEFAULT_BULLETIN_ENDPOINT, HostCallFailedError, HostError, HostUnavailableError, broadcastTransaction, createHostLocalStorage, createHostPreimageManager, createProofAuthorized, deriveEntropy, err, featureSupported, formatHostError, fromHex, getAccountsProvider, getChainSpec, getChatManager, getHostLocalStorage, getHostProvider, getNotificationManager, getPaymentManager, getPreimageManager, getStatementStore, getThemeProvider, getTruApi, isChainSupported, isHostError, isInsideContainer, navigateTo, ok, requestDevicePermission, requestPermission, requestResourceAllocation, stopTransaction, toHex };
947
+ export { BULLETIN_RPCS, ChainNotSupportedError, DEFAULT_BULLETIN_ENDPOINT, HostCallFailedError, HostError, HostUnavailableError, broadcastTransaction, createHostLocalStorage, createHostPreimageManager, createProofAuthorized, deriveEntropy, featureSupported, formatHostError, fromHex, getAccountsProvider, getChainSpec, getChatManager, getHostLocalStorage, getHostProvider, getNotificationManager, getPaymentManager, getPreimageManager, getStatementStore, getThemeProvider, getTruApi, isChainSupported, isHostError, isInsideContainer, navigateTo, requestDevicePermission, requestPermission, requestResourceAllocation, stopTransaction, toHex };
972
948
  //# sourceMappingURL=index.js.map
973
949
  //# sourceMappingURL=index.js.map