@novasamatech/host-chat 0.8.0-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/README.md ADDED
@@ -0,0 +1,102 @@
1
+ # @novasamatech/host-chat
2
+
3
+ Account lookup and chat-message codecs for host applications integrating with the Polkadot People chain.
4
+
5
+ ## Overview
6
+
7
+ `@novasamatech/host-chat` exposes the read side of the chat domain: discovering Polkadot
8
+ accounts by username and resolving their on-chain identity from `Resources.Consumers`. It
9
+ also publishes the SCALE codecs used by the chat wire protocol (messages, attachments,
10
+ local-message envelopes) so host applications can decode statements they receive over the
11
+ statement store.
12
+
13
+ The package is UI-framework agnostic. The main entry point returns plain async functions
14
+ backed by [`neverthrow`](https://github.com/supermacro/neverthrow) `ResultAsync`, and the
15
+ codec exports are pure SCALE codecs with no runtime side effects.
16
+
17
+ ## Installation
18
+
19
+ ```shell
20
+ npm install @novasamatech/host-chat --save -E
21
+ ```
22
+
23
+ ## Getting started
24
+
25
+ ```ts
26
+ import { createAccountService } from '@novasamatech/host-chat';
27
+ import { createLazyClient } from '@novasamatech/statement-store';
28
+
29
+ const lazyClient = createLazyClient(/* chain provider */);
30
+ const accounts = createAccountService('paseo-next-v2', lazyClient);
31
+
32
+ // Search the off-chain username index for accounts whose username starts with `alice`.
33
+ const search = await accounts.search('alice', 'ASSIGNED');
34
+ if (search.isOk()) {
35
+ for (const hit of search.value) {
36
+ console.log(hit.candidateAccountId, hit.username);
37
+ }
38
+ }
39
+
40
+ // Resolve a specific account's on-chain identity.
41
+ const identity = await accounts.getConsumerInfo('5GrwvaEF5zXb26Fz9rcQpDWS57CtERHpNehXCPcNoHGKutQY');
42
+ if (identity.isOk() && identity.value) {
43
+ console.log(identity.value.fullUsername, identity.value.credibility);
44
+ }
45
+ ```
46
+
47
+ ### Networks
48
+
49
+ `createAccountService` accepts one of:
50
+
51
+ | Network | People chain endpoint |
52
+ | ---------------- | -------------------------------------- |
53
+ | `stable` | Polkadot People |
54
+ | `preview` | Westend People |
55
+ | `paseo-next` | Paseo People (V1) |
56
+ | `paseo-next-v2` | Paseo People (V2 multi-device) |
57
+
58
+ Each network entry pins both the People chain WebSocket URL (used via `lazyClient`) and
59
+ the off-chain identity-backend REST endpoint that `search` queries.
60
+
61
+ ## API
62
+
63
+ ### `createAccountService(network, lazyClient)`
64
+
65
+ Returns an object with two methods:
66
+
67
+ - **`search(query, status)`** — query the off-chain username index. `status` is
68
+ `'ASSIGNED' | 'PENDING'`. Resolves to a list of `{ candidateAccountId, username, status,
69
+ onchainData, createdAt, updatedAt }` rows.
70
+ - **`getConsumerInfo(address)`** — resolve a single SS58 address to an `Identity`
71
+ (`{ accountId, fullUsername, liteUsername, credibility }`) by reading
72
+ `Resources.Consumers` from the People chain. Returns `null` if the account has no
73
+ consumer entry. Tolerates both snake_case (V1) and camelCase (V2) runtime field names.
74
+
75
+ Both methods return `ResultAsync<…, Error>`; call `.isOk()` / `.isErr()` to discriminate.
76
+
77
+ ## Codec subpath exports
78
+
79
+ The chat wire codecs are exposed under explicit subpaths so they can be tree-shaken
80
+ independently of the main entry point:
81
+
82
+ ```ts
83
+ import {
84
+ ChatMessage,
85
+ TextContent,
86
+ RichTextContent,
87
+ ChatAcceptedContent,
88
+ DeviceAddedContent,
89
+ DeviceRemovedContent,
90
+ } from '@novasamatech/host-chat/codec/message';
91
+
92
+ import {
93
+ FileMeta,
94
+ FileVariant,
95
+ P2PMixnetFile,
96
+ } from '@novasamatech/host-chat/codec/attachment';
97
+
98
+ import type { ChatSession } from '@novasamatech/host-chat/session';
99
+ ```
100
+
101
+ These are byte-compatible with the Android / iOS Polkadot Mobile clients — modify with
102
+ care, the indices are pinned by the protocol.
@@ -0,0 +1,37 @@
1
+ import type { HexString } from '@novasamatech/scale';
2
+ import type { LazyClient } from '@novasamatech/statement-store';
3
+ import type { ResultAsync } from 'neverthrow';
4
+ type AccountStatus = 'ASSIGNED' | 'PENDING';
5
+ type AccountService = {
6
+ search(query: string, status: AccountStatus): ResultAsync<SearchResponse, Error>;
7
+ getConsumerInfo(address: string): ResultAsync<Identity | null, Error>;
8
+ };
9
+ type Network = 'paseo-next' | 'paseo-next-v2' | 'preview' | 'stable';
10
+ type SearchResponse = {
11
+ candidateAccountId: string;
12
+ username: string;
13
+ status: AccountStatus;
14
+ onchainData: {
15
+ blockIndex: number;
16
+ blockNumber: number;
17
+ blockHash: HexString;
18
+ eventIndex: number;
19
+ };
20
+ createdAt: string;
21
+ updatedAt: string;
22
+ }[];
23
+ export type Credibility = {
24
+ type: 'Lite';
25
+ } | {
26
+ type: 'Person';
27
+ alias: `0x${string}`;
28
+ lastUpdate: string;
29
+ };
30
+ export type Identity = {
31
+ accountId: string;
32
+ fullUsername: string | null;
33
+ liteUsername: string;
34
+ credibility: Credibility;
35
+ };
36
+ export declare const createAccountService: (network: Network, lazyClient: LazyClient) => AccountService;
37
+ export {};
@@ -0,0 +1,84 @@
1
+ import { toHex } from '@novasamatech/scale';
2
+ import { AccountId } from '@polkadot-api/substrate-bindings';
3
+ import { errAsync, fromPromise } from 'neverthrow';
4
+ import { toError } from './helpers.js';
5
+ export const createAccountService = (network, lazyClient) => {
6
+ const networkConfig = NETWORK_CONFIGS[network];
7
+ return {
8
+ search(query, status) {
9
+ // Build query string
10
+ const params = new URLSearchParams({
11
+ prefix: query,
12
+ status,
13
+ });
14
+ const request = fromPromise(fetch(`${networkConfig.apiUrl}/usernames?${params}`, {
15
+ method: 'GET',
16
+ headers: { Accept: 'application/json' },
17
+ }), toError);
18
+ return request.andThen(response => {
19
+ if (!response.ok) {
20
+ return fromPromise(response.text(), toError).andThen(message => errAsync(new Error(`status: ${response.status}, ${message}`)));
21
+ }
22
+ return fromPromise(response.json(), toError);
23
+ });
24
+ },
25
+ getConsumerInfo(address) {
26
+ const textDecoder = new TextDecoder();
27
+ const accountId = AccountId();
28
+ const client = lazyClient.getClient();
29
+ const api = client.getUnsafeApi();
30
+ const consumerInfo = fromPromise(api.query.Resources?.Consumers?.getValue(address), toError);
31
+ return consumerInfo.map(typedRaw => {
32
+ if (!typedRaw)
33
+ return null;
34
+ // Runtime metadata may expose fields in snake_case (V1) or
35
+ // camelCase (V2 multi-device). Read defensively.
36
+ const raw = typedRaw;
37
+ const fullUsername = raw.full_username ?? raw.fullUsername;
38
+ const liteUsername = raw.lite_username ?? raw.liteUsername;
39
+ const credibility = raw.credibility.type === 'Lite'
40
+ ? {
41
+ type: 'Lite',
42
+ }
43
+ : {
44
+ type: 'Person',
45
+ alias: raw.credibility.value.alias,
46
+ lastUpdate: (raw.credibility.value.last_update ??
47
+ raw.credibility.value.lastUpdate).toString(),
48
+ };
49
+ return {
50
+ accountId: toHex(accountId.enc(address)),
51
+ fullUsername: fullUsername ? textDecoder.decode(fullUsername) : null,
52
+ liteUsername: liteUsername ? textDecoder.decode(liteUsername) : '',
53
+ credibility: credibility,
54
+ };
55
+ });
56
+ },
57
+ };
58
+ };
59
+ const NETWORK_CONFIGS = {
60
+ stable: {
61
+ id: 'stable',
62
+ name: 'PoP Stable',
63
+ wsUrl: 'wss://pop3-testnet.parity-lab.parity.io/people',
64
+ apiUrl: 'https://polkadot-app.api.polkadotcommunity.foundation/api/v1',
65
+ },
66
+ preview: {
67
+ id: 'preview',
68
+ name: 'PoP Preview',
69
+ wsUrl: 'wss://previewnet.substrate.dev/people',
70
+ apiUrl: 'https://polkadot-app-stg.parity.io/api/v1',
71
+ },
72
+ 'paseo-next': {
73
+ id: 'paseo-next',
74
+ name: 'Paseo Next',
75
+ wsUrl: 'wss://paseo-people-next-rpc.polkadot.io',
76
+ apiUrl: 'https://identity-backend.parity-testnet.parity.io/api/v1',
77
+ },
78
+ 'paseo-next-v2': {
79
+ id: 'paseo-next-v2',
80
+ name: 'Paseo Next V2',
81
+ wsUrl: 'wss://paseo-people-next-system-rpc.polkadot.io',
82
+ apiUrl: 'https://identity-backend-next.parity-testnet.parity.io/api/v1',
83
+ },
84
+ };
@@ -0,0 +1,108 @@
1
+ export declare const GeneralFileMeta: import("scale-ts").Codec<{
2
+ mimeType: string;
3
+ fileSize: number;
4
+ }>;
5
+ export declare const ImageFileMeta: import("scale-ts").Codec<{
6
+ general: {
7
+ mimeType: string;
8
+ fileSize: number;
9
+ };
10
+ width: number;
11
+ height: number;
12
+ }>;
13
+ export declare const VideoFileMeta: import("scale-ts").Codec<{
14
+ general: {
15
+ mimeType: string;
16
+ fileSize: number;
17
+ };
18
+ duration: number;
19
+ }>;
20
+ export declare const FileMeta: import("scale-ts").Codec<{
21
+ tag: "general";
22
+ value: {
23
+ mimeType: string;
24
+ fileSize: number;
25
+ };
26
+ } | {
27
+ tag: "image";
28
+ value: {
29
+ general: {
30
+ mimeType: string;
31
+ fileSize: number;
32
+ };
33
+ width: number;
34
+ height: number;
35
+ };
36
+ } | {
37
+ tag: "video";
38
+ value: {
39
+ general: {
40
+ mimeType: string;
41
+ fileSize: number;
42
+ };
43
+ duration: number;
44
+ };
45
+ }>;
46
+ export declare const P2PMixnetFile: import("scale-ts").Codec<{
47
+ identifier: Uint8Array<ArrayBufferLike>;
48
+ claimTicket: Uint8Array<ArrayBufferLike>;
49
+ meta: {
50
+ tag: "general";
51
+ value: {
52
+ mimeType: string;
53
+ fileSize: number;
54
+ };
55
+ } | {
56
+ tag: "image";
57
+ value: {
58
+ general: {
59
+ mimeType: string;
60
+ fileSize: number;
61
+ };
62
+ width: number;
63
+ height: number;
64
+ };
65
+ } | {
66
+ tag: "video";
67
+ value: {
68
+ general: {
69
+ mimeType: string;
70
+ fileSize: number;
71
+ };
72
+ duration: number;
73
+ };
74
+ };
75
+ }>;
76
+ export declare const FileVariant: import("scale-ts").Codec<{
77
+ tag: "p2pMixnet";
78
+ value: {
79
+ identifier: Uint8Array<ArrayBufferLike>;
80
+ claimTicket: Uint8Array<ArrayBufferLike>;
81
+ meta: {
82
+ tag: "general";
83
+ value: {
84
+ mimeType: string;
85
+ fileSize: number;
86
+ };
87
+ } | {
88
+ tag: "image";
89
+ value: {
90
+ general: {
91
+ mimeType: string;
92
+ fileSize: number;
93
+ };
94
+ width: number;
95
+ height: number;
96
+ };
97
+ } | {
98
+ tag: "video";
99
+ value: {
100
+ general: {
101
+ mimeType: string;
102
+ fileSize: number;
103
+ };
104
+ duration: number;
105
+ };
106
+ };
107
+ };
108
+ }>;
@@ -0,0 +1,28 @@
1
+ import { Enum } from '@novasamatech/scale';
2
+ import { Bytes, Struct, str, u32 } from 'scale-ts';
3
+ export const GeneralFileMeta = Struct({
4
+ mimeType: str,
5
+ fileSize: u32,
6
+ });
7
+ export const ImageFileMeta = Struct({
8
+ general: GeneralFileMeta,
9
+ width: u32,
10
+ height: u32,
11
+ });
12
+ export const VideoFileMeta = Struct({
13
+ general: GeneralFileMeta,
14
+ duration: u32,
15
+ });
16
+ export const FileMeta = Enum({
17
+ general: GeneralFileMeta,
18
+ image: ImageFileMeta,
19
+ video: VideoFileMeta,
20
+ });
21
+ export const P2PMixnetFile = Struct({
22
+ identifier: Bytes(),
23
+ claimTicket: Bytes(),
24
+ meta: FileMeta,
25
+ });
26
+ export const FileVariant = Enum({
27
+ p2pMixnet: P2PMixnetFile,
28
+ });
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,91 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { FileMeta, FileVariant, GeneralFileMeta, ImageFileMeta, P2PMixnetFile, VideoFileMeta } from './attachment.js';
3
+ describe('attachment codecs', () => {
4
+ describe('GeneralFileMeta', () => {
5
+ it('round-trips', () => {
6
+ const original = { mimeType: 'application/pdf', fileSize: 1024 };
7
+ const encoded = GeneralFileMeta.enc(original);
8
+ const decoded = GeneralFileMeta.dec(encoded);
9
+ expect(decoded).toEqual(original);
10
+ });
11
+ });
12
+ describe('ImageFileMeta', () => {
13
+ it('round-trips', () => {
14
+ const original = {
15
+ general: { mimeType: 'image/jpeg', fileSize: 500_000 },
16
+ width: 1920,
17
+ height: 1080,
18
+ };
19
+ const encoded = ImageFileMeta.enc(original);
20
+ const decoded = ImageFileMeta.dec(encoded);
21
+ expect(decoded).toEqual(original);
22
+ });
23
+ });
24
+ describe('VideoFileMeta', () => {
25
+ it('round-trips', () => {
26
+ const original = {
27
+ general: { mimeType: 'video/mp4', fileSize: 10_000_000 },
28
+ duration: 120,
29
+ };
30
+ const encoded = VideoFileMeta.enc(original);
31
+ const decoded = VideoFileMeta.dec(encoded);
32
+ expect(decoded).toEqual(original);
33
+ });
34
+ });
35
+ describe('FileMeta', () => {
36
+ it('round-trips all variants', () => {
37
+ const variants = [
38
+ { tag: 'general', value: { mimeType: 'application/pdf', fileSize: 1024 } },
39
+ {
40
+ tag: 'image',
41
+ value: { general: { mimeType: 'image/png', fileSize: 2048 }, width: 800, height: 600 },
42
+ },
43
+ {
44
+ tag: 'video',
45
+ value: { general: { mimeType: 'video/mp4', fileSize: 4096 }, duration: 60 },
46
+ },
47
+ ];
48
+ for (const original of variants) {
49
+ const encoded = FileMeta.enc(original);
50
+ const decoded = FileMeta.dec(encoded);
51
+ expect(decoded).toEqual(original);
52
+ }
53
+ });
54
+ });
55
+ describe('P2PMixnetFile', () => {
56
+ it('round-trips', () => {
57
+ const original = {
58
+ identifier: new Uint8Array(32).fill(0xaa),
59
+ claimTicket: new Uint8Array(32).fill(0xbb),
60
+ meta: {
61
+ tag: 'image',
62
+ value: {
63
+ general: { mimeType: 'image/jpeg', fileSize: 500_000 },
64
+ width: 1920,
65
+ height: 1080,
66
+ },
67
+ },
68
+ };
69
+ const encoded = P2PMixnetFile.enc(original);
70
+ const decoded = P2PMixnetFile.dec(encoded);
71
+ expect(decoded.identifier).toEqual(original.identifier);
72
+ expect(decoded.claimTicket).toEqual(original.claimTicket);
73
+ expect(decoded.meta).toEqual(original.meta);
74
+ });
75
+ });
76
+ describe('FileVariant', () => {
77
+ it('round-trips p2pMixnet variant', () => {
78
+ const variant = {
79
+ tag: 'p2pMixnet',
80
+ value: {
81
+ identifier: new Uint8Array(32).fill(0x11),
82
+ claimTicket: new Uint8Array(32).fill(0x22),
83
+ meta: { tag: 'general', value: { mimeType: 'text/plain', fileSize: 10 } },
84
+ },
85
+ };
86
+ const encoded = FileVariant.enc(variant);
87
+ const decoded = FileVariant.dec(encoded);
88
+ expect(decoded).toEqual(variant);
89
+ });
90
+ });
91
+ });
@@ -0,0 +1,9 @@
1
+ export declare const Contact: import("scale-ts").Codec<{
2
+ username: string;
3
+ accountId: import("@novasamatech/statement-store").AccountId;
4
+ publicKey: Uint8Array<ArrayBufferLike>;
5
+ pin: string | undefined;
6
+ pushId: string | undefined;
7
+ pushToken: Uint8Array<ArrayBufferLike> | undefined;
8
+ lastOwnToken: Uint8Array<ArrayBufferLike> | undefined;
9
+ }>;
@@ -0,0 +1,11 @@
1
+ import { AccountIdCodec } from '@novasamatech/statement-store';
2
+ import { Bytes, Option, Struct, str } from 'scale-ts';
3
+ export const Contact = Struct({
4
+ username: str,
5
+ accountId: AccountIdCodec,
6
+ publicKey: Bytes(),
7
+ pin: Option(str),
8
+ pushId: Option(str),
9
+ pushToken: Option(Bytes()),
10
+ lastOwnToken: Option(Bytes()),
11
+ });